shell.el 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. ;;; shell.el --- specialized comint.el for running the shell -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1988, 1993-1997, 2000-2017 Free Software Foundation,
  3. ;; Inc.
  4. ;; Author: Olin Shivers <shivers@cs.cmu.edu>
  5. ;; Simon Marshall <simon@gnu.org>
  6. ;; Maintainer: emacs-devel@gnu.org
  7. ;; Keywords: processes
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; This file defines a shell-in-a-buffer package (shell mode) built on
  21. ;; top of comint mode. This is actually cmushell with things renamed
  22. ;; to replace its counterpart in Emacs 18. cmushell is more
  23. ;; featureful, robust, and uniform than the Emacs 18 version.
  24. ;; Since this mode is built on top of the general command-interpreter-in-
  25. ;; a-buffer mode (comint mode), it shares a common base functionality,
  26. ;; and a common set of bindings, with all modes derived from comint mode.
  27. ;; This makes these modes easier to use.
  28. ;; For documentation on the functionality provided by comint mode, and
  29. ;; the hooks available for customizing it, see the file comint.el.
  30. ;; For further information on shell mode, see the comments below.
  31. ;; Needs fixin:
  32. ;; When sending text from a source file to a subprocess, the process-mark can
  33. ;; move off the window, so you can lose sight of the process interactions.
  34. ;; Maybe I should ensure the process mark is in the window when I send
  35. ;; text to the process? Switch selectable?
  36. ;; YOUR .EMACS FILE
  37. ;;=============================================================================
  38. ;; Some suggestions for your init file.
  39. ;;
  40. ;; ;; Define M-# to run some strange command:
  41. ;; (eval-after-load "shell"
  42. ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
  43. ;; Brief Command Documentation:
  44. ;;============================================================================
  45. ;; Comint Mode Commands: (common to shell and all comint-derived modes)
  46. ;;
  47. ;; m-p comint-previous-input Cycle backwards in input history
  48. ;; m-n comint-next-input Cycle forwards
  49. ;; m-r comint-previous-matching-input Previous input matching a regexp
  50. ;; m-s comint-next-matching-input Next input that matches
  51. ;; m-c-l comint-show-output Show last batch of process output
  52. ;; return comint-send-input
  53. ;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
  54. ;; c-c c-a comint-bol Beginning of line; skip prompt
  55. ;; c-c c-u comint-kill-input ^u
  56. ;; c-c c-w backward-kill-word ^w
  57. ;; c-c c-c comint-interrupt-subjob ^c
  58. ;; c-c c-z comint-stop-subjob ^z
  59. ;; c-c c-\ comint-quit-subjob ^\
  60. ;; c-c c-o comint-delete-output Delete last batch of process output
  61. ;; c-c c-r comint-show-output Show last batch of process output
  62. ;; c-c c-l comint-dynamic-list-input-ring List input history
  63. ;; send-invisible Read line w/o echo & send to proc
  64. ;; comint-continue-subjob Useful if you accidentally suspend
  65. ;; top-level job
  66. ;; comint-mode-hook is the comint mode hook.
  67. ;; Shell Mode Commands:
  68. ;; shell Fires up the shell process
  69. ;; tab completion-at-point Complete filename/command/history
  70. ;; m-? comint-dynamic-list-filename-completions
  71. ;; List completions in help buffer
  72. ;; c-c c-f shell-forward-command Forward a shell command
  73. ;; c-c c-b shell-backward-command Backward a shell command
  74. ;; dirs Resync the buffer's dir stack
  75. ;; shell-dirtrack-mode Turn dir tracking on/off
  76. ;; comint-strip-ctrl-m Remove trailing ^Ms from output
  77. ;;
  78. ;; The shell mode hook is shell-mode-hook
  79. ;; comint-prompt-regexp is initialized to shell-prompt-pattern, for backwards
  80. ;; compatibility.
  81. ;; Read the rest of this file for more information.
  82. ;;; Code:
  83. (require 'comint)
  84. (require 'pcomplete)
  85. ;;; Customization and Buffer Variables
  86. (defgroup shell nil
  87. "Running shell from within Emacs buffers."
  88. :group 'processes
  89. :group 'unix)
  90. (defgroup shell-directories nil
  91. "Directory support in shell mode."
  92. :group 'shell)
  93. ;; Unused.
  94. ;;; (defgroup shell-faces nil
  95. ;;; "Faces in shell buffers."
  96. ;;; :group 'shell)
  97. ;;;###autoload
  98. (defcustom shell-dumb-shell-regexp (purecopy "cmd\\(proxy\\)?\\.exe")
  99. "Regexp to match shells that don't save their command history, and
  100. don't handle the backslash as a quote character. For shells that
  101. match this regexp, Emacs will write out the command history when the
  102. shell finishes, and won't remove backslashes when it unquotes shell
  103. arguments."
  104. :type 'regexp
  105. :group 'shell)
  106. (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
  107. "Regexp to match prompts in the inferior shell.
  108. Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
  109. This variable is used to initialize `comint-prompt-regexp' in the
  110. shell buffer.
  111. If `comint-use-prompt-regexp' is nil, then this variable is only used
  112. to determine paragraph boundaries. See Info node `Shell Prompts' for
  113. how Shell mode treats paragraphs.
  114. The pattern should probably not match more than one line. If it does,
  115. Shell mode may become confused trying to distinguish prompt from input
  116. on lines which don't start with a prompt."
  117. :type 'regexp
  118. :group 'shell)
  119. (defcustom shell-completion-fignore nil
  120. "List of suffixes to be disregarded during file/command completion.
  121. This variable is used to initialize `comint-completion-fignore' in the shell
  122. buffer. The default is nil, for compatibility with most shells.
  123. Some people like (\"~\" \"#\" \"%\")."
  124. :type '(repeat (string :tag "Suffix"))
  125. :group 'shell)
  126. (defcustom shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
  127. "List of characters to recognize as separate arguments.
  128. This variable is used to initialize `comint-delimiter-argument-list' in the
  129. shell buffer. The value may depend on the operating system or shell."
  130. :type '(choice (const nil)
  131. (repeat :tag "List of characters" character))
  132. :group 'shell)
  133. (defcustom shell-file-name-chars
  134. (if (memq system-type '(ms-dos windows-nt cygwin))
  135. "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
  136. "[]~/A-Za-z0-9+@:_.$#%,={}-")
  137. "String of characters valid in a file name.
  138. This variable is used to initialize `comint-file-name-chars' in the
  139. shell buffer. The value may depend on the operating system or shell."
  140. :type 'string
  141. :group 'shell)
  142. (defcustom shell-file-name-quote-list
  143. (if (memq system-type '(ms-dos windows-nt))
  144. nil
  145. (append shell-delimiter-argument-list '(?\s ?$ ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
  146. "List of characters to quote when in a file name.
  147. This variable is used to initialize `comint-file-name-quote-list' in the
  148. shell buffer. The value may depend on the operating system or shell."
  149. :type '(repeat character)
  150. :group 'shell)
  151. (defcustom shell-dynamic-complete-functions
  152. '(comint-c-a-p-replace-by-expanded-history
  153. shell-environment-variable-completion
  154. shell-command-completion
  155. shell-c-a-p-replace-by-expanded-directory
  156. pcomplete-completions-at-point
  157. shell-filename-completion
  158. comint-filename-completion)
  159. "List of functions called to perform completion.
  160. This variable is used to initialize `comint-dynamic-complete-functions' in the
  161. shell buffer."
  162. :type '(repeat function)
  163. :group 'shell)
  164. (defcustom shell-command-regexp "[^;&|\n]+"
  165. "Regexp to match a single command within a pipeline.
  166. This is used for directory tracking and does not do a perfect job."
  167. :type 'regexp
  168. :group 'shell)
  169. (defcustom shell-command-separator-regexp "[;&|\n \t]*"
  170. "Regexp to match a single command within a pipeline.
  171. This is used for directory tracking and does not do a perfect job."
  172. :type 'regexp
  173. :group 'shell)
  174. (defcustom shell-completion-execonly t
  175. "If non-nil, use executable files only for completion candidates.
  176. This mirrors the optional behavior of tcsh.
  177. Detecting executability of files may slow command completion considerably."
  178. :type 'boolean
  179. :group 'shell)
  180. (defcustom shell-popd-regexp "popd"
  181. "Regexp to match subshell commands equivalent to popd."
  182. :type 'regexp
  183. :group 'shell-directories)
  184. (defcustom shell-pushd-regexp "pushd"
  185. "Regexp to match subshell commands equivalent to pushd."
  186. :type 'regexp
  187. :group 'shell-directories)
  188. (defcustom shell-pushd-tohome nil
  189. "If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
  190. This mirrors the optional behavior of tcsh."
  191. :type 'boolean
  192. :group 'shell-directories)
  193. (defcustom shell-pushd-dextract nil
  194. "If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
  195. This mirrors the optional behavior of tcsh."
  196. :type 'boolean
  197. :group 'shell-directories)
  198. (defcustom shell-pushd-dunique nil
  199. "If non-nil, make pushd only add unique directories to the stack.
  200. This mirrors the optional behavior of tcsh."
  201. :type 'boolean
  202. :group 'shell-directories)
  203. (defcustom shell-cd-regexp "cd"
  204. "Regexp to match subshell commands equivalent to cd."
  205. :type 'regexp
  206. :group 'shell-directories)
  207. (defcustom shell-chdrive-regexp
  208. (if (memq system-type '(ms-dos windows-nt))
  209. ; NetWare allows the five chars between upper and lower alphabetics.
  210. "[]a-zA-Z^_`\\[\\\\]:"
  211. nil)
  212. "If non-nil, is regexp used to track drive changes."
  213. :type '(choice regexp
  214. (const nil))
  215. :group 'shell-directories)
  216. (defcustom shell-dirtrack-verbose t
  217. "If non-nil, show the directory stack following directory change.
  218. This is effective only if directory tracking is enabled.
  219. The `dirtrack' package provides an alternative implementation of this feature -
  220. see the function `dirtrack-mode'."
  221. :type 'boolean
  222. :group 'shell-directories)
  223. (defcustom explicit-shell-file-name nil
  224. "If non-nil, is file name to use for explicitly requested inferior shell."
  225. :type '(choice (const :tag "None" nil) file)
  226. :group 'shell)
  227. ;; Note: There are no explicit references to the variable `explicit-csh-args'.
  228. ;; It is used implicitly by M-x shell when the shell is `csh'.
  229. (defcustom explicit-csh-args
  230. (if (eq system-type 'hpux)
  231. ;; -T persuades HP's csh not to think it is smarter
  232. ;; than us about what terminal modes to use.
  233. '("-i" "-T")
  234. '("-i"))
  235. "Args passed to inferior shell by \\[shell], if the shell is csh.
  236. Value is a list of strings, which may be nil."
  237. :type '(repeat (string :tag "Argument"))
  238. :group 'shell)
  239. ;; Note: There are no explicit references to the variable `explicit-bash-args'.
  240. ;; It is used implicitly by M-x shell when the interactive shell is `bash'.
  241. (defcustom explicit-bash-args
  242. ;; Tell bash not to use readline. It's safe to assume --noediting now,
  243. ;; as it was introduced in 1996 in Bash version 2.
  244. '("--noediting" "-i")
  245. "Args passed to inferior shell by \\[shell], if the shell is bash.
  246. Value is a list of strings, which may be nil."
  247. :type '(repeat (string :tag "Argument"))
  248. :group 'shell)
  249. (defcustom shell-input-autoexpand 'history
  250. "If non-nil, expand input command history references on completion.
  251. This mirrors the optional behavior of tcsh (its autoexpand and histlit).
  252. If the value is `input', then the expansion is seen on input.
  253. If the value is `history', then the expansion is only when inserting
  254. into the buffer's input ring. See also `comint-magic-space' and
  255. `comint-dynamic-complete-functions'.
  256. This variable supplies a default for `comint-input-autoexpand',
  257. for Shell mode only."
  258. :type '(choice (const :tag "off" nil)
  259. (const input)
  260. (const history)
  261. (const :tag "on" t))
  262. :group 'shell)
  263. (defvar shell-dirstack nil
  264. "List of directories saved by pushd in this buffer's shell.
  265. Thus, this does not include the shell's current directory.")
  266. (defvar shell-dirtrackp t
  267. "Non-nil in a shell buffer means directory tracking is enabled.")
  268. (defvar shell-last-dir nil
  269. "Keep track of last directory for ksh `cd -' command.")
  270. (defvar shell-dirstack-query nil
  271. "Command used by `shell-resync-dirs' to query the shell.")
  272. (defvar shell-mode-map
  273. (let ((map (nconc (make-sparse-keymap) comint-mode-map)))
  274. (define-key map "\C-c\C-f" 'shell-forward-command)
  275. (define-key map "\C-c\C-b" 'shell-backward-command)
  276. (define-key map "\t" 'completion-at-point)
  277. (define-key map (kbd "M-RET") 'shell-resync-dirs)
  278. (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
  279. (define-key map [menu-bar completion]
  280. (cons "Complete"
  281. (copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
  282. (define-key-after (lookup-key map [menu-bar completion])
  283. [complete-env-variable] '("Complete Env. Variable Name" .
  284. shell-dynamic-complete-environment-variable)
  285. 'complete-file)
  286. (define-key-after (lookup-key map [menu-bar completion])
  287. [expand-directory] '("Expand Directory Reference" .
  288. shell-replace-by-expanded-directory)
  289. 'complete-expand)
  290. map))
  291. (defcustom shell-mode-hook '()
  292. "Hook for customizing Shell mode."
  293. :type 'hook
  294. :group 'shell)
  295. (defvar shell-font-lock-keywords
  296. '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
  297. ("^[^ \t\n]+:.*" . font-lock-string-face)
  298. ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
  299. "Additional expressions to highlight in Shell mode.")
  300. ;;; Basic Procedures
  301. (defun shell--unquote&requote-argument (qstr &optional upos)
  302. (unless upos (setq upos 0))
  303. (let* ((qpos 0)
  304. (dquotes nil)
  305. (ustrs '())
  306. (re (concat
  307. "[\"']"
  308. "\\|\\$\\(?:\\([[:alpha:]][[:alnum:]]*\\)"
  309. "\\|{\\(?1:[^{}]+\\)}\\)"
  310. (when (memq system-type '(ms-dos windows-nt))
  311. "\\|%\\(?1:[^\\\\/]*\\)%")
  312. (when comint-file-name-quote-list
  313. "\\|\\\\\\(.\\)")))
  314. (qupos nil)
  315. (push (lambda (str end)
  316. (push str ustrs)
  317. (setq upos (- upos (length str)))
  318. (unless (or qupos (> upos 0))
  319. (setq qupos (if (< end 0) (- end) (+ upos end))))))
  320. match)
  321. (while (setq match (string-match re qstr qpos))
  322. (funcall push (substring qstr qpos match) match)
  323. (cond
  324. ((match-beginning 2) (funcall push (match-string 2 qstr) (match-end 0)))
  325. ((match-beginning 1) (funcall push (getenv (match-string 1 qstr))
  326. (- (match-end 0))))
  327. ((eq (aref qstr match) ?\") (setq dquotes (not dquotes)))
  328. ((eq (aref qstr match) ?\')
  329. (cond
  330. ;; Treat single quote as text if inside double quotes.
  331. (dquotes (funcall push "'" (match-end 0)))
  332. ((< (1+ match) (length qstr))
  333. (let ((end (string-match "'" qstr (1+ match))))
  334. (unless end
  335. (setq end (length qstr))
  336. (set-match-data (list match (length qstr))))
  337. (funcall push (substring qstr (1+ match) end) end)))
  338. ;; Ignore if at the end of string.
  339. (t nil)))
  340. (t (error "Unexpected case in shell--unquote&requote-argument!")))
  341. (setq qpos (match-end 0)))
  342. (funcall push (substring qstr qpos) (length qstr))
  343. (list (mapconcat #'identity (nreverse ustrs) "")
  344. qupos #'comint-quote-filename)))
  345. (defun shell--unquote-argument (str)
  346. (car (shell--unquote&requote-argument str)))
  347. (defun shell--requote-argument (upos qstr)
  348. ;; See `completion-table-with-quoting'.
  349. (let ((res (shell--unquote&requote-argument qstr upos)))
  350. (cons (nth 1 res) (nth 2 res))))
  351. (defun shell--parse-pcomplete-arguments ()
  352. "Parse whitespace separated arguments in the current region."
  353. ;; FIXME: share code with shell--unquote&requote-argument.
  354. (let ((begin (save-excursion (shell-backward-command 1) (point)))
  355. (end (point))
  356. begins args)
  357. (save-excursion
  358. (goto-char begin)
  359. (while (< (point) end)
  360. (skip-chars-forward " \t\n")
  361. (push (point) begins)
  362. (let ((arg ()))
  363. (while (looking-at
  364. (eval-when-compile
  365. (concat
  366. "\\(?:[^\s\t\n\\\"']+"
  367. "\\|'\\([^']*\\)'?"
  368. "\\|\"\\(\\(?:[^\"\\]\\|\\\\.\\)*\\)\"?"
  369. "\\|\\\\\\(\\(?:.\\|\n\\)?\\)\\)")))
  370. (goto-char (match-end 0))
  371. (cond
  372. ((match-beginning 3) ;Backslash escape.
  373. (push (cond
  374. ((null comint-file-name-quote-list)
  375. (goto-char (match-beginning 3)) "\\")
  376. ((= (match-beginning 3) (match-end 3)) "\\")
  377. (t (match-string 3)))
  378. arg))
  379. ((match-beginning 2) ;Double quote.
  380. (push (if (null comint-file-name-quote-list) (match-string 2)
  381. (replace-regexp-in-string
  382. "\\\\\\(.\\)" "\\1" (match-string 2)))
  383. arg))
  384. ((match-beginning 1) ;Single quote.
  385. (push (match-string 1) arg))
  386. (t (push (match-string 0) arg))))
  387. (push (mapconcat #'identity (nreverse arg) "") args)))
  388. (cons (nreverse args) (nreverse begins)))))
  389. (defun shell-command-completion-function ()
  390. "Completion function for shell command names.
  391. This is the value of `pcomplete-command-completion-function' for
  392. Shell buffers. It implements `shell-completion-execonly' for
  393. `pcomplete' completion."
  394. (pcomplete-here (pcomplete-entries nil
  395. (if shell-completion-execonly
  396. 'file-executable-p))))
  397. (defun shell-completion-vars ()
  398. "Setup completion vars for `shell-mode' and `read-shell-command'."
  399. (set (make-local-variable 'comint-completion-fignore)
  400. shell-completion-fignore)
  401. (set (make-local-variable 'comint-delimiter-argument-list)
  402. shell-delimiter-argument-list)
  403. (set (make-local-variable 'comint-file-name-chars) shell-file-name-chars)
  404. (set (make-local-variable 'comint-file-name-quote-list)
  405. shell-file-name-quote-list)
  406. (set (make-local-variable 'comint-dynamic-complete-functions)
  407. shell-dynamic-complete-functions)
  408. (setq-local comint-unquote-function #'shell--unquote-argument)
  409. (setq-local comint-requote-function #'shell--requote-argument)
  410. (set (make-local-variable 'pcomplete-parse-arguments-function)
  411. #'shell--parse-pcomplete-arguments)
  412. (set (make-local-variable 'pcomplete-termination-string)
  413. (cond ((not comint-completion-addsuffix) "")
  414. ((stringp comint-completion-addsuffix)
  415. comint-completion-addsuffix)
  416. ((not (consp comint-completion-addsuffix)) " ")
  417. (t (cdr comint-completion-addsuffix))))
  418. (set (make-local-variable 'pcomplete-command-completion-function)
  419. #'shell-command-completion-function)
  420. ;; Don't use pcomplete's defaulting mechanism, rely on
  421. ;; shell-dynamic-complete-functions instead.
  422. (set (make-local-variable 'pcomplete-default-completion-function) #'ignore)
  423. (setq comint-input-autoexpand shell-input-autoexpand)
  424. ;; Not needed in shell-mode because it's inherited from comint-mode, but
  425. ;; placed here for read-shell-command.
  426. (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t))
  427. (put 'shell-mode 'mode-class 'special)
  428. (define-derived-mode shell-mode comint-mode "Shell"
  429. "Major mode for interacting with an inferior shell.\\<shell-mode-map>
  430. \\[comint-send-input] after the end of the process' output sends the text from
  431. the end of process to the end of the current line.
  432. \\[comint-send-input] before end of process output copies the current line minus the prompt to
  433. the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
  434. \\[send-invisible] reads a line of text without echoing it, and sends it to
  435. the shell. This is useful for entering passwords. Or, add the function
  436. `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
  437. If you want to make multiple shell buffers, rename the `*shell*' buffer
  438. using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
  439. If you want to make shell buffers limited in length, add the function
  440. `comint-truncate-buffer' to `comint-output-filter-functions'.
  441. If you accidentally suspend your process, use \\[comint-continue-subjob]
  442. to continue it.
  443. `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
  444. keep this buffer's default directory the same as the shell's working directory.
  445. While directory tracking is enabled, the shell's working directory is displayed
  446. by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
  447. \\[dirs] queries the shell and resyncs Emacs's idea of what the current
  448. directory stack is.
  449. \\[shell-dirtrack-mode] turns directory tracking on and off.
  450. \(The `dirtrack' package provides an alternative implementation of this
  451. feature - see the function `dirtrack-mode'.)
  452. \\{shell-mode-map}
  453. Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
  454. `shell-mode-hook' (in that order). Before each input, the hooks on
  455. `comint-input-filter-functions' are run. After each shell output, the hooks
  456. on `comint-output-filter-functions' are run.
  457. Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
  458. and `shell-popd-regexp' are used to match their respective commands,
  459. while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
  460. control the behavior of the relevant command.
  461. Variables `comint-completion-autolist', `comint-completion-addsuffix',
  462. `comint-completion-recexact' and `comint-completion-fignore' control the
  463. behavior of file name, command name and variable name completion. Variable
  464. `shell-completion-execonly' controls the behavior of command name completion.
  465. Variable `shell-completion-fignore' is used to initialize the value of
  466. `comint-completion-fignore'.
  467. Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
  468. the initialization of the input ring history, and history expansion.
  469. Variables `comint-output-filter-functions', a hook, and
  470. `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
  471. control whether input and output cause the window to scroll to the end of the
  472. buffer."
  473. (setq comint-prompt-regexp shell-prompt-pattern)
  474. (shell-completion-vars)
  475. (setq-local paragraph-separate "\\'")
  476. (setq-local paragraph-start comint-prompt-regexp)
  477. (setq-local font-lock-defaults '(shell-font-lock-keywords t))
  478. (setq-local shell-dirstack nil)
  479. (setq-local shell-last-dir nil)
  480. ;; People expect Shell mode to keep the last line of output at
  481. ;; window bottom.
  482. (setq-local scroll-conservatively 101)
  483. (shell-dirtrack-mode 1)
  484. ;; By default, ansi-color applies faces using overlays. This is
  485. ;; very inefficient in Shell buffers (e.g. Bug#10835). We use a
  486. ;; custom `ansi-color-apply-face-function' to convert color escape
  487. ;; sequences into `font-lock-face' properties.
  488. (setq-local ansi-color-apply-face-function #'shell-apply-ansi-color)
  489. (shell-reapply-ansi-color)
  490. ;; This is not really correct, since the shell buffer does not really
  491. ;; edit this directory. But it is useful in the buffer list and menus.
  492. (setq list-buffers-directory (expand-file-name default-directory))
  493. ;; shell-dependent assignments.
  494. (when (ring-empty-p comint-input-ring)
  495. (let ((shell (file-name-nondirectory (car
  496. (process-command (get-buffer-process (current-buffer))))))
  497. (hsize (getenv "HISTSIZE")))
  498. (and (stringp hsize)
  499. (integerp (setq hsize (string-to-number hsize)))
  500. (> hsize 0)
  501. (set (make-local-variable 'comint-input-ring-size) hsize))
  502. (setq comint-input-ring-file-name
  503. (or (getenv "HISTFILE")
  504. (cond ((string-equal shell "bash") "~/.bash_history")
  505. ((string-equal shell "ksh") "~/.sh_history")
  506. (t "~/.history"))))
  507. (if (or (equal comint-input-ring-file-name "")
  508. (equal (file-truename comint-input-ring-file-name)
  509. (file-truename "/dev/null")))
  510. (setq comint-input-ring-file-name nil))
  511. ;; Arrange to write out the input ring on exit, if the shell doesn't
  512. ;; do this itself.
  513. (if (and comint-input-ring-file-name
  514. (string-match shell-dumb-shell-regexp shell))
  515. (set-process-sentinel (get-buffer-process (current-buffer))
  516. #'shell-write-history-on-exit))
  517. (setq shell-dirstack-query
  518. (cond ((string-equal shell "sh") "pwd")
  519. ((string-equal shell "ksh") "echo $PWD ~-")
  520. ;; Bypass any aliases. TODO all shells could use this.
  521. ((string-equal shell "bash") "command dirs")
  522. ((string-equal shell "zsh") "dirs -l")
  523. (t "dirs")))
  524. ;; Bypass a bug in certain versions of bash.
  525. (when (string-equal shell "bash")
  526. (add-hook 'comint-preoutput-filter-functions
  527. 'shell-filter-ctrl-a-ctrl-b nil t)))
  528. (comint-read-input-ring t)))
  529. (defun shell-apply-ansi-color (beg end face)
  530. "Apply FACE as the ansi-color face for the text between BEG and END."
  531. (when face
  532. (put-text-property beg end 'ansi-color-face face)
  533. (put-text-property beg end 'font-lock-face face)))
  534. (defun shell-reapply-ansi-color ()
  535. "Reapply ansi-color faces to the existing contents of the buffer."
  536. (save-restriction
  537. (widen)
  538. (let* ((pos (point-min))
  539. (end (or (next-single-property-change pos 'ansi-color-face)
  540. (point-max)))
  541. face)
  542. (while end
  543. (if (setq face (get-text-property pos 'ansi-color-face))
  544. (put-text-property pos (or end (point-max))
  545. 'font-lock-face face))
  546. (setq pos end
  547. end (next-single-property-change pos 'ansi-color-face))))))
  548. (defun shell-filter-ctrl-a-ctrl-b (string)
  549. "Remove `^A' and `^B' characters from comint output.
  550. Bash uses these characters as internal quoting characters in its
  551. prompt. Due to a bug in some bash versions (including 2.03,
  552. 2.04, and 2.05b), they may erroneously show up when bash is
  553. started with the `--noediting' option and Select Graphic
  554. Rendition (SGR) control sequences (formerly known as ANSI escape
  555. sequences) are used to color the prompt.
  556. This function can be put on `comint-preoutput-filter-functions'."
  557. (if (string-match "[\C-a\C-b]" string)
  558. (replace-regexp-in-string "[\C-a\C-b]" "" string t t)
  559. string))
  560. (defun shell-write-history-on-exit (process event)
  561. "Called when the shell process is stopped.
  562. Writes the input history to a history file
  563. `comint-input-ring-file-name' using `comint-write-input-ring'
  564. and inserts a short message in the shell buffer.
  565. This function is a sentinel watching the shell interpreter process.
  566. Sentinels will always get the two parameters PROCESS and EVENT."
  567. ;; Write history.
  568. (comint-write-input-ring)
  569. (let ((buf (process-buffer process)))
  570. (when (buffer-live-p buf)
  571. (with-current-buffer buf
  572. (insert (format "\nProcess %s %s\n" process event))))))
  573. ;;;###autoload
  574. (defun shell (&optional buffer)
  575. "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
  576. Interactively, a prefix arg means to prompt for BUFFER.
  577. If `default-directory' is a remote file name, it is also prompted
  578. to change if called with a prefix arg.
  579. If BUFFER exists but shell process is not running, make new shell.
  580. If BUFFER exists and shell process is running, just switch to BUFFER.
  581. Program used comes from variable `explicit-shell-file-name',
  582. or (if that is nil) from the ESHELL environment variable,
  583. or (if that is nil) from `shell-file-name'.
  584. If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
  585. it is given as initial input (but this may be lost, due to a timing
  586. error, if the shell discards input when it starts up).
  587. The buffer is put in Shell mode, giving commands for sending input
  588. and controlling the subjobs of the shell. See `shell-mode'.
  589. See also the variable `shell-prompt-pattern'.
  590. To specify a coding system for converting non-ASCII characters
  591. in the input and output to the shell, use \\[universal-coding-system-argument]
  592. before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
  593. in the shell buffer, after you start the shell.
  594. The default comes from `process-coding-system-alist' and
  595. `default-process-coding-system'.
  596. The shell file name (sans directories) is used to make a symbol name
  597. such as `explicit-csh-args'. If that symbol is a variable,
  598. its value is used as a list of arguments when invoking the shell.
  599. Otherwise, one argument `-i' is passed to the shell.
  600. \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
  601. (interactive
  602. (list
  603. (and current-prefix-arg
  604. (prog1
  605. (read-buffer "Shell buffer: "
  606. ;; If the current buffer is an inactive
  607. ;; shell buffer, use it as the default.
  608. (if (and (eq major-mode 'shell-mode)
  609. (null (get-buffer-process (current-buffer))))
  610. (buffer-name)
  611. (generate-new-buffer-name "*shell*")))
  612. (if (file-remote-p default-directory)
  613. ;; It must be possible to declare a local default-directory.
  614. ;; FIXME: This can't be right: it changes the default-directory
  615. ;; of the current-buffer rather than of the *shell* buffer.
  616. (setq default-directory
  617. (expand-file-name
  618. (read-directory-name
  619. "Default directory: " default-directory default-directory
  620. t nil))))))))
  621. (setq buffer (if (or buffer (not (derived-mode-p 'shell-mode))
  622. (comint-check-proc (current-buffer)))
  623. (get-buffer-create (or buffer "*shell*"))
  624. ;; If the current buffer is a dead shell buffer, use it.
  625. (current-buffer)))
  626. ;; On remote hosts, the local `shell-file-name' might be useless.
  627. (if (and (called-interactively-p 'any)
  628. (file-remote-p default-directory)
  629. (null explicit-shell-file-name)
  630. (null (getenv "ESHELL")))
  631. (with-current-buffer buffer
  632. (set (make-local-variable 'explicit-shell-file-name)
  633. (expand-file-name
  634. (file-local-name
  635. (read-file-name
  636. "Remote shell path: " default-directory shell-file-name
  637. t shell-file-name))))))
  638. ;; The buffer's window must be correctly set when we call comint (so
  639. ;; that comint sets the COLUMNS env var properly).
  640. (pop-to-buffer buffer)
  641. (unless (comint-check-proc buffer)
  642. (let* ((prog (or explicit-shell-file-name
  643. (getenv "ESHELL") shell-file-name))
  644. (name (file-name-nondirectory prog))
  645. (startfile (concat "~/.emacs_" name))
  646. (xargs-name (intern-soft (concat "explicit-" name "-args"))))
  647. (unless (file-exists-p startfile)
  648. (setq startfile (concat user-emacs-directory "init_" name ".sh")))
  649. (apply 'make-comint-in-buffer "shell" buffer prog
  650. (if (file-exists-p startfile) startfile)
  651. (if (and xargs-name (boundp xargs-name))
  652. (symbol-value xargs-name)
  653. '("-i")))
  654. (shell-mode)))
  655. buffer)
  656. ;;; Directory tracking
  657. ;;
  658. ;; This code provides the shell mode input sentinel
  659. ;; SHELL-DIRECTORY-TRACKER
  660. ;; that tracks cd, pushd, and popd commands issued to the shell, and
  661. ;; changes the current directory of the shell buffer accordingly.
  662. ;;
  663. ;; This is basically a fragile hack, although it's more accurate than
  664. ;; the version in Emacs 18's shell.el. It has the following failings:
  665. ;; 1. It doesn't know about the cdpath shell variable.
  666. ;; 2. It cannot infallibly deal with command sequences, though it does well
  667. ;; with these and with ignoring commands forked in another shell with ()s.
  668. ;; 3. More generally, any complex command is going to throw it. Otherwise,
  669. ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
  670. ;; that, there's no way to catch shell commands where cd's are buried
  671. ;; inside conditional expressions, aliases, and so forth.
  672. ;;
  673. ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
  674. ;; messes it up. You run other processes under the shell; these each have
  675. ;; separate working directories, and some have commands for manipulating
  676. ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
  677. ;; commands that do *not* affect the current w.d. at all, but look like they
  678. ;; do (e.g., the cd command in ftp). In shells that allow you job
  679. ;; control, you can switch between jobs, all having different w.d.'s. So
  680. ;; simply saying %3 can shift your w.d..
  681. ;;
  682. ;; The solution is to relax, not stress out about it, and settle for
  683. ;; a hack that works pretty well in typical circumstances. Remember
  684. ;; that a half-assed solution is more in keeping with the spirit of Unix,
  685. ;; anyway. Blech.
  686. ;;
  687. ;; One good hack not implemented here for users of programmable shells
  688. ;; is to program up the shell w.d. manipulation commands to output
  689. ;; a coded command sequence to the tty. Something like
  690. ;; ESC | <cwd> |
  691. ;; where <cwd> is the new current working directory. Then trash the
  692. ;; directory tracking machinery currently used in this package, and
  693. ;; replace it with a process filter that watches for and strips out
  694. ;; these messages.
  695. (defun shell-directory-tracker (str)
  696. "Tracks cd, pushd and popd commands issued to the shell.
  697. This function is called on each input passed to the shell.
  698. It watches for cd, pushd and popd commands and sets the buffer's
  699. default directory to track these commands.
  700. You may toggle this tracking on and off with \\[shell-dirtrack-mode].
  701. If Emacs gets confused, you can resync with the shell with \\[dirs].
  702. \(The `dirtrack' package provides an alternative implementation of this
  703. feature - see the function `dirtrack-mode'.)
  704. See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
  705. and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
  706. and `shell-pushd-dunique' control the behavior of the relevant command.
  707. Environment variables are expanded, see function `substitute-in-file-name'."
  708. (if shell-dirtrackp
  709. ;; We fail gracefully if we think the command will fail in the shell.
  710. ;;; (with-demoted-errors "Directory tracker failure: %s"
  711. ;; This fails so often that it seems better to just ignore errors (?).
  712. ;; Eg even: foo=/tmp; cd $foo is beyond us (bug#17159).
  713. (ignore-errors
  714. (let ((start (progn (string-match
  715. (concat "^" shell-command-separator-regexp)
  716. str) ; skip whitespace
  717. (match-end 0)))
  718. (case-fold-search)
  719. end cmd arg1)
  720. (while (string-match shell-command-regexp str start)
  721. (setq end (match-end 0)
  722. cmd (comint-arguments (substring str start end) 0 0)
  723. arg1 (comint-arguments (substring str start end) 1 1))
  724. (if arg1
  725. (setq arg1 (shell-unquote-argument arg1)))
  726. (cond ((string-match (concat "\\`\\(" shell-popd-regexp
  727. "\\)\\($\\|[ \t]\\)")
  728. cmd)
  729. (shell-process-popd (comint-substitute-in-file-name arg1)))
  730. ((string-match (concat "\\`\\(" shell-pushd-regexp
  731. "\\)\\($\\|[ \t]\\)")
  732. cmd)
  733. (shell-process-pushd (comint-substitute-in-file-name arg1)))
  734. ((string-match (concat "\\`\\(" shell-cd-regexp
  735. "\\)\\($\\|[ \t]\\)")
  736. cmd)
  737. (shell-process-cd (comint-substitute-in-file-name arg1)))
  738. ((and shell-chdrive-regexp
  739. (string-match (concat "\\`\\(" shell-chdrive-regexp
  740. "\\)\\($\\|[ \t]\\)")
  741. cmd))
  742. (shell-process-cd (comint-substitute-in-file-name cmd))))
  743. (setq start (progn (string-match shell-command-separator-regexp
  744. str end)
  745. ;; skip again
  746. (match-end 0))))))))
  747. (defun shell-unquote-argument (string)
  748. "Remove all kinds of shell quoting from STRING."
  749. (save-match-data
  750. (let ((idx 0) next inside
  751. (quote-chars
  752. (if (string-match shell-dumb-shell-regexp
  753. (file-name-nondirectory
  754. (car (process-command (get-buffer-process (current-buffer))))))
  755. "['`\"]"
  756. "[\\'`\"]")))
  757. (while (and (< idx (length string))
  758. (setq next (string-match quote-chars string next)))
  759. (cond ((= (aref string next) ?\\)
  760. (setq string (replace-match "" nil nil string))
  761. (setq next (1+ next)))
  762. ((and inside (= (aref string next) inside))
  763. (setq string (replace-match "" nil nil string))
  764. (setq inside nil))
  765. (inside
  766. (setq next (1+ next)))
  767. (t
  768. (setq inside (aref string next))
  769. (setq string (replace-match "" nil nil string)))))
  770. string)))
  771. ;; popd [+n]
  772. (defun shell-process-popd (arg)
  773. (let ((num (or (shell-extract-num arg) 0)))
  774. (cond ((and num (= num 0) shell-dirstack)
  775. (shell-cd (shell-prefixed-directory-name (car shell-dirstack)))
  776. (setq shell-dirstack (cdr shell-dirstack))
  777. (shell-dirstack-message))
  778. ((and num (> num 0) (<= num (length shell-dirstack)))
  779. (let* ((ds (cons nil shell-dirstack))
  780. (cell (nthcdr (1- num) ds)))
  781. (rplacd cell (cdr (cdr cell)))
  782. (setq shell-dirstack (cdr ds))
  783. (shell-dirstack-message)))
  784. (t
  785. (error "Couldn't popd")))))
  786. ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
  787. (defun shell-prefixed-directory-name (dir)
  788. (if (= (length comint-file-name-prefix) 0)
  789. dir
  790. (if (file-name-absolute-p dir)
  791. ;; The name is absolute, so prepend the prefix.
  792. (concat comint-file-name-prefix dir)
  793. ;; For relative name we assume default-directory already has the prefix.
  794. (expand-file-name dir))))
  795. ;; cd [dir]
  796. (defun shell-process-cd (arg)
  797. (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
  798. "~"))
  799. ((string-equal "-" arg) shell-last-dir)
  800. (t (shell-prefixed-directory-name arg)))))
  801. (setq shell-last-dir default-directory)
  802. (shell-cd new-dir)
  803. (shell-dirstack-message)))
  804. ;; pushd [+n | dir]
  805. (defun shell-process-pushd (arg)
  806. (let ((num (shell-extract-num arg)))
  807. (cond ((zerop (length arg))
  808. ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
  809. (cond (shell-pushd-tohome
  810. (shell-process-pushd (concat comint-file-name-prefix "~")))
  811. (shell-dirstack
  812. (let ((old default-directory))
  813. (shell-cd (car shell-dirstack))
  814. (setq shell-dirstack (cons old (cdr shell-dirstack)))
  815. (shell-dirstack-message)))
  816. (t
  817. (message "Directory stack empty."))))
  818. ((numberp num)
  819. ;; pushd +n
  820. (cond ((> num (length shell-dirstack))
  821. (message "Directory stack not that deep."))
  822. ((= num 0)
  823. (error "Couldn't cd"))
  824. (shell-pushd-dextract
  825. (let ((dir (nth (1- num) shell-dirstack)))
  826. (shell-process-popd arg)
  827. (shell-process-pushd default-directory)
  828. (shell-cd dir)
  829. (shell-dirstack-message)))
  830. (t
  831. (let* ((ds (cons default-directory shell-dirstack))
  832. (dslen (length ds))
  833. (front (nthcdr num ds))
  834. (back (reverse (nthcdr (- dslen num) (reverse ds))))
  835. (new-ds (append front back)))
  836. (shell-cd (car new-ds))
  837. (setq shell-dirstack (cdr new-ds))
  838. (shell-dirstack-message)))))
  839. (t
  840. ;; pushd <dir>
  841. (let ((old-wd default-directory))
  842. (shell-cd (shell-prefixed-directory-name arg))
  843. (if (or (null shell-pushd-dunique)
  844. (not (member old-wd shell-dirstack)))
  845. (setq shell-dirstack (cons old-wd shell-dirstack)))
  846. (shell-dirstack-message))))))
  847. ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
  848. (defun shell-extract-num (str)
  849. (and (string-match "^\\+[1-9][0-9]*$" str)
  850. (string-to-number str)))
  851. (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
  852. (define-minor-mode shell-dirtrack-mode
  853. "Toggle directory tracking in this shell buffer (Shell Dirtrack mode).
  854. With a prefix argument ARG, enable Shell Dirtrack mode if ARG is
  855. positive, and disable it otherwise. If called from Lisp, enable
  856. the mode if ARG is omitted or nil.
  857. The `dirtrack' package provides an alternative implementation of
  858. this feature; see the function `dirtrack-mode'."
  859. nil nil nil
  860. (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
  861. (if shell-dirtrack-mode
  862. (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
  863. (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
  864. (define-obsolete-function-alias 'shell-dirtrack-toggle 'shell-dirtrack-mode
  865. "23.1")
  866. (defun shell-cd (dir)
  867. "Do normal `cd' to DIR, and set `list-buffers-directory'."
  868. (cd dir)
  869. (if shell-dirtrackp
  870. (setq list-buffers-directory default-directory)))
  871. (defun shell-resync-dirs ()
  872. "Resync the buffer's idea of the current directory stack.
  873. This command queries the shell with the command bound to
  874. `shell-dirstack-query' (default \"dirs\"), reads the next
  875. line output and parses it to form the new directory stack.
  876. DON'T issue this command unless the buffer is at a shell prompt.
  877. Also, note that if some other subprocess decides to do output
  878. immediately after the query, its output will be taken as the
  879. new directory stack -- you lose. If this happens, just do the
  880. command again."
  881. (interactive)
  882. (let* ((proc (get-buffer-process (current-buffer)))
  883. (pmark (process-mark proc))
  884. (started-at-pmark (= (point) (marker-position pmark))))
  885. (save-excursion
  886. (goto-char pmark)
  887. ;; If the process echoes commands, don't insert a fake command in
  888. ;; the buffer or it will appear twice.
  889. (unless comint-process-echoes
  890. (insert shell-dirstack-query) (insert "\n"))
  891. (sit-for 0) ; force redisplay
  892. (comint-send-string proc shell-dirstack-query)
  893. (comint-send-string proc "\n")
  894. (set-marker pmark (point))
  895. (let ((pt (point))
  896. (regexp
  897. (concat
  898. (if comint-process-echoes
  899. ;; Skip command echo if the process echoes
  900. (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
  901. "\\(\\)")
  902. "\\(.+\n\\)")))
  903. ;; This extra newline prevents the user's pending input from spoofing us.
  904. (insert "\n") (backward-char 1)
  905. ;; Wait for one line.
  906. (while (not (looking-at regexp))
  907. (accept-process-output proc)
  908. (goto-char pt)))
  909. (goto-char pmark) (delete-char 1) ; remove the extra newline
  910. ;; That's the dirlist. grab it & parse it.
  911. (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
  912. (dl-len (length dl))
  913. (ds '()) ; new dir stack
  914. (i 0))
  915. (while (< i dl-len)
  916. ;; regexp = optional whitespace, (non-whitespace), optional whitespace
  917. (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
  918. (setq ds (cons (concat comint-file-name-prefix
  919. (substring dl (match-beginning 1)
  920. (match-end 1)))
  921. ds))
  922. (setq i (match-end 0)))
  923. (let ((ds (nreverse ds)))
  924. (with-demoted-errors "Couldn't cd: %s"
  925. (shell-cd (car ds))
  926. (setq shell-dirstack (cdr ds)
  927. shell-last-dir (car shell-dirstack))
  928. (shell-dirstack-message)))))
  929. (if started-at-pmark (goto-char (marker-position pmark)))))
  930. ;; For your typing convenience:
  931. (defalias 'dirs 'shell-resync-dirs)
  932. ;; Show the current dirstack on the message line.
  933. ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
  934. ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
  935. ;; All the commands that mung the buffer's dirstack finish by calling
  936. ;; this guy.
  937. (defun shell-dirstack-message ()
  938. (when shell-dirtrack-verbose
  939. (let* ((msg "")
  940. (ds (cons default-directory shell-dirstack))
  941. (home (expand-file-name (concat comint-file-name-prefix "~/")))
  942. (homelen (length home)))
  943. (while ds
  944. (let ((dir (car ds)))
  945. (and (>= (length dir) homelen)
  946. (string= home (substring dir 0 homelen))
  947. (setq dir (concat "~/" (substring dir homelen))))
  948. ;; Strip off comint-file-name-prefix if present.
  949. (and comint-file-name-prefix
  950. (>= (length dir) (length comint-file-name-prefix))
  951. (string= comint-file-name-prefix
  952. (substring dir 0 (length comint-file-name-prefix)))
  953. (setq dir (substring dir (length comint-file-name-prefix)))
  954. (setcar ds dir))
  955. (setq msg (concat msg (directory-file-name dir) " "))
  956. (setq ds (cdr ds))))
  957. (message "%s" msg))))
  958. ;; This was mostly copied from shell-resync-dirs.
  959. (defun shell-snarf-envar (var)
  960. "Return as a string the shell's value of environment variable VAR."
  961. (let* ((cmd (format "printenv '%s'\n" var))
  962. (proc (get-buffer-process (current-buffer)))
  963. (pmark (process-mark proc)))
  964. (goto-char pmark)
  965. (insert cmd)
  966. (sit-for 0) ; force redisplay
  967. (comint-send-string proc cmd)
  968. (set-marker pmark (point))
  969. (let ((pt (point))) ; wait for 1 line
  970. ;; This extra newline prevents the user's pending input from spoofing us.
  971. (insert "\n") (backward-char 1)
  972. (while (not (looking-at ".+\n"))
  973. (accept-process-output proc)
  974. (goto-char pt)))
  975. (goto-char pmark) (delete-char 1) ; remove the extra newline
  976. (buffer-substring (match-beginning 0) (1- (match-end 0)))))
  977. (defun shell-copy-environment-variable (variable)
  978. "Copy the environment variable VARIABLE from the subshell to Emacs.
  979. This command reads the value of the specified environment variable
  980. in the shell, and sets the same environment variable in Emacs
  981. \(what `getenv' in Emacs would return) to that value.
  982. That value will affect any new subprocesses that you subsequently start
  983. from Emacs."
  984. (interactive (list (read-envvar-name "\
  985. Copy Shell environment variable to Emacs: ")))
  986. (setenv variable (shell-snarf-envar variable)))
  987. (defun shell-forward-command (&optional arg)
  988. "Move forward across ARG shell command(s). Does not cross lines.
  989. See `shell-command-regexp'."
  990. (interactive "p")
  991. (let ((limit (line-end-position))
  992. (pt (point)))
  993. (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
  994. limit 'move arg)
  995. (and (/= pt (point))
  996. (skip-syntax-backward " " pt))))
  997. (defun shell-backward-command (&optional arg)
  998. "Move backward across ARG shell command(s). Does not cross lines.
  999. See `shell-command-regexp'."
  1000. (interactive "p")
  1001. (let ((limit (save-excursion (comint-bol nil) (point))))
  1002. (when (> limit (point))
  1003. (setq limit (line-beginning-position)))
  1004. (skip-syntax-backward " " limit)
  1005. (let ((pt (point)))
  1006. (if (re-search-backward
  1007. (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
  1008. (progn (goto-char (match-beginning 1))
  1009. (skip-chars-forward ";&|")))
  1010. (and (/= pt (point))
  1011. (skip-syntax-forward " " pt)))))
  1012. (defun shell-dynamic-complete-command ()
  1013. "Dynamically complete the command at point.
  1014. This function is similar to `comint-dynamic-complete-filename', except that it
  1015. searches `exec-path' (minus trailing `exec-directory') for completion
  1016. candidates. Note that this may not be the same as the shell's idea of the
  1017. path.
  1018. Completion is dependent on the value of `shell-completion-execonly',
  1019. `shell-completion-fignore', plus those that affect file completion. See Info
  1020. node `Shell Options'.
  1021. Returns t if successful."
  1022. (interactive)
  1023. (let ((data (shell-command-completion)))
  1024. (if data
  1025. (prog2 (unless (window-minibuffer-p)
  1026. (message "Completing command name..."))
  1027. (apply #'completion-in-region data)))))
  1028. (defun shell-command-completion ()
  1029. "Return the completion data for the command at point, if any."
  1030. (let ((filename (comint-match-partial-filename)))
  1031. (if (and filename
  1032. (save-match-data (not (string-match "[~/]" filename)))
  1033. (eq (match-beginning 0)
  1034. (save-excursion (shell-backward-command 1) (point))))
  1035. (shell--command-completion-data))))
  1036. (defun shell--command-completion-data ()
  1037. "Return the completion data for the command at point."
  1038. (let* ((filename (or (comint-match-partial-filename) ""))
  1039. (start (if (zerop (length filename)) (point) (match-beginning 0)))
  1040. (end (if (zerop (length filename)) (point) (match-end 0)))
  1041. (filenondir (file-name-nondirectory filename))
  1042. ; why cdr? see `shell-dynamic-complete-command'
  1043. (path-dirs (append (cdr (reverse exec-path))
  1044. (if (memq system-type '(windows-nt ms-dos)) '("."))))
  1045. (cwd (file-name-as-directory (expand-file-name default-directory)))
  1046. (ignored-extensions
  1047. (and comint-completion-fignore
  1048. (mapconcat (function (lambda (x) (concat (regexp-quote x) "\\'")))
  1049. comint-completion-fignore "\\|")))
  1050. (dir "") (comps-in-dir ())
  1051. (file "") (abs-file-name "") (completions ()))
  1052. ;; Go thru each dir in the search path, finding completions.
  1053. (while path-dirs
  1054. (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
  1055. comps-in-dir (and (file-accessible-directory-p dir)
  1056. (file-name-all-completions filenondir dir)))
  1057. ;; Go thru each completion found, to see whether it should be used.
  1058. (while comps-in-dir
  1059. (setq file (car comps-in-dir)
  1060. abs-file-name (concat dir file))
  1061. (if (and (not (member file completions))
  1062. (not (and ignored-extensions
  1063. (string-match ignored-extensions file)))
  1064. (or (string-equal dir cwd)
  1065. (not (file-directory-p abs-file-name)))
  1066. (or (null shell-completion-execonly)
  1067. (file-executable-p abs-file-name)))
  1068. (setq completions (cons file completions)))
  1069. (setq comps-in-dir (cdr comps-in-dir)))
  1070. (setq path-dirs (cdr path-dirs)))
  1071. ;; OK, we've got a list of completions.
  1072. (list
  1073. start end
  1074. (lambda (string pred action)
  1075. (if (string-match "/" string)
  1076. (completion-file-name-table string pred action)
  1077. (complete-with-action action completions string pred)))
  1078. :exit-function
  1079. (lambda (_string finished)
  1080. (when (memq finished '(sole finished))
  1081. (if (looking-at " ")
  1082. (goto-char (match-end 0))
  1083. (insert " ")))))))
  1084. ;; (defun shell-dynamic-complete-as-command ()
  1085. ;; "Dynamically complete at point as a command.
  1086. ;; See `shell-dynamic-complete-filename'. Returns t if successful."
  1087. ;; (apply #'completion-in-region shell--command-completion-data))
  1088. (defun shell-dynamic-complete-filename ()
  1089. "Dynamically complete the filename at point.
  1090. This completes only if point is at a suitable position for a
  1091. filename argument."
  1092. (interactive)
  1093. (let ((data (shell-filename-completion)))
  1094. (if data (apply #'completion-in-region data))))
  1095. (defun shell-filename-completion ()
  1096. "Return the completion data for file name at point, if any."
  1097. (let ((opoint (point))
  1098. (beg (comint-line-beginning-position)))
  1099. (when (save-excursion
  1100. (goto-char (if (re-search-backward "[;|&]" beg t)
  1101. (match-end 0)
  1102. beg))
  1103. (re-search-forward "[^ \t][ \t]" opoint t))
  1104. (comint-filename-completion))))
  1105. (defun shell-match-partial-variable ()
  1106. "Return the shell variable at point, or nil if none is found."
  1107. (save-excursion
  1108. (if (re-search-backward "[^A-Za-z0-9_{(]" nil 'move)
  1109. (or (looking-at "\\$") (forward-char 1)))
  1110. (if (or (eolp) (looking-at "[^A-Za-z0-9_{($]"))
  1111. nil
  1112. (looking-at "\\$?[{(]?[A-Za-z0-9_]*[})]?")
  1113. (buffer-substring (match-beginning 0) (match-end 0)))))
  1114. (defun shell-dynamic-complete-environment-variable ()
  1115. "Dynamically complete the environment variable at point.
  1116. Completes if after a variable, i.e., if it starts with a \"$\".
  1117. This function is similar to `comint-dynamic-complete-filename', except that it
  1118. searches `process-environment' for completion candidates. Note that this may
  1119. not be the same as the interpreter's idea of variable names. The main problem
  1120. with this type of completion is that `process-environment' is the environment
  1121. which Emacs started with. Emacs does not track changes to the environment made
  1122. by the interpreter. Perhaps it would be more accurate if this function was
  1123. called `shell-dynamic-complete-process-environment-variable'.
  1124. Returns non-nil if successful."
  1125. (interactive)
  1126. (let ((data (shell-environment-variable-completion)))
  1127. (if data
  1128. (prog2 (unless (window-minibuffer-p)
  1129. (message "Completing variable name..."))
  1130. (apply #'completion-in-region data)))))
  1131. (defun shell-environment-variable-completion ()
  1132. "Completion data for an environment variable at point, if any."
  1133. (let* ((var (shell-match-partial-variable))
  1134. (end (match-end 0)))
  1135. (when (and (not (zerop (length var))) (eq (aref var 0) ?$))
  1136. (let* ((start
  1137. (save-excursion
  1138. (goto-char (match-beginning 0))
  1139. (looking-at "\\$?[({]*")
  1140. (match-end 0)))
  1141. (variables (mapcar (lambda (x)
  1142. (substring x 0 (string-match "=" x)))
  1143. process-environment))
  1144. (suffix (pcase (char-before start) (?\{ "}") (?\( ")") (_ ""))))
  1145. (list start end variables
  1146. :exit-function
  1147. (lambda (s finished)
  1148. (when (memq finished '(sole finished))
  1149. (let ((suf (concat suffix
  1150. (if (file-directory-p
  1151. (comint-directory (getenv s)))
  1152. "/"))))
  1153. (if (looking-at (regexp-quote suf))
  1154. (goto-char (match-end 0))
  1155. (insert suf))))))))))
  1156. (defun shell-c-a-p-replace-by-expanded-directory ()
  1157. "Expand directory stack reference before point.
  1158. For use on `completion-at-point-functions'."
  1159. (when (comint-match-partial-filename)
  1160. (save-excursion
  1161. (goto-char (match-beginning 0))
  1162. (let ((stack (cons default-directory shell-dirstack))
  1163. (index (cond ((looking-at "=-/?")
  1164. (length shell-dirstack))
  1165. ((looking-at "=\\([0-9]+\\)/?")
  1166. (string-to-number
  1167. (buffer-substring
  1168. (match-beginning 1) (match-end 1)))))))
  1169. (when index
  1170. (let ((start (match-beginning 0))
  1171. (end (match-end 0))
  1172. (replacement (file-name-as-directory (nth index stack))))
  1173. (lambda ()
  1174. (cond
  1175. ((>= index (length stack))
  1176. (error "Directory stack not that deep"))
  1177. (t
  1178. (save-excursion
  1179. (goto-char start)
  1180. (insert replacement)
  1181. (delete-char (- end start)))
  1182. (message "Directory item: %d" index)
  1183. t)))))))))
  1184. (defun shell-replace-by-expanded-directory ()
  1185. "Expand directory stack reference before point.
  1186. Directory stack references are of the form \"=digit\" or \"=-\".
  1187. See `default-directory' and `shell-dirstack'.
  1188. Returns t if successful."
  1189. (interactive)
  1190. (let ((f (shell-c-a-p-replace-by-expanded-directory)))
  1191. (if f (funcall f))))
  1192. (provide 'shell)
  1193. ;;; shell.el ends here