]> code.delx.au - gnu-emacs/blob - lisp/comint.el
Merge branch 'emacs-25' of /home/acm/emacs/emacs.git/emacs-25 into emacs-25
[gnu-emacs] / lisp / comint.el
1 ;;; comint.el --- general command interpreter in a window stuff -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1988, 1990, 1992-2016 Free Software Foundation, Inc.
4
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Simon Marshall <simon@gnu.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: processes
9 ;; Package: emacs
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This file defines a general command-interpreter-in-a-buffer package
29 ;; (comint mode). The idea is that you can build specific process-in-a-buffer
30 ;; modes on top of comint mode -- e.g., Lisp, shell, scheme, T, soar, ....
31 ;; This way, all these specific packages share a common base functionality,
32 ;; and a common set of bindings, which makes them easier to use (and
33 ;; saves code, implementation time, etc., etc.).
34
35 ;; Several packages are already defined using comint mode:
36 ;; - shell.el defines a shell-in-a-buffer mode.
37 ;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
38 ;;
39 ;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
40 ;; - The file tea.el tunes scheme and inferior-scheme modes for T.
41 ;; - The file soar.el tunes Lisp and inferior-lisp modes for Soar.
42 ;; - cmutex.el defines TeX and LaTeX modes that invoke TeX, LaTeX, BibTeX,
43 ;; previewers, and printers from within Emacs.
44 ;; - background.el allows csh-like job control inside Emacs.
45 ;; It is pretty easy to make new derived modes for other processes.
46
47 ;; For documentation on the functionality provided by Comint mode, and
48 ;; the hooks available for customizing it, see the comments below.
49 ;; For further information on the standard derived modes (shell,
50 ;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
51
52 ;; For hints on converting existing process modes (e.g., tex-mode,
53 ;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
54 ;; instead of shell-mode, see the notes at the end of this file.
55
56 \f
57 ;; Brief Command Documentation:
58 ;;============================================================================
59 ;; Comint Mode Commands: (common to all derived modes, like shell & cmulisp
60 ;; mode)
61 ;;
62 ;; M-p comint-previous-input Cycle backwards in input history
63 ;; M-n comint-next-input Cycle forwards
64 ;; M-r comint-history-isearch-backward-regexp Isearch input regexp backward
65 ;; M-C-l comint-show-output Show last batch of process output
66 ;; RET comint-send-input
67 ;; C-d comint-delchar-or-maybe-eof Delete char unless at end of buff
68 ;; C-c C-a comint-bol-or-process-mark First time, move point to bol;
69 ;; second time, move to process-mark.
70 ;; C-c C-u comint-kill-input ^u
71 ;; C-c C-w backward-kill-word ^w
72 ;; C-c C-c comint-interrupt-subjob ^c
73 ;; C-c C-z comint-stop-subjob ^z
74 ;; C-c C-\ comint-quit-subjob ^\
75 ;; C-c C-o comint-delete-output Delete last batch of process output
76 ;; C-c C-r comint-show-output Show last batch of process output
77 ;; C-c C-l comint-dynamic-list-input-ring List input history
78 ;;
79 ;; Not bound by default in comint-mode (some are in shell mode)
80 ;; comint-run Run a program under comint-mode
81 ;; send-invisible Read a line w/o echo, and send to proc
82 ;; comint-dynamic-complete-filename Complete filename at point.
83 ;; comint-dynamic-list-filename-completions List completions in help buffer.
84 ;; comint-replace-by-expanded-filename Expand and complete filename at point;
85 ;; replace with expanded/completed name.
86 ;; comint-replace-by-expanded-history Expand history at point;
87 ;; replace with expanded name.
88 ;; comint-magic-space Expand history and add (a) space(s).
89 ;; comint-kill-subjob No mercy.
90 ;; comint-show-maximum-output Show as much output as possible.
91 ;; comint-continue-subjob Send CONT signal to buffer's process
92 ;; group. Useful if you accidentally
93 ;; suspend your process (with C-c C-z).
94 ;; comint-get-next-from-history Fetch successive input history lines
95 ;; comint-accumulate Combine lines to send them together
96 ;; as input.
97 ;; comint-goto-process-mark Move point to where process-mark is.
98 ;; comint-set-process-mark Set process-mark to point.
99
100 ;; comint-mode-hook is the Comint mode hook. Basically for your keybindings.
101
102 ;;; Code:
103
104 (require 'ring)
105 (require 'ansi-color)
106 (require 'regexp-opt) ;For regexp-opt-charset.
107 \f
108 ;; Buffer Local Variables:
109 ;;============================================================================
110 ;; Comint mode buffer local variables:
111 ;; comint-prompt-regexp string comint-bol uses to match prompt
112 ;; comint-delimiter-argument-list list For delimiters and arguments
113 ;; comint-last-input-start marker Handy if inferior always echoes
114 ;; comint-last-input-end marker For comint-delete-output command
115 ;; comint-input-ring-size integer For the input history
116 ;; comint-input-ring ring mechanism
117 ;; comint-input-ring-index number ...
118 ;; comint-save-input-ring-index number ...
119 ;; comint-input-autoexpand symbol ...
120 ;; comint-input-ignoredups boolean ...
121 ;; comint-dynamic-complete-functions hook For the completion mechanism
122 ;; comint-completion-fignore list ...
123 ;; comint-file-name-chars string ...
124 ;; comint-file-name-quote-list list ...
125 ;; comint-get-old-input function Hooks for specific
126 ;; comint-input-filter-functions hook process-in-a-buffer
127 ;; comint-output-filter-functions hook function modes.
128 ;; comint-preoutput-filter-functions hook
129 ;; comint-input-filter function ...
130 ;; comint-input-sender function ...
131 ;; comint-eol-on-send boolean ...
132 ;; comint-process-echoes boolean ...
133 ;; comint-scroll-to-bottom-on-input symbol For scroll behavior
134 ;; comint-move-point-for-output symbol ...
135 ;; comint-scroll-show-maximum-output boolean ...
136 ;; comint-accum-marker maker For comint-accumulate
137 ;;
138 ;; Comint mode non-buffer local variables:
139 ;; comint-completion-addsuffix boolean/cons For file name
140 ;; comint-completion-autolist boolean completion behavior
141 ;; comint-completion-recexact boolean ...
142
143 (defgroup comint nil
144 "General command interpreter in a window stuff."
145 :group 'processes)
146
147 (defgroup comint-completion nil
148 "Completion facilities in comint."
149 :group 'comint)
150
151 ;; Unused.
152 ;;; (defgroup comint-source nil
153 ;;; "Source finding facilities in comint."
154 ;;; :prefix "comint-"
155 ;;; :group 'comint)
156
157 (defvar comint-prompt-regexp "^"
158 "Regexp to recognize prompts in the inferior process.
159 Defaults to \"^\", the null string at BOL.
160
161 This variable is only used if the variable
162 `comint-use-prompt-regexp' is non-nil.
163
164 Good choices:
165 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
166 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
167 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
168 kcl: \"^>+ *\"
169 shell: \"^[^#$%>\\n]*[#$%>] *\"
170 T: \"^>+ *\"
171
172 This is a good thing to set in mode hooks.")
173
174 (defcustom comint-prompt-read-only nil
175 "If non-nil, the comint prompt is read only.
176 The read only region includes the newline before the prompt.
177 This does not affect existing prompts.
178 Certain derived modes may override this option.
179
180 If you set this option to t, then the safe way to temporarily
181 override the read-only-ness of comint prompts is to call
182 `comint-kill-whole-line' or `comint-kill-region' with no
183 narrowing in effect. This way you will be certain that none of
184 the remaining prompts will be accidentally messed up. You may
185 wish to put something like the following in your init file:
186
187 \(add-hook \\='comint-mode-hook
188 (lambda ()
189 (define-key comint-mode-map [remap kill-region] \\='comint-kill-region)
190 (define-key comint-mode-map [remap kill-whole-line]
191 \\='comint-kill-whole-line)))
192
193 If you sometimes use comint-mode on text-only terminals or with `emacs -nw',
194 you might wish to use another binding for `comint-kill-whole-line'."
195 :type 'boolean
196 :group 'comint
197 :version "22.1")
198
199 (defvar comint-delimiter-argument-list ()
200 "List of characters to recognize as separate arguments in input.
201 Strings comprising a character in this list will separate the arguments
202 surrounding them, and also be regarded as arguments in their own right (unlike
203 whitespace). See `comint-arguments'.
204 Defaults to the empty list.
205
206 For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?;).
207
208 This is a good thing to set in mode hooks.")
209
210 (defcustom comint-input-autoexpand nil
211 "If non-nil, expand input command history references on completion.
212 This mirrors the optional behavior of tcsh (its autoexpand and histlist).
213
214 If the value is `input', then the expansion is seen on input.
215 If the value is `history', then the expansion is only when inserting
216 into the buffer's input ring. See also `comint-magic-space' and
217 `completion-at-point'.
218
219 This variable is buffer-local."
220 :type '(choice (const :tag "off" nil)
221 (const input)
222 (const history)
223 (other :tag "on" t))
224 :group 'comint)
225
226 (defface comint-highlight-input '((t (:weight bold)))
227 "Face to use to highlight user input."
228 :group 'comint)
229
230 (defface comint-highlight-prompt
231 '((t :inherit minibuffer-prompt))
232 "Face to use to highlight prompts."
233 :group 'comint)
234
235 (defcustom comint-input-ignoredups nil
236 "If non-nil, don't add input matching the last on the input ring.
237 This mirrors the optional behavior of bash.
238
239 This variable is buffer-local."
240 :type 'boolean
241 :group 'comint)
242
243 (defcustom comint-input-ring-file-name nil
244 "If non-nil, name of the file to read/write input history.
245 See also `comint-read-input-ring' and `comint-write-input-ring'.
246 `comint-mode' makes this a buffer-local variable. You probably want
247 to set this in a mode hook, rather than customize the default value."
248 :type '(choice (const :tag "nil" nil)
249 file)
250 :group 'comint)
251
252 (defcustom comint-scroll-to-bottom-on-input nil
253 "Controls whether input to interpreter causes window to scroll.
254 If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
255 If `this', scroll only the selected window.
256
257 The default is nil.
258
259 See `comint-preinput-scroll-to-bottom'. This variable is buffer-local."
260 :type '(choice (const :tag "off" nil)
261 (const t)
262 (const all)
263 (const this))
264 :group 'comint)
265
266 (defcustom comint-move-point-for-output nil
267 "Controls whether interpreter output moves point to the end of the output.
268 If nil, then output never moves point to the output.
269 (If the output occurs at point, it is inserted before point.)
270 If t or `all', move point in all windows showing the buffer.
271 If `this', move point only the selected window.
272 If `others', move point only in other windows, not in the selected window.
273
274 The default is nil.
275
276 See the variable `comint-scroll-show-maximum-output' and the function
277 `comint-postoutput-scroll-to-bottom'.
278 This variable is buffer-local in all Comint buffers."
279 :type '(choice (const :tag "off" nil)
280 (const t)
281 (const all)
282 (const this)
283 (const others))
284 :group 'comint)
285
286 (defvaralias 'comint-scroll-to-bottom-on-output 'comint-move-point-for-output)
287
288 (defcustom comint-scroll-show-maximum-output t
289 "Controls how to scroll due to interpreter output.
290 This variable applies when point is at the end of the buffer
291 \(either because it was originally there, or because
292 `comint-move-point-for-output' said to move it there)
293 and output from the subprocess is inserted.
294
295 Non-nil means scroll so that the window is full of text
296 and point is on the last line. A value of nil
297 means don't do anything special--scroll normally.
298
299 See also the variable `comint-move-point-for-output' and the function
300 `comint-postoutput-scroll-to-bottom'.
301 This variable is buffer-local in all Comint buffers."
302 :type 'boolean
303 :group 'comint)
304
305 (defcustom comint-buffer-maximum-size 1024
306 "The maximum size in lines for Comint buffers.
307 Comint buffers are truncated from the top to be no greater than this number, if
308 the function `comint-truncate-buffer' is on `comint-output-filter-functions'."
309 :type 'integer
310 :group 'comint)
311
312 (defcustom comint-input-ring-size 500
313 "Size of the input history ring in `comint-mode'."
314 :type 'integer
315 :group 'comint
316 :version "23.2")
317
318 (defvar comint-input-ring-separator "\n"
319 "Separator between commands in the history file.")
320
321 (defvar comint-input-history-ignore "^#"
322 "Regexp for history entries that should be ignored when Comint initializes.")
323
324 (defcustom comint-process-echoes nil
325 "If non-nil, assume that the subprocess echoes any input.
326 If so, delete one copy of the input so that only one copy eventually
327 appears in the buffer.
328
329 This variable is buffer-local."
330 :type 'boolean
331 :group 'comint)
332
333 ;; AIX puts the name of the person being su'd to in front of the prompt.
334 ;; kinit prints a prompt like `Password for devnull@GNU.ORG: '.
335 ;; ksu prints a prompt like `Kerberos password for devnull/root@GNU.ORG: '.
336 ;; ssh-add prints a prompt like `Enter passphrase: '.
337 ;; plink prints a prompt like `Passphrase for key "root@GNU.ORG": '.
338 ;; Ubuntu's sudo prompts like `[sudo] password for user:'
339 ;; Some implementations of passwd use "Password (again)" as the 2nd prompt.
340 ;; Something called "perforce" uses "Enter password:".
341 ;; See M-x comint-testsuite--test-comint-password-prompt-regexp.
342 (defcustom comint-password-prompt-regexp
343 (concat
344 "\\(^ *\\|"
345 (regexp-opt
346 '("Enter" "enter" "Enter same" "enter same" "Enter the" "enter the"
347 "Old" "old" "New" "new" "'s" "login"
348 "Kerberos" "CVS" "UNIX" " SMB" "LDAP" "[sudo]" "Repeat" "Bad") t)
349 " +\\)"
350 "\\(?:" (regexp-opt password-word-equivalents) "\\|Response\\)"
351 "\\(?:\\(?:, try\\)? *again\\| (empty for no passphrase)\\| (again)\\)?\
352 \\(?: for [^::៖]+\\)?[::៖]\\s *\\'")
353 "Regexp matching prompts for passwords in the inferior process.
354 This is used by `comint-watch-for-password-prompt'."
355 :version "24.4"
356 :type 'regexp
357 :group 'comint)
358
359 ;; Here are the per-interpreter hooks.
360 (defvar comint-get-old-input (function comint-get-old-input-default)
361 "Function that returns old text in Comint mode.
362 This function is called when return is typed while the point is in old
363 text. It returns the text to be submitted as process input. The
364 default is `comint-get-old-input-default', which either grabs the
365 current input field or grabs the current line and strips off leading
366 text matching `comint-prompt-regexp', depending on the value of
367 `comint-use-prompt-regexp'.")
368
369 (defvar comint-dynamic-complete-functions
370 '(comint-c-a-p-replace-by-expanded-history comint-filename-completion)
371 "List of functions called to perform completion.
372 Works like `completion-at-point-functions'.
373 See also `completion-at-point'.
374
375 This is a good thing to set in mode hooks.")
376
377 (defvar comint-input-filter
378 (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
379 "Predicate for filtering additions to input history.
380 Takes one argument, the input. If non-nil, the input may be saved on the input
381 history list. Default is to save anything that isn't all whitespace.")
382
383 (defvar comint-input-filter-functions '()
384 "Abnormal hook run before input is sent to the process.
385 These functions get one argument, a string containing the text to send.")
386
387 ;;;###autoload
388 (defvar comint-output-filter-functions '(ansi-color-process-output comint-postoutput-scroll-to-bottom comint-watch-for-password-prompt)
389 "Functions to call after output is inserted into the buffer.
390 One possible function is `comint-postoutput-scroll-to-bottom'.
391 These functions get one argument, a string containing the text as originally
392 inserted. Note that this might not be the same as the buffer contents between
393 `comint-last-output-start' and the buffer's `process-mark', if other filter
394 functions have already modified the buffer.
395
396 See also `comint-preoutput-filter-functions'.
397
398 You can use `add-hook' to add functions to this list
399 either globally or locally.")
400
401 (defvar comint-input-sender-no-newline nil
402 "Non-nil directs the `comint-input-sender' function not to send a newline.")
403
404 (defvar comint-input-sender (function comint-simple-send)
405 "Function to actually send to PROCESS the STRING submitted by user.
406 Usually this is just `comint-simple-send', but if your mode needs to
407 massage the input string, put a different function here.
408 `comint-simple-send' just sends the string plus a newline.
409 \(If `comint-input-sender-no-newline' is non-nil, it omits the newline.)
410 This is called from the user command `comint-send-input'.")
411
412 (defcustom comint-eol-on-send t
413 "Non-nil means go to the end of the line before sending input.
414 See `comint-send-input'."
415 :type 'boolean
416 :group 'comint)
417
418 (define-obsolete-variable-alias 'comint-use-prompt-regexp-instead-of-fields
419 'comint-use-prompt-regexp "22.1")
420
421 ;; Note: If it is decided to purge comint-prompt-regexp from the source
422 ;; entirely, searching for uses of this variable will help to identify
423 ;; places that need attention.
424 (defcustom comint-use-prompt-regexp nil
425 "If non-nil, use `comint-prompt-regexp' to recognize prompts.
426 If nil, then program output and user-input are given different `field'
427 properties, which Emacs commands can use to distinguish them (in
428 particular, common movement commands such as `beginning-of-line'
429 respect field boundaries in a natural way)."
430 :type 'boolean
431 :group 'comint)
432
433 (defcustom comint-mode-hook nil
434 "Hook run upon entry to `comint-mode'.
435 This is run before the process is cranked up."
436 :type 'hook
437 :group 'comint)
438
439 (defcustom comint-exec-hook '()
440 "Hook run each time a process is exec'd by `comint-exec'.
441 This is called after the process is cranked up. It is useful for things that
442 must be done each time a process is executed in a Comint mode buffer (e.g.,
443 `(process-kill-without-query)'). In contrast, the `comint-mode-hook' is only
444 executed once when the buffer is created."
445 :type 'hook
446 :group 'comint)
447
448 (defvar comint-mode-map
449 (let ((map (make-sparse-keymap)))
450 ;; Keys:
451 (define-key map "\ep" 'comint-previous-input)
452 (define-key map "\en" 'comint-next-input)
453 (define-key map [C-up] 'comint-previous-input)
454 (define-key map [C-down] 'comint-next-input)
455 (define-key map "\er" 'comint-history-isearch-backward-regexp)
456 (define-key map [?\C-c ?\M-r] 'comint-previous-matching-input-from-input)
457 (define-key map [?\C-c ?\M-s] 'comint-next-matching-input-from-input)
458 (define-key map "\e\C-l" 'comint-show-output)
459 (define-key map "\C-m" 'comint-send-input)
460 (define-key map "\C-d" 'comint-delchar-or-maybe-eof)
461 ;; The following two are standardly bound to delete-forward-char,
462 ;; but they should never do EOF, just delete.
463 (define-key map [delete] 'delete-forward-char)
464 (define-key map [kp-delete] 'delete-forward-char)
465 (define-key map "\C-c " 'comint-accumulate)
466 (define-key map "\C-c\C-x" 'comint-get-next-from-history)
467 (define-key map "\C-c\C-a" 'comint-bol-or-process-mark)
468 (define-key map "\C-c\C-u" 'comint-kill-input)
469 (define-key map "\C-c\C-w" 'backward-kill-word)
470 (define-key map "\C-c\C-c" 'comint-interrupt-subjob)
471 (define-key map "\C-c\C-z" 'comint-stop-subjob)
472 (define-key map "\C-c\C-\\" 'comint-quit-subjob)
473 (define-key map "\C-c\C-m" 'comint-copy-old-input)
474 (define-key map "\C-c\C-o" 'comint-delete-output)
475 (define-key map "\C-c\M-o" 'comint-clear-buffer)
476 (define-key map "\C-c\C-r" 'comint-show-output)
477 (define-key map "\C-c\C-e" 'comint-show-maximum-output)
478 (define-key map "\C-c\C-l" 'comint-dynamic-list-input-ring)
479 (define-key map "\C-c\C-n" 'comint-next-prompt)
480 (define-key map "\C-c\C-p" 'comint-previous-prompt)
481 (define-key map "\C-c\C-d" 'comint-send-eof)
482 (define-key map "\C-c\C-s" 'comint-write-output)
483 (define-key map "\C-c." 'comint-insert-previous-argument)
484 ;; Mouse Buttons:
485 (define-key map [mouse-2] 'comint-insert-input)
486 ;; Menu bars:
487 ;; completion:
488 (define-key map [menu-bar completion]
489 (cons "Complete" (make-sparse-keymap "Complete")))
490 (define-key map [menu-bar completion complete-expand]
491 '("Expand File Name" . comint-replace-by-expanded-filename))
492 (define-key map [menu-bar completion complete-listing]
493 '("File Completion Listing" . comint-dynamic-list-filename-completions))
494 (define-key map [menu-bar completion complete-file]
495 '("Complete File Name" . comint-dynamic-complete-filename))
496 (define-key map [menu-bar completion complete]
497 '("Complete at Point" . completion-at-point))
498 ;; Input history:
499 (define-key map [menu-bar inout]
500 (cons "In/Out" (make-sparse-keymap "In/Out")))
501 (define-key map [menu-bar inout delete-output]
502 '("Delete Current Output Group" . comint-delete-output))
503 (define-key map [menu-bar inout append-output-to-file]
504 '("Append Current Output Group to File" . comint-append-output-to-file))
505 (define-key map [menu-bar inout write-output]
506 '("Write Current Output Group to File" . comint-write-output))
507 (define-key map [menu-bar inout next-prompt]
508 '("Forward Output Group" . comint-next-prompt))
509 (define-key map [menu-bar inout previous-prompt]
510 '("Backward Output Group" . comint-previous-prompt))
511 (define-key map [menu-bar inout show-maximum-output]
512 '("Show Maximum Output" . comint-show-maximum-output))
513 (define-key map [menu-bar inout show-output]
514 '("Show Current Output Group" . comint-show-output))
515 (define-key map [menu-bar inout kill-input]
516 '("Kill Current Input" . comint-kill-input))
517 (define-key map [menu-bar inout copy-input]
518 '("Copy Old Input" . comint-copy-old-input))
519 (define-key map [menu-bar inout history-isearch-backward-regexp]
520 '("Isearch Input Regexp Backward..." . comint-history-isearch-backward-regexp))
521 (define-key map [menu-bar inout history-isearch-backward]
522 '("Isearch Input String Backward..." . comint-history-isearch-backward))
523 (define-key map [menu-bar inout forward-matching-history]
524 '("Forward Matching Input..." . comint-forward-matching-input))
525 (define-key map [menu-bar inout backward-matching-history]
526 '("Backward Matching Input..." . comint-backward-matching-input))
527 (define-key map [menu-bar inout next-matching-history]
528 '("Next Matching Input..." . comint-next-matching-input))
529 (define-key map [menu-bar inout previous-matching-history]
530 '("Previous Matching Input..." . comint-previous-matching-input))
531 (define-key map [menu-bar inout next-matching-history-from-input]
532 '("Next Matching Current Input" . comint-next-matching-input-from-input))
533 (define-key map [menu-bar inout previous-matching-history-from-input]
534 '("Previous Matching Current Input" . comint-previous-matching-input-from-input))
535 (define-key map [menu-bar inout next-history]
536 '("Next Input" . comint-next-input))
537 (define-key map [menu-bar inout previous-history]
538 '("Previous Input" . comint-previous-input))
539 (define-key map [menu-bar inout list-history]
540 '("List Input History" . comint-dynamic-list-input-ring))
541 (define-key map [menu-bar inout expand-history]
542 '("Expand History Before Point" . comint-replace-by-expanded-history))
543 ;; Signals
544 (let ((signals-map (make-sparse-keymap "Signals")))
545 (define-key map [menu-bar signals] (cons "Signals" signals-map))
546 (define-key signals-map [eof] '("EOF" . comint-send-eof))
547 (define-key signals-map [kill] '("KILL" . comint-kill-subjob))
548 (define-key signals-map [quit] '("QUIT" . comint-quit-subjob))
549 (define-key signals-map [cont] '("CONT" . comint-continue-subjob))
550 (define-key signals-map [stop] '("STOP" . comint-stop-subjob))
551 (define-key signals-map [break] '("BREAK" . comint-interrupt-subjob)))
552 ;; Put them in the menu bar:
553 (setq menu-bar-final-items (append '(completion inout signals)
554 menu-bar-final-items))
555 map))
556
557 ;; Fixme: Is this still relevant?
558 (defvar comint-ptyp t
559 "Non-nil if communications via pty; false if by pipe. Buffer local.
560 This is to work around a bug in Emacs process signaling.")
561
562 (defvar comint-input-ring nil)
563 (defvar comint-last-input-start nil)
564 (defvar comint-last-input-end nil)
565 (defvar comint-last-output-start nil)
566 (defvar comint-input-ring-index nil
567 "Index of last matched history element.")
568 (defvar comint-matching-input-from-input-string ""
569 "Input previously used to match input history.")
570 (defvar comint-save-input-ring-index nil
571 "Last input ring index which you copied.
572 This is to support the command \\[comint-get-next-from-history].")
573
574 (defvar comint-accum-marker nil
575 "Non-nil if you are accumulating input lines to send as input together.
576 The command \\[comint-accumulate] sets this.")
577
578 (defvar comint-stored-incomplete-input nil
579 "Stored input for history cycling.")
580
581 (put 'comint-replace-by-expanded-history 'menu-enable 'comint-input-autoexpand)
582 (put 'comint-input-ring 'permanent-local t)
583 (put 'comint-input-ring-index 'permanent-local t)
584 (put 'comint-save-input-ring-index 'permanent-local t)
585 (put 'comint-input-autoexpand 'permanent-local t)
586 (put 'comint-input-filter-functions 'permanent-local t)
587 (put 'comint-output-filter-functions 'permanent-local t)
588 (put 'comint-preoutput-filter-functions 'permanent-local t)
589 (put 'comint-scroll-to-bottom-on-input 'permanent-local t)
590 (put 'comint-move-point-for-output 'permanent-local t)
591 (put 'comint-scroll-show-maximum-output 'permanent-local t)
592 (put 'comint-ptyp 'permanent-local t)
593
594 (put 'comint-mode 'mode-class 'special)
595
596 (define-derived-mode comint-mode fundamental-mode "Comint"
597 "Major mode for interacting with an inferior interpreter.
598 Interpreter name is same as buffer name, sans the asterisks.
599 Return at end of buffer sends line as input.
600 Return not at end copies rest of line to end and sends it.
601 Setting variable `comint-eol-on-send' means jump to the end of the line
602 before submitting new input.
603
604 This mode is customized to create major modes such as Inferior Lisp
605 mode, Shell mode, etc. This can be done by setting the hooks
606 `comint-input-filter-functions', `comint-input-filter', `comint-input-sender'
607 and `comint-get-old-input' to appropriate functions, and the variable
608 `comint-prompt-regexp' to the appropriate regular expression.
609
610 The mode maintains an input history of size `comint-input-ring-size'.
611 You can access this with the commands \\[comint-next-input],
612 \\[comint-previous-input], and \\[comint-dynamic-list-input-ring].
613 Input ring history expansion can be achieved with the commands
614 \\[comint-replace-by-expanded-history] or \\[comint-magic-space].
615 Input ring expansion is controlled by the variable `comint-input-autoexpand',
616 and addition is controlled by the variable `comint-input-ignoredups'.
617
618 Commands with no default key bindings include `send-invisible',
619 `completion-at-point', `comint-dynamic-list-filename-completions', and
620 `comint-magic-space'.
621
622 Input to, and output from, the subprocess can cause the window to scroll to
623 the end of the buffer. See variables `comint-output-filter-functions',
624 `comint-preoutput-filter-functions', `comint-scroll-to-bottom-on-input',
625 and `comint-move-point-for-output'.
626
627 If you accidentally suspend your process, use \\[comint-continue-subjob]
628 to continue it.
629
630 \\{comint-mode-map}
631
632 Entry to this mode runs the hooks on `comint-mode-hook'."
633 (setq mode-line-process '(":%s"))
634 (setq-local window-point-insertion-type t)
635 (setq-local comint-last-input-start (point-min-marker))
636 (setq-local comint-last-input-end (point-min-marker))
637 (setq-local comint-last-output-start (make-marker))
638 (make-local-variable 'comint-last-prompt)
639 (make-local-variable 'comint-prompt-regexp) ; Don't set; default
640 (make-local-variable 'comint-input-ring-size) ; ...to global val.
641 (make-local-variable 'comint-input-ring)
642 (make-local-variable 'comint-input-ring-file-name)
643 (or (and (boundp 'comint-input-ring) comint-input-ring)
644 (setq comint-input-ring (make-ring comint-input-ring-size)))
645 (make-local-variable 'comint-input-ring-index)
646 (make-local-variable 'comint-save-input-ring-index)
647 (or (and (boundp 'comint-input-ring-index) comint-input-ring-index)
648 (setq comint-input-ring-index nil))
649 (or (and (boundp 'comint-save-input-ring-index) comint-save-input-ring-index)
650 (setq comint-save-input-ring-index nil))
651 (make-local-variable 'comint-matching-input-from-input-string)
652 (make-local-variable 'comint-input-autoexpand)
653 (make-local-variable 'comint-input-ignoredups)
654 (make-local-variable 'comint-delimiter-argument-list)
655 (make-local-variable 'comint-completion-fignore)
656 (make-local-variable 'comint-get-old-input)
657 (make-local-variable 'comint-input-filter)
658 (make-local-variable 'comint-input-sender)
659 (make-local-variable 'comint-eol-on-send)
660 (make-local-variable 'comint-scroll-to-bottom-on-input)
661 (make-local-variable 'comint-move-point-for-output)
662 (make-local-variable 'comint-scroll-show-maximum-output)
663 (make-local-variable 'comint-stored-incomplete-input)
664 ;; Following disabled because it seems to break the case when
665 ;; comint-scroll-show-maximum-output is nil, and no-one can remember
666 ;; what the original problem was. If there are problems with point
667 ;; not going to the end, consider re-enabling this.
668 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00827.html
669 ;;
670 ;; This makes it really work to keep point at the bottom.
671 ;; (make-local-variable 'scroll-conservatively)
672 ;; (setq scroll-conservatively 10000)
673 (add-hook 'pre-command-hook 'comint-preinput-scroll-to-bottom t t)
674 (make-local-variable 'comint-ptyp)
675 (make-local-variable 'comint-process-echoes)
676 (make-local-variable 'comint-file-name-chars)
677 (make-local-variable 'comint-file-name-quote-list)
678 ;; dir tracking on remote files
679 (setq-local comint-file-name-prefix
680 (or (file-remote-p default-directory) ""))
681 (setq-local comint-accum-marker (make-marker))
682 (setq-local font-lock-defaults '(nil t))
683 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
684 (add-hook 'isearch-mode-hook 'comint-history-isearch-setup nil t)
685 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t)
686 ;; This behavior is not useful in comint buffers, and is annoying
687 (setq-local next-line-add-newlines nil))
688
689 (defun comint-check-proc (buffer)
690 "Return non-nil if there is a living process associated w/buffer BUFFER.
691 Living means the status is `open', `run', or `stop'.
692 BUFFER can be either a buffer or the name of one."
693 (let ((proc (get-buffer-process buffer)))
694 (and proc (memq (process-status proc) '(open run stop)))))
695
696 ;;;###autoload
697 (defun make-comint-in-buffer (name buffer program &optional startfile &rest switches)
698 "Make a Comint process NAME in BUFFER, running PROGRAM.
699 If BUFFER is nil, it defaults to NAME surrounded by `*'s.
700 If there is a running process in BUFFER, it is not restarted.
701
702 PROGRAM should be one of the following:
703 - a string, denoting an executable program to create via
704 `start-file-process'
705 - a cons pair of the form (HOST . SERVICE), denoting a TCP
706 connection to be opened via `open-network-stream'
707 - nil, denoting a newly-allocated pty.
708
709 Optional fourth arg STARTFILE is the name of a file, whose
710 contents are sent to the process as its initial input.
711
712 If PROGRAM is a string, any more args are arguments to PROGRAM.
713
714 Return the (possibly newly created) process buffer."
715 (or (fboundp 'start-file-process)
716 (error "Multi-processing is not supported for this system"))
717 (setq buffer (get-buffer-create (or buffer (concat "*" name "*"))))
718 ;; If no process, or nuked process, crank up a new one and put buffer in
719 ;; comint mode. Otherwise, leave buffer and existing process alone.
720 (unless (comint-check-proc buffer)
721 (with-current-buffer buffer
722 (unless (derived-mode-p 'comint-mode)
723 (comint-mode))) ; Install local vars, mode, keymap, ...
724 (comint-exec buffer name program startfile switches))
725 buffer)
726
727 ;;;###autoload
728 (defun make-comint (name program &optional startfile &rest switches)
729 "Make a Comint process NAME in a buffer, running PROGRAM.
730 The name of the buffer is made by surrounding NAME with `*'s.
731 PROGRAM should be either a string denoting an executable program to create
732 via `start-file-process', or a cons pair of the form (HOST . SERVICE) denoting
733 a TCP connection to be opened via `open-network-stream'. If there is already
734 a running process in that buffer, it is not restarted. Optional third arg
735 STARTFILE is the name of a file, whose contents are sent to the
736 process as its initial input.
737
738 If PROGRAM is a string, any more args are arguments to PROGRAM.
739
740 Returns the (possibly newly created) process buffer."
741 (apply #'make-comint-in-buffer name nil program startfile switches))
742
743 ;;;###autoload
744 (defun comint-run (program)
745 "Run PROGRAM in a Comint buffer and switch to it.
746 The buffer name is made by surrounding the file name of PROGRAM with `*'s.
747 The file name is used to make a symbol name, such as `comint-sh-hook', and any
748 hooks on this symbol are run in the buffer.
749 See `make-comint' and `comint-exec'."
750 (declare (interactive-only make-comint))
751 (interactive "sRun program: ")
752 (let ((name (file-name-nondirectory program)))
753 (switch-to-buffer (make-comint name program))
754 (run-hooks (intern-soft (concat "comint-" name "-hook")))))
755
756 (defun comint-exec (buffer name command startfile switches)
757 "Start up a process named NAME in buffer BUFFER for Comint modes.
758 Runs the given COMMAND with SWITCHES, and initial input from STARTFILE.
759
760 COMMAND should be one of the following:
761 - a string, denoting an executable program to create via
762 `start-file-process'
763 - a cons pair of the form (HOST . SERVICE), denoting a TCP
764 connection to be opened via `open-network-stream'
765 - nil, denoting a newly-allocated pty.
766
767 This function blasts any old process running in the buffer, and
768 does not set the buffer mode. You can use this to cheaply run a
769 series of processes in the same Comint buffer. The hook
770 `comint-exec-hook' is run after each exec."
771 (with-current-buffer buffer
772 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
773 (if proc (delete-process proc)))
774 ;; Crank up a new process
775 (let ((proc
776 (if (consp command)
777 (open-network-stream name buffer (car command) (cdr command))
778 (comint-exec-1 name buffer command switches))))
779 (set-process-filter proc 'comint-output-filter)
780 (setq-local comint-ptyp process-connection-type) ; t if pty, nil if pipe.
781 ;; Jump to the end, and set the process mark.
782 (goto-char (point-max))
783 (set-marker (process-mark proc) (point))
784 ;; Feed it the startfile.
785 (cond (startfile
786 ;;This is guaranteed to wait long enough
787 ;;but has bad results if the comint does not prompt at all
788 ;; (while (= size (buffer-size))
789 ;; (sleep-for 1))
790 ;;I hope 1 second is enough!
791 (sleep-for 1)
792 (goto-char (point-max))
793 (insert-file-contents startfile)
794 (setq startfile (buffer-substring (point) (point-max)))
795 (delete-region (point) (point-max))
796 (comint-send-string proc startfile)))
797 (run-hooks 'comint-exec-hook)
798 buffer)))
799
800 ;; This auxiliary function cranks up the process for comint-exec in
801 ;; the appropriate environment.
802
803 (defun comint-exec-1 (name buffer command switches)
804 (let ((process-environment
805 (nconc
806 ;; If using termcap, we specify `emacs' as the terminal type
807 ;; because that lets us specify a width.
808 ;; If using terminfo, we specify `dumb' because that is
809 ;; a defined terminal type. `emacs' is not a defined terminal type
810 ;; and there is no way for us to define it here.
811 ;; Some programs that use terminfo get very confused
812 ;; if TERM is not a valid terminal type.
813 ;; ;; There is similar code in compile.el.
814 (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
815 (list "TERM=dumb" "TERMCAP="
816 (format "COLUMNS=%d" (window-width)))
817 (list "TERM=emacs"
818 (format "TERMCAP=emacs:co#%d:tc=unknown:" (window-width))))
819
820 ;; This hack is for backward compatibility with Bash 4.3 and
821 ;; earlier. It can break common uses of 'configure', so
822 ;; remove it once Bash 4.4 or later is common.
823 (unless (getenv "EMACS")
824 (list "EMACS=t"))
825
826 (list (format "INSIDE_EMACS=%s,comint" emacs-version))
827 process-environment))
828 (default-directory
829 (if (file-accessible-directory-p default-directory)
830 default-directory
831 "/"))
832 proc decoding encoding changed)
833 (let ((exec-path (if (and command (file-name-directory command))
834 ;; If the command has slashes, make sure we
835 ;; first look relative to the current directory.
836 (cons default-directory exec-path) exec-path)))
837 (setq proc (apply 'start-file-process name buffer command switches)))
838 ;; Some file name handler cannot start a process, fe ange-ftp.
839 (unless (processp proc) (error "No process started"))
840 (let ((coding-systems (process-coding-system proc)))
841 (setq decoding (car coding-systems)
842 encoding (cdr coding-systems)))
843 ;; Even if start-file-process left the coding system for encoding data
844 ;; sent from the process undecided, we had better use the same one
845 ;; as what we use for decoding. But, we should suppress EOL
846 ;; conversion.
847 (if (and decoding (not encoding))
848 (setq encoding (coding-system-change-eol-conversion decoding 'unix)
849 changed t))
850 (if changed
851 (set-process-coding-system proc decoding encoding))
852 proc))
853
854 (defun comint-insert-input (event)
855 "In a Comint buffer, set the current input to the previous input at point.
856 If there is no previous input at point, run the command specified
857 by the global keymap (usually `mouse-yank-at-click')."
858 (interactive "e")
859 ;; Don't set the mouse here, since it may otherwise change the behavior
860 ;; of the command on which we fallback if there's no field at point.
861 ;; (mouse-set-point event)
862 (let ((pos (posn-point (event-end event)))
863 field input)
864 (with-selected-window (posn-window (event-end event))
865 ;; If pos is at the very end of a field, the mouse-click was
866 ;; probably outside (to the right) of the field.
867 (and (< pos (field-end pos))
868 (< (field-end pos) (point-max))
869 (progn (setq field (field-at-pos pos))
870 (setq input (field-string-no-properties pos)))))
871 (if (or (null input) (null comint-accum-marker) field)
872 ;; Fall back to the global definition if (i) the selected
873 ;; buffer is not a comint buffer (which can happen if a
874 ;; non-comint window was selected and we clicked in a comint
875 ;; window), or (ii) there is no input at POS.
876 (let* ((keys (this-command-keys))
877 (last-key (and (vectorp keys) (aref keys (1- (length keys)))))
878 (fun (and last-key (lookup-key global-map (vector last-key)))))
879 (and fun (not (eq fun 'comint-insert-input))
880 (call-interactively fun)))
881 (with-selected-window (posn-window (event-end event))
882 ;; Otherwise, insert the previous input.
883 (goto-char (point-max))
884 ;; First delete any old unsent input at the end
885 (delete-region
886 (or (marker-position comint-accum-marker)
887 (process-mark (get-buffer-process (current-buffer))))
888 (point))
889 ;; Insert the input at point
890 (insert input)))))
891 \f
892 ;; Input history processing in a buffer
893 ;; ===========================================================================
894 ;; Useful input history functions, courtesy of the Ergo group.
895
896 ;; Eleven commands:
897 ;; comint-dynamic-list-input-ring List history in help buffer.
898 ;; comint-previous-input Previous input...
899 ;; comint-previous-matching-input ...matching a string.
900 ;; comint-previous-matching-input-from-input ... matching the current input.
901 ;; comint-next-input Next input...
902 ;; comint-next-matching-input ...matching a string.
903 ;; comint-next-matching-input-from-input ... matching the current input.
904 ;; comint-backward-matching-input Backwards input...
905 ;; comint-forward-matching-input ...matching a string.
906 ;; comint-replace-by-expanded-history Expand history at point;
907 ;; replace with expanded history.
908 ;; comint-magic-space Expand history and insert space.
909 ;;
910 ;; Three functions:
911 ;; comint-read-input-ring Read into comint-input-ring...
912 ;; comint-write-input-ring Write to comint-input-ring-file-name.
913 ;; comint-replace-by-expanded-history-before-point Workhorse function.
914
915 (defun comint-read-input-ring (&optional silent)
916 "Set the buffer's `comint-input-ring' from a history file.
917 The name of the file is given by the variable `comint-input-ring-file-name'.
918 The history ring is of size `comint-input-ring-size', regardless of file size.
919 If `comint-input-ring-file-name' is nil this function does nothing.
920
921 If the optional argument SILENT is non-nil, we say nothing about a
922 failure to read the history file.
923
924 This function is useful for major mode commands and mode hooks.
925
926 The commands stored in the history file are separated by the
927 `comint-input-ring-separator', and entries that match
928 `comint-input-history-ignore' are ignored. The most recent command
929 comes last.
930
931 See also `comint-input-ignoredups' and `comint-write-input-ring'."
932 (cond ((or (null comint-input-ring-file-name)
933 (equal comint-input-ring-file-name ""))
934 nil)
935 ((not (file-readable-p comint-input-ring-file-name))
936 (or silent
937 (message "Cannot read history file %s"
938 comint-input-ring-file-name)))
939 (t
940 (let* ((file comint-input-ring-file-name)
941 (count 0)
942 ;; Some users set HISTSIZE or `comint-input-ring-size'
943 ;; to huge numbers. Don't allocate a huge ring right
944 ;; away; there might not be that much history.
945 (ring-size (min 1500 comint-input-ring-size))
946 (ring (make-ring ring-size)))
947 (with-temp-buffer
948 (insert-file-contents file)
949 ;; Save restriction in case file is already visited...
950 ;; Watch for those date stamps in history files!
951 (goto-char (point-max))
952 (let (start end history)
953 (while (and (< count comint-input-ring-size)
954 (re-search-backward comint-input-ring-separator
955 nil t)
956 (setq end (match-beginning 0)))
957 (setq start
958 (if (re-search-backward comint-input-ring-separator
959 nil t)
960 (match-end 0)
961 (point-min)))
962 (setq history (buffer-substring start end))
963 (goto-char start)
964 (when (and (not (string-match comint-input-history-ignore
965 history))
966 (or (null comint-input-ignoredups)
967 (ring-empty-p ring)
968 (not (string-equal (ring-ref ring 0)
969 history))))
970 (when (= count ring-size)
971 (ring-extend ring (min (- comint-input-ring-size ring-size)
972 ring-size))
973 (setq ring-size (ring-size ring)))
974 (ring-insert-at-beginning ring history)
975 (setq count (1+ count))))))
976 (setq comint-input-ring ring
977 comint-input-ring-index nil)))))
978
979 (defun comint-write-input-ring ()
980 "Writes the buffer's `comint-input-ring' to a history file.
981 The name of the file is given by the variable `comint-input-ring-file-name'.
982 The original contents of the file are lost if `comint-input-ring' is not empty.
983 If `comint-input-ring-file-name' is nil this function does nothing.
984
985 Useful within process sentinels.
986
987 See also `comint-read-input-ring'."
988 (cond ((or (null comint-input-ring-file-name)
989 (equal comint-input-ring-file-name "")
990 (null comint-input-ring) (ring-empty-p comint-input-ring))
991 nil)
992 ((not (file-writable-p comint-input-ring-file-name))
993 (message "Cannot write history file %s" comint-input-ring-file-name))
994 (t
995 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
996 (ring comint-input-ring)
997 (file comint-input-ring-file-name)
998 (index (ring-length ring)))
999 ;; Write it all out into a buffer first. Much faster, but messier,
1000 ;; than writing it one line at a time.
1001 (with-current-buffer history-buf
1002 (erase-buffer)
1003 (while (> index 0)
1004 (setq index (1- index))
1005 (insert (ring-ref ring index) comint-input-ring-separator))
1006 (write-region (buffer-string) nil file nil 'no-message)
1007 (kill-buffer nil))))))
1008
1009
1010 (defvar comint-dynamic-list-input-ring-window-conf)
1011
1012 (defun comint-dynamic-list-input-ring-select ()
1013 "Choose the input history entry that point is in or next to."
1014 (interactive)
1015 (let ((buffer completion-reference-buffer)
1016 beg end completion)
1017 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
1018 (setq end (point) beg (1+ (point))))
1019 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
1020 (setq end (1- (point)) beg (point)))
1021 (if (null beg)
1022 (error "No history entry here"))
1023 (setq beg (previous-single-property-change beg 'mouse-face))
1024 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
1025 (setq completion (buffer-substring beg end))
1026 (set-window-configuration comint-dynamic-list-input-ring-window-conf)
1027 (choose-completion-string completion buffer)))
1028
1029 (defun comint-dynamic-list-input-ring ()
1030 "Display a list of recent inputs entered into the current buffer."
1031 (interactive)
1032 (if (or (not (ring-p comint-input-ring))
1033 (ring-empty-p comint-input-ring))
1034 (message "No history")
1035 (let ((history nil)
1036 (history-buffer " *Input History*")
1037 (conf (current-window-configuration)))
1038 ;; We have to build up a list ourselves from the ring vector.
1039 (dotimes (index (ring-length comint-input-ring))
1040 (push (ring-ref comint-input-ring index) history))
1041 ;; Show them most-recent-first.
1042 (setq history (nreverse history))
1043 ;; Change "completion" to "history reference"
1044 ;; to make the display accurate.
1045 (with-output-to-temp-buffer history-buffer
1046 (display-completion-list history)
1047 (set-buffer history-buffer)
1048 (let ((keymap (make-sparse-keymap)))
1049 (set-keymap-parent keymap (current-local-map))
1050 (define-key keymap "\C-m" 'comint-dynamic-list-input-ring-select)
1051 (use-local-map keymap))
1052 (forward-line 3)
1053 (while (search-backward "completion" nil 'move)
1054 (replace-match "history reference")))
1055 (sit-for 0)
1056 (message "Hit space to flush")
1057 (setq comint-dynamic-list-input-ring-window-conf conf)
1058 (let ((ch (read-event)))
1059 (if (eq ch ?\s)
1060 (set-window-configuration conf)
1061 (push ch unread-command-events))))))
1062
1063
1064 (defun comint-regexp-arg (prompt)
1065 "Return list of regexp and prefix arg using PROMPT."
1066 (let* (;; Don't clobber this.
1067 (last-command last-command)
1068 (regexp (read-from-minibuffer prompt nil nil nil
1069 'minibuffer-history-search-history)))
1070 ;; If the user didn't enter anything, nothing is added to m-h-s-h.
1071 ;; Use the previous search regexp, if there is one.
1072 (list (if (string-equal regexp "")
1073 (or (car minibuffer-history-search-history)
1074 regexp)
1075 regexp)
1076 (prefix-numeric-value current-prefix-arg))))
1077
1078 (defun comint-search-arg (arg)
1079 ;; First make sure there is a ring and that we are after the process mark
1080 (cond ((not (comint-after-pmark-p))
1081 (user-error "Not at command line"))
1082 ((or (null comint-input-ring)
1083 (ring-empty-p comint-input-ring))
1084 (user-error "Empty input ring"))
1085 ((zerop arg)
1086 ;; arg of zero resets search from beginning, and uses arg of 1
1087 (setq comint-input-ring-index nil)
1088 1)
1089 (t
1090 arg)))
1091
1092 (defun comint-restore-input ()
1093 "Restore unfinished input."
1094 (interactive)
1095 (when comint-input-ring-index
1096 (comint-delete-input)
1097 (when (> (length comint-stored-incomplete-input) 0)
1098 (insert comint-stored-incomplete-input)
1099 (message "Input restored"))
1100 (setq comint-input-ring-index nil)))
1101
1102 (defun comint-search-start (arg)
1103 "Index to start a directional search, starting at `comint-input-ring-index'."
1104 (if comint-input-ring-index
1105 ;; If a search is running, offset by 1 in direction of arg
1106 (mod (+ comint-input-ring-index (if (> arg 0) 1 -1))
1107 (ring-length comint-input-ring))
1108 ;; For a new search, start from beginning or end, as appropriate
1109 (if (>= arg 0)
1110 0 ; First elt for forward search
1111 (1- (ring-length comint-input-ring))))) ; Last elt for backward search
1112
1113 (defun comint-previous-input-string (arg)
1114 "Return the string ARG places along the input ring.
1115 Moves relative to `comint-input-ring-index'."
1116 (ring-ref comint-input-ring (if comint-input-ring-index
1117 (mod (+ arg comint-input-ring-index)
1118 (ring-length comint-input-ring))
1119 arg)))
1120
1121 (defun comint-previous-input (arg)
1122 "Cycle backwards through input history, saving input."
1123 (interactive "*p")
1124 (if (and comint-input-ring-index
1125 (or ;; leaving the "end" of the ring
1126 (and (< arg 0) ; going down
1127 (eq comint-input-ring-index 0))
1128 (and (> arg 0) ; going up
1129 (eq comint-input-ring-index
1130 (1- (ring-length comint-input-ring)))))
1131 comint-stored-incomplete-input)
1132 (comint-restore-input)
1133 (comint-previous-matching-input "." arg)))
1134
1135 (defun comint-next-input (arg)
1136 "Cycle forwards through input history."
1137 (interactive "*p")
1138 (comint-previous-input (- arg)))
1139
1140 (defun comint-previous-matching-input-string (regexp arg)
1141 "Return the string matching REGEXP ARG places along the input ring.
1142 Moves relative to `comint-input-ring-index'."
1143 (let* ((pos (comint-previous-matching-input-string-position regexp arg)))
1144 (if pos (ring-ref comint-input-ring pos))))
1145
1146 (defun comint-previous-matching-input-string-position (regexp arg &optional start)
1147 "Return the index matching REGEXP ARG places along the input ring.
1148 Moves relative to START, or `comint-input-ring-index'."
1149 (if (or (not (ring-p comint-input-ring))
1150 (ring-empty-p comint-input-ring))
1151 (user-error "No history"))
1152 (let* ((len (ring-length comint-input-ring))
1153 (motion (if (> arg 0) 1 -1))
1154 (n (mod (- (or start (comint-search-start arg)) motion) len))
1155 (tried-each-ring-item nil)
1156 (prev nil))
1157 ;; Do the whole search as many times as the argument says.
1158 (while (and (/= arg 0) (not tried-each-ring-item))
1159 ;; Step once.
1160 (setq prev n
1161 n (mod (+ n motion) len))
1162 ;; If we haven't reached a match, step some more.
1163 (while (and (< n len) (not tried-each-ring-item)
1164 (not (string-match regexp (ring-ref comint-input-ring n))))
1165 (setq n (mod (+ n motion) len)
1166 ;; If we have gone all the way around in this search.
1167 tried-each-ring-item (= n prev)))
1168 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1169 ;; Now that we know which ring element to use, if we found it, return that.
1170 (if (string-match regexp (ring-ref comint-input-ring n))
1171 n)))
1172
1173 (defun comint-delete-input ()
1174 "Delete all input between accumulation or process mark and point."
1175 (delete-region
1176 ;; Can't use kill-region as it sets this-command
1177 (or (marker-position comint-accum-marker)
1178 (process-mark (get-buffer-process (current-buffer))))
1179 (point-max)))
1180
1181 (defun comint-previous-matching-input (regexp n)
1182 "Search backwards through input history for match for REGEXP.
1183 \(Previous history elements are earlier commands.)
1184 With prefix argument N, search for Nth previous match.
1185 If N is negative, find the next or Nth next match."
1186 (interactive (comint-regexp-arg "Previous input matching (regexp): "))
1187 (setq n (comint-search-arg n))
1188 (let ((pos (comint-previous-matching-input-string-position regexp n)))
1189 ;; Has a match been found?
1190 (if (null pos)
1191 (user-error "Not found")
1192 ;; If leaving the edit line, save partial input
1193 (if (null comint-input-ring-index) ;not yet on ring
1194 (setq comint-stored-incomplete-input
1195 (funcall comint-get-old-input)))
1196 (setq comint-input-ring-index pos)
1197 (unless isearch-mode
1198 (let ((message-log-max nil)) ; Do not write to *Messages*.
1199 (message "History item: %d" (1+ pos))))
1200 (comint-delete-input)
1201 (insert (ring-ref comint-input-ring pos)))))
1202
1203 (defun comint-next-matching-input (regexp n)
1204 "Search forwards through input history for match for REGEXP.
1205 \(Later history elements are more recent commands.)
1206 With prefix argument N, search for Nth following match.
1207 If N is negative, find the previous or Nth previous match."
1208 (interactive (comint-regexp-arg "Next input matching (regexp): "))
1209 (comint-previous-matching-input regexp (- n)))
1210
1211 (defun comint-previous-matching-input-from-input (n)
1212 "Search backwards through input history for match for current input.
1213 \(Previous history elements are earlier commands.)
1214 With prefix argument N, search for Nth previous match.
1215 If N is negative, search forwards for the -Nth following match."
1216 (interactive "p")
1217 (let ((opoint (point)))
1218 (unless (memq last-command '(comint-previous-matching-input-from-input
1219 comint-next-matching-input-from-input))
1220 ;; Starting a new search
1221 (setq comint-matching-input-from-input-string
1222 (buffer-substring
1223 (or (marker-position comint-accum-marker)
1224 (process-mark (get-buffer-process (current-buffer))))
1225 (point))
1226 comint-input-ring-index nil))
1227 (comint-previous-matching-input
1228 (concat "^" (regexp-quote comint-matching-input-from-input-string))
1229 n)
1230 (goto-char opoint)))
1231
1232 (defun comint-next-matching-input-from-input (n)
1233 "Search forwards through input history for match for current input.
1234 \(Following history elements are more recent commands.)
1235 With prefix argument N, search for Nth following match.
1236 If N is negative, search backwards for the -Nth previous match."
1237 (interactive "p")
1238 (comint-previous-matching-input-from-input (- n)))
1239
1240
1241 (defun comint-replace-by-expanded-history (&optional silent start)
1242 "Expand input command history references before point.
1243 Expansion is dependent on the value of `comint-input-autoexpand'.
1244
1245 This function depends on the buffer's idea of the input history, which may not
1246 match the command interpreter's idea, assuming it has one.
1247
1248 Assumes history syntax is like typical Un*x shells'. However, since Emacs
1249 cannot know the interpreter's idea of input line numbers, assuming it has one,
1250 it cannot expand absolute input line number references.
1251
1252 If the optional argument SILENT is non-nil, never complain
1253 even if history reference seems erroneous.
1254
1255 If the optional argument START is non-nil, that specifies the
1256 start of the text to scan for history references, rather
1257 than the logical beginning of line.
1258
1259 See `comint-magic-space' and `comint-replace-by-expanded-history-before-point'.
1260
1261 Returns t if successful."
1262 (interactive)
1263 (let ((f (comint-c-a-p-replace-by-expanded-history silent start)))
1264 (if f (funcall f))))
1265
1266 (defun comint-c-a-p-replace-by-expanded-history (&optional silent start)
1267 "Expand input command history at point.
1268 For use on `completion-at-point-functions'."
1269 (if (and comint-input-autoexpand
1270 (if comint-use-prompt-regexp
1271 ;; Use comint-prompt-regexp
1272 (save-excursion
1273 (beginning-of-line)
1274 (looking-at (concat comint-prompt-regexp "!\\|\\^")))
1275 ;; Use input fields. User input that hasn't been entered
1276 ;; yet, at the end of the buffer, has a nil `field' property.
1277 (and (null (get-char-property (point) 'field))
1278 (string-match "!\\|^\\^" (field-string))))
1279 (catch 'dry-run
1280 (comint-replace-by-expanded-history-before-point
1281 silent start 'dry-run)))
1282 (lambda ()
1283 ;; Looks like there might be history references in the command.
1284 (let ((previous-modified-tick (buffer-modified-tick)))
1285 (comint-replace-by-expanded-history-before-point silent start)
1286 (/= previous-modified-tick (buffer-modified-tick))))))
1287
1288
1289 (defun comint-replace-by-expanded-history-before-point
1290 (silent &optional start dry-run)
1291 "Expand directory stack reference before point.
1292 See `comint-replace-by-expanded-history'. Returns t if successful.
1293
1294 If the optional argument START is non-nil, that specifies the
1295 start of the text to scan for history references, rather
1296 than the logical beginning of line.
1297
1298 If DRY-RUN is non-nil, throw to DRY-RUN before performing any
1299 actual side-effect."
1300 (save-excursion
1301 (let ((toend (- (line-end-position) (point)))
1302 (start (or start (comint-line-beginning-position))))
1303 (goto-char start)
1304 (while (progn
1305 (skip-chars-forward "^!^" (- (line-end-position) toend))
1306 (< (point) (- (line-end-position) toend)))
1307 ;; This seems a bit complex. We look for references such as !!, !-num,
1308 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1309 ;; If that wasn't enough, the plings can be suffixed with argument
1310 ;; range specifiers.
1311 ;; Argument ranges are complex too, so we hive off the input line,
1312 ;; referenced with plings, with the range string to `comint-args'.
1313 (setq comint-input-ring-index nil)
1314 (cond ((or (= (preceding-char) ?\\)
1315 (comint-within-quotes start (point)))
1316 ;; The history is quoted, or we're in quotes.
1317 (goto-char (1+ (point))))
1318 ((looking-at "![0-9]+\\($\\|[^-]\\)")
1319 ;; We cannot know the interpreter's idea of input line numbers.
1320 (if dry-run (throw dry-run 'message))
1321 (goto-char (match-end 0))
1322 (message "Absolute reference cannot be expanded"))
1323 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1324 ;; Just a number of args from `number' lines backward.
1325 (if dry-run (throw dry-run 'history))
1326 (let ((number (1- (string-to-number
1327 (buffer-substring (match-beginning 1)
1328 (match-end 1))))))
1329 (if (<= number (ring-length comint-input-ring))
1330 (progn
1331 (replace-match
1332 (comint-args (comint-previous-input-string number)
1333 (match-beginning 2) (match-end 2))
1334 t t)
1335 (setq comint-input-ring-index number)
1336 (message "History item: %d" (1+ number)))
1337 (goto-char (match-end 0))
1338 (message "Relative reference exceeds input history size"))))
1339 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1340 ;; Just a number of args from the previous input line.
1341 (if dry-run (throw dry-run 'expand))
1342 (replace-match (comint-args (comint-previous-input-string 0)
1343 (match-beginning 1) (match-end 1))
1344 t t)
1345 (message "History item: previous"))
1346 ((looking-at
1347 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1348 ;; Most recent input starting with or containing (possibly
1349 ;; protected) string, maybe just a number of args. Phew.
1350 (if dry-run (throw dry-run 'expand))
1351 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1352 (mb2 (match-beginning 2)) (me2 (match-end 2))
1353 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1354 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1355 (pos (save-match-data
1356 (comint-previous-matching-input-string-position
1357 (concat pref (regexp-quote exp)) 1))))
1358 (if (null pos)
1359 (progn
1360 (goto-char (match-end 0))
1361 (or silent
1362 (progn (message "Not found")
1363 (ding))))
1364 (setq comint-input-ring-index pos)
1365 (replace-match
1366 (comint-args (ring-ref comint-input-ring pos)
1367 (match-beginning 4) (match-end 4))
1368 t t)
1369 (message "History item: %d" (1+ pos)))))
1370 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1371 ;; Quick substitution on the previous input line.
1372 (if dry-run (throw dry-run 'expand))
1373 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1374 (new (buffer-substring (match-beginning 2) (match-end 2)))
1375 (pos nil))
1376 (replace-match (comint-previous-input-string 0) t t)
1377 (setq pos (point))
1378 (goto-char (match-beginning 0))
1379 (if (not (search-forward old pos t))
1380 (or silent
1381 (user-error "Not found"))
1382 (replace-match new t t)
1383 (message "History item: substituted"))))
1384 (t
1385 (forward-char 1)))))
1386 nil))
1387
1388
1389 (defun comint-magic-space (arg)
1390 "Expand input history references before point and insert ARG spaces.
1391 A useful command to bind to SPC. See `comint-replace-by-expanded-history'."
1392 (interactive "p")
1393 (comint-replace-by-expanded-history)
1394 (self-insert-command arg))
1395 \f
1396 ;; Isearch in comint input history
1397
1398 (defcustom comint-history-isearch nil
1399 "Non-nil to Isearch in input history only, not in comint buffer output.
1400 If t, usual Isearch keys like `C-r' and `C-M-r' in comint mode search
1401 in the input history.
1402 If `dwim', Isearch keys search in the input history only when initial
1403 point position is at the comint command line. When starting Isearch
1404 from other parts of the comint buffer, they search in the comint buffer.
1405 If nil, Isearch operates on the whole comint buffer."
1406 :type '(choice (const :tag "Don't search in input history" nil)
1407 (const :tag "When point is on command line initially, search history" dwim)
1408 (const :tag "Always search in input history" t))
1409 :group 'comint
1410 :version "23.2")
1411
1412 (defun comint-history-isearch-backward ()
1413 "Search for a string backward in input history using Isearch."
1414 (interactive)
1415 (let ((comint-history-isearch t))
1416 (isearch-backward nil t)))
1417
1418 (defun comint-history-isearch-backward-regexp ()
1419 "Search for a regular expression backward in input history using Isearch."
1420 (interactive)
1421 (let ((comint-history-isearch t))
1422 (isearch-backward-regexp nil t)))
1423
1424 (defvar-local comint-history-isearch-message-overlay nil)
1425
1426 (defun comint-history-isearch-setup ()
1427 "Set up a comint for using Isearch to search the input history.
1428 Intended to be added to `isearch-mode-hook' in `comint-mode'."
1429 (when (or (eq comint-history-isearch t)
1430 (and (eq comint-history-isearch 'dwim)
1431 ;; Point is at command line.
1432 (comint-after-pmark-p)))
1433 (setq isearch-message-prefix-add "history ")
1434 (setq-local isearch-search-fun-function
1435 #'comint-history-isearch-search)
1436 (setq-local isearch-message-function
1437 #'comint-history-isearch-message)
1438 (setq-local isearch-wrap-function
1439 #'comint-history-isearch-wrap)
1440 (setq-local isearch-push-state-function
1441 #'comint-history-isearch-push-state)
1442 (add-hook 'isearch-mode-end-hook 'comint-history-isearch-end nil t)))
1443
1444 (defun comint-history-isearch-end ()
1445 "Clean up the comint after terminating Isearch in comint."
1446 (if comint-history-isearch-message-overlay
1447 (delete-overlay comint-history-isearch-message-overlay))
1448 (setq isearch-message-prefix-add nil)
1449 (setq isearch-search-fun-function 'isearch-search-fun-default)
1450 (setq isearch-message-function nil)
1451 (setq isearch-wrap-function nil)
1452 (setq isearch-push-state-function nil)
1453 (remove-hook 'isearch-mode-end-hook 'comint-history-isearch-end t))
1454
1455 (defun comint-goto-input (pos)
1456 "Put input history item of the absolute history position POS."
1457 ;; If leaving the edit line, save partial unfinished input.
1458 (if (null comint-input-ring-index)
1459 (setq comint-stored-incomplete-input
1460 (funcall comint-get-old-input)))
1461 (setq comint-input-ring-index pos)
1462 (comint-delete-input)
1463 (if (and pos (not (ring-empty-p comint-input-ring)))
1464 (insert (ring-ref comint-input-ring pos))
1465 ;; Restore partial unfinished input.
1466 (when (> (length comint-stored-incomplete-input) 0)
1467 (insert comint-stored-incomplete-input))))
1468
1469 (defun comint-history-isearch-search ()
1470 "Return the proper search function, for Isearch in input history."
1471 (lambda (string bound noerror)
1472 (let ((search-fun
1473 ;; Use standard functions to search within comint text
1474 (isearch-search-fun-default))
1475 found)
1476 ;; Avoid lazy-highlighting matches in the comint prompt and in the
1477 ;; output when searching forward. Lazy-highlight calls this lambda
1478 ;; with the bound arg, so skip the prompt and the output.
1479 (if (and bound isearch-forward (not (comint-after-pmark-p)))
1480 (goto-char (process-mark (get-buffer-process (current-buffer)))))
1481 (or
1482 ;; 1. First try searching in the initial comint text
1483 (funcall search-fun string
1484 (if isearch-forward bound (comint-line-beginning-position))
1485 noerror)
1486 ;; 2. If the above search fails, start putting next/prev history
1487 ;; elements in the comint successively, and search the string
1488 ;; in them. Do this only when bound is nil (i.e. not while
1489 ;; lazy-highlighting search strings in the current comint text).
1490 (unless bound
1491 (condition-case nil
1492 (progn
1493 (while (not found)
1494 (cond (isearch-forward
1495 ;; Signal an error here explicitly, because
1496 ;; `comint-next-input' doesn't signal an error.
1497 (when (null comint-input-ring-index)
1498 (error "End of history; no next item"))
1499 (comint-next-input 1)
1500 (goto-char (comint-line-beginning-position)))
1501 (t
1502 ;; Signal an error here explicitly, because
1503 ;; `comint-previous-input' doesn't signal an error.
1504 (when (eq comint-input-ring-index
1505 (1- (ring-length comint-input-ring)))
1506 (error "Beginning of history; no preceding item"))
1507 (comint-previous-input 1)
1508 (goto-char (point-max))))
1509 (setq isearch-barrier (point) isearch-opoint (point))
1510 ;; After putting the next/prev history element, search
1511 ;; the string in them again, until comint-next-input
1512 ;; or comint-previous-input raises an error at the
1513 ;; beginning/end of history.
1514 (setq found (funcall search-fun string
1515 (unless isearch-forward
1516 ;; For backward search, don't search
1517 ;; in the comint prompt
1518 (comint-line-beginning-position))
1519 noerror)))
1520 ;; Return point of the new search result
1521 (point))
1522 ;; Return nil on the error "no next/preceding item"
1523 (error nil)))))))
1524
1525 (defun comint-history-isearch-message (&optional c-q-hack ellipsis)
1526 "Display the input history search prompt.
1527 If there are no search errors, this function displays an overlay with
1528 the Isearch prompt which replaces the original comint prompt.
1529 Otherwise, it displays the standard Isearch message returned from
1530 the function `isearch-message'."
1531 (if (not (and isearch-success (not isearch-error)))
1532 ;; Use standard function `isearch-message' when not in comint prompt,
1533 ;; or search fails, or has an error (like incomplete regexp).
1534 ;; This function displays isearch message in the echo area,
1535 ;; so it's possible to see what is wrong in the search string.
1536 (isearch-message c-q-hack ellipsis)
1537 ;; Otherwise, put the overlay with the standard isearch prompt over
1538 ;; the initial comint prompt.
1539 (if (overlayp comint-history-isearch-message-overlay)
1540 (move-overlay comint-history-isearch-message-overlay
1541 (save-excursion
1542 (goto-char (comint-line-beginning-position))
1543 (forward-line 0)
1544 (point))
1545 (comint-line-beginning-position))
1546 (setq comint-history-isearch-message-overlay
1547 (make-overlay (save-excursion
1548 (goto-char (comint-line-beginning-position))
1549 (forward-line 0)
1550 (point))
1551 (comint-line-beginning-position)))
1552 (overlay-put comint-history-isearch-message-overlay 'evaporate t))
1553 (overlay-put comint-history-isearch-message-overlay
1554 'display (isearch-message-prefix ellipsis isearch-nonincremental))
1555 (if (and comint-input-ring-index (not ellipsis))
1556 ;; Display the current history index.
1557 (message "History item: %d" (1+ comint-input-ring-index))
1558 ;; Or clear a previous isearch message.
1559 (message ""))))
1560
1561 (defun comint-history-isearch-wrap ()
1562 "Wrap the input history search when search fails.
1563 Move point to the first history element for a forward search,
1564 or to the last history element for a backward search."
1565 ;; When `comint-history-isearch-search' fails on reaching the
1566 ;; beginning/end of the history, wrap the search to the first/last
1567 ;; input history element.
1568 (if isearch-forward
1569 (comint-goto-input (1- (ring-length comint-input-ring)))
1570 (comint-goto-input nil))
1571 (setq isearch-success t)
1572 (goto-char (if isearch-forward (comint-line-beginning-position) (point-max))))
1573
1574 (defun comint-history-isearch-push-state ()
1575 "Save a function restoring the state of input history search.
1576 Save `comint-input-ring-index' to the additional state parameter
1577 in the search status stack."
1578 (let ((index comint-input-ring-index))
1579 (lambda (cmd)
1580 (comint-history-isearch-pop-state cmd index))))
1581
1582 (defun comint-history-isearch-pop-state (_cmd hist-pos)
1583 "Restore the input history search state.
1584 Go to the history element by the absolute history position HIST-POS."
1585 (comint-goto-input hist-pos))
1586
1587 \f
1588 (defun comint-within-quotes (beg end)
1589 "Return t if the number of quotes between BEG and END is odd.
1590 Quotes are single and double."
1591 (let ((countsq (comint-how-many-region "\\(^\\|[^\\\\]\\)'" beg end))
1592 (countdq (comint-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1593 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1594
1595 (defun comint-how-many-region (regexp beg end)
1596 "Return number of matches for REGEXP from BEG to END."
1597 (let ((count 0))
1598 (save-excursion
1599 (save-match-data
1600 (goto-char beg)
1601 (while (re-search-forward regexp end t)
1602 (setq count (1+ count)))))
1603 count))
1604
1605 (defun comint-args (string begin end)
1606 ;; From STRING, return the args depending on the range specified in the text
1607 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1608 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1609 (save-match-data
1610 (if (null begin)
1611 (comint-arguments string 0 nil)
1612 (let* ((range (buffer-substring
1613 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1614 (nth (cond ((string-match "^[*^]" range) 1)
1615 ((string-match "^-" range) 0)
1616 ((string-equal range "$") nil)
1617 (t (string-to-number range))))
1618 (mth (cond ((string-match "[-*$]$" range) nil)
1619 ((string-match "-" range)
1620 (string-to-number (substring range (match-end 0))))
1621 (t nth))))
1622 (comint-arguments string nth mth)))))
1623
1624 (defun comint-delim-arg (arg)
1625 "Return a list of arguments from ARG.
1626 Break it up at the delimiters in `comint-delimiter-argument-list'.
1627 Returned list is backwards.
1628
1629 Characters with non-nil values of the text property `literal' are
1630 assumed to have literal values (e.g., backslash-escaped
1631 characters), and are not considered to be delimiters."
1632 (if (null comint-delimiter-argument-list)
1633 (list arg)
1634 (let ((args nil)
1635 (pos 0)
1636 (len (length arg)))
1637 (while (< pos len)
1638 (let ((char (aref arg pos))
1639 (start pos))
1640 (if (and (memq char comint-delimiter-argument-list)
1641 ;; Ignore backslash-escaped characters.
1642 (not (get-text-property pos 'literal arg)))
1643 (while (and (< pos len) (eq (aref arg pos) char))
1644 (setq pos (1+ pos)))
1645 (while (and (< pos len)
1646 (not (and (memq (aref arg pos)
1647 comint-delimiter-argument-list)
1648 (not (get-text-property
1649 pos 'literal arg)))))
1650 (setq pos (1+ pos))))
1651 (setq args (cons (substring arg start pos) args))))
1652 args)))
1653
1654 (defun comint-arguments (string nth mth)
1655 "Return from STRING the NTH to MTH arguments.
1656 NTH and/or MTH can be nil, which means the last argument.
1657 Returned arguments are separated by single spaces.
1658 We assume whitespace separates arguments, except within quotes
1659 and except for a space or tab that immediately follows a backslash.
1660 Also, a run of one or more of a single character
1661 in `comint-delimiter-argument-list' is a separate argument.
1662 Argument 0 is the command name."
1663 ;; The first line handles ordinary characters and backslash-sequences
1664 ;; (except with w32 msdos-like shells, where backslashes are valid).
1665 ;; The second matches "-quoted strings.
1666 ;; The third matches '-quoted strings.
1667 ;; The fourth matches `-quoted strings.
1668 ;; This seems to fit the syntax of BASH 2.0.
1669 (let* ((backslash-escape (not (and (fboundp 'w32-shell-dos-semantics)
1670 (w32-shell-dos-semantics))))
1671 (first (if backslash-escape
1672 "[^ \n\t\"'`\\]\\|\\(\\\\.\\)\\|"
1673 "[^ \n\t\"'`]+\\|"))
1674 (argpart (concat first
1675 "\\(\"\\([^\"\\]\\|\\\\.\\)*\"\\|\
1676 '[^']*'\\|\
1677 `[^`]*`\\)"))
1678 (quote-subexpr (if backslash-escape 2 1))
1679 (args ()) (pos 0)
1680 (count 0)
1681 beg str quotes)
1682 ;; Build a list of all the args until we have as many as we want.
1683 (while (and (or (null mth) (<= count mth))
1684 (string-match argpart string pos))
1685 ;; Apply the `literal' text property to backslash-escaped
1686 ;; characters, so that `comint-delim-arg' won't break them up.
1687 (and backslash-escape
1688 (match-beginning 1)
1689 (put-text-property (match-beginning 1) (match-end 1)
1690 'literal t string))
1691 (if (and beg (= pos (match-beginning 0)))
1692 ;; It's contiguous, part of the same arg.
1693 (setq pos (match-end 0)
1694 quotes (or quotes (match-beginning quote-subexpr)))
1695 ;; It's a new separate arg.
1696 (if beg
1697 ;; Put the previous arg, if there was one, onto ARGS.
1698 (setq str (substring string beg pos)
1699 args (if quotes (cons str args)
1700 (nconc (comint-delim-arg str) args))))
1701 (setq count (length args))
1702 (setq quotes (match-beginning quote-subexpr))
1703 (setq beg (match-beginning 0))
1704 (setq pos (match-end 0))))
1705 (if beg
1706 (setq str (substring string beg pos)
1707 args (if quotes (cons str args)
1708 (nconc (comint-delim-arg str) args))))
1709 (setq count (length args))
1710 (let ((n (or nth (1- count)))
1711 (m (if mth (1- (- count mth)) 0)))
1712 (mapconcat
1713 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1714 \f
1715 ;;
1716 ;; Input processing stuff
1717 ;;
1718 (defun comint-add-to-input-history (cmd)
1719 "Add CMD to the input history.
1720 Ignore duplicates if `comint-input-ignoredups' is non-nil."
1721 (when (and (funcall comint-input-filter cmd)
1722 (or (null comint-input-ignoredups)
1723 (not (ring-p comint-input-ring))
1724 (ring-empty-p comint-input-ring)
1725 (not (string-equal (ring-ref comint-input-ring 0) cmd))))
1726 ;; If `comint-input-ring' is full, maybe grow it.
1727 (let ((size (ring-size comint-input-ring)))
1728 (and (= size (ring-length comint-input-ring))
1729 (< size comint-input-ring-size)
1730 (ring-extend comint-input-ring
1731 (min size (- comint-input-ring-size size)))))
1732 (ring-insert comint-input-ring cmd)))
1733
1734 (defun comint-send-input (&optional no-newline artificial)
1735 "Send input to process.
1736 After the process output mark, sends all text from the process mark to
1737 point as input to the process. Before the process output mark, calls
1738 value of variable `comint-get-old-input' to retrieve old input, copies
1739 it to the process mark, and sends it.
1740
1741 This command also sends and inserts a final newline, unless
1742 NO-NEWLINE is non-nil.
1743
1744 Any history reference may be expanded depending on the value of the variable
1745 `comint-input-autoexpand'. The list of function names contained in the value
1746 of `comint-input-filter-functions' is called on the input before sending it.
1747 The input is entered into the input history ring, if the value of variable
1748 `comint-input-filter' returns non-nil when called on the input.
1749
1750 If variable `comint-eol-on-send' is non-nil, then point is moved to the
1751 end of line before sending the input.
1752
1753 After the input has been sent, if `comint-process-echoes' is non-nil,
1754 then `comint-send-input' waits to see if the process outputs a string
1755 matching the input, and if so, deletes that part of the output.
1756 If ARTIFICIAL is non-nil, it inhibits such deletion.
1757 Callers sending input not from the user should use ARTIFICIAL = t.
1758
1759 The values of `comint-get-old-input', `comint-input-filter-functions', and
1760 `comint-input-filter' are chosen according to the command interpreter running
1761 in the buffer. E.g.,
1762
1763 If the interpreter is the csh,
1764 `comint-get-old-input' is the default:
1765 If `comint-use-prompt-regexp' is nil, then
1766 either return the current input field, if point is on an input
1767 field, or the current line, if point is on an output field.
1768 If `comint-use-prompt-regexp' is non-nil, then
1769 return the current line with any initial string matching the
1770 regexp `comint-prompt-regexp' removed.
1771 `comint-input-filter-functions' monitors input for \"cd\", \"pushd\", and
1772 \"popd\" commands. When it sees one, it cd's the buffer.
1773 `comint-input-filter' is the default: returns t if the input isn't all white
1774 space.
1775
1776 If the Comint is Lucid Common Lisp,
1777 `comint-get-old-input' snarfs the sexp ending at point.
1778 `comint-input-filter-functions' does nothing.
1779 `comint-input-filter' returns nil if the input matches input-filter-regexp,
1780 which matches (1) all whitespace (2) :a, :c, etc.
1781
1782 Similarly for Soar, Scheme, etc."
1783 (interactive)
1784 ;; If we're currently completing, stop. We're definitely done
1785 ;; completing, and by sending the input, we might cause side effects
1786 ;; that will confuse the code running in the completion
1787 ;; post-command-hook.
1788 (when completion-in-region-mode
1789 (completion-in-region-mode -1))
1790 ;; Note that the input string does not include its terminal newline.
1791 (let ((proc (get-buffer-process (current-buffer))))
1792 (if (not proc) (user-error "Current buffer has no process")
1793 (widen)
1794 (let* ((pmark (process-mark proc))
1795 (intxt (if (>= (point) (marker-position pmark))
1796 (progn (if comint-eol-on-send
1797 (if comint-use-prompt-regexp
1798 (end-of-line)
1799 (goto-char (field-end))))
1800 (buffer-substring pmark (point)))
1801 (let ((copy (funcall comint-get-old-input)))
1802 (goto-char pmark)
1803 (insert copy)
1804 copy)))
1805 (input (if (not (eq comint-input-autoexpand 'input))
1806 ;; Just whatever's already there.
1807 intxt
1808 ;; Expand and leave it visible in buffer.
1809 (comint-replace-by-expanded-history t pmark)
1810 (buffer-substring pmark (point))))
1811 (history (if (not (eq comint-input-autoexpand 'history))
1812 input
1813 ;; This is messy 'cos ultimately the original
1814 ;; functions used do insertion, rather than return
1815 ;; strings. We have to expand, then insert back.
1816 (comint-replace-by-expanded-history t pmark)
1817 (let ((copy (buffer-substring pmark (point)))
1818 (start (point)))
1819 (insert input)
1820 (delete-region pmark start)
1821 copy))))
1822
1823 (unless no-newline
1824 (insert ?\n))
1825
1826 (comint-add-to-input-history history)
1827
1828 (run-hook-with-args 'comint-input-filter-functions
1829 (if no-newline input
1830 (concat input "\n")))
1831
1832 (let ((beg (marker-position pmark))
1833 (end (if no-newline (point) (1- (point)))))
1834 (with-silent-modifications
1835 (when (> end beg)
1836 (add-text-properties beg end
1837 '(front-sticky t
1838 font-lock-face comint-highlight-input))
1839 (unless comint-use-prompt-regexp
1840 ;; Give old user input a field property of `input', to
1841 ;; distinguish it from both process output and unsent
1842 ;; input. The terminating newline is put into a special
1843 ;; `boundary' field to make cursor movement between input
1844 ;; and output fields smoother.
1845 (add-text-properties
1846 beg end
1847 '(mouse-face highlight
1848 help-echo "mouse-2: insert after prompt as new input"))))
1849 (unless (or no-newline comint-use-prompt-regexp)
1850 ;; Cover the terminating newline
1851 (add-text-properties end (1+ end)
1852 '(rear-nonsticky t
1853 field boundary
1854 inhibit-line-move-field-capture t)))))
1855
1856 (comint-snapshot-last-prompt)
1857
1858 (setq comint-save-input-ring-index comint-input-ring-index)
1859 (setq comint-input-ring-index nil)
1860 ;; Update the markers before we send the input
1861 ;; in case we get output amidst sending the input.
1862 (set-marker comint-last-input-start pmark)
1863 (set-marker comint-last-input-end (point))
1864 (set-marker (process-mark proc) (point))
1865 ;; clear the "accumulation" marker
1866 (set-marker comint-accum-marker nil)
1867 (let ((comint-input-sender-no-newline no-newline))
1868 (funcall comint-input-sender proc input))
1869
1870 ;; Optionally delete echoed input (after checking it).
1871 (when (and comint-process-echoes (not artificial))
1872 (let ((echo-len (- comint-last-input-end
1873 comint-last-input-start)))
1874 ;; Wait for all input to be echoed:
1875 (while (and (> (+ comint-last-input-end echo-len)
1876 (point-max))
1877 (accept-process-output proc)
1878 (zerop
1879 (compare-buffer-substrings
1880 nil comint-last-input-start
1881 (- (point-max) echo-len)
1882 ;; Above difference is equivalent to
1883 ;; (+ comint-last-input-start
1884 ;; (- (point-max) comint-last-input-end))
1885 nil comint-last-input-end (point-max)))))
1886 (if (and
1887 (<= (+ comint-last-input-end echo-len)
1888 (point-max))
1889 (zerop
1890 (compare-buffer-substrings
1891 nil comint-last-input-start comint-last-input-end
1892 nil comint-last-input-end
1893 (+ comint-last-input-end echo-len))))
1894 ;; Certain parts of the text to be deleted may have
1895 ;; been mistaken for prompts. We have to prevent
1896 ;; problems when `comint-prompt-read-only' is non-nil.
1897 (let ((inhibit-read-only t))
1898 (delete-region comint-last-input-end
1899 (+ comint-last-input-end echo-len))
1900 (when comint-prompt-read-only
1901 (save-excursion
1902 (goto-char comint-last-input-end)
1903 (comint-update-fence)))))))
1904
1905 ;; This used to call comint-output-filter-functions,
1906 ;; but that scrolled the buffer in undesirable ways.
1907 (run-hook-with-args 'comint-output-filter-functions "")))))
1908
1909 (defvar comint-preoutput-filter-functions nil
1910 "List of functions to call before inserting Comint output into the buffer.
1911 Each function gets one argument, a string containing the text received
1912 from the subprocess. It should return the string to insert, perhaps
1913 the same string that was received, or perhaps a modified or transformed
1914 string.
1915
1916 The functions on the list are called sequentially, and each one is
1917 given the string returned by the previous one. The string returned by
1918 the last function is the text that is actually inserted in the
1919 redirection buffer.
1920
1921 You can use `add-hook' to add functions to this list
1922 either globally or locally.")
1923
1924 (defvar comint-inhibit-carriage-motion nil
1925 "If nil, Comint will interpret `carriage control' characters in output.
1926 See `comint-carriage-motion' for details.")
1927
1928 (defvar comint-last-prompt nil
1929 "Markers pointing to the last prompt.
1930 If non-nil, a cons cell containing markers. The car points to
1931 the start, the cdr to the end of the last prompt recognized.")
1932
1933 (defun comint-snapshot-last-prompt ()
1934 "Snapshot the current `comint-last-prompt'.
1935 Freezes the `font-lock-face' text property in place."
1936 (when comint-last-prompt
1937 (with-silent-modifications
1938 (font-lock-prepend-text-property
1939 (car comint-last-prompt)
1940 (cdr comint-last-prompt)
1941 'font-lock-face 'comint-highlight-prompt))
1942 ;; Reset comint-last-prompt so later on comint-output-filter does
1943 ;; not remove the font-lock-face text property of the previous
1944 ;; (this) prompt.
1945 (setq comint-last-prompt nil)))
1946
1947 (defun comint-carriage-motion (start end)
1948 "Interpret carriage control characters in the region from START to END.
1949 Translate carriage return/linefeed sequences to linefeeds.
1950 Make single carriage returns delete to the beginning of the line.
1951 Make backspaces delete the previous character."
1952 (save-excursion
1953 ;; We used to check the existence of \b and \r at first to avoid
1954 ;; calling save-match-data and save-restriction. But, such a
1955 ;; check is not necessary now because we don't use regexp search
1956 ;; nor save-restriction. Note that the buffer is already widen,
1957 ;; and calling narrow-to-region and widen are not that heavy.
1958 (goto-char start)
1959 (let* ((inhibit-field-text-motion t)
1960 (inhibit-read-only t)
1961 (lbeg (line-beginning-position))
1962 delete-end ch)
1963 ;; If the preceding text is marked as "must-overwrite", record
1964 ;; it in delete-end.
1965 (when (and (> start (point-min))
1966 (get-text-property (1- start) 'comint-must-overwrite))
1967 (setq delete-end (point-marker))
1968 (remove-text-properties lbeg start '(comint-must-overwrite nil)))
1969 (narrow-to-region lbeg end)
1970 ;; Handle BS, LF, and CR specially.
1971 (while (and (skip-chars-forward "^\b\n\r") (not (eobp)))
1972 (setq ch (following-char))
1973 (cond ((= ch ?\b) ; CH = BS
1974 (delete-char 1)
1975 (if (> (point) lbeg)
1976 (delete-char -1)))
1977 ((= ch ?\n)
1978 (when delete-end ; CH = LF
1979 (if (< delete-end (point))
1980 (delete-region lbeg delete-end))
1981 (set-marker delete-end nil)
1982 (setq delete-end nil))
1983 (forward-char 1)
1984 (setq lbeg (point)))
1985 (t ; CH = CR
1986 (delete-char 1)
1987 (if delete-end
1988 (when (< delete-end (point))
1989 (delete-region lbeg delete-end)
1990 (move-marker delete-end (point)))
1991 (setq delete-end (point-marker))))))
1992 (when delete-end
1993 (if (< delete-end (point))
1994 ;; As there's a text after the last CR, make the current
1995 ;; line contain only that text.
1996 (delete-region lbeg delete-end)
1997 ;; Remember that the process output ends by CR, and thus we
1998 ;; must overwrite the contents of the current line next
1999 ;; time.
2000 (put-text-property lbeg delete-end 'comint-must-overwrite t))
2001 (set-marker delete-end nil))
2002 (widen))))
2003
2004 ;; The purpose of using this filter for comint processes
2005 ;; is to keep comint-last-input-end from moving forward
2006 ;; when output is inserted.
2007 (defun comint-output-filter (process string)
2008 (let ((oprocbuf (process-buffer process)))
2009 ;; First check for killed buffer or no input.
2010 (when (and string oprocbuf (buffer-name oprocbuf))
2011 (with-current-buffer oprocbuf
2012 ;; Run preoutput filters
2013 (let ((functions comint-preoutput-filter-functions))
2014 (while (and functions string)
2015 (if (eq (car functions) t)
2016 (let ((functions
2017 (default-value 'comint-preoutput-filter-functions)))
2018 (while (and functions string)
2019 (setq string (funcall (car functions) string))
2020 (setq functions (cdr functions))))
2021 (setq string (funcall (car functions) string)))
2022 (setq functions (cdr functions))))
2023
2024 ;; Insert STRING
2025 (let ((inhibit-read-only t)
2026 ;; The point should float after any insertion we do.
2027 (saved-point (copy-marker (point) t)))
2028
2029 ;; We temporarily remove any buffer narrowing, in case the
2030 ;; process mark is outside of the restriction
2031 (save-restriction
2032 (widen)
2033
2034 (goto-char (process-mark process))
2035 (set-marker comint-last-output-start (point))
2036
2037 ;; Try to skip repeated prompts, which can occur as a result of
2038 ;; commands sent without inserting them in the buffer.
2039 (let ((bol (save-excursion (forward-line 0) (point)))) ;No fields.
2040 (when (and (not (bolp))
2041 (looking-back comint-prompt-regexp bol))
2042 (let* ((prompt (buffer-substring bol (point)))
2043 (prompt-re (concat "\\`" (regexp-quote prompt))))
2044 (while (string-match prompt-re string)
2045 (setq string (substring string (match-end 0)))))))
2046 (while (string-match (concat "\\(^" comint-prompt-regexp
2047 "\\)\\1+")
2048 string)
2049 (setq string (replace-match "\\1" nil nil string)))
2050
2051 ;; insert-before-markers is a bad thing. XXX
2052 ;; Luckily we don't have to use it any more, we use
2053 ;; window-point-insertion-type instead.
2054 (insert string)
2055
2056 ;; Advance process-mark
2057 (set-marker (process-mark process) (point))
2058
2059 (unless comint-inhibit-carriage-motion
2060 ;; Interpret any carriage motion characters (newline, backspace)
2061 (comint-carriage-motion comint-last-output-start (point)))
2062
2063 ;; Run these hooks with point where the user had it.
2064 (goto-char saved-point)
2065 (run-hook-with-args 'comint-output-filter-functions string)
2066 (set-marker saved-point (point))
2067
2068 (goto-char (process-mark process)) ; In case a filter moved it.
2069
2070 (unless comint-use-prompt-regexp
2071 (with-silent-modifications
2072 (add-text-properties comint-last-output-start (point)
2073 '(front-sticky
2074 (field inhibit-line-move-field-capture)
2075 rear-nonsticky t
2076 field output
2077 inhibit-line-move-field-capture t))))
2078
2079 ;; Highlight the prompt, where we define `prompt' to mean
2080 ;; the most recent output that doesn't end with a newline.
2081 (let ((prompt-start (save-excursion (forward-line 0) (point)))
2082 (inhibit-read-only t))
2083 (when comint-prompt-read-only
2084 (with-silent-modifications
2085 (or (= (point-min) prompt-start)
2086 (get-text-property (1- prompt-start) 'read-only)
2087 (put-text-property (1- prompt-start)
2088 prompt-start 'read-only 'fence))
2089 (add-text-properties prompt-start (point)
2090 '(read-only t front-sticky (read-only)))))
2091 (when comint-last-prompt
2092 ;; There might be some keywords here waiting for
2093 ;; fontification, so no `with-silent-modifications'.
2094 (font-lock--remove-face-from-text-property
2095 (car comint-last-prompt)
2096 (cdr comint-last-prompt)
2097 'font-lock-face
2098 'comint-highlight-prompt))
2099 (setq comint-last-prompt
2100 (cons (copy-marker prompt-start) (point-marker)))
2101 (font-lock-prepend-text-property prompt-start (point)
2102 'font-lock-face
2103 'comint-highlight-prompt)
2104 (add-text-properties prompt-start (point) '(rear-nonsticky t)))
2105 (goto-char saved-point)))))))
2106
2107 (defun comint-preinput-scroll-to-bottom ()
2108 "Go to the end of buffer in all windows showing it.
2109 Movement occurs if point in the selected window is not after the process mark,
2110 and `this-command' is an insertion command. Insertion commands recognized
2111 are `self-insert-command', `comint-magic-space', `yank', and `hilit-yank'.
2112 Depends on the value of `comint-scroll-to-bottom-on-input'.
2113
2114 This function should be a pre-command hook."
2115 (if (and comint-scroll-to-bottom-on-input
2116 (memq this-command '(self-insert-command comint-magic-space yank
2117 hilit-yank)))
2118 (let* ((current (current-buffer))
2119 (process (get-buffer-process current))
2120 (scroll comint-scroll-to-bottom-on-input))
2121 (if (and process (< (point) (process-mark process)))
2122 (if (eq scroll 'this)
2123 (goto-char (point-max))
2124 (walk-windows
2125 (lambda (window)
2126 (if (and (eq (window-buffer window) current)
2127 (or (eq scroll t) (eq scroll 'all)))
2128 (with-selected-window window
2129 (goto-char (point-max)))))
2130 nil t))))))
2131
2132 (defvar follow-mode)
2133 (declare-function follow-comint-scroll-to-bottom "follow" (&optional window))
2134
2135 (defun comint-postoutput-scroll-to-bottom (_string)
2136 "Go to the end of buffer in some or all windows showing it.
2137 Do not scroll if the current line is the last line in the buffer.
2138 Depends on the value of `comint-move-point-for-output' and
2139 `comint-scroll-show-maximum-output'.
2140
2141 This function should be in the list `comint-output-filter-functions'."
2142 (let* ((current (current-buffer))
2143 (process (get-buffer-process current)))
2144 (unwind-protect
2145 (cond
2146 ((null process))
2147 ((bound-and-true-p follow-mode)
2148 (follow-comint-scroll-to-bottom))
2149 (t
2150 (dolist (w (get-buffer-window-list current nil t))
2151 (comint-adjust-window-point w process)
2152 ;; Optionally scroll to the bottom of the window.
2153 (and comint-scroll-show-maximum-output
2154 (eq (window-point w) (point-max))
2155 (with-selected-window w
2156 (recenter (- -1 scroll-margin)))))))
2157 (set-buffer current))))
2158
2159
2160 (defun comint-adjust-window-point (window process)
2161 "Move point in WINDOW based on Comint settings.
2162 For point adjustment use the process-mark of PROCESS."
2163 (and (< (window-point window) (process-mark process))
2164 (or (memq comint-move-point-for-output '(t all))
2165 ;; Maybe user wants point to jump to end.
2166 (eq comint-move-point-for-output
2167 (if (eq (selected-window) window) 'this 'others))
2168 ;; If point was at the end, keep it at end.
2169 (and (marker-position comint-last-output-start)
2170 (>= (window-point window) comint-last-output-start)))
2171 (set-window-point window (process-mark process))))
2172
2173
2174 ;; this function is nowhere used
2175 (defun comint-adjust-point (selected)
2176 "Move point in the selected window based on Comint settings.
2177 SELECTED is the window that was originally selected."
2178 (let ((process (get-buffer-process (current-buffer))))
2179 (and (< (point) (process-mark process))
2180 (or (memq comint-move-point-for-output '(t all))
2181 ;; Maybe user wants point to jump to end.
2182 (eq comint-move-point-for-output
2183 (if (eq (selected-window) selected) 'this 'others))
2184 ;; If point was at the end, keep it at end.
2185 (and (marker-position comint-last-output-start)
2186 (>= (point) comint-last-output-start)))
2187 (goto-char (process-mark process)))))
2188
2189 (defun comint-truncate-buffer (&optional _string)
2190 "Truncate the buffer to `comint-buffer-maximum-size'.
2191 This function could be on `comint-output-filter-functions' or bound to a key."
2192 (interactive)
2193 (save-excursion
2194 (goto-char (process-mark (get-buffer-process (current-buffer))))
2195 (forward-line (- comint-buffer-maximum-size))
2196 (beginning-of-line)
2197 (let ((inhibit-read-only t))
2198 (delete-region (point-min) (point)))))
2199
2200 (defun comint-strip-ctrl-m (&optional _string)
2201 "Strip trailing `^M' characters from the current output group.
2202 This function could be on `comint-output-filter-functions' or bound to a key."
2203 (interactive)
2204 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2205 (save-excursion
2206 (condition-case nil
2207 (goto-char
2208 (if (called-interactively-p 'interactive)
2209 comint-last-input-end comint-last-output-start))
2210 (error nil))
2211 (while (re-search-forward "\r+$" pmark t)
2212 (replace-match "" t t)))))
2213 (defalias 'shell-strip-ctrl-m 'comint-strip-ctrl-m)
2214
2215 (defun comint-show-maximum-output ()
2216 "Put the end of the buffer at the bottom of the window."
2217 (interactive)
2218 (goto-char (point-max))
2219 (recenter (- -1 scroll-margin)))
2220
2221 (defun comint-get-old-input-default ()
2222 "Default for `comint-get-old-input'.
2223 If `comint-use-prompt-regexp' is nil, then either
2224 return the current input field, if point is on an input field, or the
2225 current line, if point is on an output field.
2226 If `comint-use-prompt-regexp' is non-nil, then return
2227 the current line with any initial string matching the regexp
2228 `comint-prompt-regexp' removed."
2229 (let (bof)
2230 (if (and (not comint-use-prompt-regexp)
2231 ;; Make sure we're in an input rather than output field.
2232 (null (get-char-property (setq bof (field-beginning)) 'field)))
2233 (field-string-no-properties bof)
2234 (comint-bol)
2235 (buffer-substring-no-properties (point)
2236 (if comint-use-prompt-regexp
2237 (line-end-position)
2238 (field-end))))))
2239
2240 (defun comint-copy-old-input ()
2241 "Insert after prompt old input at point as new input to be edited.
2242 Calls `comint-get-old-input' to get old input."
2243 (interactive)
2244 (let ((input (funcall comint-get-old-input))
2245 (process (get-buffer-process (current-buffer))))
2246 (if (not process)
2247 (user-error "Current buffer has no process")
2248 (goto-char (process-mark process))
2249 (insert input))))
2250
2251 (defun comint-skip-prompt ()
2252 "Skip past the text matching regexp `comint-prompt-regexp'.
2253 If this takes us past the end of the current line, don't skip at all."
2254 (if (and (looking-at comint-prompt-regexp)
2255 (<= (match-end 0) (line-end-position)))
2256 (goto-char (match-end 0))))
2257
2258 (defun comint-after-pmark-p ()
2259 "Return t if point is after the process output marker."
2260 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2261 (<= (marker-position pmark) (point))))
2262
2263 (defun comint-simple-send (proc string)
2264 "Default function for sending to PROC input STRING.
2265 This just sends STRING plus a newline. To override this,
2266 set the hook `comint-input-sender'."
2267 (let ((send-string
2268 (if comint-input-sender-no-newline
2269 string
2270 ;; Sending as two separate strings does not work
2271 ;; on Windows, so concat the \n before sending.
2272 (concat string "\n"))))
2273 (comint-send-string proc send-string))
2274 (if (and comint-input-sender-no-newline
2275 (not (string-equal string "")))
2276 (process-send-eof)))
2277
2278 (defun comint-line-beginning-position ()
2279 "Return the buffer position of the beginning of the line, after any prompt.
2280 If `comint-use-prompt-regexp' is non-nil, then the prompt skip is done by
2281 skipping text matching the regular expression `comint-prompt-regexp',
2282 a buffer local variable."
2283 (if comint-use-prompt-regexp
2284 ;; Use comint-prompt-regexp
2285 (save-excursion
2286 (beginning-of-line)
2287 (comint-skip-prompt)
2288 (point))
2289 ;; Use input fields. Note that, unlike the behavior of
2290 ;; `line-beginning-position' inside a field, this function will
2291 ;; return the position of the end of a prompt, even if the point is
2292 ;; already inside the prompt. In order to do this, it assumes that
2293 ;; if there are two fields on a line, then the first one is the
2294 ;; prompt, and the second one is an input field, and is front-sticky
2295 ;; (as input fields should be).
2296 (constrain-to-field (if (eq (field-at-pos (point)) 'output)
2297 (line-beginning-position)
2298 (field-beginning))
2299 (line-end-position))))
2300
2301 (defun comint-bol (&optional arg)
2302 "Go to the beginning of line, then skip past the prompt, if any.
2303 If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
2304 If `comint-use-prompt-regexp' is non-nil, then the prompt skip is done
2305 by skipping text matching the regular expression `comint-prompt-regexp',
2306 a buffer local variable."
2307 (interactive "P")
2308 (if arg
2309 ;; Unlike `beginning-of-line', forward-line ignores field boundaries
2310 (forward-line 0)
2311 (goto-char (comint-line-beginning-position))))
2312
2313 ;; For compatibility.
2314 (defun comint-read-noecho (prompt &optional _ignore)
2315 (read-passwd prompt))
2316
2317 ;; These three functions are for entering text you don't want echoed or
2318 ;; saved -- typically passwords to ftp, telnet, or somesuch.
2319 ;; Just enter m-x send-invisible and type in your line.
2320
2321 (defun send-invisible (&optional prompt)
2322 "Read a string without echoing.
2323 Then send it to the process running in the current buffer.
2324 The string is sent using `comint-input-sender'.
2325 Security bug: your string can still be temporarily recovered with
2326 \\[view-lossage]; `clear-this-command-keys' can fix that."
2327 (interactive "P") ; Defeat snooping via C-x ESC ESC
2328 (let ((proc (get-buffer-process (current-buffer)))
2329 (prefix
2330 (if (eq (window-buffer) (current-buffer))
2331 ""
2332 (format "(In buffer %s) "
2333 (current-buffer)))))
2334 (if proc
2335 (let ((str (read-passwd (concat prefix
2336 (or prompt "Non-echoed text: ")))))
2337 (if (stringp str)
2338 (progn
2339 (comint-snapshot-last-prompt)
2340 (funcall comint-input-sender proc str))
2341 (message "Warning: text will be echoed")))
2342 (error "Buffer %s has no process" (current-buffer)))))
2343
2344 (defun comint-watch-for-password-prompt (string)
2345 "Prompt in the minibuffer for password and send without echoing.
2346 This function uses `send-invisible' to read and send a password to the buffer's
2347 process if STRING contains a password prompt defined by
2348 `comint-password-prompt-regexp'.
2349
2350 This function could be in the list `comint-output-filter-functions'."
2351 (when (let ((case-fold-search t))
2352 (string-match comint-password-prompt-regexp string))
2353 (when (string-match "^[ \n\r\t\v\f\b\a]+" string)
2354 (setq string (replace-match "" t t string)))
2355 (send-invisible string)))
2356 \f
2357 ;; Low-level process communication
2358
2359 (defun comint-send-string (process string)
2360 "Like `process-send-string', but also does extra bookkeeping for Comint mode."
2361 (if process
2362 (with-current-buffer (if (processp process)
2363 (process-buffer process)
2364 (get-buffer process))
2365 (comint-snapshot-last-prompt))
2366 (comint-snapshot-last-prompt))
2367 (process-send-string process string))
2368
2369 (defun comint-send-region (process start end)
2370 "Like `process-send-region', but also does extra bookkeeping for Comint mode."
2371 (if process
2372 (with-current-buffer (if (processp process)
2373 (process-buffer process)
2374 (get-buffer process))
2375 (comint-snapshot-last-prompt))
2376 (comint-snapshot-last-prompt))
2377 (process-send-region process start end))
2378
2379 \f
2380 ;; Random input hackage
2381
2382 (defun comint-delete-output ()
2383 "Delete all output from interpreter since last input.
2384 Does not delete the prompt."
2385 (interactive)
2386 (let ((proc (get-buffer-process (current-buffer)))
2387 (replacement nil)
2388 (inhibit-read-only t))
2389 (save-excursion
2390 (let ((pmark (progn (goto-char (process-mark proc))
2391 (forward-line 0)
2392 (point-marker))))
2393 (delete-region comint-last-input-end pmark)
2394 (goto-char (process-mark proc))
2395 (setq replacement (concat "*** output flushed ***\n"
2396 (buffer-substring pmark (point))))
2397 (delete-region pmark (point))))
2398 ;; Output message and put back prompt
2399 (comint-output-filter proc replacement)))
2400
2401 (defun comint-write-output (filename &optional append mustbenew)
2402 "Write output from interpreter since last input to FILENAME.
2403 Any prompt at the end of the output is not written.
2404
2405 If the optional argument APPEND (the prefix argument when interactive)
2406 is non-nil, the output is appended to the file instead.
2407
2408 If the optional argument MUSTBENEW is non-nil, check for an existing
2409 file with the same name. If MUSTBENEW is `excl', that means to get an
2410 error if the file already exists; never overwrite. If MUSTBENEW is
2411 neither nil nor `excl', that means ask for confirmation before
2412 overwriting, but do go ahead and overwrite the file if the user
2413 confirms. When interactive, MUSTBENEW is nil when appending, and t
2414 otherwise."
2415 (interactive
2416 (list (read-file-name
2417 (if current-prefix-arg
2418 "Append output to file: "
2419 "Write output to file: "))
2420 current-prefix-arg
2421 (not current-prefix-arg)))
2422 (save-excursion
2423 (goto-char (process-mark (get-buffer-process (current-buffer))))
2424 (forward-line 0)
2425 (write-region comint-last-input-end (point) filename
2426 append nil nil mustbenew)))
2427
2428 ;; This function exists for the benefit of the menu; from the keyboard,
2429 ;; users can just use `comint-write-output' with a prefix arg.
2430 (defun comint-append-output-to-file (filename)
2431 "Append output from interpreter since last input to FILENAME.
2432 Any prompt at the end of the output is not written."
2433 (interactive "fAppend output to file: ")
2434 (comint-write-output filename t))
2435
2436 (defun comint-show-output ()
2437 "Display start of this batch of interpreter output at top of window.
2438 Sets mark to the value of point when this command is run."
2439 (interactive)
2440 (push-mark)
2441 (let ((pos (or (marker-position comint-last-input-end) (point-max))))
2442 (cond (comint-use-prompt-regexp
2443 (goto-char pos)
2444 (beginning-of-line 0)
2445 (set-window-start (selected-window) (point))
2446 (comint-skip-prompt))
2447 (t
2448 (goto-char (field-beginning pos))
2449 (set-window-start (selected-window) (point))))))
2450
2451 (defun comint-clear-buffer ()
2452 "Clear the comint buffer."
2453 (interactive)
2454 (let ((comint-buffer-maximum-size 0))
2455 (comint-truncate-buffer)))
2456
2457 (defun comint-interrupt-subjob ()
2458 "Interrupt the current subjob.
2459 This command also kills the pending input
2460 between the process mark and point."
2461 (interactive)
2462 (comint-skip-input)
2463 (interrupt-process nil comint-ptyp)
2464 ;; (process-send-string nil "\n")
2465 )
2466
2467 (defun comint-kill-subjob ()
2468 "Send kill signal to the current subjob.
2469 This command also kills the pending input
2470 between the process mark and point."
2471 (interactive)
2472 (comint-skip-input)
2473 (kill-process nil comint-ptyp))
2474
2475 (defun comint-quit-subjob ()
2476 "Send quit signal to the current subjob.
2477 This command also kills the pending input
2478 between the process mark and point."
2479 (interactive)
2480 (comint-skip-input)
2481 (quit-process nil comint-ptyp))
2482
2483 (defun comint-stop-subjob ()
2484 "Stop the current subjob.
2485 This command also kills the pending input
2486 between the process mark and point.
2487
2488 WARNING: if there is no current subjob, you can end up suspending
2489 the top-level process running in the buffer. If you accidentally do
2490 this, use \\[comint-continue-subjob] to resume the process. (This
2491 is not a problem with most shells, since they ignore this signal.)"
2492 (interactive)
2493 (comint-skip-input)
2494 (stop-process nil comint-ptyp))
2495
2496 (defun comint-continue-subjob ()
2497 "Send CONT signal to process buffer's process group.
2498 Useful if you accidentally suspend the top-level process."
2499 (interactive)
2500 (continue-process nil comint-ptyp))
2501
2502 (defun comint-skip-input ()
2503 "Skip all pending input, from last stuff output by interpreter to point.
2504 This means mark it as if it had been sent as input, without sending it."
2505 (let ((comint-input-sender 'ignore)
2506 (comint-input-filter-functions nil))
2507 (comint-send-input t t))
2508 (end-of-line)
2509 (let ((pos (point))
2510 (marker (process-mark (get-buffer-process (current-buffer)))))
2511 (insert " " (key-description (this-command-keys)))
2512 (if (= marker pos)
2513 (set-marker marker (point)))))
2514
2515 (defun comint-kill-input ()
2516 "Kill all text from last stuff output by interpreter to point."
2517 (interactive)
2518 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2519 (if (> (point) (marker-position pmark))
2520 (kill-region pmark (point)))))
2521
2522 (defun comint-delchar-or-maybe-eof (arg)
2523 "Delete ARG characters forward or send an EOF to subprocess.
2524 Sends an EOF only if point is at the end of the buffer and there is no input."
2525 (interactive "p")
2526 (let ((proc (get-buffer-process (current-buffer))))
2527 (if (and (eobp) proc (= (point) (marker-position (process-mark proc))))
2528 (comint-send-eof)
2529 (delete-char arg))))
2530
2531 (defun comint-send-eof ()
2532 "Send an EOF to the current buffer's process."
2533 (interactive)
2534 (comint-send-input t t)
2535 (process-send-eof))
2536
2537
2538 (defun comint-backward-matching-input (regexp n)
2539 "Search backward through buffer for input fields that match REGEXP.
2540 If `comint-use-prompt-regexp' is non-nil, then input fields are identified
2541 by lines that match `comint-prompt-regexp'.
2542
2543 With prefix argument N, search for Nth previous match.
2544 If N is negative, find the next or Nth next match."
2545 (interactive (comint-regexp-arg "Backward input matching (regexp): "))
2546 (if comint-use-prompt-regexp
2547 ;; Use comint-prompt-regexp
2548 (let* ((re (concat comint-prompt-regexp ".*" regexp))
2549 (pos (save-excursion (end-of-line (if (> n 0) 0 1))
2550 (if (re-search-backward re nil t n)
2551 (point)))))
2552 (if (null pos)
2553 (progn (message "Not found")
2554 (ding))
2555 (goto-char pos)
2556 (comint-bol nil)))
2557 ;; Use input fields
2558 (let* ((dir (if (< n 0) -1 1))
2559 (pos
2560 (save-excursion
2561 (while (/= n 0)
2562 (unless (re-search-backward regexp nil t dir)
2563 (user-error "Not found"))
2564 (unless (get-char-property (point) 'field)
2565 (setq n (- n dir))))
2566 (field-beginning))))
2567 (goto-char pos))))
2568
2569
2570 (defun comint-forward-matching-input (regexp n)
2571 "Search forward through buffer for input fields that match REGEXP.
2572 If `comint-use-prompt-regexp' is non-nil, then input fields are identified
2573 by lines that match `comint-prompt-regexp'.
2574
2575 With prefix argument N, search for Nth following match.
2576 If N is negative, find the previous or Nth previous match."
2577 (interactive (comint-regexp-arg "Forward input matching (regexp): "))
2578 (comint-backward-matching-input regexp (- n)))
2579
2580
2581 (defun comint-next-prompt (n)
2582 "Move to end of Nth next prompt in the buffer.
2583 If `comint-use-prompt-regexp' is nil, then this means the beginning of
2584 the Nth next `input' field, otherwise, it means the Nth occurrence of
2585 text matching `comint-prompt-regexp'."
2586 (interactive "p")
2587 (if comint-use-prompt-regexp
2588 ;; Use comint-prompt-regexp
2589 (let ((paragraph-start comint-prompt-regexp))
2590 (end-of-line (if (> n 0) 1 0))
2591 (forward-paragraph n)
2592 (comint-skip-prompt))
2593 ;; Use input fields
2594 (let ((pos (point))
2595 (input-pos nil)
2596 prev-pos)
2597 (while (/= n 0)
2598 (setq prev-pos pos)
2599 (setq pos
2600 (if (> n 0)
2601 (next-single-char-property-change pos 'field)
2602 (previous-single-char-property-change pos 'field)))
2603 (cond ((= pos prev-pos)
2604 ;; Ran off the end of the buffer.
2605 (when (> n 0)
2606 ;; There's always an input field at the end of the
2607 ;; buffer, but it has a `field' property of nil.
2608 (setq input-pos (point-max)))
2609 ;; stop iterating
2610 (setq n 0))
2611 ((null (get-char-property pos 'field))
2612 (setq n (if (< n 0) (1+ n) (1- n)))
2613 (setq input-pos pos))))
2614 (when input-pos
2615 (goto-char input-pos)))))
2616
2617
2618 (defun comint-previous-prompt (n)
2619 "Move to end of Nth previous prompt in the buffer.
2620 If `comint-use-prompt-regexp' is nil, then this means the beginning of
2621 the Nth previous `input' field, otherwise, it means the Nth occurrence of
2622 text matching `comint-prompt-regexp'."
2623 (interactive "p")
2624 (comint-next-prompt (- n)))
2625
2626 ;; State used by `comint-insert-previous-argument' when cycling.
2627 (defvar-local comint-insert-previous-argument-last-start-pos nil)
2628 (defvar-local comint-insert-previous-argument-last-index nil)
2629
2630 ;; Needs fixing:
2631 ;; make comint-arguments understand negative indices as bash does
2632 (defun comint-insert-previous-argument (index)
2633 "Insert the INDEXth argument from the previous Comint command-line at point.
2634 Spaces are added at beginning and/or end of the inserted string if
2635 necessary to ensure that it's separated from adjacent arguments.
2636 Interactively, if no prefix argument is given, the last argument is inserted.
2637 Repeated interactive invocations will cycle through the same argument
2638 from progressively earlier commands (using the value of INDEX specified
2639 with the first command).
2640 This command is like `M-.' in bash."
2641 (interactive "P")
2642 (unless (null index)
2643 (setq index (prefix-numeric-value index)))
2644 (cond ((eq last-command this-command)
2645 ;; Delete last input inserted by this command.
2646 (delete-region comint-insert-previous-argument-last-start-pos (point))
2647 (setq index comint-insert-previous-argument-last-index))
2648 (t
2649 ;; This is a non-repeat invocation, so initialize state.
2650 (setq comint-input-ring-index nil)
2651 (setq comint-insert-previous-argument-last-index index)
2652 (when (null comint-insert-previous-argument-last-start-pos)
2653 ;; First usage; initialize to a marker
2654 (setq comint-insert-previous-argument-last-start-pos
2655 (make-marker)))))
2656 ;; Make sure we're not in the prompt, and add a beginning space if necessary.
2657 (if (<= (point) (comint-line-beginning-position))
2658 (comint-bol)
2659 (just-one-space))
2660 ;; Remember the beginning of what we insert, so we can delete it if
2661 ;; the command is repeated.
2662 (set-marker comint-insert-previous-argument-last-start-pos (point))
2663 ;; Insert the argument.
2664 (let ((input-string (comint-previous-input-string 0)))
2665 (when (string-match "[ \t\n]*&" input-string)
2666 ;; strip terminating '&'
2667 (setq input-string (substring input-string 0 (match-beginning 0))))
2668 (insert (comint-arguments input-string index index)))
2669 ;; Make next invocation return arg from previous input
2670 (setq comint-input-ring-index (1+ (or comint-input-ring-index 0)))
2671 ;; Add a terminating space if necessary.
2672 (unless (eolp)
2673 (just-one-space)))
2674
2675 \f
2676 ;; Support editing with `comint-prompt-read-only' set to t.
2677
2678 (defun comint-update-fence ()
2679 "Update read-only status of newline before point.
2680 The `fence' read-only property is used to indicate that a newline
2681 is read-only for no other reason than to \"fence off\" a
2682 following front-sticky read-only region. This is used to
2683 implement comint read-only prompts. If the text after a newline
2684 changes, the read-only status of that newline may need updating.
2685 That is what this function does.
2686
2687 This function does nothing if point is not at the beginning of a
2688 line, or is at the beginning of the accessible portion of the buffer.
2689 Otherwise, if the character after point has a front-sticky
2690 read-only property, then the preceding newline is given a
2691 read-only property of `fence', unless it already is read-only.
2692 If the character after point does not have a front-sticky
2693 read-only property, any read-only property of `fence' on the
2694 preceding newline is removed."
2695 (let* ((pt (point)) (lst (get-text-property pt 'front-sticky)))
2696 (and (bolp)
2697 (not (bobp))
2698 (with-silent-modifications
2699 (if (and (get-text-property pt 'read-only)
2700 (if (listp lst) (memq 'read-only lst) t))
2701 (unless (get-text-property (1- pt) 'read-only)
2702 (put-text-property (1- pt) pt 'read-only 'fence))
2703 (when (eq (get-text-property (1- pt) 'read-only) 'fence)
2704 (remove-list-of-text-properties (1- pt) pt '(read-only))))))))
2705
2706 (defun comint-kill-whole-line (&optional count)
2707 "Kill current line, ignoring read-only and field properties.
2708 With prefix arg COUNT, kill that many lines starting from the current line.
2709 If COUNT is negative, kill backward. Also kill the preceding newline,
2710 instead of the trailing one. \(This is meant to make \\[repeat] work well
2711 with negative arguments.)
2712 If COUNT is zero, kill current line but exclude the trailing newline.
2713 The read-only status of newlines is updated with `comint-update-fence',
2714 if necessary."
2715 (interactive "p")
2716 (let ((inhibit-read-only t) (inhibit-field-text-motion t))
2717 (kill-whole-line count)
2718 (when (>= count 0) (comint-update-fence))))
2719
2720 (defun comint-kill-region (beg end)
2721 "Like `kill-region', but ignores read-only properties, if safe.
2722 This command assumes that the buffer contains read-only
2723 \"prompts\" which are regions with front-sticky read-only
2724 properties at the beginning of a line, with the preceding newline
2725 being read-only to protect the prompt. This is true of the
2726 comint prompts if `comint-prompt-read-only' is non-nil. This
2727 command will not delete the region if this would create mutilated
2728 or out of place prompts. That is, if any part of a prompt is
2729 deleted, the entire prompt must be deleted and all remaining
2730 prompts should stay at the beginning of a line. If this is not
2731 the case, this command just calls `kill-region' with all
2732 read-only properties intact. The read-only status of newlines is
2733 updated using `comint-update-fence', if necessary."
2734 (interactive "r")
2735 (save-excursion
2736 (let* ((true-beg (min beg end))
2737 (true-end (max beg end))
2738 (beg-bolp (progn (goto-char true-beg) (bolp)))
2739 (beg-lst (get-text-property true-beg 'front-sticky))
2740 (beg-bad (and (get-text-property true-beg 'read-only)
2741 (if (listp beg-lst) (memq 'read-only beg-lst) t)))
2742 (end-bolp (progn (goto-char true-end) (bolp)))
2743 (end-lst (get-text-property true-end 'front-sticky))
2744 (end-bad (and (get-text-property true-end 'read-only)
2745 (if (listp end-lst) (memq 'read-only end-lst) t))))
2746 (if (or (and (not beg-bolp) (or beg-bad end-bad))
2747 (and (not end-bolp) end-bad))
2748 (kill-region beg end)
2749 (let ((inhibit-read-only t))
2750 (kill-region beg end)
2751 (comint-update-fence))))))
2752 \f
2753 ;; Support for source-file processing commands.
2754 ;;============================================================================
2755 ;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2756 ;; commands that process files of source text (e.g. loading or compiling
2757 ;; files). So the corresponding process-in-a-buffer modes have commands
2758 ;; for doing this (e.g., lisp-load-file). The functions below are useful
2759 ;; for defining these commands.
2760 ;;
2761 ;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2762 ;; and Soar, in that they don't know anything about file extensions.
2763 ;; So the compile/load interface gets the wrong default occasionally.
2764 ;; The load-file/compile-file default mechanism could be smarter -- it
2765 ;; doesn't know about the relationship between filename extensions and
2766 ;; whether the file is source or executable. If you compile foo.lisp
2767 ;; with compile-file, then the next load-file should use foo.bin for
2768 ;; the default, not foo.lisp. This is tricky to do right, particularly
2769 ;; because the extension for executable files varies so much (.o, .bin,
2770 ;; .lbin, .mo, .vo, .ao, ...).
2771
2772
2773 ;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
2774 ;; commands.
2775 ;;
2776 ;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2777 ;; want to save the buffer before issuing any process requests to the command
2778 ;; interpreter.
2779 ;;
2780 ;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
2781 ;; for the file to process.
2782
2783 (defun comint-source-default (previous-dir/file source-modes)
2784 "Compute the defaults for `load-file' and `compile-file' commands.
2785
2786 PREVIOUS-DIR/FILE is a pair (DIRECTORY . FILENAME) from the last
2787 source-file processing command, or nil if there hasn't been one yet.
2788 SOURCE-MODES is a list used to determine what buffers contain source
2789 files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2790 Typically, (lisp-mode) or (scheme-mode).
2791
2792 If the command is given while the cursor is inside a string, *and*
2793 the string is an existing filename, *and* the filename is not a directory,
2794 then the string is taken as default. This allows you to just position
2795 your cursor over a string that's a filename and have it taken as default.
2796
2797 If the command is given in a file buffer whose major mode is in
2798 SOURCE-MODES, then the filename is the default file, and the
2799 file's directory is the default directory.
2800
2801 If the buffer isn't a source file buffer (e.g., it's the process buffer),
2802 then the default directory & file are what was used in the last source-file
2803 processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2804 the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2805 is the cwd, with no default file. (\"no default file\" = nil)
2806
2807 SOURCE-MODES is typically going to be something like (tea-mode)
2808 for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2809 for Soar programs, etc.
2810
2811 The function returns a pair: (default-directory . default-file)."
2812 (cond ((and buffer-file-name (memq major-mode source-modes))
2813 (cons (file-name-directory buffer-file-name)
2814 (file-name-nondirectory buffer-file-name)))
2815 (previous-dir/file)
2816 (t
2817 (cons default-directory nil))))
2818
2819
2820 (defun comint-check-source (fname)
2821 "Check whether to save buffers visiting file FNAME.
2822 Prior to loading or compiling (or otherwise processing) a file (in the CMU
2823 process-in-a-buffer modes), this function can be called on the filename.
2824 If the file is loaded into a buffer, and the buffer is modified, the user
2825 is queried to see if he wants to save the buffer before proceeding with
2826 the load or compile."
2827 (let ((buff (get-file-buffer fname)))
2828 (if (and buff
2829 (buffer-modified-p buff)
2830 (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
2831 (with-current-buffer buff
2832 (save-buffer)))))
2833
2834 (defun comint-extract-string ()
2835 "Return string around point, or nil."
2836 (let ((syntax (syntax-ppss)))
2837 (when (nth 3 syntax)
2838 (condition-case ()
2839 (buffer-substring-no-properties (1+ (nth 8 syntax))
2840 (progn (goto-char (nth 8 syntax))
2841 (forward-sexp)
2842 (1- (point))))
2843 (error nil)))))
2844
2845 (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
2846 "Prompt for filenames in commands that process source files,
2847 e.g. loading or compiling a file.
2848 Provides a default, if there is one, and returns the result filename.
2849
2850 See `comint-source-default' for more on determining defaults.
2851
2852 PROMPT is the prompt string. PREV-DIR/FILE is the (DIRECTORY . FILE) pair
2853 from the last source processing command. SOURCE-MODES is a list of major
2854 modes used to determine what file buffers contain source files. (These
2855 two arguments are used for determining defaults.) If MUSTMATCH-P is true,
2856 then the filename reader will only accept a file that exists.
2857
2858 A typical use:
2859 (interactive (comint-get-source \"Compile file: \" prev-lisp-dir/file
2860 \\='(lisp-mode) t))"
2861 (let* ((def (comint-source-default prev-dir/file source-modes))
2862 (stringfile (comint-extract-string))
2863 (sfile-p (and stringfile
2864 (condition-case ()
2865 (file-exists-p stringfile)
2866 (error nil))
2867 (not (file-directory-p stringfile))))
2868 (defdir (if sfile-p (file-name-directory stringfile)
2869 (car def)))
2870 (deffile (if sfile-p (file-name-nondirectory stringfile)
2871 (cdr def)))
2872 (ans (read-file-name (if deffile (format "%s(default %s) "
2873 prompt deffile)
2874 prompt)
2875 defdir
2876 (concat defdir deffile)
2877 mustmatch-p)))
2878 (list (expand-file-name (substitute-in-file-name ans)))))
2879
2880 ;; I am somewhat divided on this string-default feature. It seems
2881 ;; to violate the principle-of-least-astonishment, in that it makes
2882 ;; the default harder to predict, so you actually have to look and see
2883 ;; what the default really is before choosing it. This can trip you up.
2884 ;; On the other hand, it can be useful, I guess. I would appreciate feedback
2885 ;; on this.
2886 ;; -Olin
2887
2888 \f
2889 ;; Simple process query facility.
2890 ;; ===========================================================================
2891 ;; This function is for commands that want to send a query to the process
2892 ;; and show the response to the user. For example, a command to get the
2893 ;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2894 ;; to an inferior Common Lisp process.
2895 ;;
2896 ;; This simple facility just sends strings to the inferior process and pops
2897 ;; up a window for the process buffer so you can see what the process
2898 ;; responds with. We don't do anything fancy like try to intercept what the
2899 ;; process responds with and put it in a pop-up window or on the message
2900 ;; line. We just display the buffer. Low tech. Simple. Works good.
2901
2902 (defun comint-proc-query (proc str)
2903 "Send to the inferior process PROC the string STR.
2904 Pop-up but do not select a window for the inferior process so that
2905 its response can be seen."
2906 (let* ((proc-buf (process-buffer proc))
2907 (proc-mark (process-mark proc)))
2908 (display-buffer proc-buf)
2909 (set-buffer proc-buf) ; but it's not the selected *window*
2910 (let ((proc-win (get-buffer-window proc-buf 0))
2911 (proc-pt (marker-position proc-mark)))
2912 (comint-send-string proc str) ; send the query
2913 (accept-process-output proc) ; wait for some output
2914 ;; Try to position the proc window so you can see the answer.
2915 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2916 ;; I don't know why. Wizards invited to improve it.
2917 (unless (pos-visible-in-window-p proc-pt proc-win)
2918 (let ((opoint (window-point proc-win)))
2919 (set-window-point proc-win proc-mark)
2920 (sit-for 0)
2921 (if (not (pos-visible-in-window-p opoint proc-win))
2922 (push-mark opoint)
2923 (set-window-point proc-win opoint)))))))
2924
2925 \f
2926 ;; Filename/command/history completion in a buffer
2927 ;; ===========================================================================
2928 ;; Useful completion functions, courtesy of the Ergo group.
2929
2930 ;; Six commands:
2931 ;; completion-at-point Complete or expand command, filename,
2932 ;; history at point.
2933 ;; comint-dynamic-complete-filename Complete filename at point.
2934 ;; comint-dynamic-list-filename-completions List completions in help buffer.
2935 ;; comint-replace-by-expanded-filename Expand and complete filename at point;
2936 ;; replace with expanded/completed name.
2937
2938 ;; These are not installed in the comint-mode keymap. But they are
2939 ;; available for people who want them. Shell-mode installs them:
2940 ;; (define-key shell-mode-map "\t" 'completion-at-point)
2941 ;; (define-key shell-mode-map "\M-?"
2942 ;; 'comint-dynamic-list-filename-completions)))
2943 ;;
2944 ;; Commands like this are fine things to put in load hooks if you
2945 ;; want them present in specific modes.
2946
2947 (defcustom comint-completion-autolist nil
2948 "If non-nil, automatically list possibilities on partial completion.
2949 This mirrors the optional behavior of tcsh."
2950 :type 'boolean
2951 :group 'comint-completion)
2952
2953 (defcustom comint-completion-addsuffix t
2954 "If non-nil, add ` ' to file names.
2955 It can either be a string FILESUFFIX or a cons (DIRSUFFIX . FILESUFFIX)
2956 where DIRSUFFIX is ignored and FILESUFFIX is a string added on unambiguous
2957 or exact completion.
2958 This mirrors the optional behavior of tcsh."
2959 :type '(choice (const :tag "None" nil)
2960 (const :tag "Add SPC" t)
2961 (string :tag "File suffix")
2962 (cons :tag "Obsolete suffix pair"
2963 (string :tag "Ignored")
2964 (string :tag "File suffix")))
2965 :group 'comint-completion)
2966
2967 (defcustom comint-completion-recexact nil
2968 "If non-nil, use shortest completion if characters cannot be added.
2969 This mirrors the optional behavior of tcsh.
2970
2971 A non-nil value is useful if `comint-completion-autolist' is non-nil too."
2972 :type 'boolean
2973 :group 'comint-completion)
2974
2975 (defcustom comint-completion-fignore nil
2976 "List of suffixes to be disregarded during file completion.
2977 This mirrors the optional behavior of bash and tcsh.
2978
2979 Note that this applies to `comint-dynamic-complete-filename' only."
2980 :type '(repeat (string :tag "Suffix"))
2981 :group 'comint-completion)
2982
2983 ;;;###autoload
2984 (defvar comint-file-name-prefix (purecopy "")
2985 "Prefix prepended to absolute file names taken from process input.
2986 This is used by Comint's and shell's completion functions, and by shell's
2987 directory tracking functions.")
2988
2989 (defvar comint-file-name-chars
2990 (if (memq system-type '(ms-dos windows-nt cygwin))
2991 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
2992 "[]~/A-Za-z0-9+@:_.$#%,={}-")
2993 "String of characters valid in a file name.
2994 Note that all non-ASCII characters are considered valid in a file name
2995 regardless of what this variable says.
2996
2997 This is a good thing to set in mode hooks.")
2998
2999 (defvar comint-file-name-quote-list nil
3000 "List of characters to quote with `\\' when in a file name.
3001
3002 This is a good thing to set in mode hooks.")
3003
3004
3005 (defun comint-directory (directory)
3006 "Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute."
3007 (expand-file-name (if (file-name-absolute-p directory)
3008 (concat comint-file-name-prefix directory)
3009 directory)))
3010
3011
3012 (defun comint-word (word-chars)
3013 "Return the word of WORD-CHARS at point, or nil if none is found.
3014 Word constituents are considered to be those in WORD-CHARS, which is like the
3015 inside of a \"[...]\" (see `skip-chars-forward'), plus all non-ASCII characters."
3016 ;; FIXME: Need to handle "..." and '...' quoting in shell.el!
3017 ;; This should be combined with completion parsing somehow.
3018 (save-excursion
3019 (let ((here (point))
3020 giveup)
3021 (while (not giveup)
3022 (let ((startpoint (point)))
3023 (skip-chars-backward (concat "\\\\" word-chars))
3024 (if (and comint-file-name-quote-list
3025 (eq (char-before (1- (point))) ?\\))
3026 (forward-char -2))
3027 ;; FIXME: This isn't consistent with Bash, at least -- not
3028 ;; all non-ASCII chars should be word constituents.
3029 (if (and (not (bobp)) (>= (char-before) 128))
3030 (forward-char -1))
3031 (if (= (point) startpoint)
3032 (setq giveup t))))
3033 ;; Set match-data to match the entire string.
3034 (when (< (point) here)
3035 (set-match-data (list (point) here))
3036 (match-string 0)))))
3037
3038 (defun comint-substitute-in-file-name (filename)
3039 "Return FILENAME with environment variables substituted.
3040 Supports additional environment variable syntax of the command
3041 interpreter (e.g., the percent notation of cmd.exe on Windows)."
3042 (let ((name (substitute-in-file-name filename)))
3043 (if (memq system-type '(ms-dos windows-nt))
3044 (let (env-var-name
3045 env-var-val)
3046 (save-match-data
3047 (while (string-match "%\\([^\\\\/]*\\)%" name)
3048 (setq env-var-name (match-string 1 name))
3049 (setq env-var-val (or (getenv env-var-name) ""))
3050 (setq name (replace-match env-var-val t t name))))))
3051 name))
3052
3053 (defun comint--match-partial-filename ()
3054 "Return the filename at point as-is, or nil if none is found.
3055 See `comint-word'."
3056 (comint-word comint-file-name-chars))
3057
3058 (defun comint--unquote&requote-argument (qstr &optional upos)
3059 (unless upos (setq upos 0))
3060 (let* ((qpos 0)
3061 (ustrs '())
3062 (re (concat
3063 "\\$\\(?:\\([[:alpha:]][[:alnum:]]*\\)"
3064 "\\|{\\(?1:[^{}]+\\)}\\)"
3065 (when (memq system-type '(ms-dos windows-nt))
3066 "\\|%\\(?1:[^\\\\/]*\\)%")
3067 (when comint-file-name-quote-list
3068 "\\|\\\\\\(.\\)")))
3069 (qupos nil)
3070 (push (lambda (str end)
3071 (push str ustrs)
3072 (setq upos (- upos (length str)))
3073 (unless (or qupos (> upos 0))
3074 (setq qupos (if (< end 0) (- end) (+ upos end))))))
3075 match)
3076 (while (setq match (string-match re qstr qpos))
3077 (funcall push (substring qstr qpos match) match)
3078 (cond
3079 ((match-beginning 2) (funcall push (match-string 2 qstr) (match-end 0)))
3080 ((match-beginning 1) (funcall push (getenv (match-string 1 qstr))
3081 (- (match-end 0))))
3082 (t (error "Unexpected case in comint--unquote&requote-argument!")))
3083 (setq qpos (match-end 0)))
3084 (funcall push (substring qstr qpos) (length qstr))
3085 (list (mapconcat #'identity (nreverse ustrs) "")
3086 qupos #'comint-quote-filename)))
3087
3088 (defun comint--unquote-argument (str)
3089 (car (comint--unquote&requote-argument str)))
3090 (define-obsolete-function-alias 'comint--unquote&expand-filename
3091 #'comint--unquote-argument "24.3")
3092
3093 (defun comint-match-partial-filename ()
3094 "Return the unquoted&expanded filename at point, or nil if none is found.
3095 Environment variables are substituted. See `comint-word'."
3096 (let ((filename (comint--match-partial-filename)))
3097 (and filename (comint--unquote-argument filename))))
3098
3099 (defun comint-quote-filename (filename)
3100 "Return FILENAME with magic characters quoted.
3101 Magic characters are those in `comint-file-name-quote-list'."
3102 (if (null comint-file-name-quote-list)
3103 filename
3104 (let ((regexp (regexp-opt-charset comint-file-name-quote-list)))
3105 (save-match-data
3106 (let ((i 0))
3107 (while (string-match regexp filename i)
3108 (setq filename (replace-match "\\\\\\&" nil nil filename))
3109 (setq i (1+ (match-end 0)))))
3110 filename))))
3111
3112 (defun comint-unquote-filename (filename)
3113 "Return FILENAME with quoted characters unquoted."
3114 (declare (obsolete nil "24.3"))
3115 (if (null comint-file-name-quote-list)
3116 filename
3117 (save-match-data
3118 (replace-regexp-in-string "\\\\\\(.\\)" "\\1" filename t))))
3119
3120 (defun comint--requote-argument (upos qstr)
3121 ;; See `completion-table-with-quoting'.
3122 (let ((res (comint--unquote&requote-argument qstr upos)))
3123 (cons (nth 1 res) (nth 2 res))))
3124
3125 (defun comint-completion-at-point ()
3126 (run-hook-with-args-until-success 'comint-dynamic-complete-functions))
3127
3128 (define-obsolete-function-alias
3129 'comint-dynamic-complete
3130 'completion-at-point "24.1")
3131
3132 (defun comint-dynamic-complete-filename ()
3133 "Dynamically complete the filename at point.
3134 Completes if after a filename.
3135 This function is similar to `comint-replace-by-expanded-filename', except that
3136 it won't change parts of the filename already entered in the buffer; it just
3137 adds completion characters to the end of the filename. A completions listing
3138 may be shown in a separate buffer if completion is ambiguous.
3139
3140 Completion is dependent on the value of `comint-completion-addsuffix',
3141 `comint-completion-recexact' and `comint-completion-fignore', and the timing of
3142 completions listing is dependent on the value of `comint-completion-autolist'.
3143
3144 Returns t if successful."
3145 (interactive)
3146 (when (comint--match-partial-filename)
3147 (unless (window-minibuffer-p)
3148 (message "Completing file name..."))
3149 (let ((data (comint--complete-file-name-data)))
3150 (completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)))))
3151
3152 (defun comint-filename-completion ()
3153 "Return completion data for filename at point, if any."
3154 (when (comint--match-partial-filename)
3155 (comint--complete-file-name-data)))
3156
3157 (defun comint-completion-file-name-table (string pred action)
3158 (if (not (file-name-absolute-p string))
3159 (completion-file-name-table string pred action)
3160 (cond
3161 ((memq action '(t lambda))
3162 (completion-file-name-table
3163 (concat comint-file-name-prefix string) pred action))
3164 ((null action)
3165 (let ((res (completion-file-name-table
3166 (concat comint-file-name-prefix string) pred action)))
3167 (if (and (stringp res)
3168 (string-match
3169 (concat "\\`" (regexp-quote comint-file-name-prefix))
3170 res))
3171 (substring res (match-end 0))
3172 res)))
3173 (t (completion-file-name-table string pred action)))))
3174
3175 (defvar comint-unquote-function #'comint--unquote-argument
3176 "Function to use for completion of quoted data.
3177 See `completion-table-with-quoting' and `comint-requote-function'.")
3178 (defvar comint-requote-function #'comint--requote-argument
3179 "Function to use for completion of quoted data.
3180 See `completion-table-with-quoting' and `comint-unquote-function'.")
3181
3182 (defun comint--complete-file-name-data ()
3183 "Return the completion data for file name at point."
3184 (let* ((filesuffix (cond ((not comint-completion-addsuffix) "")
3185 ((stringp comint-completion-addsuffix)
3186 comint-completion-addsuffix)
3187 ((not (consp comint-completion-addsuffix)) " ")
3188 (t (cdr comint-completion-addsuffix))))
3189 (filename (comint--match-partial-filename))
3190 (filename-beg (if filename (match-beginning 0) (point)))
3191 (filename-end (if filename (match-end 0) (point)))
3192 (table
3193 (completion-table-with-quoting
3194 #'comint-completion-file-name-table
3195 comint-unquote-function
3196 comint-requote-function)))
3197 (nconc
3198 (list
3199 filename-beg filename-end
3200 (lambda (string pred action)
3201 (let ((completion-ignore-case read-file-name-completion-ignore-case)
3202 (completion-ignored-extensions comint-completion-fignore))
3203 (complete-with-action action table string pred))))
3204 (unless (zerop (length filesuffix))
3205 (list :exit-function
3206 (lambda (_s status)
3207 (when (eq status 'finished)
3208 (if (looking-at (regexp-quote filesuffix))
3209 (goto-char (match-end 0))
3210 (insert filesuffix)))))))))
3211
3212 (defun comint-dynamic-complete-as-filename ()
3213 "Dynamically complete at point as a filename.
3214 See `comint-dynamic-complete-filename'. Returns t if successful."
3215 (declare (obsolete comint-filename-completion "24.1"))
3216 (let ((data (comint--complete-file-name-data)))
3217 (completion-in-region (nth 0 data) (nth 1 data) (nth 2 data))))
3218
3219 (defun comint-replace-by-expanded-filename ()
3220 "Dynamically expand and complete the filename at point.
3221 Replace the filename with an expanded, canonicalized and
3222 completed replacement, i.e. substituting environment
3223 variables (e.g. $HOME), `~'s, `..', and `.', and making the
3224 filename absolute. For expansion see `expand-file-name' and
3225 `substitute-in-file-name'. For completion see
3226 `comint-dynamic-complete-filename'."
3227 (interactive)
3228 (let ((filename (comint-match-partial-filename)))
3229 (when filename
3230 (replace-match (expand-file-name filename) t t)
3231 (comint-dynamic-complete-filename))))
3232
3233
3234 (defun comint-dynamic-simple-complete (stub candidates)
3235 "Dynamically complete STUB from CANDIDATES list.
3236 This function inserts completion characters at point by
3237 completing STUB from the strings in CANDIDATES. If completion is
3238 ambiguous, possibly show a completions listing in a separate
3239 buffer.
3240
3241 Return nil if no completion was inserted.
3242 Return `sole' if completed with the only completion match.
3243 Return `shortest' if completed with the shortest match.
3244 Return `partial' if completed as far as possible.
3245 Return `listed' if a completion listing was shown.
3246
3247 See also `comint-dynamic-complete-filename'."
3248 (declare (obsolete completion-in-region "24.1"))
3249 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
3250 (minibuffer-p (window-minibuffer-p))
3251 (suffix (cond ((not comint-completion-addsuffix) "")
3252 ((not (consp comint-completion-addsuffix)) " ")
3253 (t (cdr comint-completion-addsuffix))))
3254 (completions (all-completions stub candidates)))
3255 (cond ((null completions)
3256 (if minibuffer-p
3257 (minibuffer-message "No completions of %s" stub)
3258 (message "No completions of %s" stub))
3259 nil)
3260 ((= 1 (length completions)) ; Gotcha!
3261 (let ((completion (car completions)))
3262 (if (string-equal completion stub)
3263 (unless minibuffer-p
3264 (message "Sole completion"))
3265 (insert (substring completion (length stub)))
3266 (unless minibuffer-p
3267 (message "Completed")))
3268 (insert suffix)
3269 'sole))
3270 (t ; There's no unique completion.
3271 (let ((completion (try-completion stub candidates)))
3272 ;; Insert the longest substring.
3273 (insert (substring completion (length stub)))
3274 (cond ((and comint-completion-recexact comint-completion-addsuffix
3275 (string-equal stub completion)
3276 (member completion completions))
3277 ;; It's not unique, but user wants shortest match.
3278 (insert suffix)
3279 (unless minibuffer-p
3280 (message "Completed shortest"))
3281 'shortest)
3282 ((or comint-completion-autolist
3283 (string-equal stub completion))
3284 ;; It's not unique, list possible completions.
3285 (comint-dynamic-list-completions completions stub)
3286 'listed)
3287 (t
3288 (unless minibuffer-p
3289 (message "Partially completed"))
3290 'partial)))))))
3291
3292 (defun comint-dynamic-list-filename-completions ()
3293 "Display a list of possible completions for the filename at point."
3294 (interactive)
3295 (let* ((data (comint--complete-file-name-data))
3296 (minibuffer-completion-table (nth 2 data))
3297 (minibuffer-completion-predicate nil)
3298 (ol (make-overlay (nth 0 data) (nth 1 data) nil nil t)))
3299 (overlay-put ol 'field 'completion)
3300 (unwind-protect
3301 (call-interactively 'minibuffer-completion-help)
3302 (delete-overlay ol))))
3303
3304
3305 ;; This is bound locally in a *Completions* buffer to the list of
3306 ;; completions displayed, and is used to detect the case where the same
3307 ;; command is repeatedly used without the set of completions changing.
3308 (defvar comint-displayed-dynamic-completions nil)
3309
3310 (defvar comint-dynamic-list-completions-config nil)
3311
3312 (defun comint-dynamic-list-completions (completions &optional common-substring)
3313 "Display a list of sorted COMPLETIONS.
3314 Typing SPC flushes the completions buffer.
3315
3316 The optional argument COMMON-SUBSTRING, if non-nil, should be a string
3317 specifying a common substring for adding the faces
3318 `completions-first-difference' and `completions-common-part' to
3319 the completions."
3320 (let ((window (get-buffer-window "*Completions*" 0)))
3321 (setq completions (sort completions 'string-lessp))
3322 (if (and (eq last-command this-command)
3323 window (window-live-p window) (window-buffer window)
3324 (buffer-name (window-buffer window))
3325 ;; The above tests are not sufficient to detect the case where we
3326 ;; should scroll, because the top-level interactive command may
3327 ;; not have displayed a completions window the last time it was
3328 ;; invoked, and there may be such a window left over from a
3329 ;; previous completion command with a different set of
3330 ;; completions. To detect that case, we also test that the set
3331 ;; of displayed completions is in fact the same as the previously
3332 ;; displayed set.
3333 (equal completions
3334 (buffer-local-value 'comint-displayed-dynamic-completions
3335 (window-buffer window))))
3336 ;; If this command was repeated, and
3337 ;; there's a fresh completion window with a live buffer,
3338 ;; and this command is repeated, scroll that window.
3339 (with-current-buffer (window-buffer window)
3340 (if (pos-visible-in-window-p (point-max) window)
3341 (set-window-start window (point-min))
3342 (save-selected-window
3343 (select-window window)
3344 (scroll-up))))
3345
3346 ;; Display a completion list for the first time.
3347 (setq comint-dynamic-list-completions-config
3348 (current-window-configuration))
3349 (with-output-to-temp-buffer "*Completions*"
3350 (display-completion-list
3351 (completion-hilit-commonality completions (length common-substring))))
3352 (if (window-minibuffer-p)
3353 (minibuffer-message "Type space to flush; repeat completion command to scroll")
3354 (message "Type space to flush; repeat completion command to scroll")))
3355
3356 ;; Read the next key, to process SPC.
3357 (let (key first)
3358 (if (with-current-buffer (get-buffer "*Completions*")
3359 (setq-local comint-displayed-dynamic-completions
3360 completions)
3361 (setq key (read-key-sequence nil)
3362 first (aref key 0))
3363 (and (consp first) (consp (event-start first))
3364 (eq (window-buffer (posn-window (event-start first)))
3365 (get-buffer "*Completions*"))
3366 (memq (key-binding key)
3367 '(mouse-choose-completion choose-completion))))
3368 ;; If the user does choose-completion with the mouse,
3369 ;; execute the command, then delete the completion window.
3370 (progn
3371 (choose-completion first)
3372 (set-window-configuration comint-dynamic-list-completions-config))
3373 (if (eq first ?\s)
3374 (set-window-configuration comint-dynamic-list-completions-config)
3375 (setq unread-command-events
3376 (nconc (listify-key-sequence key) unread-command-events)))))))
3377 \f
3378 (defun comint-get-next-from-history ()
3379 "After fetching a line from input history, this fetches the following line.
3380 In other words, this recalls the input line after the line you recalled last.
3381 You can use this to repeat a sequence of input lines."
3382 (interactive)
3383 (if comint-save-input-ring-index
3384 (progn
3385 (setq comint-input-ring-index (1+ comint-save-input-ring-index))
3386 (comint-next-input 1))
3387 (message "No previous history command")))
3388
3389 (defun comint-accumulate ()
3390 "Accumulate a line to send as input along with more lines.
3391 This inserts a newline so that you can enter more text
3392 to be sent along with this line. Use \\[comint-send-input]
3393 to send all the accumulated input, at once.
3394 The entire accumulated text becomes one item in the input history
3395 when you send it."
3396 (interactive)
3397 (insert "\n")
3398 (set-marker comint-accum-marker (point))
3399 (if comint-input-ring-index
3400 (setq comint-save-input-ring-index
3401 (- comint-input-ring-index 1))))
3402
3403 (defun comint-goto-process-mark ()
3404 "Move point to the process mark.
3405 The process mark separates output, and input already sent,
3406 from input that has not yet been sent."
3407 (interactive)
3408 (let ((proc (or (get-buffer-process (current-buffer))
3409 (user-error "Current buffer has no process"))))
3410 (goto-char (process-mark proc))
3411 (when (called-interactively-p 'interactive)
3412 (message "Point is now at the process mark"))))
3413
3414 (defun comint-bol-or-process-mark ()
3415 "Move point to beginning of line (after prompt) or to the process mark.
3416 The first time you use this command, it moves to the beginning of the line
3417 \(but after the prompt, if any). If you repeat it again immediately,
3418 it moves point to the process mark.
3419
3420 The process mark separates the process output, along with input already sent,
3421 from input that has not yet been sent. Ordinarily, the process mark
3422 is at the beginning of the current input line; but if you have
3423 used \\[comint-accumulate] to send multiple lines at once,
3424 the process mark is at the beginning of the accumulated input."
3425 (interactive)
3426 (if (not (eq last-command 'comint-bol-or-process-mark))
3427 (comint-bol nil)
3428 (comint-goto-process-mark)))
3429
3430 (defun comint-set-process-mark ()
3431 "Set the process mark at point."
3432 (interactive)
3433 (let ((proc (or (get-buffer-process (current-buffer))
3434 (user-error "Current buffer has no process"))))
3435 (set-marker (process-mark proc) (point))
3436 (message "Process mark set")))
3437
3438 \f
3439 ;; Author: Peter Breton <pbreton@cs.umb.edu>
3440
3441 ;; This little add-on for comint is intended to make it easy to get
3442 ;; output from currently active comint buffers into another buffer,
3443 ;; or buffers, and then go back to using the comint shell.
3444 ;;
3445 ;; My particular use is SQL interpreters; I want to be able to execute a
3446 ;; query using the process associated with a comint-buffer, and save that
3447 ;; somewhere else. Because the process might have state (for example, it
3448 ;; could be in an uncommitted transaction), just running starting a new
3449 ;; process and having it execute the query and then finish, would not
3450 ;; work. I'm sure there are other uses as well, although in many cases
3451 ;; starting a new process is the simpler, and thus preferable, approach.
3452 ;;
3453 ;; The basic implementation is as follows: comint-redirect changes the
3454 ;; preoutput filter functions (`comint-preoutput-filter-functions') to use
3455 ;; its own filter. The filter puts the output into the designated buffer,
3456 ;; or buffers, until it sees a regexp that tells it to stop (by default,
3457 ;; this is the prompt for the interpreter, `comint-prompt-regexp'). When it
3458 ;; sees the stop regexp, it restores the old filter functions, and runs
3459 ;; `comint-redirect-hook'.
3460 ;;
3461 ;; Each comint buffer may only use one redirection at a time, but any number
3462 ;; of different comint buffers may be simultaneously redirected.
3463 ;;
3464 ;; NOTE: It is EXTREMELY important that `comint-prompt-regexp' be set to the
3465 ;; correct prompt for your interpreter, or that you supply a regexp that says
3466 ;; when the redirection is finished. Otherwise, redirection will continue
3467 ;; indefinitely. The code now does a sanity check to ensure that it can find
3468 ;; a prompt in the comint buffer; however, it is still important to ensure that
3469 ;; this prompt is set correctly.
3470 ;;
3471 ;; XXX: This doesn't work so well unless `comint-prompt-regexp' is set;
3472 ;; perhaps it should prompt for a terminating string (with an
3473 ;; appropriate magic default by examining what we think is the prompt)?
3474 ;;
3475 ;; Fixme: look for appropriate fields, rather than regexp, if
3476 ;; `comint-use-prompt-regexp' is true.
3477
3478 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3479 ;; Variables
3480 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3481
3482 (defcustom comint-redirect-verbose nil
3483 "If non-nil, print messages each time the redirection filter is invoked.
3484 Also print a message when redirection is completed."
3485 :group 'comint
3486 :type 'boolean)
3487
3488 ;; Directly analogous to comint-preoutput-filter-functions
3489 (defvar comint-redirect-filter-functions nil
3490 "List of functions to call before inserting redirected process output.
3491 Each function gets one argument, a string containing the text received
3492 from the subprocess. It should return the string to insert, perhaps
3493 the same string that was received, or perhaps a modified or transformed
3494 string.
3495
3496 The functions on the list are called sequentially, and each one is given
3497 the string returned by the previous one. The string returned by the
3498 last function is the text that is actually inserted in the redirection buffer.
3499
3500 You can use `add-hook' to add functions to this list
3501 either globally or locally.")
3502
3503 ;; Internal variables
3504
3505 (defvar comint-redirect-output-buffer nil
3506 "The buffer or list of buffers to put output into.")
3507
3508 (defvar comint-redirect-finished-regexp nil
3509 "Regular expression that determines when to stop redirection in Comint.
3510 When the redirection filter function is given output that matches this regexp,
3511 the output is inserted as usual, and redirection is completed.")
3512
3513 (defvar comint-redirect-insert-matching-regexp nil
3514 "If non-nil, the text that ends a redirection is included in it.
3515 More precisely, the text that matches `comint-redirect-finished-regexp'
3516 and therefore terminates an output redirection is inserted in the
3517 redirection target buffer, along with the preceding output.")
3518
3519 (defvar comint-redirect-echo-input nil
3520 "Non-nil means echo input in the process buffer even during redirection.")
3521
3522 (defvar comint-redirect-completed nil
3523 "Non-nil if redirection has completed in the current buffer.")
3524
3525 (defvar comint-redirect-original-mode-line-process nil
3526 "Original mode line for redirected process.")
3527
3528 (defvar comint-redirect-perform-sanity-check t
3529 "If non-nil, check that redirection is likely to complete successfully.
3530 More precisely, before starting a redirection, verify that the
3531 regular expression `comint-redirect-finished-regexp' that controls
3532 when to terminate it actually matches some text already in the process
3533 buffer. The idea is that this regular expression should match a prompt
3534 string, and that there ought to be at least one copy of your prompt string
3535 in the process buffer already.")
3536
3537 (defvar comint-redirect-subvert-readonly nil
3538 "Non-nil means `comint-redirect' can insert into read-only buffers.
3539 This works by binding `inhibit-read-only' around the insertion.
3540 This is useful, for instance, for insertion into Help mode buffers.
3541 You probably want to set it locally to the output buffer.")
3542
3543 (defvar comint-redirect-previous-input-string nil
3544 "Last redirected line of text.
3545 Allows detection of the end of the redirection in case the
3546 completion string is split between two output segments.")
3547
3548 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3549 ;; Functions
3550 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3551
3552 (defun comint-redirect-setup (output-buffer
3553 comint-buffer
3554 finished-regexp
3555 &optional echo-input)
3556 "Set up for output redirection.
3557 This function sets local variables that are used by `comint-redirect-filter'
3558 to perform redirection.
3559
3560 Output from COMINT-BUFFER is redirected to OUTPUT-BUFFER, until something
3561 in the output matches FINISHED-REGEXP.
3562
3563 If optional argument ECHO-INPUT is non-nil, output is echoed to the
3564 original Comint buffer.
3565
3566 This function is called by `comint-redirect-send-command-to-process',
3567 and does not normally need to be invoked by the end user or programmer."
3568 (with-current-buffer comint-buffer
3569
3570 (setq-local comint-redirect-original-mode-line-process mode-line-process)
3571
3572 (setq-local comint-redirect-output-buffer output-buffer)
3573
3574 (setq-local comint-redirect-finished-regexp finished-regexp)
3575
3576 (setq-local comint-redirect-echo-input echo-input)
3577
3578 (setq-local comint-redirect-completed nil)
3579
3580 (setq-local comint-redirect-previous-input-string "")
3581
3582 (setq mode-line-process
3583 (if mode-line-process
3584 (list (concat (elt mode-line-process 0) " Redirection"))
3585 (list ":%s Redirection")))))
3586
3587 (defun comint-redirect-cleanup ()
3588 "End a Comint redirection. See `comint-redirect-send-command'."
3589 (interactive)
3590 ;; Release the last redirected string
3591 (setq comint-redirect-previous-input-string nil)
3592 ;; Restore the process filter
3593 (remove-function (process-filter (get-buffer-process (current-buffer)))
3594 #'comint-redirect-filter)
3595 ;; Restore the mode line
3596 (setq mode-line-process comint-redirect-original-mode-line-process)
3597 ;; Set the completed flag
3598 (setq comint-redirect-completed t))
3599
3600 ;; Because the cleanup happens as a callback, it's not easy to guarantee
3601 ;; that it really occurs.
3602 (defalias 'comint-redirect-remove-redirection 'comint-redirect-cleanup)
3603
3604 (defun comint-redirect-filter (orig-filter process input-string)
3605 "Filter function which redirects output from PROCESS to a buffer or buffers.
3606 The variable `comint-redirect-output-buffer' says which buffer(s) to
3607 place output in.
3608
3609 INPUT-STRING is the input from the Comint process.
3610
3611 This function runs as a process filter, and does not need to be invoked by the
3612 end user."
3613 (and process
3614 (with-current-buffer (process-buffer process)
3615 (comint-redirect-preoutput-filter input-string)
3616 ;; If we have to echo output, give it to the original filter function
3617 (and comint-redirect-echo-input
3618 orig-filter
3619 (funcall orig-filter process input-string)))))
3620
3621
3622 (defun comint-redirect-preoutput-filter (input-string)
3623 "Comint filter function which redirects Comint output to a buffer or buffers.
3624 The variable `comint-redirect-output-buffer' says which buffer(s) to
3625 place output in.
3626
3627 INPUT-STRING is the input from the Comint process.
3628
3629 This function does not need to be invoked by the end user."
3630 (let ((output-buffer-list
3631 (if (listp comint-redirect-output-buffer)
3632 comint-redirect-output-buffer
3633 (list comint-redirect-output-buffer)))
3634 (filtered-input-string input-string))
3635
3636 ;; If there are any filter functions, give them a chance to modify
3637 ;; the string.
3638 (let ((functions comint-redirect-filter-functions))
3639 (while (and functions filtered-input-string)
3640 (if (eq (car functions) t)
3641 ;; If a local value says "use the default value too",
3642 ;; do that.
3643 (let ((functions
3644 (default-value 'comint-redirect-filter-functions)))
3645 (while (and functions filtered-input-string)
3646 (setq filtered-input-string
3647 (funcall (car functions) filtered-input-string))
3648 (setq functions (cdr functions))))
3649 (setq filtered-input-string
3650 (funcall (car functions) filtered-input-string)))
3651 (setq functions (cdr functions))))
3652
3653 ;; Clobber `comint-redirect-finished-regexp'
3654 (or comint-redirect-insert-matching-regexp
3655 (and (string-match comint-redirect-finished-regexp filtered-input-string)
3656 (setq filtered-input-string
3657 (replace-match "" nil nil filtered-input-string))))
3658
3659 ;; Send output to all registered buffers
3660 (save-excursion
3661 (dolist (buf output-buffer-list)
3662 ;; Set this buffer to the output buffer
3663 (set-buffer (get-buffer-create buf))
3664 ;; Go to the end of the buffer
3665 (goto-char (point-max))
3666 ;; Insert the output
3667 (let ((inhibit-read-only comint-redirect-subvert-readonly))
3668 (insert filtered-input-string))))
3669
3670 ;; Message
3671 (and comint-redirect-verbose
3672 (message "Redirected output to buffer(s) %s" output-buffer-list))
3673
3674 ;; If we see the prompt, tidy up
3675 ;; We'll look for the prompt in the original string, so nobody can
3676 ;; clobber it
3677 (and (string-match comint-redirect-finished-regexp
3678 (concat comint-redirect-previous-input-string
3679 input-string))
3680 (progn
3681 (and comint-redirect-verbose
3682 (message "Redirection completed"))
3683 (comint-redirect-cleanup)
3684 (run-hooks 'comint-redirect-hook)))
3685 (setq comint-redirect-previous-input-string input-string)
3686
3687 ;; Echo input?
3688 (if comint-redirect-echo-input
3689 filtered-input-string
3690 "")))
3691
3692 ;;;###autoload
3693 (defun comint-redirect-send-command (command output-buffer echo &optional no-display)
3694 "Send COMMAND to process in current buffer, with output to OUTPUT-BUFFER.
3695 With prefix arg ECHO, echo output in process buffer.
3696
3697 If NO-DISPLAY is non-nil, do not show the output buffer."
3698 (interactive "sCommand: \nBOutput Buffer: \nP")
3699 (let ((process (get-buffer-process (current-buffer))))
3700 (if process
3701 (comint-redirect-send-command-to-process
3702 command output-buffer (current-buffer) echo no-display)
3703 (error "No process for current buffer"))))
3704
3705 ;;;###autoload
3706 (defun comint-redirect-send-command-to-process
3707 (command output-buffer process echo &optional no-display)
3708 "Send COMMAND to PROCESS, with output to OUTPUT-BUFFER.
3709 With prefix arg, echo output in process buffer.
3710
3711 If NO-DISPLAY is non-nil, do not show the output buffer."
3712 (interactive "sCommand: \nBOutput Buffer: \nbProcess Buffer: \nP")
3713 (let* (;; The process buffer
3714 (process-buffer (if (processp process)
3715 (process-buffer process)
3716 process))
3717 (proc (get-buffer-process process-buffer)))
3718 ;; Change to the process buffer
3719 (with-current-buffer process-buffer
3720
3721 ;; Make sure there's a prompt in the current process buffer
3722 (and comint-redirect-perform-sanity-check
3723 (save-excursion
3724 (goto-char (point-max))
3725 (or (re-search-backward comint-prompt-regexp nil t)
3726 (error "No prompt found or `comint-prompt-regexp' not set properly"))))
3727
3728 ;; Set up for redirection
3729 (comint-redirect-setup
3730 output-buffer
3731 (current-buffer) ; Comint Buffer
3732 comint-prompt-regexp ; Finished Regexp
3733 echo) ; Echo input
3734
3735 ;; Set the filter.
3736 (add-function :around (process-filter proc) #'comint-redirect-filter)
3737
3738 ;; Send the command
3739 (process-send-string (current-buffer) (concat command "\n"))
3740
3741 ;; Show the output
3742 (or no-display
3743 (display-buffer
3744 (get-buffer-create
3745 (if (listp output-buffer)
3746 (car output-buffer)
3747 output-buffer)))))))
3748
3749 ;;;###autoload
3750 (defun comint-redirect-results-list (command regexp regexp-group)
3751 "Send COMMAND to current process.
3752 Return a list of expressions in the output which match REGEXP.
3753 REGEXP-GROUP is the regular expression group in REGEXP to use."
3754 (comint-redirect-results-list-from-process
3755 (get-buffer-process (current-buffer))
3756 command regexp regexp-group))
3757
3758 ;;;###autoload
3759 (defun comint-redirect-results-list-from-process (process command regexp regexp-group)
3760 "Send COMMAND to PROCESS.
3761 Return a list of expressions in the output which match REGEXP.
3762 REGEXP-GROUP is the regular expression group in REGEXP to use."
3763 (let ((output-buffer " *Comint Redirect Work Buffer*")
3764 results)
3765 (with-current-buffer (get-buffer-create output-buffer)
3766 (erase-buffer)
3767 (comint-redirect-send-command-to-process command
3768 output-buffer process nil t)
3769 ;; Wait for the process to complete
3770 (set-buffer (process-buffer process))
3771 (while (and (null comint-redirect-completed)
3772 (accept-process-output process)))
3773 ;; Collect the output
3774 (set-buffer output-buffer)
3775 (goto-char (point-min))
3776 ;; Skip past the command, if it was echoed
3777 (and (looking-at command)
3778 (forward-line))
3779 (while (and (not (eobp))
3780 (re-search-forward regexp nil t))
3781 (push (buffer-substring-no-properties
3782 (match-beginning regexp-group)
3783 (match-end regexp-group))
3784 results))
3785 (nreverse results))))
3786 \f
3787 ;; Converting process modes to use comint mode
3788 ;; ===========================================================================
3789 ;; The code in the Emacs 19 distribution has all been modified to use comint
3790 ;; where needed. However, there are `third-party' packages out there that
3791 ;; still use the old shell mode. Here's a guide to conversion.
3792 ;;
3793 ;; Renaming variables
3794 ;; Most of the work is renaming variables and functions. These are the common
3795 ;; ones:
3796 ;; Local variables:
3797 ;; last-input-start comint-last-input-start
3798 ;; last-input-end comint-last-input-end
3799 ;; shell-prompt-pattern comint-prompt-regexp
3800 ;; shell-set-directory-error-hook <no equivalent>
3801 ;; Miscellaneous:
3802 ;; shell-set-directory <unnecessary>
3803 ;; shell-mode-map comint-mode-map
3804 ;; Commands:
3805 ;; shell-send-input comint-send-input
3806 ;; shell-send-eof comint-delchar-or-maybe-eof
3807 ;; kill-shell-input comint-kill-input
3808 ;; interrupt-shell-subjob comint-interrupt-subjob
3809 ;; stop-shell-subjob comint-stop-subjob
3810 ;; quit-shell-subjob comint-quit-subjob
3811 ;; kill-shell-subjob comint-kill-subjob
3812 ;; kill-output-from-shell comint-delete-output
3813 ;; show-output-from-shell comint-show-output
3814 ;; copy-last-shell-input Use comint-previous-input/comint-next-input
3815 ;;
3816 ;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
3817 ;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-filter-functions.
3818 ;; Comint mode does not provide functionality equivalent to
3819 ;; shell-set-directory-error-hook; it is gone.
3820 ;;
3821 ;; comint-last-input-start is provided for modes which want to munge
3822 ;; the buffer after input is sent, perhaps because the inferior
3823 ;; insists on echoing the input. The LAST-INPUT-START variable in
3824 ;; the old shell package was used to implement a history mechanism,
3825 ;; but you should think twice before using comint-last-input-start
3826 ;; for this; the input history ring often does the job better.
3827 ;;
3828 ;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
3829 ;; *not* create the comint-mode local variables in your foo-mode function.
3830 ;; This is not modular. Instead, call comint-mode, and let *it* create the
3831 ;; necessary comint-specific local variables. Then create the
3832 ;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
3833 ;; be foo-mode-map, and its mode to be foo-mode. Set the comint-mode hooks
3834 ;; (comint-{prompt-regexp, input-filter, input-filter-functions,
3835 ;; get-old-input) that need to be different from the defaults. Call
3836 ;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
3837 ;; comint-mode will take care of it. The following example, from shell.el,
3838 ;; is typical:
3839 ;;
3840 ;; (defvar shell-mode-map
3841 ;; (let ((map (make-sparse-keymap)))
3842 ;; (set-keymap-parent map comint-mode-map)
3843 ;; (define-key map "\C-c\C-f" 'shell-forward-command)
3844 ;; (define-key map "\C-c\C-b" 'shell-backward-command)
3845 ;; (define-key map "\t" 'completion-at-point)
3846 ;; (define-key map "\M-?"
3847 ;; 'comint-dynamic-list-filename-completions)
3848 ;; map))
3849 ;;
3850 ;; (define-derived-mode shell-mode comint-mode "Shell"
3851 ;; "Doc."
3852 ;; (setq comint-prompt-regexp shell-prompt-pattern)
3853 ;; (setq-local shell-directory-stack nil)
3854 ;; (add-hook 'comint-input-filter-functions 'shell-directory-tracker))
3855 ;;
3856 ;;
3857 ;; Completion for comint-mode users
3858 ;;
3859 ;; For modes that use comint-mode, comint-dynamic-complete-functions is the
3860 ;; hook to add completion functions to. Functions on this list should return
3861 ;; the completion data according to the documentation of
3862 ;; `completion-at-point-functions'
3863 \f
3864
3865 (provide 'comint)
3866
3867 ;;; comint.el ends here