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