1;;; esh-mode.el --- user interface
2
3;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author: John Wiegley <johnw@gnu.org>
7
8;; This file is part of GNU Emacs.
9
10;; GNU Emacs is free software; you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
12;; the Free Software Foundation; either version 2, or (at your option)
13;; any later version.
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
21;; along with GNU Emacs; see the file COPYING.  If not, write to the
22;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23;; Boston, MA 02110-1301, USA.
24
25(provide 'esh-mode)
26
27(eval-when-compile (require 'esh-maint))
28
29(defgroup eshell-mode nil
30  "This module contains code for handling input from the user."
31  :tag "User interface"
32  :group 'eshell)
33
34;;; Commentary:
35
36;; Basically, Eshell is used just like shell mode (<M-x shell>).  The
37;; keystrokes for navigating the buffer, and accessing the command
38;; history, are identical.  Unlike shell mode, however, Eshell mode's
39;; governing process is Emacs itself.  With shell mode, an inferior
40;; shell process is executed that communicates with Emacs via comint
41;; -- a mode for handling sub-process interaction.  Eshell mode, on
42;; the other hand, is a truly native Emacs shell.  No subprocess are
43;; invoked except the ones requested by the user at the prompt.
44;;
45;; After entering a command, use <RET> to invoke it ([Command
46;; invocation]) .  If there is a command on disk, it will be executed
47;; as in a normal shell.  If there is no command by that name on disk,
48;; but a Lisp function with that name is defined, the Lisp function
49;; will be called, using the arguments passed on the command line.
50;;
51;; Some of the other features of the command interaction mode are:
52;;
53;; @ <M-RET> can be used to accumulate further commands while a
54;;   command is currently running.  Since all input is passed to the
55;;   subprocess being executed, there is no automatic input queueing
56;;   as there is with other shells.
57;;
58;; @ <C-c C-t> can be used to truncate the buffer if it grows too
59;;   large.
60;;
61;; @ <C-c C-r> will move point to the beginning of the output of the
62;;   last command.  With a prefix argument, it will narrow to view
63;;   only that output.
64;;
65;; @ <C-c C-o> will delete the output from the last command.
66;;
67;; @ <C-c C-f> will move forward a complete shell argument.
68;;
69;; @ <C-c C-b> will move backward a complete shell argument.
70
71(require 'esh-module)
72(require 'esh-cmd)
73(require 'esh-io)
74(require 'esh-var)
75
76;;; User Variables:
77
78(defcustom eshell-mode-unload-hook nil
79  "*A hook that gets run when `eshell-mode' is unloaded."
80  :type 'hook
81  :group 'eshell-mode)
82
83(defcustom eshell-mode-hook nil
84  "*A hook that gets run when `eshell-mode' is entered."
85  :type 'hook
86  :group 'eshell-mode)
87
88(defcustom eshell-first-time-mode-hook nil
89  "*A hook that gets run the first time `eshell-mode' is entered.
90That is to say, the first time during an Emacs session."
91  :type 'hook
92  :group 'eshell-mode)
93
94(defcustom eshell-exit-hook '(eshell-query-kill-processes)
95  "*A hook that is run whenever `eshell' is exited.
96This hook is only run if exiting actually kills the buffer."
97  :type 'hook
98  :group 'eshell-mode)
99
100(defcustom eshell-kill-on-exit t
101  "*If non-nil, kill the Eshell buffer on the `exit' command.
102Otherwise, the buffer will simply be buried."
103  :type 'boolean
104  :group 'eshell-mode)
105
106(defcustom eshell-input-filter-functions nil
107  "*Functions to call before input is processed.
108The input is contained in the region from `eshell-last-input-start' to
109`eshell-last-input-end'."
110  :type 'hook
111  :group 'eshell-mode)
112
113(defcustom eshell-send-direct-to-subprocesses nil
114  "*If t, send any input immediately to a subprocess."
115  :type 'boolean
116  :group 'eshell-mode)
117
118(defcustom eshell-expand-input-functions nil
119  "*Functions to call before input is parsed.
120Each function is passed two arguments, which bounds the region of the
121current input text."
122  :type 'hook
123  :group 'eshell-mode)
124
125(defcustom eshell-scroll-to-bottom-on-input nil
126  "*Controls whether input to interpreter causes window to scroll.
127If nil, then do not scroll.  If t or `all', scroll all windows showing
128buffer.  If `this', scroll only the selected window.
129
130See `eshell-preinput-scroll-to-bottom'."
131  :type '(radio (const :tag "Do not scroll Eshell windows" nil)
132		(const :tag "Scroll all windows showing the buffer" all)
133		(const :tag "Scroll only the selected window" this))
134  :group 'eshell-mode)
135
136(defcustom eshell-scroll-to-bottom-on-output nil
137  "*Controls whether interpreter output causes window to scroll.
138If nil, then do not scroll.  If t or `all', scroll all windows showing
139buffer.  If `this', scroll only the selected window.  If `others',
140scroll only those that are not the selected window.
141
142See variable `eshell-scroll-show-maximum-output' and function
143`eshell-postoutput-scroll-to-bottom'."
144  :type '(radio (const :tag "Do not scroll Eshell windows" nil)
145		(const :tag "Scroll all windows showing the buffer" all)
146		(const :tag "Scroll only the selected window" this)
147		(const :tag "Scroll all windows other than selected" this))
148  :group 'eshell-mode)
149
150(defcustom eshell-scroll-show-maximum-output t
151  "*Controls how interpreter output causes window to scroll.
152If non-nil, then show the maximum output when the window is scrolled.
153
154See variable `eshell-scroll-to-bottom-on-output' and function
155`eshell-postoutput-scroll-to-bottom'."
156  :type 'boolean
157  :group 'eshell-mode)
158
159(defcustom eshell-buffer-maximum-lines 1024
160  "*The maximum size in lines for eshell buffers.
161Eshell buffers are truncated from the top to be no greater than this
162number, if the function `eshell-truncate-buffer' is on
163`eshell-output-filter-functions'."
164  :type 'integer
165  :group 'eshell-mode)
166
167(defcustom eshell-output-filter-functions
168  '(eshell-handle-control-codes
169    eshell-watch-for-password-prompt)
170  "*Functions to call before output is displayed.
171These functions are only called for output that is displayed
172interactively, and not for output which is redirected."
173  :type 'hook
174  :group 'eshell-mode)
175
176(defcustom eshell-preoutput-filter-functions nil
177  "*Functions to call before output is inserted into the buffer.
178These functions get one argument, a string containing the text to be
179inserted.  They return the string as it should be inserted."
180  :type 'hook
181  :group 'eshell-mode)
182
183(defcustom eshell-password-prompt-regexp
184  "[Pp]ass\\(word\\|phrase\\).*:\\s *\\'"
185  "*Regexp matching prompts for passwords in the inferior process.
186This is used by `eshell-watch-for-password-prompt'."
187  :type 'regexp
188  :group 'eshell-mode)
189
190(defcustom eshell-skip-prompt-function nil
191  "*A function called from beginning of line to skip the prompt."
192  :type '(choice (const nil) function)
193  :group 'eshell-mode)
194
195(defcustom eshell-status-in-modeline t
196  "*If non-nil, let the user know a command is running in the modeline."
197  :type 'boolean
198  :group 'eshell-mode)
199
200(defvar eshell-first-time-p t
201  "A variable which is non-nil the first time Eshell is loaded.")
202
203;; Internal Variables:
204
205;; these are only set to `nil' initially for the sake of the
206;; byte-compiler, when compiling other files which `require' this one
207(defvar eshell-mode nil)
208(defvar eshell-mode-map nil)
209(defvar eshell-command-running-string "--")
210(defvar eshell-command-map nil)
211(defvar eshell-command-prefix nil)
212(defvar eshell-last-input-start nil)
213(defvar eshell-last-input-end nil)
214(defvar eshell-last-output-start nil)
215(defvar eshell-last-output-block-begin nil)
216(defvar eshell-last-output-end nil)
217
218(defvar eshell-currently-handling-window nil)
219(defvar eshell-mode-syntax-table nil)
220(defvar eshell-mode-abbrev-table nil)
221
222(define-abbrev-table 'eshell-mode-abbrev-table ())
223
224(eval-when-compile
225  (unless (eshell-under-xemacs-p)
226    (defalias 'characterp 'ignore)
227    (defalias 'char-int 'ignore)))
228
229(if (not eshell-mode-syntax-table)
230    (let ((i 0))
231      (setq eshell-mode-syntax-table (make-syntax-table))
232      (while (< i ?0)
233	(modify-syntax-entry i "_   " eshell-mode-syntax-table)
234	(setq i (1+ i)))
235      (setq i (1+ ?9))
236      (while (< i ?A)
237	(modify-syntax-entry i "_   " eshell-mode-syntax-table)
238	(setq i (1+ i)))
239      (setq i (1+ ?Z))
240      (while (< i ?a)
241	(modify-syntax-entry i "_   " eshell-mode-syntax-table)
242	(setq i (1+ i)))
243      (setq i (1+ ?z))
244      (while (< i 128)
245	(modify-syntax-entry i "_   " eshell-mode-syntax-table)
246	(setq i (1+ i)))
247      (modify-syntax-entry ?  "    " eshell-mode-syntax-table)
248      (modify-syntax-entry ?\t "    " eshell-mode-syntax-table)
249      (modify-syntax-entry ?\f "    " eshell-mode-syntax-table)
250      (modify-syntax-entry ?\n ">   " eshell-mode-syntax-table)
251      ;; Give CR the same syntax as newline, for selective-display.
252      (modify-syntax-entry ?\^m ">   " eshell-mode-syntax-table)
253;;;   (modify-syntax-entry ?\; "<   " eshell-mode-syntax-table)
254      (modify-syntax-entry ?` "'   " eshell-mode-syntax-table)
255      (modify-syntax-entry ?' "'   " eshell-mode-syntax-table)
256      (modify-syntax-entry ?, "'   " eshell-mode-syntax-table)
257      ;; Used to be singlequote; changed for flonums.
258      (modify-syntax-entry ?. "_   " eshell-mode-syntax-table)
259      (modify-syntax-entry ?- "_   " eshell-mode-syntax-table)
260      (modify-syntax-entry ?| ".   " eshell-mode-syntax-table)
261      (modify-syntax-entry ?# "'   " eshell-mode-syntax-table)
262      (modify-syntax-entry ?\" "\"    " eshell-mode-syntax-table)
263      (modify-syntax-entry ?\\ "/   " eshell-mode-syntax-table)
264      (modify-syntax-entry ?\( "()  " eshell-mode-syntax-table)
265      (modify-syntax-entry ?\) ")(  " eshell-mode-syntax-table)
266      (modify-syntax-entry ?\{ "(}  " eshell-mode-syntax-table)
267      (modify-syntax-entry ?\} "){  " eshell-mode-syntax-table)
268      (modify-syntax-entry ?\[ "(]  " eshell-mode-syntax-table)
269      (modify-syntax-entry ?\] ")[  " eshell-mode-syntax-table)
270      ;; All non-word multibyte characters should be `symbol'.
271      (if (eshell-under-xemacs-p)
272	  (map-char-table
273	   (function
274	    (lambda (key val)
275	      (and (characterp key)
276		   (>= (char-int key) 256)
277		   (/= (char-syntax key) ?w)
278		   (modify-syntax-entry key "_   "
279					eshell-mode-syntax-table))))
280	   (standard-syntax-table))
281	(map-char-table
282	 (function
283	  (lambda (key val)
284	    (and (>= key 256)
285		 (/= (char-syntax key) ?w)
286		 (modify-syntax-entry key "_   "
287				      eshell-mode-syntax-table))))
288	 (standard-syntax-table)))))
289
290;;; User Functions:
291
292;;;###autoload
293(defun eshell-mode ()
294  "Emacs shell interactive mode.
295
296\\{eshell-mode-map}"
297  (kill-all-local-variables)
298
299  (setq major-mode 'eshell-mode)
300  (setq mode-name "EShell")
301  (set (make-local-variable 'eshell-mode) t)
302
303  (make-local-variable 'eshell-mode-map)
304  (setq eshell-mode-map (make-sparse-keymap))
305  (use-local-map eshell-mode-map)
306
307  (when eshell-status-in-modeline
308    (make-local-variable 'eshell-command-running-string)
309    (let ((fmt (copy-sequence mode-line-format)))
310      (make-local-variable 'mode-line-format)
311      (setq mode-line-format fmt))
312    (let ((modeline (memq 'mode-line-modified mode-line-format)))
313      (if modeline
314	  (setcar modeline 'eshell-command-running-string))))
315
316  (define-key eshell-mode-map [return] 'eshell-send-input)
317  (define-key eshell-mode-map [(control ?m)] 'eshell-send-input)
318  (define-key eshell-mode-map [(control ?j)] 'eshell-send-input)
319  (define-key eshell-mode-map [(meta return)] 'eshell-queue-input)
320  (define-key eshell-mode-map [(meta control ?m)] 'eshell-queue-input)
321  (define-key eshell-mode-map [(meta control ?l)] 'eshell-show-output)
322
323  (set (make-local-variable 'eshell-command-prefix)
324       (make-symbol "eshell-command-prefix"))
325  (fset eshell-command-prefix (make-sparse-keymap))
326  (set (make-local-variable 'eshell-command-map)
327       (symbol-function eshell-command-prefix))
328  (define-key eshell-mode-map [(control ?c)] eshell-command-prefix)
329
330  ;; without this, find-tag complains about read-only text being
331  ;; modified
332  (if (eq (key-binding [(meta ?.)]) 'find-tag)
333      (define-key eshell-mode-map [(meta ?.)] 'eshell-find-tag))
334  (define-key eshell-command-map [(meta ?o)] 'eshell-mark-output)
335  (define-key eshell-command-map [(meta ?d)] 'eshell-toggle-direct-send)
336
337  (define-key eshell-command-map [(control ?a)] 'eshell-bol)
338  (define-key eshell-command-map [(control ?b)] 'eshell-backward-argument)
339  (define-key eshell-command-map [(control ?e)] 'eshell-show-maximum-output)
340  (define-key eshell-command-map [(control ?f)] 'eshell-forward-argument)
341  (define-key eshell-command-map [return]       'eshell-copy-old-input)
342  (define-key eshell-command-map [(control ?m)] 'eshell-copy-old-input)
343  (define-key eshell-command-map [(control ?o)] 'eshell-kill-output)
344  (define-key eshell-command-map [(control ?r)] 'eshell-show-output)
345  (define-key eshell-command-map [(control ?t)] 'eshell-truncate-buffer)
346  (define-key eshell-command-map [(control ?u)] 'eshell-kill-input)
347  (define-key eshell-command-map [(control ?w)] 'backward-kill-word)
348  (define-key eshell-command-map [(control ?y)] 'eshell-repeat-argument)
349
350  (setq local-abbrev-table eshell-mode-abbrev-table)
351  (set-syntax-table eshell-mode-syntax-table)
352
353  (set (make-local-variable 'dired-directory) default-directory)
354  (set (make-local-variable 'list-buffers-directory)
355       (expand-file-name default-directory))
356
357  ;; always set the tab width to 8 in Eshell buffers, since external
358  ;; commands which do their own formatting almost always expect this
359  (set (make-local-variable 'tab-width) 8)
360
361  ;; don't ever use auto-fill in Eshell buffers
362  (setq auto-fill-function nil)
363
364  ;; always display everything from a return value
365  (if (boundp 'print-length)
366      (set (make-local-variable 'print-length) nil))
367  (if (boundp 'print-level)
368      (set (make-local-variable 'print-level) nil))
369
370  ;; set require-final-newline to nil; otherwise, all redirected
371  ;; output will end with a newline, whether or not the source
372  ;; indicated it!
373  (set (make-local-variable 'require-final-newline) nil)
374
375  (set (make-local-variable 'max-lisp-eval-depth)
376       (max 3000 max-lisp-eval-depth))
377  (set (make-local-variable 'max-specpdl-size)
378       (max 6000 max-lisp-eval-depth))
379
380  (set (make-local-variable 'eshell-last-input-start) (point-marker))
381  (set (make-local-variable 'eshell-last-input-end) (point-marker))
382  (set (make-local-variable 'eshell-last-output-start) (point-marker))
383  (set (make-local-variable 'eshell-last-output-end) (point-marker))
384  (set (make-local-variable 'eshell-last-output-block-begin) (point))
385
386  (let ((modules-list (copy-sequence eshell-modules-list)))
387    (make-local-variable 'eshell-modules-list)
388    (setq eshell-modules-list modules-list))
389
390  ;; load extension modules into memory.  This will cause any global
391  ;; variables they define to be visible, since some of the core
392  ;; modules sometimes take advantage of their functionality if used.
393  (eshell-for module eshell-modules-list
394    (let ((module-fullname (symbol-name module))
395	  module-shortname)
396      (if (string-match "^eshell-\\(.*\\)" module-fullname)
397	  (setq module-shortname
398		(concat "em-" (match-string 1 module-fullname))))
399      (unless module-shortname
400	(error "Invalid Eshell module name: %s" module-fullname))
401      (unless (featurep (intern module-shortname))
402	(load module-shortname))))
403
404  (unless (file-exists-p eshell-directory-name)
405    (eshell-make-private-directory eshell-directory-name t))
406
407  ;; load core Eshell modules for this session
408  (eshell-for module (eshell-subgroups 'eshell)
409    (run-hooks (intern-soft (concat (symbol-name module)
410				    "-load-hook"))))
411
412  ;; load extension modules for this session
413  (eshell-for module eshell-modules-list
414    (let ((load-hook (intern-soft (concat (symbol-name module)
415					  "-load-hook"))))
416      (if (and load-hook (boundp load-hook))
417	  (run-hooks load-hook))))
418
419  (if eshell-send-direct-to-subprocesses
420      (add-hook 'pre-command-hook 'eshell-intercept-commands t t))
421
422  (if eshell-scroll-to-bottom-on-input
423      (add-hook 'pre-command-hook 'eshell-preinput-scroll-to-bottom t t))
424
425  (when eshell-scroll-show-maximum-output
426    (set (make-local-variable 'scroll-conservatively) 1000))
427
428  (when eshell-status-in-modeline
429    (add-hook 'eshell-pre-command-hook 'eshell-command-started nil t)
430    (add-hook 'eshell-post-command-hook 'eshell-command-finished nil t))
431
432  (add-hook 'kill-buffer-hook
433	    (function
434	     (lambda ()
435	       (run-hooks 'eshell-exit-hook))) t t)
436
437  (if eshell-first-time-p
438      (run-hooks 'eshell-first-time-mode-hook))
439  (run-mode-hooks 'eshell-mode-hook)
440  (run-hooks 'eshell-post-command-hook))
441
442(put 'eshell-mode 'mode-class 'special)
443
444(eshell-deftest mode major-mode
445  "Major mode is correct"
446  (eq major-mode 'eshell-mode))
447
448(eshell-deftest mode eshell-mode-variable
449  "`eshell-mode' is true"
450  (eq eshell-mode t))
451
452(eshell-deftest var window-height
453  "LINES equals window height"
454  (let ((eshell-stringify-t t))
455    (eshell-command-result-p "= $LINES (window-height)" "t\n")))
456
457(defun eshell-command-started ()
458  "Indicate in the modeline that a command has started."
459  (setq eshell-command-running-string "**")
460  (force-mode-line-update))
461
462(defun eshell-command-finished ()
463  "Indicate in the modeline that a command has finished."
464  (setq eshell-command-running-string "--")
465  (force-mode-line-update))
466
467(eshell-deftest mode command-running-p
468  "Modeline shows no command running"
469  (or (eshell-under-xemacs-p)
470      (not eshell-status-in-modeline)
471      (and (memq 'eshell-command-running-string mode-line-format)
472	   (equal eshell-command-running-string "--"))))
473
474;;; Internal Functions:
475
476(defun eshell-toggle-direct-send ()
477  (interactive)
478  (if eshell-send-direct-to-subprocesses
479      (progn
480	(setq eshell-send-direct-to-subprocesses nil)
481	(remove-hook 'pre-command-hook 'eshell-intercept-commands t)
482	(message "Sending subprocess input on RET"))
483    (setq eshell-send-direct-to-subprocesses t)
484    (add-hook 'pre-command-hook 'eshell-intercept-commands t t)
485    (message "Sending subprocess input directly")))
486
487(defun eshell-self-insert-command (N)
488  (interactive "i")
489  (process-send-string
490   (eshell-interactive-process)
491   (char-to-string (if (symbolp last-command-char)
492		       (get last-command-char 'ascii-character)
493		     last-command-char))))
494
495(defun eshell-intercept-commands ()
496  (when (and (eshell-interactive-process)
497	     (not (and (integerp last-input-event)
498		       (memq last-input-event '(?\C-x ?\C-c)))))
499    (let ((possible-events (where-is-internal this-command))
500	  (name (symbol-name this-command))
501	  (intercept t))
502      ;; Assume that any multikey combination which does NOT target an
503      ;; Eshell command, is a combo the user wants invoked rather than
504      ;; sent to the underlying subprocess.
505      (unless (and (> (length name) 7)
506		   (equal (substring name 0 7) "eshell-"))
507	(while possible-events
508	  (if (> (length (car possible-events)) 1)
509	      (setq intercept nil possible-events nil)
510	    (setq possible-events (cdr possible-events)))))
511      (if intercept
512	  (setq this-command 'eshell-self-insert-command)))))
513
514(defun eshell-find-tag (&optional tagname next-p regexp-p)
515  "A special version of `find-tag' that ignores read-onlyness."
516  (interactive)
517  (require 'etags)
518  (let ((inhibit-read-only t)
519	(no-default (eobp))
520	(find-tag-default-function 'ignore))
521    (with-no-warnings
522      (setq tagname (car (find-tag-interactive "Find tag: "))))
523    (find-tag tagname next-p regexp-p)))
524
525(defun eshell-move-argument (limit func property arg)
526  "Move forward ARG arguments."
527  (catch 'eshell-incomplete
528    (eshell-parse-arguments (save-excursion (eshell-bol) (point))
529			    (line-end-position)))
530  (let ((pos (save-excursion
531	       (funcall func 1)
532	       (while (and (> arg 0) (/= (point) limit))
533		 (if (get-text-property (point) property)
534		     (setq arg (1- arg)))
535		 (if (> arg 0)
536		     (funcall func 1)))
537	       (point))))
538    (goto-char pos)
539    (if (and (eq func 'forward-char)
540	     (= (1+ pos) limit))
541	(forward-char 1))))
542
543(eshell-deftest arg forward-arg
544  "Move across command arguments"
545  (eshell-insert-command "echo $(+ 1 (- 4 3)) \"alpha beta\" file" 'ignore)
546  (let ((here (point)) begin valid)
547    (eshell-bol)
548    (setq begin (point))
549    (eshell-forward-argument 4)
550    (setq valid (= here (point)))
551    (eshell-backward-argument 4)
552    (prog1
553	(and valid (= begin (point)))
554      (eshell-bol)
555      (delete-region (point) (point-max)))))
556
557(defun eshell-forward-argument (&optional arg)
558  "Move forward ARG arguments."
559  (interactive "p")
560  (eshell-move-argument (point-max) 'forward-char 'arg-end arg))
561
562(defun eshell-backward-argument (&optional arg)
563  "Move backward ARG arguments."
564  (interactive "p")
565  (eshell-move-argument (point-min) 'backward-char 'arg-begin arg))
566
567(defun eshell-repeat-argument (&optional arg)
568  (interactive "p")
569  (let ((begin (save-excursion
570		 (eshell-backward-argument arg)
571		 (point))))
572    (kill-ring-save begin (point))
573    (yank)))
574
575(defun eshell-bol ()
576  "Goes to the beginning of line, then skips past the prompt, if any."
577  (interactive)
578  (beginning-of-line)
579  (and eshell-skip-prompt-function
580       (funcall eshell-skip-prompt-function)))
581
582(defsubst eshell-push-command-mark ()
583  "Push a mark at the end of the last input text."
584  (push-mark (1- eshell-last-input-end) t))
585
586(custom-add-option 'eshell-pre-command-hook 'eshell-push-command-mark)
587
588(defsubst eshell-goto-input-start ()
589  "Goto the start of the last command input.
590Putting this function on `eshell-pre-command-hook' will mimic Plan 9's
5919term behavior."
592  (goto-char eshell-last-input-start))
593
594(custom-add-option 'eshell-pre-command-hook 'eshell-push-command-mark)
595
596(defsubst eshell-interactive-print (string)
597  "Print STRING to the eshell display buffer."
598  (eshell-output-filter nil string))
599
600(defsubst eshell-begin-on-new-line ()
601  "This function outputs a newline if not at beginning of line."
602  (save-excursion
603    (goto-char eshell-last-output-end)
604    (or (bolp)
605	(eshell-interactive-print "\n"))))
606
607(defsubst eshell-reset (&optional no-hooks)
608  "Output a prompt on a new line, aborting any current input.
609If NO-HOOKS is non-nil, then `eshell-post-command-hook' won't be run."
610  (goto-char (point-max))
611  (setq eshell-last-input-start (point-marker)
612	eshell-last-input-end (point-marker)
613	eshell-last-output-start (point-marker)
614	eshell-last-output-block-begin (point)
615	eshell-last-output-end (point-marker))
616  (eshell-begin-on-new-line)
617  (unless no-hooks
618    (run-hooks 'eshell-post-command-hook)
619    (goto-char (point-max))))
620
621(defun eshell-parse-command-input (beg end &optional args)
622  "Parse the command input from BEG to END.
623The difference is that `eshell-parse-command' expects a complete
624command string (and will error if it doesn't get one), whereas this
625function will inform the caller whether more input is required.
626
627If nil is returned, more input is necessary (probably because a
628multi-line input string wasn't terminated properly).  Otherwise, it
629will return the parsed command."
630  (let (delim command)
631    (if (setq delim
632	      (catch 'eshell-incomplete
633		(ignore
634		 (setq command (eshell-parse-command (cons beg end)
635						     args t)))))
636	(ignore
637	 (message "Expecting completion of delimeter %c ..."
638		  (if (listp delim)
639		      (car delim)
640		    delim)))
641      command)))
642
643(defun eshell-update-markers (pmark)
644  "Update the input and output markers relative to point and PMARK."
645  (set-marker eshell-last-input-start pmark)
646  (set-marker eshell-last-input-end (point))
647  (set-marker eshell-last-output-end (point)))
648
649(defun eshell-queue-input (&optional use-region)
650  "Queue the current input text for execution by Eshell.
651Particularly, don't send the text to the current process, even if it's
652waiting for input."
653  (interactive "P")
654  (eshell-send-input use-region t))
655
656(eshell-deftest mode queue-input
657  "Queue command input"
658  (eshell-insert-command "sleep 2")
659  (eshell-insert-command "echo alpha" 'eshell-queue-input)
660  (let ((count 10))
661    (while (and eshell-current-command
662		(> count 0))
663      (sit-for 1 0)
664      (setq count (1- count))))
665  (eshell-match-result "alpha\n"))
666
667(defun eshell-send-input (&optional use-region queue-p no-newline)
668  "Send the input received to Eshell for parsing and processing.
669After `eshell-last-output-end', sends all text from that marker to
670point as input.  Before that marker, calls `eshell-get-old-input' to
671retrieve old input, copies it to the end of the buffer, and sends it.
672
673If USE-REGION is non-nil, the current region (between point and mark)
674will be used as input.
675
676If QUEUE-P is non-nil, input will be queued until the next prompt,
677rather than sent to the currently active process.  If no process, the
678input is processed immediately.
679
680If NO-NEWLINE is non-nil, the input is sent without an implied final
681newline."
682  (interactive "P")
683  ;; Note that the input string does not include its terminal newline.
684  (let ((proc-running-p (and (eshell-interactive-process)
685			     (not queue-p)))
686	(inhibit-point-motion-hooks t)
687	after-change-functions)
688    (unless (and proc-running-p
689		 (not (eq (process-status
690			   (eshell-interactive-process)) 'run)))
691      (if (or proc-running-p
692	      (>= (point) eshell-last-output-end))
693	  (goto-char (point-max))
694	(let ((copy (eshell-get-old-input use-region)))
695	  (goto-char eshell-last-output-end)
696	  (insert-and-inherit copy)))
697      (unless (or no-newline
698		  (and eshell-send-direct-to-subprocesses
699		       proc-running-p))
700	(insert-before-markers-and-inherit ?\n))
701      (if proc-running-p
702	  (progn
703	    (eshell-update-markers eshell-last-output-end)
704	    (if (or eshell-send-direct-to-subprocesses
705		    (= eshell-last-input-start eshell-last-input-end))
706		(unless no-newline
707		  (process-send-string (eshell-interactive-process) "\n"))
708	      (process-send-region (eshell-interactive-process)
709				   eshell-last-input-start
710				   eshell-last-input-end)))
711	(if (= eshell-last-output-end (point))
712	    (run-hooks 'eshell-post-command-hook)
713	  (let (input)
714	    (eshell-condition-case err
715		(progn
716		  (setq input (buffer-substring-no-properties
717			       eshell-last-output-end (1- (point))))
718		  (run-hook-with-args 'eshell-expand-input-functions
719				      eshell-last-output-end (1- (point)))
720		  (let ((cmd (eshell-parse-command-input
721			      eshell-last-output-end (1- (point)))))
722		    (when cmd
723		      (eshell-update-markers eshell-last-output-end)
724		      (setq input (buffer-substring-no-properties
725				   eshell-last-input-start
726				   (1- eshell-last-input-end)))
727		      (run-hooks 'eshell-input-filter-functions)
728		      (and (catch 'eshell-terminal
729			     (ignore
730			      (if (eshell-invoke-directly cmd input)
731				  (eval cmd)
732				(eshell-eval-command cmd input))))
733			   (eshell-life-is-too-much)))))
734	      (quit
735	       (eshell-reset t)
736	       (run-hooks 'eshell-post-command-hook)
737	       (signal 'quit nil))
738	      (error
739	       (eshell-reset t)
740	       (eshell-interactive-print
741		(concat (error-message-string err) "\n"))
742	       (run-hooks 'eshell-post-command-hook)
743	       (insert-and-inherit input)))))))))
744
745; (eshell-deftest proc send-to-subprocess
746;   "Send input to a subprocess"
747;   ;; jww (1999-12-06): what about when bc is unavailable?
748;   (if (not (eshell-search-path "bc"))
749;       t
750;     (eshell-insert-command "bc")
751;     (eshell-insert-command "1 + 2")
752;     (sit-for 1 0)
753;     (forward-line -1)
754;     (prog1
755; 	(looking-at "3\n")
756;       (eshell-insert-command "quit")
757;       (sit-for 1 0))))
758
759(defsubst eshell-kill-new ()
760  "Add the last input text to the kill ring."
761  (kill-ring-save eshell-last-input-start eshell-last-input-end))
762
763(custom-add-option 'eshell-input-filter-functions 'eshell-kill-new)
764
765(defun eshell-output-filter (process string)
766  "Send the output from PROCESS (STRING) to the interactive display.
767This is done after all necessary filtering has been done."
768  (let ((oprocbuf (if process (process-buffer process)
769		    (current-buffer)))
770	(inhibit-point-motion-hooks t)
771	after-change-functions)
772    (let ((functions eshell-preoutput-filter-functions))
773      (while (and functions string)
774	(setq string (funcall (car functions) string))
775	(setq functions (cdr functions))))
776    (if (and string oprocbuf (buffer-name oprocbuf))
777	(let ((obuf (current-buffer))
778	      opoint obeg oend)
779	  (set-buffer oprocbuf)
780	  (setq opoint (point))
781	  (setq obeg (point-min))
782	  (setq oend (point-max))
783	  (let ((buffer-read-only nil)
784		(nchars (length string))
785		(ostart nil))
786	    (widen)
787	    (goto-char eshell-last-output-end)
788	    (setq ostart (point))
789	    (if (<= (point) opoint)
790		(setq opoint (+ opoint nchars)))
791	    (if (< (point) obeg)
792		(setq obeg (+ obeg nchars)))
793	    (if (<= (point) oend)
794		(setq oend (+ oend nchars)))
795	    (insert-before-markers string)
796	    (if (= (window-start (selected-window)) (point))
797		(set-window-start (selected-window)
798				  (- (point) nchars)))
799	    (if (= (point) eshell-last-input-end)
800		(set-marker eshell-last-input-end
801			    (- eshell-last-input-end nchars)))
802	    (set-marker eshell-last-output-start ostart)
803	    (set-marker eshell-last-output-end (point))
804	    (force-mode-line-update))
805	  (narrow-to-region obeg oend)
806	  (goto-char opoint)
807	  (eshell-run-output-filters)
808	  (set-buffer obuf)))))
809
810(defun eshell-run-output-filters ()
811  "Run the `eshell-output-filter-functions' on the current output."
812  (save-current-buffer
813    (run-hooks 'eshell-output-filter-functions))
814  (setq eshell-last-output-block-begin
815	(marker-position eshell-last-output-end)))
816
817;;; jww (1999-10-23): this needs testing
818(defun eshell-preinput-scroll-to-bottom ()
819  "Go to the end of buffer in all windows showing it.
820Movement occurs if point in the selected window is not after the
821process mark, and `this-command' is an insertion command.  Insertion
822commands recognized are `self-insert-command', `yank', and
823`hilit-yank'.  Depends on the value of
824`eshell-scroll-to-bottom-on-input'.
825
826This function should be a pre-command hook."
827  (if (memq this-command '(self-insert-command yank hilit-yank))
828      (let* ((selected (selected-window))
829	     (current (current-buffer))
830	     (scroll eshell-scroll-to-bottom-on-input))
831	(if (< (point) eshell-last-output-end)
832	    (if (eq scroll 'this)
833		(goto-char (point-max))
834	      (walk-windows
835	       (function
836		(lambda (window)
837		  (when (and (eq (window-buffer window) current)
838			     (or (eq scroll t) (eq scroll 'all)))
839		    (select-window window)
840		    (goto-char (point-max))
841		    (select-window selected))))
842	       nil t))))))
843
844;;; jww (1999-10-23): this needs testing
845(defun eshell-postoutput-scroll-to-bottom ()
846  "Go to the end of buffer in all windows showing it.
847Does not scroll if the current line is the last line in the buffer.
848Depends on the value of `eshell-scroll-to-bottom-on-output' and
849`eshell-scroll-show-maximum-output'.
850
851This function should be in the list `eshell-output-filter-functions'."
852  (let* ((selected (selected-window))
853	 (current (current-buffer))
854	 (scroll eshell-scroll-to-bottom-on-output))
855    (unwind-protect
856	(walk-windows
857	 (function
858	  (lambda (window)
859	    (if (eq (window-buffer window) current)
860		(progn
861		  (select-window window)
862		  (if (and (< (point) eshell-last-output-end)
863			   (or (eq scroll t) (eq scroll 'all)
864			       ;; Maybe user wants point to jump to end.
865			       (and (eq scroll 'this)
866				    (eq selected window))
867			       (and (eq scroll 'others)
868				    (not (eq selected window)))
869			       ;; If point was at the end, keep it at end.
870			       (>= (point) eshell-last-output-start)))
871		      (goto-char eshell-last-output-end))
872		  ;; Optionally scroll so that the text
873		  ;; ends at the bottom of the window.
874		  (if (and eshell-scroll-show-maximum-output
875			   (>= (point) eshell-last-output-end))
876		      (save-excursion
877			(goto-char (point-max))
878			(recenter -1)))
879		  (select-window selected)))))
880	 nil t)
881      (set-buffer current))))
882
883(custom-add-option 'eshell-output-filter-functions
884		   'eshell-postoutput-scroll-to-bottom)
885
886(defun eshell-beginning-of-input ()
887  "Return the location of the start of the previous input."
888  eshell-last-input-start)
889
890(defun eshell-beginning-of-output ()
891  "Return the location of the end of the previous output block."
892  eshell-last-input-end)
893
894(defun eshell-end-of-output ()
895  "Return the location of the end of the previous output block."
896  (if (eshell-using-module 'eshell-prompt)
897      eshell-last-output-start
898    eshell-last-output-end))
899
900(defun eshell-kill-output ()
901  "Kill all output from interpreter since last input.
902Does not delete the prompt."
903  (interactive)
904  (save-excursion
905    (goto-char (eshell-beginning-of-output))
906    (insert "*** output flushed ***\n")
907    (delete-region (point) (eshell-end-of-output))))
908
909(eshell-deftest io flush-output
910  "Flush previous output"
911  (eshell-insert-command "echo alpha")
912  (eshell-kill-output)
913  (and (eshell-match-result (regexp-quote "*** output flushed ***\n"))
914       (forward-line)
915       (= (point) eshell-last-output-start)))
916
917(defun eshell-show-output (&optional arg)
918  "Display start of this batch of interpreter output at top of window.
919Sets mark to the value of point when this command is run.
920With a prefix argument, narrows region to last command output."
921  (interactive "P")
922  (goto-char (eshell-beginning-of-output))
923  (set-window-start (selected-window)
924		    (save-excursion
925		      (goto-char (eshell-beginning-of-input))
926		      (line-beginning-position)))
927  (if arg
928      (narrow-to-region (eshell-beginning-of-output)
929			(eshell-end-of-output)))
930  (eshell-end-of-output))
931
932(defun eshell-mark-output (&optional arg)
933  "Display start of this batch of interpreter output at top of window.
934Sets mark to the value of point when this command is run.
935With a prefix argument, narrows region to last command output."
936  (interactive "P")
937  (push-mark (eshell-show-output arg)))
938
939(defun eshell-kill-input ()
940  "Kill all text from last stuff output by interpreter to point."
941  (interactive)
942  (if (> (point) eshell-last-output-end)
943      (kill-region eshell-last-output-end (point))
944    (let ((here (point)))
945      (eshell-bol)
946      (kill-region (point) here))))
947
948(defun eshell-show-maximum-output (&optional interactive)
949  "Put the end of the buffer at the bottom of the window.
950When run interactively, widen the buffer first."
951  (interactive "p")
952  (if interactive
953      (widen))
954  (goto-char (point-max))
955  (recenter -1))
956
957(defun eshell-get-old-input (&optional use-current-region)
958  "Return the command input on the current line."
959  (if use-current-region
960      (buffer-substring (min (point) (mark))
961			(max (point) (mark)))
962    (save-excursion
963      (beginning-of-line)
964      (and eshell-skip-prompt-function
965	   (funcall eshell-skip-prompt-function))
966      (let ((beg (point)))
967	(end-of-line)
968	(buffer-substring beg (point))))))
969
970(defun eshell-copy-old-input ()
971  "Insert after prompt old input at point as new input to be edited."
972  (interactive)
973  (let ((input (eshell-get-old-input)))
974    (goto-char eshell-last-output-end)
975    (insert-and-inherit input)))
976
977(eshell-deftest mode run-old-command
978  "Re-run an old command"
979  (eshell-insert-command "echo alpha")
980  (goto-char eshell-last-input-start)
981  (string= (eshell-get-old-input) "echo alpha"))
982
983(defun eshell/exit ()
984  "Leave or kill the Eshell buffer, depending on `eshell-kill-on-exit'."
985  (throw 'eshell-terminal t))
986
987(defun eshell-life-is-too-much ()
988  "Kill the current buffer (or bury it).  Good-bye Eshell."
989  (interactive)
990  (if (not eshell-kill-on-exit)
991      (bury-buffer)
992    (kill-buffer (current-buffer))))
993
994(defun eshell-truncate-buffer ()
995  "Truncate the buffer to `eshell-buffer-maximum-lines'.
996This function could be on `eshell-output-filter-functions' or bound to
997a key."
998  (interactive)
999  (save-excursion
1000    (goto-char eshell-last-output-end)
1001    (let ((lines (count-lines 1 (point)))
1002	  (inhibit-read-only t))
1003      (forward-line (- eshell-buffer-maximum-lines))
1004      (beginning-of-line)
1005      (let ((pos (point)))
1006	(if (bobp)
1007	    (if (interactive-p)
1008		(message "Buffer too short to truncate"))
1009	  (delete-region (point-min) (point))
1010	  (if (interactive-p)
1011	      (message "Truncated buffer from %d to %d lines (%.1fk freed)"
1012		       lines eshell-buffer-maximum-lines
1013		       (/ pos 1024.0))))))))
1014
1015(custom-add-option 'eshell-output-filter-functions
1016		   'eshell-truncate-buffer)
1017
1018(defun eshell-send-invisible (str)
1019  "Read a string without echoing.
1020Then send it to the process running in the current buffer."
1021  (interactive "P")                     ; Defeat snooping via C-x ESC ESC
1022  (let ((str (read-passwd
1023	      (format "%s Password: "
1024		      (process-name (eshell-interactive-process))))))
1025    (if (stringp str)
1026	(process-send-string (eshell-interactive-process)
1027			     (concat str "\n"))
1028      (message "Warning: text will be echoed"))))
1029
1030(defun eshell-watch-for-password-prompt ()
1031  "Prompt in the minibuffer for password and send without echoing.
1032This function uses `eshell-send-invisible' to read and send a password to the
1033buffer's process if STRING contains a password prompt defined by
1034`eshell-password-prompt-regexp'.
1035
1036This function could be in the list `eshell-output-filter-functions'."
1037  (when (eshell-interactive-process)
1038    (save-excursion
1039      (goto-char eshell-last-output-block-begin)
1040      (beginning-of-line)
1041      (if (re-search-forward eshell-password-prompt-regexp
1042			     eshell-last-output-end t)
1043	  (eshell-send-invisible nil)))))
1044
1045(custom-add-option 'eshell-output-filter-functions
1046		   'eshell-watch-for-password-prompt)
1047
1048(defun eshell-handle-control-codes ()
1049  "Act properly when certain control codes are seen."
1050  (save-excursion
1051    (let ((orig (point)))
1052      (goto-char eshell-last-output-block-begin)
1053      (unless (eolp)
1054	(beginning-of-line))
1055      (while (< (point) eshell-last-output-end)
1056	(let ((char (char-after)))
1057	  (cond
1058	   ((eq char ?\r)
1059	    (if (< (1+ (point)) eshell-last-output-end)
1060		(if (memq (char-after (1+ (point)))
1061			  '(?\n ?\r))
1062		    (delete-char 1)
1063		  (let ((end (1+ (point))))
1064		    (beginning-of-line)
1065		    (delete-region (point) end)))
1066	      (add-text-properties (point) (1+ (point))
1067				   '(invisible t))
1068	      (forward-char)))
1069	   ((eq char ?\a)
1070	    (delete-char 1)
1071	    (beep))
1072	   ((eq char ?\C-h)
1073	    (delete-backward-char 1)
1074	    (delete-char 1))
1075	   (t
1076	    (forward-char))))))))
1077
1078(custom-add-option 'eshell-output-filter-functions
1079		   'eshell-handle-control-codes)
1080
1081(defun eshell-handle-ansi-color ()
1082  "Handle ANSI color codes."
1083  (require 'ansi-color)
1084  (ansi-color-apply-on-region eshell-last-output-start
1085                              eshell-last-output-end))
1086
1087(custom-add-option 'eshell-output-filter-functions
1088		   'eshell-handle-ansi-color)
1089
1090;;; Code:
1091
1092;;; arch-tag: ec65bc2b-da14-4547-81d3-a32af3a4dc57
1093;;; esh-mode.el ends here
1094