Klimi's new dotfiles with stow.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

861 lines
36 KiB

4 years ago
  1. ;;; with-editor.el --- Use the Emacsclient as $EDITOR -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2014-2019 The Magit Project Contributors
  3. ;;
  4. ;; You should have received a copy of the AUTHORS.md file. If not,
  5. ;; see https://github.com/magit/with-editor/blob/master/AUTHORS.md.
  6. ;; Author: Jonas Bernoulli <jonas@bernoul.li>
  7. ;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>
  8. ;; Package-Requires: ((emacs "24.4") (async "1.9"))
  9. ;; Keywords: tools
  10. ;; Homepage: https://github.com/magit/with-editor
  11. ;; This file is not part of GNU Emacs.
  12. ;; This file is free software; you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation; either version 3, or (at your option)
  15. ;; any later version.
  16. ;; This file is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with Magit. If not, see http://www.gnu.org/licenses.
  22. ;;; Commentary:
  23. ;; This library makes it possible to reliably use the Emacsclient as
  24. ;; the `$EDITOR' of child processes. It makes sure that they know how
  25. ;; to call home. For remote processes a substitute is provided, which
  26. ;; communicates with Emacs on standard output/input instead of using a
  27. ;; socket as the Emacsclient does.
  28. ;; It provides the commands `with-editor-async-shell-command' and
  29. ;; `with-editor-shell-command', which are intended as replacements
  30. ;; for `async-shell-command' and `shell-command'. They automatically
  31. ;; export `$EDITOR' making sure the executed command uses the current
  32. ;; Emacs instance as "the editor". With a prefix argument these
  33. ;; commands prompt for an alternative environment variable such as
  34. ;; `$GIT_EDITOR'. To always use these variants add this to your init
  35. ;; file:
  36. ;;
  37. ;; (define-key (current-global-map)
  38. ;; [remap async-shell-command] 'with-editor-async-shell-command)
  39. ;; (define-key (current-global-map)
  40. ;; [remap shell-command] 'with-editor-shell-command)
  41. ;; Alternatively use the global `shell-command-with-editor-mode',
  42. ;; which always sets `$EDITOR' for all Emacs commands which ultimately
  43. ;; use `shell-command' to asynchronously run some shell command.
  44. ;; The command `with-editor-export-editor' exports `$EDITOR' or
  45. ;; another such environment variable in `shell-mode', `term-mode' and
  46. ;; `eshell-mode' buffers. Use this Emacs command before executing a
  47. ;; shell command which needs the editor set, or always arrange for the
  48. ;; current Emacs instance to be used as editor by adding it to the
  49. ;; appropriate mode hooks:
  50. ;;
  51. ;; (add-hook 'shell-mode-hook 'with-editor-export-editor)
  52. ;; (add-hook 'term-exec-hook 'with-editor-export-editor)
  53. ;; (add-hook 'eshell-mode-hook 'with-editor-export-editor)
  54. ;; Some variants of this function exist, these two forms are
  55. ;; equivalent:
  56. ;;
  57. ;; (add-hook 'shell-mode-hook
  58. ;; (apply-partially 'with-editor-export-editor "GIT_EDITOR"))
  59. ;; (add-hook 'shell-mode-hook 'with-editor-export-git-editor)
  60. ;; This library can also be used by other packages which need to use
  61. ;; the current Emacs instance as editor. In fact this library was
  62. ;; written for Magit and its `git-commit-mode' and `git-rebase-mode'.
  63. ;; Consult `git-rebase.el' and the related code in `magit-sequence.el'
  64. ;; for a simple example.
  65. ;;; Code:
  66. (require 'cl-lib)
  67. ;; `pcase-dolist' is not autoloaded on Emacs 24.
  68. (eval-when-compile (require 'pcase))
  69. (require 'server)
  70. (require 'shell)
  71. (and (require 'async-bytecomp nil t)
  72. (memq 'magit (bound-and-true-p async-bytecomp-allowed-packages))
  73. (fboundp 'async-bytecomp-package-mode)
  74. (async-bytecomp-package-mode 1))
  75. (eval-when-compile
  76. (progn (require 'dired nil t)
  77. (require 'eshell nil t)
  78. (require 'term nil t)
  79. (require 'warnings nil t)))
  80. (declare-function dired-get-filename 'dired)
  81. (declare-function term-emulate-terminal 'term)
  82. (defvar eshell-preoutput-filter-functions)
  83. ;;; Options
  84. (defgroup with-editor nil
  85. "Use the Emacsclient as $EDITOR."
  86. :group 'external
  87. :group 'server)
  88. (defun with-editor-locate-emacsclient ()
  89. "Search for a suitable Emacsclient executable."
  90. (or (with-editor-locate-emacsclient-1
  91. (with-editor-emacsclient-path)
  92. (length (split-string emacs-version "\\.")))
  93. (prog1 nil (display-warning 'with-editor "\
  94. Cannot determine a suitable Emacsclient
  95. Determining an Emacsclient executable suitable for the
  96. current Emacs instance failed. For more information
  97. please see https://github.com/magit/magit/wiki/Emacsclient."))))
  98. (defun with-editor-locate-emacsclient-1 (path depth)
  99. (let* ((version-lst (cl-subseq (split-string emacs-version "\\.") 0 depth))
  100. (version-reg (concat "^" (mapconcat #'identity version-lst "\\."))))
  101. (or (locate-file-internal
  102. (if (equal (downcase invocation-name) "remacs")
  103. "remacsclient"
  104. "emacsclient")
  105. path
  106. (cl-mapcan
  107. (lambda (v) (cl-mapcar (lambda (e) (concat v e)) exec-suffixes))
  108. (nconc (and (boundp 'debian-emacs-flavor)
  109. (list (format ".%s" debian-emacs-flavor)))
  110. (cl-mapcon (lambda (v)
  111. (setq v (mapconcat #'identity (reverse v) "."))
  112. (list v (concat "-" v) (concat ".emacs" v)))
  113. (reverse version-lst))
  114. (list "" "-snapshot" ".emacs-snapshot")))
  115. (lambda (exec)
  116. (ignore-errors
  117. (string-match-p version-reg
  118. (with-editor-emacsclient-version exec)))))
  119. (and (> depth 1)
  120. (with-editor-locate-emacsclient-1 path (1- depth))))))
  121. (defun with-editor-emacsclient-version (exec)
  122. (let ((default-directory (file-name-directory exec)))
  123. (ignore-errors
  124. (cadr (split-string (car (process-lines exec "--version")))))))
  125. (defun with-editor-emacsclient-path ()
  126. (let ((path exec-path))
  127. (when invocation-directory
  128. (push (directory-file-name invocation-directory) path)
  129. (let* ((linkname (expand-file-name invocation-name invocation-directory))
  130. (truename (file-chase-links linkname)))
  131. (unless (equal truename linkname)
  132. (push (directory-file-name (file-name-directory truename)) path)))
  133. (when (eq system-type 'darwin)
  134. (let ((dir (expand-file-name "bin" invocation-directory)))
  135. (when (file-directory-p dir)
  136. (push dir path)))
  137. (when (string-match-p "Cellar" invocation-directory)
  138. (let ((dir (expand-file-name "../../../bin" invocation-directory)))
  139. (when (file-directory-p dir)
  140. (push dir path))))))
  141. (cl-remove-duplicates path :test 'equal)))
  142. (defcustom with-editor-emacsclient-executable (with-editor-locate-emacsclient)
  143. "The Emacsclient executable used by the `with-editor' macro."
  144. :group 'with-editor
  145. :type '(choice (string :tag "Executable")
  146. (const :tag "Don't use Emacsclient" nil)))
  147. (defcustom with-editor-sleeping-editor "\
  148. sh -c '\
  149. echo \"WITH-EDITOR: $$ OPEN $0 IN $(pwd)\"; \
  150. sleep 604800 & sleep=$!; \
  151. trap \"kill $sleep; exit 0\" USR1; \
  152. trap \"kill $sleep; exit 1\" USR2; \
  153. wait $sleep'"
  154. "The sleeping editor, used when the Emacsclient cannot be used.
  155. This fallback is used for asynchronous processes started inside
  156. the macro `with-editor', when the process runs on a remote machine
  157. or for local processes when `with-editor-emacsclient-executable'
  158. is nil (i.e. when no suitable Emacsclient was found, or the user
  159. decided not to use it).
  160. Where the latter uses a socket to communicate with Emacs' server,
  161. this substitute prints edit requests to its standard output on
  162. which a process filter listens for such requests. As such it is
  163. not a complete substitute for a proper Emacsclient, it can only
  164. be used as $EDITOR of child process of the current Emacs instance.
  165. Some shells do not execute traps immediately when waiting for a
  166. child process, but by default we do use such a blocking child
  167. process.
  168. If you use such a shell (e.g. `csh' on FreeBSD, but not Debian),
  169. then you have to edit this option. You can either replace \"sh\"
  170. with \"bash\" (and install that), or you can use the older, less
  171. performant implementation:
  172. \"sh -c '\\
  173. echo \\\"WITH-EDITOR: $$ OPEN $0 IN $(pwd)\\\"; \\
  174. trap \\\"exit 0\\\" USR1; \\
  175. trap \\\"exit 1\" USR2; \\
  176. while true; do sleep 1; done'\"
  177. Note that the unit seperator character () right after the file
  178. name ($0) is required.
  179. Also note that using this alternative implementation leads to a
  180. delay of up to a second. The delay can be shortened by replacing
  181. \"sleep 1\" with \"sleep 0.01\", or if your implementation does
  182. not support floats, then by using \"nanosleep\" instead."
  183. :package-version '(with-editor . "2.8.0")
  184. :group 'with-editor
  185. :type 'string)
  186. (defcustom with-editor-finish-query-functions nil
  187. "List of functions called to query before finishing session.
  188. The buffer in question is current while the functions are called.
  189. If any of them returns nil, then the session is not finished and
  190. the buffer is not killed. The user should then fix the issue and
  191. try again. The functions are called with one argument. If it is
  192. non-nil then that indicates that the user used a prefix argument
  193. to force finishing the session despite issues. Functions should
  194. usually honor that and return non-nil."
  195. :group 'with-editor
  196. :type 'hook)
  197. (put 'with-editor-finish-query-functions 'permanent-local t)
  198. (defcustom with-editor-cancel-query-functions nil
  199. "List of functions called to query before canceling session.
  200. The buffer in question is current while the functions are called.
  201. If any of them returns nil, then the session is not canceled and
  202. the buffer is not killed. The user should then fix the issue and
  203. try again. The functions are called with one argument. If it is
  204. non-nil then that indicates that the user used a prefix argument
  205. to force canceling the session despite issues. Functions should
  206. usually honor that and return non-nil."
  207. :group 'with-editor
  208. :type 'hook)
  209. (put 'with-editor-cancel-query-functions 'permanent-local t)
  210. (defcustom with-editor-mode-lighter " WE"
  211. "The mode-line lighter of the With-Editor mode."
  212. :group 'with-editor
  213. :type '(choice (const :tag "No lighter" "") string))
  214. (defvar with-editor-server-window-alist nil
  215. "Alist of filename patterns vs corresponding `server-window'.
  216. Each element looks like (REGEXP . FUNCTION). Files matching
  217. REGEXP are selected using FUNCTION instead of the default in
  218. `server-window'.
  219. Note that when a package adds an entry here then it probably
  220. has a reason to disrespect `server-window' and it likely is
  221. not a good idea to change such entries.")
  222. (defvar with-editor-file-name-history-exclude nil
  223. "List of regexps for filenames `server-visit' should not remember.
  224. When a filename matches any of the regexps, then `server-visit'
  225. does not add it to the variable `file-name-history', which is
  226. used when reading a filename in the minibuffer.")
  227. (defcustom with-editor-shell-command-use-emacsclient t
  228. "Whether to use the emacsclient when running shell commands.
  229. This affects `with-editor-shell-command-async' and, if the input
  230. ends with \"&\" `with-editor-shell-command' .
  231. If `shell-command-with-editor-mode' is enabled, then it also
  232. affects `shell-command-async' and, if the input ends with \"&\"
  233. `shell-command'.
  234. This is a temporary kludge that lets you choose between two
  235. possible defects, the ones described in the issues #23 and #40.
  236. When t, then use the emacsclient. This has the disadvantage that
  237. `with-editor-mode' won't be enabled because we don't know whether
  238. this package was involved at all in the call to the emacsclient,
  239. and when it is not, then we really should. The problem is that
  240. the emacsclient doesn't pass a long any environment variables to
  241. the server. This will hopefully be fixed in Emacs eventually.
  242. When nil, then use the sleeping editor. Because in this case we
  243. know that this package is involved, we can enable the mode. But
  244. this makes it necessary that you invoke $EDITOR in shell scripts
  245. like so:
  246. eval \"$EDITOR\" file
  247. And some tools that do not handle $EDITOR properly also break."
  248. :package-version '(with-editor . "2.7.1")
  249. :group 'with-editor
  250. :type 'boolean)
  251. ;;; Mode Commands
  252. (defvar with-editor-pre-finish-hook nil)
  253. (defvar with-editor-pre-cancel-hook nil)
  254. (defvar with-editor-post-finish-hook nil)
  255. (defvar with-editor-post-finish-hook-1 nil)
  256. (defvar with-editor-post-cancel-hook nil)
  257. (defvar with-editor-post-cancel-hook-1 nil)
  258. (defvar with-editor-cancel-alist nil)
  259. (put 'with-editor-pre-finish-hook 'permanent-local t)
  260. (put 'with-editor-pre-cancel-hook 'permanent-local t)
  261. (put 'with-editor-post-finish-hook 'permanent-local t)
  262. (put 'with-editor-post-cancel-hook 'permanent-local t)
  263. (defvar with-editor-show-usage t)
  264. (defvar with-editor-cancel-message nil)
  265. (defvar with-editor-previous-winconf nil)
  266. (make-variable-buffer-local 'with-editor-show-usage)
  267. (make-variable-buffer-local 'with-editor-cancel-message)
  268. (make-variable-buffer-local 'with-editor-previous-winconf)
  269. (put 'with-editor-cancel-message 'permanent-local t)
  270. (put 'with-editor-previous-winconf 'permanent-local t)
  271. (defvar-local with-editor--pid nil "For internal use.")
  272. (put 'with-editor--pid 'permanent-local t)
  273. (defun with-editor-finish (force)
  274. "Finish the current edit session."
  275. (interactive "P")
  276. (when (run-hook-with-args-until-failure
  277. 'with-editor-finish-query-functions force)
  278. (let ((post-finish-hook with-editor-post-finish-hook)
  279. (post-commit-hook (bound-and-true-p git-commit-post-finish-hook))
  280. (dir default-directory))
  281. (run-hooks 'with-editor-pre-finish-hook)
  282. (with-editor-return nil)
  283. (accept-process-output nil 0.1)
  284. (with-temp-buffer
  285. (setq default-directory dir)
  286. (setq-local with-editor-post-finish-hook post-finish-hook)
  287. (when (bound-and-true-p git-commit-post-finish-hook)
  288. (setq-local git-commit-post-finish-hook post-commit-hook))
  289. (run-hooks 'with-editor-post-finish-hook)))))
  290. (defun with-editor-cancel (force)
  291. "Cancel the current edit session."
  292. (interactive "P")
  293. (when (run-hook-with-args-until-failure
  294. 'with-editor-cancel-query-functions force)
  295. (let ((message with-editor-cancel-message))
  296. (when (functionp message)
  297. (setq message (funcall message)))
  298. (let ((post-cancel-hook with-editor-post-cancel-hook)
  299. (with-editor-cancel-alist nil)
  300. (dir default-directory))
  301. (run-hooks 'with-editor-pre-cancel-hook)
  302. (with-editor-return t)
  303. (accept-process-output nil 0.1)
  304. (with-temp-buffer
  305. (setq default-directory dir)
  306. (setq-local with-editor-post-cancel-hook post-cancel-hook)
  307. (run-hooks 'with-editor-post-cancel-hook)))
  308. (message (or message "Canceled by user")))))
  309. (defun with-editor-return (cancel)
  310. (let ((winconf with-editor-previous-winconf)
  311. (clients server-buffer-clients)
  312. (dir default-directory)
  313. (pid with-editor--pid))
  314. (remove-hook 'kill-buffer-query-functions
  315. 'with-editor-kill-buffer-noop t)
  316. (cond (cancel
  317. (save-buffer)
  318. (if clients
  319. (dolist (client clients)
  320. (ignore-errors
  321. (server-send-string client "-error Canceled by user"))
  322. (delete-process client))
  323. ;; Fallback for when emacs was used as $EDITOR
  324. ;; instead of emacsclient or the sleeping editor.
  325. ;; See https://github.com/magit/magit/issues/2258.
  326. (ignore-errors (delete-file buffer-file-name))
  327. (kill-buffer)))
  328. (t
  329. (save-buffer)
  330. (if clients
  331. ;; Don't use `server-edit' because we do not want to
  332. ;; show another buffer belonging to another client.
  333. ;; See https://github.com/magit/magit/issues/2197.
  334. (server-done)
  335. (kill-buffer))))
  336. (when pid
  337. (let ((default-directory dir))
  338. (process-file "kill" nil nil nil
  339. "-s" (if cancel "USR2" "USR1") pid)))
  340. (when (and winconf (eq (window-configuration-frame winconf)
  341. (selected-frame)))
  342. (set-window-configuration winconf))))
  343. ;;; Mode
  344. (defvar with-editor-mode-map
  345. (let ((map (make-sparse-keymap)))
  346. (define-key map "\C-c\C-c" 'with-editor-finish)
  347. (define-key map [remap server-edit] 'with-editor-finish)
  348. (define-key map [remap evil-save-and-close] 'with-editor-finish)
  349. (define-key map [remap evil-save-modified-and-close] 'with-editor-finish)
  350. (define-key map "\C-c\C-k" 'with-editor-cancel)
  351. (define-key map [remap kill-buffer] 'with-editor-cancel)
  352. (define-key map [remap ido-kill-buffer] 'with-editor-cancel)
  353. (define-key map [remap iswitchb-kill-buffer] 'with-editor-cancel)
  354. (define-key map [remap evil-quit] 'with-editor-cancel)
  355. map))
  356. (define-minor-mode with-editor-mode
  357. "Edit a file as the $EDITOR of an external process."
  358. :lighter with-editor-mode-lighter
  359. ;; Protect the user from killing the buffer without using
  360. ;; either `with-editor-finish' or `with-editor-cancel',
  361. ;; and from removing the key bindings for these commands.
  362. (unless with-editor-mode
  363. (user-error "With-Editor mode cannot be turned off"))
  364. (add-hook 'kill-buffer-query-functions
  365. 'with-editor-kill-buffer-noop nil t)
  366. ;; `server-execute' displays a message which is not
  367. ;; correct when using this mode.
  368. (when with-editor-show-usage
  369. (with-editor-usage-message)))
  370. (put 'with-editor-mode 'permanent-local t)
  371. (defun with-editor-kill-buffer-noop ()
  372. (if (memq this-command '(save-buffers-kill-terminal
  373. save-buffers-kill-emacs))
  374. (let ((with-editor-cancel-query-functions nil))
  375. (with-editor-cancel nil)
  376. t)
  377. (user-error (substitute-command-keys "\
  378. Don't kill this buffer. Instead cancel using \\[with-editor-cancel]"))))
  379. (defvar-local with-editor-usage-message "\
  380. Type \\[with-editor-finish] to finish, \
  381. or \\[with-editor-cancel] to cancel")
  382. (defun with-editor-usage-message ()
  383. ;; Run after `server-execute', which is run using
  384. ;; a timer which starts immediately.
  385. (let ((buffer (current-buffer)))
  386. (run-with-timer
  387. 0.05 nil
  388. (lambda ()
  389. (with-current-buffer buffer
  390. (message (substitute-command-keys with-editor-usage-message)))))))
  391. ;;; Wrappers
  392. (defvar with-editor--envvar nil "For internal use.")
  393. (defmacro with-editor (&rest body)
  394. "Use the Emacsclient as $EDITOR while evaluating BODY.
  395. Modify the `process-environment' for processes started in BODY,
  396. instructing them to use the Emacsclient as $EDITOR. If optional
  397. ENVVAR is a literal string then bind that environment variable
  398. instead.
  399. \n(fn [ENVVAR] BODY...)"
  400. (declare (indent defun) (debug (body)))
  401. `(let ((with-editor--envvar ,(if (stringp (car body))
  402. (pop body)
  403. '(or with-editor--envvar "EDITOR")))
  404. (process-environment process-environment))
  405. (with-editor--setup)
  406. ,@body))
  407. (defmacro with-editor* (envvar &rest body)
  408. "Use the Emacsclient as the editor while evaluating BODY.
  409. Modify the `process-environment' for processes started in BODY,
  410. instructing them to use the Emacsclient as editor. ENVVAR is the
  411. environment variable that is exported to do so, it is evaluated
  412. at run-time.
  413. \n(fn [ENVVAR] BODY...)"
  414. (declare (indent defun) (debug (sexp body)))
  415. `(let ((with-editor--envvar ,envvar)
  416. (process-environment process-environment))
  417. (with-editor--setup)
  418. ,@body))
  419. (defun with-editor--setup ()
  420. (if (or (not with-editor-emacsclient-executable)
  421. (file-remote-p default-directory))
  422. (push (concat with-editor--envvar "=" with-editor-sleeping-editor)
  423. process-environment)
  424. ;; Make sure server-use-tcp's value is valid.
  425. (unless (featurep 'make-network-process '(:family local))
  426. (setq server-use-tcp t))
  427. ;; Make sure the server is running.
  428. (unless (process-live-p server-process)
  429. (when (server-running-p server-name)
  430. (setq server-name (format "server%s" (emacs-pid)))
  431. (when (server-running-p server-name)
  432. (server-force-delete server-name)))
  433. (server-start))
  434. ;; Tell $EDITOR to use the Emacsclient.
  435. (push (concat with-editor--envvar "="
  436. (shell-quote-argument with-editor-emacsclient-executable)
  437. ;; Tell the process where the server file is.
  438. (and (not server-use-tcp)
  439. (concat " --socket-name="
  440. (shell-quote-argument
  441. (expand-file-name server-name
  442. server-socket-dir)))))
  443. process-environment)
  444. (when server-use-tcp
  445. (push (concat "EMACS_SERVER_FILE="
  446. (expand-file-name server-name server-auth-dir))
  447. process-environment))
  448. ;; As last resort fallback to the sleeping editor.
  449. (push (concat "ALTERNATE_EDITOR=" with-editor-sleeping-editor)
  450. process-environment)))
  451. (defun with-editor-server-window ()
  452. (or (and buffer-file-name
  453. (cdr (cl-find-if (lambda (cons)
  454. (string-match-p (car cons) buffer-file-name))
  455. with-editor-server-window-alist)))
  456. server-window))
  457. (defun server-switch-buffer--with-editor-server-window-alist
  458. (fn &optional next-buffer killed-one filepos)
  459. "Honor `with-editor-server-window-alist' (which see)."
  460. (let ((server-window (with-current-buffer
  461. (or next-buffer (current-buffer))
  462. (when with-editor-mode
  463. (setq with-editor-previous-winconf
  464. (current-window-configuration)))
  465. (with-editor-server-window))))
  466. (funcall fn next-buffer killed-one filepos)))
  467. (advice-add 'server-switch-buffer :around
  468. 'server-switch-buffer--with-editor-server-window-alist)
  469. (defun start-file-process--with-editor-process-filter
  470. (fn name buffer program &rest program-args)
  471. "When called inside a `with-editor' form and the Emacsclient
  472. cannot be used, then give the process the filter function
  473. `with-editor-process-filter'. To avoid overriding the filter
  474. being added here you should use `with-editor-set-process-filter'
  475. instead of `set-process-filter' inside `with-editor' forms.
  476. When the `default-directory' is located on a remote machine,
  477. then also manipulate PROGRAM and PROGRAM-ARGS in order to set
  478. the appropriate editor environment variable."
  479. (if (not with-editor--envvar)
  480. (apply fn name buffer program program-args)
  481. (when (file-remote-p default-directory)
  482. (unless (equal program "env")
  483. (push program program-args)
  484. (setq program "env"))
  485. (push (concat with-editor--envvar "=" with-editor-sleeping-editor)
  486. program-args))
  487. (let ((process (apply fn name buffer program program-args)))
  488. (set-process-filter process 'with-editor-process-filter)
  489. (process-put process 'default-dir default-directory)
  490. process)))
  491. (advice-add 'start-file-process :around
  492. 'start-file-process--with-editor-process-filter)
  493. (defun with-editor-set-process-filter (process filter)
  494. "Like `set-process-filter' but keep `with-editor-process-filter'.
  495. Give PROCESS the new FILTER but keep `with-editor-process-filter'
  496. if that was added earlier by the adviced `start-file-process'.
  497. Do so by wrapping the two filter functions using a lambda, which
  498. becomes the actual filter. It calls `with-editor-process-filter'
  499. first, passing t as NO-STANDARD-FILTER. Then it calls FILTER,
  500. which may or may not insert the text into the PROCESS' buffer."
  501. (set-process-filter
  502. process
  503. (if (eq (process-filter process) 'with-editor-process-filter)
  504. `(lambda (proc str)
  505. (,filter proc str)
  506. (with-editor-process-filter proc str t))
  507. filter)))
  508. (defvar with-editor-filter-visit-hook nil)
  509. (defun with-editor-output-filter (string)
  510. (save-match-data
  511. (if (string-match "^WITH-EDITOR: \
  512. \\([0-9]+\\) OPEN \\([^]+?\\)\
  513. \\(?: IN \\([^\r]+?\\)\\)?\r?$" string)
  514. (let ((pid (match-string 1 string))
  515. (file (match-string 2 string))
  516. (dir (match-string 3 string)))
  517. (unless (file-name-absolute-p file)
  518. (setq file (expand-file-name file dir)))
  519. (when default-directory
  520. (setq file (concat (file-remote-p default-directory) file)))
  521. (with-current-buffer (find-file-noselect file)
  522. (with-editor-mode 1)
  523. (setq with-editor--pid pid)
  524. (run-hooks 'with-editor-filter-visit-hook)
  525. (funcall (or (with-editor-server-window) 'switch-to-buffer)
  526. (current-buffer))
  527. (kill-local-variable 'server-window))
  528. nil)
  529. string)))
  530. (defun with-editor-process-filter
  531. (process string &optional no-default-filter)
  532. "Listen for edit requests by child processes."
  533. (let ((default-directory (process-get process 'default-dir)))
  534. (with-editor-output-filter string))
  535. (unless no-default-filter
  536. (internal-default-process-filter process string)))
  537. (advice-add 'server-visit-files :after
  538. 'server-visit-files--with-editor-file-name-history-exclude)
  539. (defun server-visit-files--with-editor-file-name-history-exclude
  540. (files _proc &optional _nowait)
  541. (pcase-dolist (`(,file . ,_) files)
  542. (when (cl-find-if (lambda (regexp)
  543. (string-match-p regexp file))
  544. with-editor-file-name-history-exclude)
  545. (setq file-name-history (delete file file-name-history)))))
  546. ;;; Augmentations
  547. ;;;###autoload
  548. (cl-defun with-editor-export-editor (&optional (envvar "EDITOR"))
  549. "Teach subsequent commands to use current Emacs instance as editor.
  550. Set and export the environment variable ENVVAR, by default
  551. \"EDITOR\". The value is automatically generated to teach
  552. commands to use the current Emacs instance as \"the editor\".
  553. This works in `shell-mode', `term-mode' and `eshell-mode'."
  554. (interactive (list (with-editor-read-envvar)))
  555. (cond
  556. ((derived-mode-p 'comint-mode 'term-mode)
  557. (let ((process (get-buffer-process (current-buffer))))
  558. (goto-char (process-mark process))
  559. (process-send-string
  560. process (format " export %s=%s\n" envvar
  561. (shell-quote-argument with-editor-sleeping-editor)))
  562. (while (accept-process-output process 0.1))
  563. (if (derived-mode-p 'term-mode)
  564. (with-editor-set-process-filter process 'with-editor-emulate-terminal)
  565. (add-hook 'comint-output-filter-functions 'with-editor-output-filter
  566. nil t))))
  567. ((derived-mode-p 'eshell-mode)
  568. (add-to-list 'eshell-preoutput-filter-functions
  569. 'with-editor-output-filter)
  570. (setenv envvar with-editor-sleeping-editor))
  571. (t
  572. (error "Cannot export environment variables in this buffer")))
  573. (message "Successfully exported %s" envvar))
  574. ;;;###autoload
  575. (defun with-editor-export-git-editor ()
  576. "Like `with-editor-export-editor' but always set `$GIT_EDITOR'."
  577. (interactive)
  578. (with-editor-export-editor "GIT_EDITOR"))
  579. ;;;###autoload
  580. (defun with-editor-export-hg-editor ()
  581. "Like `with-editor-export-editor' but always set `$HG_EDITOR'."
  582. (interactive)
  583. (with-editor-export-editor "HG_EDITOR"))
  584. (defun with-editor-emulate-terminal (process string)
  585. "Like `term-emulate-terminal' but also handle edit requests."
  586. (when (with-editor-output-filter string)
  587. (term-emulate-terminal process string)))
  588. (defvar with-editor-envvars '("EDITOR" "GIT_EDITOR" "HG_EDITOR"))
  589. (cl-defun with-editor-read-envvar
  590. (&optional (prompt "Set environment variable")
  591. (default "EDITOR"))
  592. (let ((reply (completing-read (if default
  593. (format "%s (%s): " prompt default)
  594. (concat prompt ": "))
  595. with-editor-envvars nil nil nil nil default)))
  596. (if (string= reply "") (user-error "Nothing selected") reply)))
  597. ;;;###autoload
  598. (define-minor-mode shell-command-with-editor-mode
  599. "Teach `shell-command' to use current Emacs instance as editor.
  600. Teach `shell-command', and all commands that ultimately call that
  601. command, to use the current Emacs instance as editor by executing
  602. \"EDITOR=CLIENT COMMAND&\" instead of just \"COMMAND&\".
  603. CLIENT is automatically generated; EDITOR=CLIENT instructs
  604. COMMAND to use to the current Emacs instance as \"the editor\",
  605. assuming no other variable overrides the effect of \"$EDITOR\".
  606. CLIENT may be the path to an appropriate emacsclient executable
  607. with arguments, or a script which also works over Tramp.
  608. Alternatively you can use the `with-editor-async-shell-command',
  609. which also allows the use of another variable instead of
  610. \"EDITOR\"."
  611. :global t)
  612. ;;;###autoload
  613. (defun with-editor-async-shell-command
  614. (command &optional output-buffer error-buffer envvar)
  615. "Like `async-shell-command' but with `$EDITOR' set.
  616. Execute string \"ENVVAR=CLIENT COMMAND\" in an inferior shell;
  617. display output, if any. With a prefix argument prompt for an
  618. environment variable, otherwise the default \"EDITOR\" variable
  619. is used. With a negative prefix argument additionally insert
  620. the COMMAND's output at point.
  621. CLIENT is automatically generated; ENVVAR=CLIENT instructs
  622. COMMAND to use to the current Emacs instance as \"the editor\",
  623. assuming it respects ENVVAR as an \"EDITOR\"-like variable.
  624. CLIENT may be the path to an appropriate emacsclient executable
  625. with arguments, or a script which also works over Tramp.
  626. Also see `async-shell-command' and `shell-command'."
  627. (interactive (with-editor-shell-command-read-args "Async shell command: " t))
  628. (let ((with-editor--envvar envvar))
  629. (with-editor
  630. (async-shell-command command output-buffer error-buffer))))
  631. ;;;###autoload
  632. (defun with-editor-shell-command
  633. (command &optional output-buffer error-buffer envvar)
  634. "Like `shell-command' or `with-editor-async-shell-command'.
  635. If COMMAND ends with \"&\" behave like the latter,
  636. else like the former."
  637. (interactive (with-editor-shell-command-read-args "Shell command: "))
  638. (if (string-match "&[ \t]*\\'" command)
  639. (with-editor-async-shell-command
  640. command output-buffer error-buffer envvar)
  641. (shell-command command output-buffer error-buffer)))
  642. (defun with-editor-shell-command-read-args (prompt &optional async)
  643. (let ((command (read-shell-command
  644. prompt nil nil
  645. (let ((filename (or buffer-file-name
  646. (and (eq major-mode 'dired-mode)
  647. (dired-get-filename nil t)))))
  648. (and filename (file-relative-name filename))))))
  649. (list command
  650. (if (or async (setq async (string-match-p "&[ \t]*\\'" command)))
  651. (< (prefix-numeric-value current-prefix-arg) 0)
  652. current-prefix-arg)
  653. shell-command-default-error-buffer
  654. (and async current-prefix-arg (with-editor-read-envvar)))))
  655. (defun shell-command--shell-command-with-editor-mode
  656. (fn command &optional output-buffer error-buffer)
  657. ;; `shell-mode' and its hook are intended for buffers in which an
  658. ;; interactive shell is running, but `shell-command' also turns on
  659. ;; that mode, even though it only runs the shell to run a single
  660. ;; command. The `with-editor-export-editor' hook function is only
  661. ;; intended to be used in buffers in which an interactive shell is
  662. ;; running, so it has to be remove here.
  663. (let ((shell-mode-hook (remove 'with-editor-export-editor shell-mode-hook)))
  664. (cond ((or (not (or with-editor--envvar shell-command-with-editor-mode))
  665. (not (string-match-p "&\\'" command)))
  666. (funcall fn command output-buffer error-buffer))
  667. ((and with-editor-shell-command-use-emacsclient
  668. with-editor-emacsclient-executable
  669. (not (file-remote-p default-directory)))
  670. (with-editor (funcall fn command output-buffer error-buffer)))
  671. (t
  672. (apply fn (format "%s=%s %s"
  673. (or with-editor--envvar "EDITOR")
  674. (shell-quote-argument with-editor-sleeping-editor)
  675. command)
  676. output-buffer error-buffer)
  677. (ignore-errors
  678. (let ((process (get-buffer-process
  679. (or output-buffer
  680. (get-buffer "*Async Shell Command*")))))
  681. (set-process-filter
  682. process (lambda (proc str)
  683. (comint-output-filter proc str)
  684. (with-editor-process-filter proc str t)))
  685. process))))))
  686. (advice-add 'shell-command :around
  687. 'shell-command--shell-command-with-editor-mode)
  688. ;;; _
  689. (defun with-editor-debug ()
  690. "Debug configuration issues.
  691. See info node `(with-editor)Debugging' for instructions."
  692. (interactive)
  693. (with-current-buffer (get-buffer-create "*with-editor-debug*")
  694. (pop-to-buffer (current-buffer))
  695. (erase-buffer)
  696. (ignore-errors (with-editor))
  697. (insert
  698. (format "with-editor: %s\n" (locate-library "with-editor.el"))
  699. (format "emacs: %s (%s)\n"
  700. (expand-file-name invocation-name invocation-directory)
  701. emacs-version)
  702. "system:\n"
  703. (format " system-type: %s\n" system-type)
  704. (format " system-configuration: %s\n" system-configuration)
  705. (format " system-configuration-options: %s\n" system-configuration-options)
  706. "server:\n"
  707. (format " server-running-p: %s\n" (server-running-p))
  708. (format " server-process: %S\n" server-process)
  709. (format " server-use-tcp: %s\n" server-use-tcp)
  710. (format " server-name: %s\n" server-name)
  711. (format " server-socket-dir: %s\n" server-socket-dir))
  712. (if (and server-socket-dir (file-accessible-directory-p server-socket-dir))
  713. (dolist (file (directory-files server-socket-dir nil "^[^.]"))
  714. (insert (format " %s\n" file)))
  715. (insert (format " %s: not an accessible directory\n"
  716. (if server-use-tcp "WARNING" "ERROR"))))
  717. (insert (format " server-auth-dir: %s\n" server-auth-dir))
  718. (if (file-accessible-directory-p server-auth-dir)
  719. (dolist (file (directory-files server-auth-dir nil "^[^.]"))
  720. (insert (format " %s\n" file)))
  721. (insert (format " %s: not an accessible directory\n"
  722. (if server-use-tcp "ERROR" "WARNING"))))
  723. (let ((val with-editor-emacsclient-executable)
  724. (def (default-value 'with-editor-emacsclient-executable))
  725. (fun (let ((warning-minimum-level :error)
  726. (warning-minimum-log-level :error))
  727. (with-editor-locate-emacsclient))))
  728. (insert "with-editor-emacsclient-executable:\n"
  729. (format " value: %s (%s)\n" val
  730. (and val (with-editor-emacsclient-version val)))
  731. (format " default: %s (%s)\n" def
  732. (and def (with-editor-emacsclient-version def)))
  733. (format " funcall: %s (%s)\n" fun
  734. (and fun (with-editor-emacsclient-version fun)))))
  735. (insert "path:\n"
  736. (format " $PATH: %S\n" (getenv "PATH"))
  737. (format " exec-path: %s\n" exec-path))
  738. (insert (format " with-editor-emacsclient-path:\n"))
  739. (dolist (dir (with-editor-emacsclient-path))
  740. (insert (format " %s (%s)\n" dir (car (file-attributes dir))))
  741. (when (file-directory-p dir)
  742. ;; Don't match emacsclientw.exe, it makes popup windows.
  743. (dolist (exec (directory-files dir t "emacsclient\\(?:[^w]\\|\\'\\)"))
  744. (insert (format " %s (%s)\n" exec
  745. (with-editor-emacsclient-version exec))))))))
  746. (defconst with-editor-font-lock-keywords
  747. '(("(\\(with-\\(?:git-\\)?editor\\)\\_>" (1 'font-lock-keyword-face))))
  748. (font-lock-add-keywords 'emacs-lisp-mode with-editor-font-lock-keywords)
  749. (provide 'with-editor)
  750. ;; Local Variables:
  751. ;; indent-tabs-mode: nil
  752. ;; End:
  753. ;;; with-editor.el ends here