mirrored from git://git.sv.gnu.org/emacs.git
/
shell.el
1833 lines (1648 loc) · 72.8 KB
/
shell.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; shell.el --- specialized comint.el for running the shell -*- lexical-binding: t -*-
;; Copyright (C) 1988, 1993-1997, 2000-2024 Free Software Foundation,
;; Inc.
;; Author: Olin Shivers <shivers@cs.cmu.edu>
;; Simon Marshall <simon@gnu.org>
;; Maintainer: emacs-devel@gnu.org
;; Keywords: processes
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This file defines a shell-in-a-buffer package (shell mode) built on
;; top of comint mode.
;; Since this mode is built on top of the general command-interpreter-in-
;; a-buffer mode (comint mode), it shares a common base functionality,
;; and a common set of bindings, with all modes derived from comint mode.
;; This makes these modes easier to use.
;; For documentation on the functionality provided by comint mode, and
;; the hooks available for customizing it, see the file comint.el.
;; For further information on shell mode, see the comments below.
;; Needs fixin:
;; When sending text from a source file to a subprocess, the process-mark can
;; move off the window, so you can lose sight of the process interactions.
;; Maybe I should ensure the process mark is in the window when I send
;; text to the process? Switch selectable?
;; YOUR .EMACS FILE
;;=============================================================================
;; Some suggestions for your init file.
;;
;; ;; Define M-# to run some strange command:
;; (eval-after-load "shell"
;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
;; Brief Command Documentation:
;;============================================================================
;; Comint Mode Commands: (common to shell and all comint-derived modes)
;;
;; m-p comint-previous-input Cycle backwards in input history
;; m-n comint-next-input Cycle forwards
;; m-r comint-previous-matching-input Previous input matching a regexp
;; m-s comint-next-matching-input Next input that matches
;; m-c-l comint-show-output Show last batch of process output
;; return comint-send-input
;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
;; c-c c-a comint-bol Beginning of line; skip prompt
;; c-c c-u comint-kill-input ^u
;; c-c c-w backward-kill-word ^w
;; c-c c-c comint-interrupt-subjob ^c
;; c-c c-z comint-stop-subjob ^z
;; c-c c-\ comint-quit-subjob ^\
;; c-c c-o comint-delete-output Delete last batch of process output
;; c-c c-r comint-show-output Show last batch of process output
;; c-c c-l comint-dynamic-list-input-ring List input history
;; comint-send-invisible Read line without echo & send to proc
;; comint-continue-subjob Useful if you accidentally suspend
;; top-level job
;; comint-mode-hook is the comint mode hook.
;; Shell Mode Commands:
;; shell Fires up the shell process
;; tab completion-at-point Complete filename/command/history
;; m-? comint-dynamic-list-filename-completions
;; List completions in help buffer
;; c-c c-f shell-forward-command Forward a shell command
;; c-c c-b shell-backward-command Backward a shell command
;; dirs Resync the buffer's dir stack
;; shell-dirtrack-mode Turn dir tracking on/off
;; comint-strip-ctrl-m Remove trailing ^Ms from output
;;
;; The shell mode hook is shell-mode-hook
;; comint-prompt-regexp is initialized to shell-prompt-pattern, for backwards
;; compatibility.
;; Read the rest of this file for more information.
;;; Code:
(require 'comint)
(require 'pcomplete)
(eval-when-compile (require 'files-x)) ;with-connection-local-variables
(require 'subr-x)
(eval-when-compile (require 'cl-lib))
;;; Customization and Buffer Variables
(defgroup shell nil
"Running shell from within Emacs buffers."
:group 'processes
:group 'unix)
(defgroup shell-directories nil
"Directory support in shell mode."
:group 'shell)
;;;###autoload
(defcustom shell-dumb-shell-regexp (purecopy "cmd\\(proxy\\)?\\.exe")
"Regexp to match shells that don't save their command history, and
don't handle the backslash as a quote character. For shells that
match this regexp, Emacs will write out the command history when the
shell finishes, and won't remove backslashes when it unquotes shell
arguments."
:type 'regexp
:group 'shell)
(defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
"Regexp to match prompts in the inferior shell.
Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
This variable is used to initialize `comint-prompt-regexp' in the
shell buffer.
If `comint-use-prompt-regexp' is nil, then this variable is only used
to determine paragraph boundaries. See Info node `Shell Prompts' for
how Shell mode treats paragraphs.
The pattern should probably not match more than one line. If it does,
Shell mode may become confused trying to distinguish prompt from input
on lines which don't start with a prompt."
:type 'regexp
:group 'shell)
(defcustom shell-completion-fignore nil
"List of suffixes to be disregarded during file/command completion.
This variable is used to initialize `comint-completion-fignore' in the shell
buffer. The default is nil, for compatibility with most shells.
Some people like (\"~\" \"#\" \"%\")."
:type '(repeat (string :tag "Suffix"))
:group 'shell)
(defcustom shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
"List of characters to recognize as separate arguments.
This variable is used to initialize `comint-delimiter-argument-list' in the
shell buffer. The value may depend on the operating system or shell."
:type '(choice (const nil)
(repeat :tag "List of characters" character))
:group 'shell)
(defcustom shell-file-name-chars
(if (memq system-type '(ms-dos windows-nt cygwin))
"~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
"[]~/A-Za-z0-9+@:_.$#%,={}-")
"String of characters valid in a file name.
This variable is used to initialize `comint-file-name-chars' in the
shell buffer. The value may depend on the operating system or shell."
:type 'string
:group 'shell)
(defcustom shell-file-name-quote-list
(if (memq system-type '(ms-dos windows-nt))
nil
(append shell-delimiter-argument-list '(?\s ?$ ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
"List of characters to quote when in a file name.
This variable is used to initialize `comint-file-name-quote-list' in the
shell buffer. The value may depend on the operating system or shell."
:type '(repeat character)
:group 'shell)
(defcustom shell-dynamic-complete-functions
'(comint-c-a-p-replace-by-expanded-history
shell-environment-variable-completion
shell-command-completion
shell-c-a-p-replace-by-expanded-directory
pcomplete-completions-at-point
shell-filename-completion
comint-filename-completion)
"List of functions called to perform completion.
This variable is used to initialize `comint-dynamic-complete-functions' in the
shell buffer."
:type '(repeat function)
:group 'shell)
(defcustom shell-command-regexp "[^;&|\n]+"
"Regexp to match a single command within a pipeline.
This is used for directory tracking and does not do a perfect job."
:type 'regexp
:group 'shell)
(defcustom shell-command-separator-regexp "[;&|\n \t]*"
"Regexp to match a single command within a pipeline.
This is used for directory tracking and does not do a perfect job."
:type 'regexp
:group 'shell)
(defcustom shell-completion-execonly t
"If non-nil, use executable files only for completion candidates.
This mirrors the optional behavior of tcsh.
Detecting executability of files may slow command completion considerably."
:type 'boolean
:group 'shell)
(defcustom shell-popd-regexp "popd"
"Regexp to match subshell commands equivalent to popd."
:type 'regexp
:group 'shell-directories)
(defcustom shell-pushd-regexp "pushd"
"Regexp to match subshell commands equivalent to pushd."
:type 'regexp
:group 'shell-directories)
(defcustom shell-pushd-tohome nil
"If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
This mirrors the optional behavior of tcsh."
:type 'boolean
:group 'shell-directories)
(defcustom shell-pushd-dextract nil
"If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
This mirrors the optional behavior of tcsh."
:type 'boolean
:group 'shell-directories)
(defcustom shell-pushd-dunique nil
"If non-nil, make pushd only add unique directories to the stack.
This mirrors the optional behavior of tcsh."
:type 'boolean
:group 'shell-directories)
(defcustom shell-cd-regexp "cd"
"Regexp to match subshell commands equivalent to cd."
:type 'regexp
:group 'shell-directories)
(defcustom shell-chdrive-regexp
(if (memq system-type '(ms-dos windows-nt))
; NetWare allows the five chars between upper and lower alphabetics.
"[]a-zA-Z^_`[\\]:"
nil)
"If non-nil, is regexp used to track drive changes."
:type '(choice regexp
(const nil))
:group 'shell-directories)
(defcustom shell-dirtrack-verbose t
"If non-nil, show the directory stack following directory change.
This is effective only if directory tracking is enabled.
The `dirtrack' package provides an alternative implementation of this feature -
see the function `dirtrack-mode'."
:type 'boolean
:group 'shell-directories)
(defcustom explicit-shell-file-name nil
"If non-nil, the file name to use for explicitly requested inferior shells.
When nil, such interactive shell sessions fall back to using the
shell specified in either the environment variable \"ESHELL\" or
`shell-file-name'."
:type '(choice (const :tag "Default" nil) file)
:group 'shell)
;; Note: There are no explicit references to the variable `explicit-csh-args'.
;; It is used implicitly by M-x shell when the shell is `csh'.
(defcustom explicit-csh-args
(if (eq system-type 'hpux)
;; -T persuades HP's csh not to think it is smarter
;; than us about what terminal modes to use.
'("-i" "-T")
'("-i"))
"Args passed to inferior shell by \\[shell], if the shell is csh.
Value is a list of strings, which may be nil."
:type '(repeat (string :tag "Argument"))
:group 'shell)
;; Note: There are no explicit references to the variable `explicit-bash-args'.
;; It is used implicitly by M-x shell when the interactive shell is `bash'.
(defcustom explicit-bash-args
;; Tell bash not to use readline. It's safe to assume --noediting now,
;; as it was introduced in 1996 in Bash version 2.
'("--noediting" "-i")
"Args passed to inferior shell by \\[shell], if the shell is bash.
Value is a list of strings, which may be nil."
:type '(repeat (string :tag "Argument"))
:group 'shell)
(defcustom shell-input-autoexpand 'history
"If non-nil, expand input command history references on completion.
This mirrors the optional behavior of tcsh (its autoexpand and histlit).
If the value is `input', then the expansion is seen on input.
If the value is `history', then the expansion is only when inserting
into the buffer's input ring. See also `comint-magic-space' and
`comint-dynamic-complete-functions'.
This variable supplies a default for `comint-input-autoexpand',
for Shell mode only."
:type '(choice (const :tag "off" nil)
(const input)
(const history)
(const :tag "on" t))
:group 'shell)
(defcustom shell-fontify-input-enable t
"Enable fontification of input in shell buffers.
This variable only has effect when the shell is started. Use the
command `comint-fontify-input-mode' to toggle fontification of
input."
:type 'boolean
:group 'shell
:safe 'booleanp
:version "29.1")
(defcustom shell-indirect-setup-hook nil
"Hook run in an indirect buffer for input fontification.
Input fontification and indentation of a `shell-mode' buffer, if
enabled, is performed in an indirect buffer, whose indentation
and syntax highlighting is set up with `sh-mode'. In addition to
`comint-indirect-setup-hook', run this hook with the indirect
buffer as the current buffer after its setup is done. This can
be used to further customize fontification and other behavior of
the indirect buffer."
:type 'hook
:group 'shell
:version "29.1")
(defcustom shell-highlight-undef-enable nil
"Enable highlighting of undefined commands in shell buffers.
This variable only has effect when the shell is started. Use the
command `shell-highlight-undef-mode' to toggle highlighting of
undefined commands."
:type 'boolean
:group 'shell
:safe 'booleanp
:version "29.1")
(defvar shell-dirstack nil
"List of directories saved by pushd in this buffer's shell.
Thus, this does not include the shell's current directory.")
(defvaralias 'shell-dirtrackp 'shell-dirtrack-mode
"Non-nil in a shell buffer means directory tracking is enabled.
Directory tracking (`shell-dirtrack-mode') is automatically enabled
when `shell-mode' is activated.")
(defvar shell-last-dir nil
"Keep track of last directory for ksh `cd -' command.")
(defvar shell-dirstack-query nil
"Command used by `shell-resync-dirs' to query the shell.")
(defcustom shell-has-auto-cd nil
"If non-nil, `shell-mode' handles implicit \"cd\" commands.
Implicit \"cd\" is changing the directory if the command is a directory.
You can make this variable buffer-local to change it, per shell-mode instance.
Useful for shells like zsh that has this feature."
:type 'boolean
:group 'shell-directories
:version "28.1")
(defcustom shell-get-old-input-include-continuation-lines nil
"Whether `shell-get-old-input' includes \"\\\" lines."
:type 'boolean
:group 'shell
:version "30.1")
(defcustom shell-kill-buffer-on-exit nil
"Kill a shell buffer after the shell process terminates."
:type 'boolean
:group 'shell
:version "29.1")
(defvar shell-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-f" 'shell-forward-command)
(define-key map "\C-c\C-b" 'shell-backward-command)
(define-key map "\t" 'completion-at-point)
(define-key map (kbd "M-RET") 'shell-resync-dirs)
(define-key map "\M-?" 'comint-dynamic-list-filename-completions)
(define-key map (kbd "C-x n d") 'shell-narrow-to-prompt)
(define-key map [menu-bar completion]
(cons "Complete"
(copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
(define-key-after (lookup-key map [menu-bar completion])
[complete-env-variable] '("Complete Env. Variable Name" .
shell-dynamic-complete-environment-variable)
'complete-file)
(define-key-after (lookup-key map [menu-bar completion])
[expand-directory] '("Expand Directory Reference" .
shell-replace-by-expanded-directory)
'complete-expand)
map))
(defvar-keymap shell-repeat-map
:doc "Keymap to repeat shell key sequences. Used in `repeat-mode'."
:repeat t
"C-f" #'shell-forward-command
"C-b" #'shell-backward-command)
(defcustom shell-mode-hook '()
"Hook for customizing Shell mode."
:type 'hook
:group 'shell)
(defvar shell-font-lock-keywords
'(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
("^[^ \t\n]+:.*" . font-lock-string-face)
("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
"Additional expressions to highlight in Shell mode.")
(defvar-local shell--start-prog nil
"Shell file name started in `shell'.")
(put 'shell--start-prog 'permanent-local t)
;;; Basic Procedures
(defun shell--unquote&requote-argument (qstr &optional upos)
(unless upos (setq upos 0))
(let* ((qpos 0)
(dquotes nil)
(ustrs '())
(re (concat
"[\"']"
"\\|\\$\\(?:\\([[:alpha:]][[:alnum:]]*\\)"
"\\|{\\(?1:[^{}]+\\)}\\)"
(when (memq system-type '(ms-dos windows-nt))
"\\|%\\(?1:[^\\/]*\\)%")
(when comint-file-name-quote-list
"\\|\\\\\\(.\\)")))
(qupos nil)
(push (lambda (str end)
(push str ustrs)
(setq upos (- upos (length str)))
(unless (or qupos (> upos 0))
(setq qupos (if (< end 0) (- end) (+ upos end))))))
match)
(while (setq match (string-match re qstr qpos))
(funcall push (substring qstr qpos match) match)
(cond
((match-beginning 2) (funcall push (match-string 2 qstr) (match-end 0)))
((match-beginning 1) (funcall push (getenv (match-string 1 qstr))
(- (match-end 0))))
((eq (aref qstr match) ?\") (setq dquotes (not dquotes)))
((eq (aref qstr match) ?\')
(cond
;; Treat single quote as text if inside double quotes.
(dquotes (funcall push "'" (match-end 0)))
((< (1+ match) (length qstr))
(let ((end (string-match "'" qstr (1+ match))))
(unless end
(setq end (length qstr))
(set-match-data (list match (length qstr))))
(funcall push (substring qstr (1+ match) end) end)))
;; Ignore if at the end of string.
(t nil)))
(t (error "Unexpected case in shell--unquote&requote-argument!")))
(setq qpos (match-end 0)))
(funcall push (substring qstr qpos) (length qstr))
(list (mapconcat #'identity (nreverse ustrs) "")
qupos #'comint-quote-filename)))
(defun shell--unquote-argument (str)
(car (shell--unquote&requote-argument str)))
(defun shell--requote-argument (upos qstr)
;; See `completion-table-with-quoting'.
(let ((res (shell--unquote&requote-argument qstr upos)))
(cons (nth 1 res) (nth 2 res))))
(defun shell--parse-pcomplete-arguments ()
"Parse whitespace separated arguments in the current region."
;; FIXME: share code with shell--unquote&requote-argument.
(let ((begin (save-excursion (shell-backward-command 1) (point)))
(end (point))
begins args)
(save-excursion
(goto-char begin)
(while (< (point) end)
(skip-chars-forward " \t\n;")
(push (point) begins)
(let ((arg ()))
(while (looking-at
(concat
"\\(?:[^\s\t\n\\\"';]+"
"\\|'\\([^']*\\)'?"
"\\|\"\\(\\(?:[^\"\\]\\|\\\\.\\)*\\)\"?"
"\\|\\\\\\(\\(?:.\\|\n\\)?\\)\\)"))
(goto-char (match-end 0))
(cond
((match-beginning 3) ;Backslash escape.
(push (cond
((null comint-file-name-quote-list)
(goto-char (match-beginning 3)) "\\")
((= (match-beginning 3) (match-end 3)) "\\")
(t (match-string 3)))
arg))
((match-beginning 2) ;Double quote.
(push (if (null comint-file-name-quote-list) (match-string 2)
(replace-regexp-in-string
"\\\\\\(.\\)" "\\1" (match-string 2)))
arg))
((match-beginning 1) ;Single quote.
(push (match-string 1) arg))
(t (push (match-string 0) arg))))
(push (mapconcat #'identity (nreverse arg) "") args)))
(cons (nreverse args) (nreverse begins)))))
(defun shell-get-old-input ()
"Default for `comint-get-old-input' in `shell-mode'.
If `comint-use-prompt-regexp' is nil, then either
return the current input field (if point is on an input field), or the
current line (if point is on an output field).
If `comint-use-prompt-regexp' is non-nil, then return
the current line, with any initial string matching the regexp
`comint-prompt-regexp' removed.
In either case, if `shell-get-old-input-include-continuation-lines'
is non-nil and the current line ends with a backslash, the next
line is also included and examined for a backslash, ending with a
final line without a backslash."
(let (field-prop bof)
(if (and (not comint-use-prompt-regexp)
;; Make sure we're in an input rather than output field.
(not (setq field-prop (get-char-property
(setq bof (field-beginning)) 'field))))
(field-string-no-properties bof)
(comint-bol)
(let ((start (point)))
(cond ((or comint-use-prompt-regexp
(eq field-prop 'output))
(goto-char (line-end-position))
(when shell-get-old-input-include-continuation-lines
;; Include continuation lines as long as the current
;; line ends with a backslash.
(while (and (not (eobp))
(= (char-before) ?\\))
(goto-char (line-end-position 2)))))
(t
(goto-char (field-end))))
(buffer-substring-no-properties start (point))))))
;;;###autoload
(defun split-string-shell-command (string)
"Split STRING (a shell command) into a list of strings.
General shell syntax, like single and double quoting, as well as
backslash quoting, is respected."
(with-temp-buffer
(insert string)
(let ((comint-file-name-quote-list shell-file-name-quote-list))
(car (shell--parse-pcomplete-arguments)))))
(defun shell-command-completion-function ()
"Completion function for shell command names.
This is the value of `pcomplete-command-completion-function' for
Shell buffers. It implements `shell-completion-execonly' for
`pcomplete' completion."
(if (pcomplete-match "/")
(pcomplete-here (pcomplete-entries nil
(if shell-completion-execonly
#'file-executable-p)))
(pcomplete-here
(nth 2 (shell--command-completion-data)))))
(defun shell-completion-vars ()
"Setup completion vars for `shell-mode' and `read-shell-command'."
(setq-local comint-completion-fignore
shell-completion-fignore)
(setq-local comint-delimiter-argument-list
shell-delimiter-argument-list)
(setq-local comint-file-name-chars shell-file-name-chars)
(setq-local comint-file-name-quote-list
shell-file-name-quote-list)
(setq-local comint-file-name-prefix
(or (file-remote-p default-directory) ""))
(setq-local comint-dynamic-complete-functions
shell-dynamic-complete-functions)
(setq-local comint-unquote-function #'shell--unquote-argument)
(setq-local comint-requote-function #'shell--requote-argument)
(setq-local pcomplete-parse-arguments-function
#'shell--parse-pcomplete-arguments)
(setq-local pcomplete-termination-string
(cond ((not comint-completion-addsuffix) "")
((stringp comint-completion-addsuffix)
comint-completion-addsuffix)
((not (consp comint-completion-addsuffix)) " ")
(t (cdr comint-completion-addsuffix))))
(setq-local pcomplete-command-completion-function
#'shell-command-completion-function)
;; Don't use pcomplete's defaulting mechanism, rely on
;; shell-dynamic-complete-functions instead.
(setq-local pcomplete-default-completion-function #'ignore)
;; Do not expand remote file names.
(setq-local pcomplete-remote-file-ignore
(not (file-remote-p default-directory)))
(setq-local comint-input-autoexpand shell-input-autoexpand)
;; Not needed in shell-mode because it's inherited from comint-mode, but
;; placed here for read-shell-command.
(add-hook 'completion-at-point-functions #'comint-completion-at-point nil t))
(put 'shell-mode 'mode-class 'special)
(defvar sh-shell-file)
(declare-function w32-application-type "w32proc.c"
(program) t)
(define-derived-mode shell-mode comint-mode "Shell"
"Major mode for interacting with an inferior shell.
\\<shell-mode-map>
\\[comint-send-input] after the end of the process' output sends the text from
the end of process to the end of the current line.
\\[comint-send-input] before end of process output copies the current line minus the prompt to
the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
\\[comint-send-invisible] reads a line of text without echoing it, and sends it to
the shell. This is useful for entering passwords. Or, add the function
`comint-watch-for-password-prompt' to `comint-output-filter-functions'.
If you want to make multiple shell buffers, rename the \"*shell*\" buffer
using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
If you want to make shell buffers limited in length, add the function
`comint-truncate-buffer' to `comint-output-filter-functions'.
If you accidentally suspend your process, use \\[comint-continue-subjob]
to continue it.
`cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
keep this buffer's default directory the same as the shell's working directory.
While directory tracking is enabled, the shell's working directory is displayed
by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
\\[dirs] queries the shell and resyncs Emacs's idea of what the current
directory stack is.
\\[shell-dirtrack-mode] turns directory tracking on and off.
\(The `dirtrack' package provides an alternative implementation of this
feature - see the function `dirtrack-mode'.)
\\{shell-mode-map}
Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
`shell-mode-hook' (in that order). Before each input, the hooks on
`comint-input-filter-functions' are run. After each shell output, the hooks
on `comint-output-filter-functions' are run.
Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
and `shell-popd-regexp' are used to match their respective commands,
while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
control the behavior of the relevant command.
Variables `comint-completion-autolist', `comint-completion-addsuffix',
`comint-completion-recexact' and `comint-completion-fignore' control the
behavior of file name, command name and variable name completion. Variable
`shell-completion-execonly' controls the behavior of command name completion.
Variable `shell-completion-fignore' is used to initialize the value of
`comint-completion-fignore'.
Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
the initialization of the input ring history, and history expansion.
Variables `comint-output-filter-functions', a hook, and
`comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
control whether input and output cause the window to scroll to the end of the
buffer.
By default, shell mode does nothing special when it receives a
\"bell\" character (C-g or ^G). If you
(add-hook \\='comint-output-filter-functions #\\='shell-filter-ring-bell nil t)
from `shell-mode-hook', Emacs will call the `ding' function
whenever it receives the bell character in output from a
command."
:interactive nil
:after-hook
(unless comint-use-prompt-regexp
(if shell-fontify-input-enable
(comint-fontify-input-mode))
(if shell-highlight-undef-enable
(shell-highlight-undef-mode)))
(setq comint-prompt-regexp shell-prompt-pattern)
(shell-completion-vars)
(setq-local paragraph-separate "\\'")
(setq-local paragraph-start comint-prompt-regexp)
(setq-local font-lock-defaults '(shell-font-lock-keywords t))
(setq-local shell-dirstack nil)
(setq-local shell-last-dir nil)
(setq-local comint-get-old-input #'shell-get-old-input)
;; People expect Shell mode to keep the last line of output at
;; window bottom.
(setq-local scroll-conservatively 101)
(shell-dirtrack-mode 1)
;; By default, ansi-color applies faces using overlays. This is
;; very inefficient in Shell buffers (e.g. Bug#10835). We use a
;; custom `ansi-color-apply-face-function' to convert color escape
;; sequences into `font-lock-face' properties.
(setq-local ansi-color-apply-face-function #'shell-apply-ansi-color)
(shell-reapply-ansi-color)
(add-hook 'comint-indirect-setup-hook
#'shell-indirect-setup-hook 'append t)
(setq comint-indirect-setup-function
(let ((shell shell--start-prog))
(lambda ()
(require 'sh-script)
(cl-letf
(((default-value 'sh-shell-file)
(or shell sh-shell-file))
(inhibit-message t)
(message-log-max nil))
(sh-mode)))))
(setq-local indent-line-function #'comint-indent-input-line-default)
(setq-local indent-region-function
#'comint-indent-input-region-default)
;; This is not really correct, since the shell buffer does not really
;; edit this directory. But it is useful in the buffer list and menus.
(setq list-buffers-directory (expand-file-name default-directory))
;; shell-dependent assignments.
(when (ring-empty-p comint-input-ring)
(let ((remote (file-remote-p default-directory))
(shell (or shell--start-prog ""))
(hsize (getenv "HISTSIZE"))
(hfile (getenv "HISTFILE")))
(when remote
;; `shell-snarf-envar' does not work trustworthy.
(setq hsize (shell-command-to-string "echo -n $HISTSIZE")
hfile (shell-command-to-string "echo -n $HISTFILE")))
(and (string-equal hfile "") (setq hfile nil))
(and (stringp hsize)
(integerp (setq hsize (string-to-number hsize)))
(> hsize 0)
(setq-local comint-input-ring-size hsize))
(setq comint-input-ring-file-name
(concat
remote
(or hfile
(cond ((string-equal shell "bash") "~/.bash_history")
((string-equal shell "ksh") "~/.sh_history")
((string-equal shell "zsh") "~/.zsh_history")
(t "~/.history")))))
(if (or (equal comint-input-ring-file-name "")
(equal (file-truename comint-input-ring-file-name)
(file-truename null-device)))
(setq comint-input-ring-file-name nil))
;; Arrange to write out the input ring on exit, if the shell doesn't
;; do this itself.
(if (and comint-input-ring-file-name
(string-match shell-dumb-shell-regexp shell))
(set-process-sentinel (get-buffer-process (current-buffer))
#'shell-write-history-on-exit))
(setq shell-dirstack-query
(cond ((string-equal shell "sh") "pwd")
((string-equal shell "ksh") "echo $PWD ~-")
;; Bypass any aliases. TODO all shells could use this.
((string-equal shell "bash") "command dirs")
((and (string-equal shell "bash.exe")
(eq system-type 'windows-nt)
(eq (w32-application-type (executable-find "bash.exe"))
'msys))
"command pwd -W")
((string-equal shell "zsh") "dirs -l")
(t "dirs")))
;; Bypass a bug in certain versions of bash.
(when (string-equal shell "bash")
(add-hook 'comint-preoutput-filter-functions
#'shell-filter-ctrl-a-ctrl-b nil t))
;; Skip extended history for zsh.
(when (string-equal shell "zsh")
(setq-local comint-input-ring-file-prefix
": [[:digit:]]+:[[:digit:]]+;")))
(comint-read-input-ring t)))
(defun shell-indirect-setup-hook ()
"Run `shell-indirect-setup-hook'."
(run-hooks 'shell-indirect-setup-hook))
(defun shell-apply-ansi-color (beg end face)
"Apply FACE as the ansi-color face for the text between BEG and END."
(when face
(put-text-property beg end 'ansi-color-face face)
(put-text-property beg end 'font-lock-face face)))
(defun shell-reapply-ansi-color ()
"Reapply ansi-color faces to the existing contents of the buffer."
(save-restriction
(widen)
(let* ((pos (point-min))
(end (or (next-single-property-change pos 'ansi-color-face)
(point-max)))
face)
(while end
(if (setq face (get-text-property pos 'ansi-color-face))
(put-text-property pos (or end (point-max))
'font-lock-face face))
(setq pos end
end (next-single-property-change pos 'ansi-color-face))))))
(defun shell-filter-ctrl-a-ctrl-b (string)
"Remove `^A' and `^B' characters from comint output.
Bash uses these characters as internal quoting characters in its
prompt. Due to a bug in some bash versions (including 2.03,
2.04, and 2.05b), they may erroneously show up when bash is
started with the `--noediting' option and Select Graphic
Rendition (SGR) control sequences (formerly known as ANSI escape
sequences) are used to color the prompt.
This function can be put on `comint-preoutput-filter-functions'."
(if (string-match "[\C-a\C-b]" string)
(replace-regexp-in-string "[\C-a\C-b]" "" string t t)
string))
(defun shell-filter-ring-bell (string)
"Call `ding' if STRING contains a \"^G\" character.
This function can be put on `comint-output-filter-functions'."
(when (string-search "\a" string)
(ding))
string)
(defun shell-write-history-on-exit (process event)
"Called when the shell process is stopped.
Writes the input history to a history file
`comint-input-ring-file-name' using `comint-write-input-ring'
and inserts a short message in the shell buffer.
This function is a sentinel watching the shell interpreter process.
Sentinels will always get the two parameters PROCESS and EVENT."
;; Write history.
(comint-write-input-ring)
(let ((buf (process-buffer process)))
(when (buffer-live-p buf)
(with-current-buffer buf
(insert (format "\nProcess %s %s\n" process event))))))
;;;###autoload
(defun shell (&optional buffer file-name)
"Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
Interactively, a prefix arg means to prompt for BUFFER.
If `default-directory' is a remote file name, it is also prompted
to change if called with a prefix arg.
If BUFFER exists but shell process is not running, make new shell.
If BUFFER exists and shell process is running, just switch to BUFFER.
Program used comes from variable `explicit-shell-file-name',
or (if that is nil) from the ESHELL environment variable,
or (if that is nil) from `shell-file-name'.
Non-interactively, it can also be specified via the FILE-NAME arg.
If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
it is given as initial input (but this may be lost, due to a timing
error, if the shell discards input when it starts up).
The buffer is put in Shell mode, giving commands for sending input
and controlling the subjobs of the shell. See `shell-mode'.
See also the variable `shell-prompt-pattern'.
\\<shell-mode-map>To specify a coding system for converting non-ASCII characters
in the input and output to the shell, use \\[universal-coding-system-argument]
before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
in the shell buffer, after you start the shell.
The default comes from `process-coding-system-alist' and
`default-process-coding-system'.
The shell file name (sans directories) is used to make a symbol name
such as `explicit-csh-args'. If that symbol is a variable,
its value is used as a list of arguments when invoking the shell.
Otherwise, one argument `-i' is passed to the shell.
Make the shell buffer the current buffer, and return it.
\(Type \\[describe-mode] in the shell buffer for a list of commands.)"
(interactive
(let* ((buffer
(and current-prefix-arg
(read-buffer "Shell buffer: "
;; If the current buffer is an inactive
;; shell buffer, use it as the default.
(if (and (eq major-mode 'shell-mode)
(null (get-buffer-process
(current-buffer))))
(buffer-name)
(generate-new-buffer-name "*shell*")))))
(buf (if (or buffer (not (derived-mode-p 'shell-mode))
(comint-check-proc (current-buffer)))
(get-buffer-create (or buffer "*shell*"))
;; If the current buffer is a dead shell buffer, use it.
(current-buffer))))
(with-current-buffer buf
(when (and buffer (file-remote-p default-directory))
;; It must be possible to declare a local default-directory.
(setq default-directory
(expand-file-name
(read-directory-name
"Default directory: " default-directory default-directory
t nil))))
(list
buffer
;; On remote hosts, the local `shell-file-name' might be useless.
(with-connection-local-variables
(when (and (file-remote-p default-directory)
(null explicit-shell-file-name)
(null (getenv "ESHELL")))
;; `expand-file-name' shall not add the MS Windows volume letter
;; (Bug#49229).
(replace-regexp-in-string
"^[[:alpha:]]:" ""
(file-local-name
(expand-file-name
(read-file-name "Remote shell path: " default-directory
shell-file-name t shell-file-name
#'file-remote-p))))))))))
(setq buffer (if (or buffer (not (derived-mode-p 'shell-mode))
(comint-check-proc (current-buffer)))
(get-buffer-create (or buffer "*shell*"))
;; If the current buffer is a dead shell buffer, use it.
(current-buffer)))
;; The buffer's window must be correctly set when we call comint
;; (so that comint sets the COLUMNS env var properly).
(with-suppressed-warnings ((obsolete display-comint-buffer-action))
(pop-to-buffer buffer display-comint-buffer-action))
(with-connection-local-variables
(when file-name
(setq-local explicit-shell-file-name file-name))
;; Rain or shine, BUFFER must be current by now.
(unless (comint-check-proc buffer)
(let* ((prog (or explicit-shell-file-name
(getenv "ESHELL") shell-file-name))
(name (file-name-nondirectory prog))
(startfile (concat "~/.emacs_" name))
(xargs-name (intern-soft (concat "explicit-" name "-args")))
(start-point (point)))
(unless (file-exists-p startfile)
(setq startfile (locate-user-emacs-file
(concat "init_" name ".sh"))))
(setq-local shell--start-prog (file-name-nondirectory prog))
(apply #'make-comint-in-buffer "shell" buffer prog
nil
(if (and xargs-name (boundp xargs-name))
(symbol-value xargs-name)
'("-i")))
(shell-mode)
(when (file-exists-p startfile)
;; Wait until the prompt has appeared.
(while (= start-point (point))
(sleep-for 0.1))
(shell-eval-command
(with-temp-buffer
(insert-file-contents startfile)
(buffer-string)))))))
(when shell-kill-buffer-on-exit
(let* ((buffer (current-buffer))
(process (get-buffer-process buffer))
(sentinel (process-sentinel process)))
(set-process-sentinel
process
(lambda (proc event)
(when sentinel
(funcall sentinel proc event))
(unless (buffer-live-p proc)
(kill-buffer buffer))))))
buffer)
;;; Directory tracking
;;
;; This code provides the shell mode input sentinel
;; SHELL-DIRECTORY-TRACKER
;; that tracks cd, pushd, and popd commands issued to the shell, and
;; changes the current directory of the shell buffer accordingly.
;;
;; This is basically a fragile hack. It has the following failings:
;; 1. It doesn't know about the cdpath shell variable.
;; 2. It cannot infallibly deal with command sequences, though it does well
;; with these and with ignoring commands forked in another shell with ()s.
;; 3. More generally, any complex command is going to throw it. Otherwise,
;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
;; that, there's no way to catch shell commands where cd's are buried
;; inside conditional expressions, aliases, and so forth.
;;
;; The whole approach is a crock. Shell aliases mess it up. File sourcing
;; messes it up. You run other processes under the shell; these each have
;; separate working directories, and some have commands for manipulating
;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
;; commands that do *not* affect the current w.d. at all, but look like they
;; do (e.g., the cd command in ftp). In shells that allow you job
;; control, you can switch between jobs, all having different w.d.'s. So
;; simply saying %3 can shift your w.d..
;;
;; The solution is to relax, not stress out about it, and settle for
;; a hack that works pretty well in typical circumstances. Remember
;; that a half-assed solution is more in keeping with the spirit of Unix,
;; anyway. Blech.