shell.el 50 KB

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