(eshell-defgroup): New alias.
[bpt/emacs.git] / lisp / eshell / em-hist.el
CommitLineData
60370d40 1;;; em-hist.el --- history list management
affbf647 2
f2e3589a 3;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
8b72699e 4;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
affbf647 5
7de5b421
GM
6;; Author: John Wiegley <johnw@gnu.org>
7
affbf647
GM
8;; This file is part of GNU Emacs.
9
4ee57b2a 10;; GNU Emacs is free software: you can redistribute it and/or modify
affbf647 11;; it under the terms of the GNU General Public License as published by
4ee57b2a
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
affbf647
GM
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
4ee57b2a 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
affbf647 22
affbf647
GM
23;;; Commentary:
24
25;; Eshell's history facility imitates the syntax used by bash
26;; ([(bash)History Interaction]). Thus:
27;;
28;; !ls ; repeat the last command beginning with 'ls'
29;; !?ls ; repeat the last command containing ls
30;; echo !ls:2 ; echo the second arg of the last 'ls' command
31;; !ls<tab> ; complete against all possible words in this
32;; ; position, by looking at the history list
33;; !ls<C-c SPC> ; expand any matching history input at point
34;;
35;; Also, most of `comint-mode's keybindings are accepted:
36;;
37;; M-r ; search backward for a previous command by regexp
38;; M-s ; search forward for a previous command by regexp
39;; M-p ; access the last command entered, repeatable
40;; M-n ; access the first command entered, repeatable
41;;
42;; C-c M-r ; using current input, find a matching command thus, with
43;; ; 'ls' as the current input, it will go back to the same
44;; ; command that '!ls' would have selected
45;; C-c M-s ; same, but in reverse order
46;;
47;; Note that some of these keybindings are only available if the
48;; `eshell-rebind' is not in use, in which case M-p does what C-c M-r
49;; normally would do, and C-p is used instead of M-p. It may seem
50;; confusing, but the intention is to make the most useful
51;; functionality the most easily accessible. If `eshell-rebind' is
52;; not being used, history navigation will use comint's keybindings;
53;; if it is, history navigation tries to use similar keybindings to
54;; bash. This is all configurable, of course.
55
56;;; Code:
57
58(require 'ring)
59(require 'esh-opt)
60(require 'em-pred)
dbba8a04
GM
61(require 'eshell)
62
63(defgroup eshell-hist nil
64 "This module provides command history management."
65 :tag "History list management"
66 :group 'eshell-module)
affbf647
GM
67
68;;; User Variables:
69
70(defcustom eshell-hist-load-hook '(eshell-hist-initialize)
71 "*A list of functions to call when loading `eshell-hist'."
72 :type 'hook
73 :group 'eshell-hist)
74
75(defcustom eshell-hist-unload-hook
76 (list
77 (function
78 (lambda ()
79 (remove-hook 'kill-emacs-hook 'eshell-save-some-history))))
80 "*A hook that gets run when `eshell-hist' is unloaded."
81 :type 'hook
82 :group 'eshell-hist)
83
84(defcustom eshell-history-file-name
85 (concat eshell-directory-name "history")
86 "*If non-nil, name of the file to read/write input history.
87See also `eshell-read-history' and `eshell-write-history'.
88If it is nil, Eshell will use the value of HISTFILE."
89 :type 'file
90 :group 'eshell-hist)
91
92(defcustom eshell-history-size 128
93 "*Size of the input history ring. If nil, use envvar HISTSIZE."
94 :type 'integer
95 :group 'eshell-hist)
96
97(defcustom eshell-hist-ignoredups nil
98 "*If non-nil, don't add input matching the last on the input ring.
99This mirrors the optional behavior of bash."
100 :type 'boolean
101 :group 'eshell-hist)
102
7d7b15b8 103(defcustom eshell-save-history-on-exit 'ask
affbf647
GM
104 "*Determine if history should be automatically saved.
105History is always preserved after sanely exiting an Eshell buffer.
106However, when Emacs is being shut down, this variable determines
107whether to prompt the user.
7d7b15b8
JW
108If set to nil, it means never save history on termination of Emacs.
109If set to `ask', ask if any Eshell buffers are open at exit time.
110If set to t, history will always be saved, silently."
affbf647 111 :type '(choice (const :tag "Never" nil)
7d7b15b8
JW
112 (const :tag "Ask" ask)
113 (const :tag "Always save" t))
affbf647
GM
114 :group 'eshell-hist)
115
116(defcustom eshell-input-filter
117 (function
118 (lambda (str)
119 (not (string-match "\\`\\s-*\\'" str))))
120 "*Predicate for filtering additions to input history.
121Takes one argument, the input. If non-nil, the input may be saved on
122the input history list. Default is to save anything that isn't all
123whitespace."
124 :type 'function
125 :group 'eshell-hist)
126
127(put 'eshell-input-filter 'risky-local-variable t)
128
129(defcustom eshell-hist-match-partial t
130 "*If non-nil, movement through history is constrained by current input.
131Otherwise, typing <M-p> and <M-n> will always go to the next history
132element, regardless of any text on the command line. In that case,
133<C-c M-r> and <C-c M-s> still offer that functionality."
134 :type 'boolean
135 :group 'eshell-hist)
136
137(defcustom eshell-hist-move-to-end t
138 "*If non-nil, move to the end of the buffer before cycling history."
139 :type 'boolean
140 :group 'eshell-hist)
141
142(defcustom eshell-hist-event-designator
143 "^!\\(!\\|-?[0-9]+\\|\\??[^:^$%*?]+\\??\\|#\\)"
144 "*The regexp used to identifier history event designators."
145 :type 'regexp
146 :group 'eshell-hist)
147
148(defcustom eshell-hist-word-designator
149 "^:?\\([0-9]+\\|[$^%*]\\)?\\(\\*\\|-[0-9]*\\|[$^%*]\\)?"
150 "*The regexp used to identify history word designators."
151 :type 'regexp
152 :group 'eshell-hist)
153
154(defcustom eshell-hist-modifier
155 "^\\(:\\([hretpqx&g]\\|s/\\([^/]*\\)/\\([^/]*\\)/\\)\\)*"
156 "*The regexp used to identity history modifiers."
157 :type 'regexp
158 :group 'eshell-hist)
159
160(defcustom eshell-hist-rebind-keys-alist
161 '(([(control ?p)] . eshell-previous-input)
162 ([(control ?n)] . eshell-next-input)
163 ([(control up)] . eshell-previous-input)
164 ([(control down)] . eshell-next-input)
165 ([(control ?r)] . eshell-isearch-backward)
166 ([(control ?s)] . eshell-isearch-forward)
167 ([(meta ?r)] . eshell-previous-matching-input)
168 ([(meta ?s)] . eshell-next-matching-input)
169 ([(meta ?p)] . eshell-previous-matching-input-from-input)
170 ([(meta ?n)] . eshell-next-matching-input-from-input)
171 ([up] . eshell-previous-matching-input-from-input)
172 ([down] . eshell-next-matching-input-from-input))
173 "*History keys to bind differently if point is in input text."
174 :type '(repeat (cons (vector :tag "Keys to bind"
175 (repeat :inline t sexp))
176 (function :tag "Command")))
177 :group 'eshell-hist)
178
179;;; Internal Variables:
180
181(defvar eshell-history-ring nil)
182(defvar eshell-history-index nil)
183(defvar eshell-matching-input-from-input-string "")
184(defvar eshell-save-history-index nil)
185
186(defvar eshell-isearch-map nil)
187
188(unless eshell-isearch-map
189 (setq eshell-isearch-map (copy-keymap isearch-mode-map))
190 (define-key eshell-isearch-map [(control ?m)] 'eshell-isearch-return)
191 (define-key eshell-isearch-map [return] 'eshell-isearch-return)
192 (define-key eshell-isearch-map [(control ?r)] 'eshell-isearch-repeat-backward)
193 (define-key eshell-isearch-map [(control ?s)] 'eshell-isearch-repeat-forward)
194 (define-key eshell-isearch-map [(control ?g)] 'eshell-isearch-abort)
195 (define-key eshell-isearch-map [backspace] 'eshell-isearch-delete-char)
196 (define-key eshell-isearch-map [delete] 'eshell-isearch-delete-char)
197 (defvar eshell-isearch-cancel-map)
198 (define-prefix-command 'eshell-isearch-cancel-map)
199 (define-key eshell-isearch-map [(control ?c)] 'eshell-isearch-cancel-map)
200 (define-key eshell-isearch-cancel-map [(control ?c)] 'eshell-isearch-cancel))
201
3c54e8f1
RS
202(defvar eshell-rebind-keys-alist)
203
affbf647
GM
204;;; Functions:
205
206(defun eshell-hist-initialize ()
207 "Initialize the history management code for one Eshell buffer."
affbf647
GM
208 (add-hook 'eshell-expand-input-functions
209 'eshell-expand-history-references nil t)
210
211 (when (eshell-using-module 'eshell-cmpl)
affbf647
GM
212 (add-hook 'pcomplete-try-first-hook
213 'eshell-complete-history-reference nil t))
214
7a3bfc32
JW
215 (if (and (eshell-using-module 'eshell-rebind)
216 (not eshell-non-interactive-p))
3c54e8f1 217 (let ((rebind-alist eshell-rebind-keys-alist))
affbf647 218 (make-local-variable 'eshell-rebind-keys-alist)
3c54e8f1
RS
219 (setq eshell-rebind-keys-alist
220 (append rebind-alist eshell-hist-rebind-keys-alist))
affbf647
GM
221 (set (make-local-variable 'search-invisible) t)
222 (set (make-local-variable 'search-exit-option) t)
affbf647
GM
223 (add-hook 'isearch-mode-hook
224 (function
225 (lambda ()
226 (if (>= (point) eshell-last-output-end)
227 (setq overriding-terminal-local-map
228 eshell-isearch-map)))) nil t)
affbf647
GM
229 (add-hook 'isearch-mode-end-hook
230 (function
231 (lambda ()
232 (setq overriding-terminal-local-map nil))) nil t))
233 (define-key eshell-mode-map [up] 'eshell-previous-matching-input-from-input)
234 (define-key eshell-mode-map [down] 'eshell-next-matching-input-from-input)
235 (define-key eshell-mode-map [(control up)] 'eshell-previous-input)
236 (define-key eshell-mode-map [(control down)] 'eshell-next-input)
237 (define-key eshell-mode-map [(meta ?r)] 'eshell-previous-matching-input)
238 (define-key eshell-mode-map [(meta ?s)] 'eshell-next-matching-input)
239 (define-key eshell-command-map [(meta ?r)]
240 'eshell-previous-matching-input-from-input)
241 (define-key eshell-command-map [(meta ?s)]
242 'eshell-next-matching-input-from-input)
243 (if eshell-hist-match-partial
244 (progn
245 (define-key eshell-mode-map [(meta ?p)]
246 'eshell-previous-matching-input-from-input)
247 (define-key eshell-mode-map [(meta ?n)]
248 'eshell-next-matching-input-from-input)
249 (define-key eshell-command-map [(meta ?p)] 'eshell-previous-input)
250 (define-key eshell-command-map [(meta ?n)] 'eshell-next-input))
251 (define-key eshell-mode-map [(meta ?p)] 'eshell-previous-input)
252 (define-key eshell-mode-map [(meta ?n)] 'eshell-next-input)
253 (define-key eshell-command-map [(meta ?p)]
254 'eshell-previous-matching-input-from-input)
255 (define-key eshell-command-map [(meta ?n)]
256 'eshell-next-matching-input-from-input)))
257
258 (make-local-variable 'eshell-history-size)
259 (or eshell-history-size
260 (setq eshell-history-size (getenv "HISTSIZE")))
261
262 (make-local-variable 'eshell-history-file-name)
263 (or eshell-history-file-name
264 (setq eshell-history-file-name (getenv "HISTFILE")))
265
266 (make-local-variable 'eshell-history-index)
267 (make-local-variable 'eshell-save-history-index)
7a3bfc32
JW
268
269 (if (minibuffer-window-active-p (selected-window))
7d7b15b8 270 (set (make-local-variable 'eshell-save-history-on-exit) nil)
7a3bfc32
JW
271 (set (make-local-variable 'eshell-history-ring) nil)
272 (if eshell-history-file-name
273 (eshell-read-history nil t))
274
7a3bfc32
JW
275 (add-hook 'eshell-exit-hook 'eshell-write-history nil t))
276
affbf647
GM
277 (unless eshell-history-ring
278 (setq eshell-history-ring (make-ring eshell-history-size)))
279
affbf647
GM
280 (add-hook 'eshell-exit-hook 'eshell-write-history nil t)
281
282 (add-hook 'kill-emacs-hook 'eshell-save-some-history)
283
284 (make-local-variable 'eshell-input-filter-functions)
285 (add-hook 'eshell-input-filter-functions 'eshell-add-to-history nil t)
286
287 (define-key eshell-command-map [(control ?l)] 'eshell-list-history)
288 (define-key eshell-command-map [(control ?x)] 'eshell-get-next-from-history))
289
290(defun eshell-save-some-history ()
291 "Save the history for any open Eshell buffers."
292 (eshell-for buf (buffer-list)
293 (if (buffer-live-p buf)
294 (with-current-buffer buf
295 (if (and eshell-mode
296 eshell-history-file-name
7d7b15b8
JW
297 eshell-save-history-on-exit
298 (or (eq eshell-save-history-on-exit t)
affbf647
GM
299 (y-or-n-p
300 (format "Save input history for Eshell buffer `%s'? "
301 (buffer-name buf)))))
302 (eshell-write-history))))))
303
304(defun eshell/history (&rest args)
305 "List in help buffer the buffer's input history."
306 (eshell-init-print-buffer)
307 (eshell-eval-using-options
308 "history" args
309 '((?r "read" nil read-history
310 "read from history file to current history list")
311 (?w "write" nil write-history
312 "write current history list to history file")
313 (?a "append" nil append-history
314 "append current history list to history file")
315 (?h "help" nil nil "display this usage message")
316 :usage "[n] [-rwa [filename]]"
317 :post-usage
318"When Eshell is started, history is read from `eshell-history-file-name'.
319This is also the location where history info will be saved by this command,
320unless a different file is specified on the command line.")
321 (and (or (not (ring-p eshell-history-ring))
322 (ring-empty-p eshell-history-ring))
323 (error "No history"))
324 (let (length command file)
325 (when (and args (string-match "^[0-9]+$" (car args)))
326 (setq length (min (eshell-convert (car args))
327 (ring-length eshell-history-ring))
328 args (cdr args)))
329 (and length
330 (or read-history write-history append-history)
331 (error "history: extra arguments"))
332 (when (and args (stringp (car args)))
333 (setq file (car args)
334 args (cdr args)))
335 (cond
336 (read-history (eshell-read-history file))
337 (write-history (eshell-write-history file))
338 (append-history (eshell-write-history file t))
339 (t
340 (let* ((history nil)
341 (index (1- (or length (ring-length eshell-history-ring))))
342 (ref (- (ring-length eshell-history-ring) index)))
343 ;; We have to build up a list ourselves from the ring vector.
344 (while (>= index 0)
345 (eshell-buffered-print
346 (format "%5d %s\n" ref (eshell-get-history index)))
347 (setq index (1- index)
348 ref (1+ ref)))))))
349 (eshell-flush)
350 nil))
351
352(defun eshell-put-history (input &optional ring at-beginning)
353 "Put a new input line into the history ring."
354 (unless ring (setq ring eshell-history-ring))
affbf647
GM
355 (if at-beginning
356 (ring-insert-at-beginning ring input)
357 (ring-insert ring input)))
358
359(defun eshell-get-history (index &optional ring)
360 "Get an input line from the history ring."
ca7aae91 361 (ring-ref (or ring eshell-history-ring) index))
affbf647 362
7a3bfc32
JW
363(defun eshell-add-input-to-history (input)
364 "Add the string INPUT to the history ring.
365Input is entered into the input history ring, if the value of
affbf647
GM
366variable `eshell-input-filter' returns non-nil when called on the
367input."
7a3bfc32
JW
368 (if (and (funcall eshell-input-filter input)
369 (or (null eshell-hist-ignoredups)
370 (not (ring-p eshell-history-ring))
371 (ring-empty-p eshell-history-ring)
372 (not (string-equal (eshell-get-history 0) input))))
373 (eshell-put-history input))
374 (setq eshell-save-history-index eshell-history-index)
375 (setq eshell-history-index nil))
376
377(defun eshell-add-command-to-history ()
378 "Add the command entered at `eshell-command's prompt to the history ring.
379The command is added to the input history ring, if the value of
380variable `eshell-input-filter' returns non-nil when called on the
381command.
382
383This function is supposed to be called from the minibuffer, presumably
384as a minibuffer-exit-hook."
385 (eshell-add-input-to-history
386 (buffer-substring (minibuffer-prompt-end) (point-max))))
387
388(defun eshell-add-to-history ()
389 "Add last Eshell command to the history ring.
390The command is entered into the input history ring, if the value of
391variable `eshell-input-filter' returns non-nil when called on the
392command."
affbf647
GM
393 (when (> (1- eshell-last-input-end) eshell-last-input-start)
394 (let ((input (buffer-substring eshell-last-input-start
395 (1- eshell-last-input-end))))
7a3bfc32 396 (eshell-add-input-to-history input))))
affbf647
GM
397
398(defun eshell-read-history (&optional filename silent)
399 "Sets the buffer's `eshell-history-ring' from a history file.
400The name of the file is given by the variable
401`eshell-history-file-name'. The history ring is of size
402`eshell-history-size', regardless of file size. If
403`eshell-history-file-name' is nil this function does nothing.
404
405If the optional argument SILENT is non-nil, we say nothing about a
406failure to read the history file.
407
408This function is useful for major mode commands and mode hooks.
409
410The structure of the history file should be one input command per
411line, with the most recent command last. See also
412`eshell-hist-ignoredups' and `eshell-write-history'."
413 (let ((file (or filename eshell-history-file-name)))
414 (cond
415 ((or (null file)
416 (equal file ""))
417 nil)
418 ((not (file-readable-p file))
419 (or silent
420 (message "Cannot read history file %s" file)))
421 (t
422 (let* ((count 0)
423 (size eshell-history-size)
424 (ring (make-ring size))
425 (ignore-dups eshell-hist-ignoredups))
426 (with-temp-buffer
427 (insert-file-contents file)
428 ;; Save restriction in case file is already visited...
429 ;; Watch for those date stamps in history files!
430 (goto-char (point-max))
431 (while (and (< count size)
432 (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
433 nil t))
434 (let ((history (match-string 1)))
435 (if (or (null ignore-dups)
436 (ring-empty-p ring)
437 (not (string-equal (ring-ref ring 0) history)))
ca7aae91
JW
438 (ring-insert-at-beginning
439 ring (subst-char-in-string ?\177 ?\n history))))
affbf647
GM
440 (setq count (1+ count))))
441 (setq eshell-history-ring ring
442 eshell-history-index nil))))))
443
444(defun eshell-write-history (&optional filename append)
445 "Writes the buffer's `eshell-history-ring' to a history file.
446The name of the file is given by the variable
447`eshell-history-file-name'. The original contents of the file are
448lost if `eshell-history-ring' is not empty. If
449`eshell-history-file-name' is nil this function does nothing.
450
451Useful within process sentinels.
452
453See also `eshell-read-history'."
454 (let ((file (or filename eshell-history-file-name)))
455 (cond
456 ((or (null file)
457 (equal file "")
458 (null eshell-history-ring)
459 (ring-empty-p eshell-history-ring))
460 nil)
461 ((not (file-writable-p file))
462 (message "Cannot write history file %s" file))
463 (t
464 (let* ((ring eshell-history-ring)
465 (index (ring-length ring)))
466 ;; Write it all out into a buffer first. Much faster, but
467 ;; messier, than writing it one line at a time.
468 (with-temp-buffer
469 (while (> index 0)
470 (setq index (1- index))
ca7aae91
JW
471 (let ((start (point)))
472 (insert (ring-ref ring index) ?\n)
473 (subst-char-in-region start (1- (point)) ?\n ?\177)))
affbf647
GM
474 (eshell-with-private-file-modes
475 (write-region (point-min) (point-max) file append
476 'no-message))))))))
477
478(defun eshell-list-history ()
479 "List in help buffer the buffer's input history."
480 (interactive)
481 (let (prefix prelen)
482 (save-excursion
483 (if (re-search-backward "!\\(.+\\)" (line-beginning-position) t)
484 (setq prefix (match-string 1)
485 prelen (length prefix))))
486 (if (or (not (ring-p eshell-history-ring))
487 (ring-empty-p eshell-history-ring))
488 (message "No history")
489 (let ((history nil)
490 (history-buffer " *Input History*")
491 (index (1- (ring-length eshell-history-ring)))
492 (conf (current-window-configuration)))
493 ;; We have to build up a list ourselves from the ring vector.
494 (while (>= index 0)
495 (let ((hist (eshell-get-history index)))
496 (if (or (not prefix)
497 (and (>= (length hist) prelen)
498 (string= (substring hist 0 prelen) prefix)))
499 (setq history (cons hist history))))
500 (setq index (1- index)))
501 ;; Change "completion" to "history reference"
502 ;; to make the display accurate.
503 (with-output-to-temp-buffer history-buffer
f5fab556 504 (display-completion-list history prefix)
affbf647
GM
505 (set-buffer history-buffer)
506 (forward-line 3)
507 (while (search-backward "completion" nil 'move)
508 (replace-match "history reference")))
509 (eshell-redisplay)
510 (message "Hit space to flush")
511 (let ((ch (read-event)))
512 (if (eq ch ?\ )
513 (set-window-configuration conf)
514 (setq unread-command-events (list ch))))))))
515
516(defun eshell-hist-word-reference (ref)
517 "Return the word designator index referred to by REF."
518 (cond
519 ((string-match "^[0-9]+$" ref)
520 (string-to-number ref))
521 ((string= "^" ref) 1)
522 ((string= "$" ref) nil)
523 ((string= "%" ref)
7f076e08 524 (error "`%%' history word designator not yet implemented"))))
affbf647
GM
525
526(defun eshell-hist-parse-arguments (&optional silent b e)
527 "Parse current command arguments in a history-code-friendly way."
528 (let ((end (or e (point)))
529 (begin (or b (save-excursion (eshell-bol) (point))))
530 (posb (list t))
531 (pose (list t))
532 (textargs (list t))
533 hist args)
534 (unless (catch 'eshell-incomplete
535 (ignore
536 (setq args (eshell-parse-arguments begin end))))
537 (save-excursion
538 (goto-char begin)
539 (while (< (point) end)
540 (if (get-text-property (point) 'arg-begin)
541 (nconc posb (list (point))))
542 (if (get-text-property (point) 'arg-end)
543 (nconc pose
544 (list (if (= (1+ (point)) end)
545 (1+ (point))
546 (point)))))
547 (forward-char))
548 (setq posb (cdr posb)
549 pose (cdr pose))
550 (assert (= (length posb) (length args)))
551 (assert (<= (length posb) (length pose))))
552 (setq hist (buffer-substring-no-properties begin end))
553 (let ((b posb) (e pose))
554 (while b
555 (nconc textargs
556 (list (substring hist (- (car b) begin)
557 (- (car e) begin))))
558 (setq b (cdr b)
559 e (cdr e))))
560 (setq textargs (cdr textargs))
561 (assert (= (length textargs) (length args)))
562 (list textargs posb pose))))
563
564(defun eshell-expand-history-references (beg end)
565 "Parse and expand any history references in current input."
566 (let ((result (eshell-hist-parse-arguments t beg end)))
567 (when result
568 (let ((textargs (nreverse (nth 0 result)))
569 (posb (nreverse (nth 1 result)))
570 (pose (nreverse (nth 2 result))))
571 (save-excursion
572 (while textargs
573 (let ((str (eshell-history-reference (car textargs))))
574 (unless (eq str (car textargs))
575 (goto-char (car posb))
576 (insert-and-inherit str)
577 (delete-char (- (car pose) (car posb)))))
578 (setq textargs (cdr textargs)
579 posb (cdr posb)
580 pose (cdr pose))))))))
581
582(defun eshell-complete-history-reference ()
583 "Complete a history reference, by completing the event designator."
584 (let ((arg (pcomplete-actual-arg)))
585 (when (string-match "\\`![^:^$*%]*\\'" arg)
586 (setq pcomplete-stub (substring arg 1)
587 pcomplete-last-completion-raw t)
588 (throw 'pcomplete-completions
589 (let ((history nil)
590 (index (1- (ring-length eshell-history-ring)))
591 (stublen (length pcomplete-stub)))
592 ;; We have to build up a list ourselves from the ring
593 ;; vector.
594 (while (>= index 0)
595 (let ((hist (eshell-get-history index)))
596 (if (and (>= (length hist) stublen)
597 (string= (substring hist 0 stublen)
598 pcomplete-stub)
599 (string-match "^\\([^:^$*% \t\n]+\\)" hist))
600 (setq history (cons (match-string 1 hist)
601 history))))
602 (setq index (1- index)))
603 (let ((fhist (list t)))
604 ;; uniqify the list, but preserve the order
605 (while history
606 (unless (member (car history) fhist)
607 (nconc fhist (list (car history))))
608 (setq history (cdr history)))
609 (cdr fhist)))))))
610
611(defun eshell-history-reference (reference)
612 "Expand directory stack REFERENCE.
613The syntax used here was taken from the Bash info manual.
614Returns the resultant reference, or the same string REFERENCE if none
615matched."
616 ;; `^string1^string2^'
617 ;; Quick Substitution. Repeat the last command, replacing
618 ;; STRING1 with STRING2. Equivalent to `!!:s/string1/string2/'
619 (if (and (eshell-using-module 'eshell-pred)
620 (string-match "\\^\\([^^]+\\)\\^\\([^^]+\\)\\^?\\s-*$"
621 reference))
622 (setq reference (format "!!:s/%s/%s/"
623 (match-string 1 reference)
624 (match-string 2 reference))))
625 ;; `!'
626 ;; Start a history substitution, except when followed by a
627 ;; space, tab, the end of the line, = or (.
628 (if (not (string-match "^![^ \t\n=\(]" reference))
629 reference
630 (setq eshell-history-index nil)
631 (let ((event (eshell-hist-parse-event-designator reference)))
632 (unless event
633 (error "Could not find history event `%s'" reference))
634 (setq eshell-history-index (car event)
635 reference (substring reference (cdr event))
636 event (eshell-get-history eshell-history-index))
637 (if (not (string-match "^[:^$*%]" reference))
638 event
639 (let ((word (eshell-hist-parse-word-designator
640 event reference)))
641 (unless word
642 (error "Unable to honor word designator `%s'" reference))
643 (unless (string-match "^[:^$*%][[$^*%0-9-]" reference)
644 (setcdr word 0))
645 (setq event (car word)
646 reference (substring reference (cdr word)))
647 (if (not (and (eshell-using-module 'eshell-pred)
648 (string-match "^:" reference)))
649 event
650 (eshell-hist-parse-modifier event reference)))))))
651
652(defun eshell-hist-parse-event-designator (reference)
653 "Parse a history event designator beginning in REFERENCE."
654 (let* ((index (string-match eshell-hist-event-designator reference))
655 (end (and index (match-end 0))))
656 (unless index
657 (error "Invalid history event designator `%s'" reference))
658 (let* ((event (match-string 1 reference))
659 (pos
660 (cond
661 ((string= event "!") (ring-length eshell-history-ring))
662 ((string= event "#") (error "!# not yet implemented"))
663 ((string-match "^-?[0-9]+$" event)
664 (let ((num (string-to-number event)))
665 (if (>= num 0)
666 (- (ring-length eshell-history-ring) num)
667 (1- (abs num)))))
668 ((string-match "^\\(\\??\\)\\([^?]+\\)\\??$" event)
669 (let ((pref (if (> (length (match-string 1 event)) 0)
670 "" "^"))
671 (str (match-string 2 event)))
672 (save-match-data
673 (eshell-previous-matching-input-string-position
674 (concat pref (regexp-quote str)) 1))))
675 (t
676 (error "Failed to parse event designator `%s'" event)))))
677 (and pos (cons pos end)))))
678
679(defun eshell-hist-parse-word-designator (hist reference)
680 "Parse a history word designator beginning for HIST in REFERENCE."
681 (let* ((index (string-match eshell-hist-word-designator reference))
682 (end (and index (match-end 0))))
683 (unless (memq (aref reference 0) '(?: ?^ ?$ ?* ?%))
684 (error "Invalid history word designator `%s'" reference))
685 (let ((nth (match-string 1 reference))
686 (mth (match-string 2 reference))
687 (here (point))
688 textargs)
689 (insert hist)
690 (setq textargs (car (eshell-hist-parse-arguments nil here (point))))
691 (delete-region here (point))
692 (if (string= nth "*")
693 (if mth
694 (error "Invalid history word designator `%s'"
695 reference)
696 (setq nth 1 mth "-$")))
697 (if (not mth)
698 (if nth
699 (setq mth nth)
700 (setq nth 0 mth "$"))
701 (if (string= mth "-")
702 (setq mth (- (length textargs) 2))
703 (if (string= mth "*")
704 (setq mth "$")
705 (if (not (and (> (length mth) 1)
706 (eq (aref mth 0) ?-)))
707 (error "Invalid history word designator `%s'"
708 reference)
709 (setq mth (substring mth 1))))))
710 (unless (numberp nth)
711 (setq nth (eshell-hist-word-reference nth)))
712 (unless (numberp mth)
713 (setq mth (eshell-hist-word-reference mth)))
714 (cons (mapconcat 'identity (eshell-sublist textargs nth mth) "")
715 end))))
716
717(defun eshell-hist-parse-modifier (hist reference)
718 "Parse a history modifier beginning for HIST in REFERENCE."
719 (let ((here (point)))
720 (insert reference)
721 (prog1
722 (save-restriction
723 (narrow-to-region here (point))
724 (goto-char (point-min))
725 (let ((modifiers (cdr (eshell-parse-modifiers))))
726 (eshell-for mod modifiers
727 (setq hist (funcall mod hist)))
728 hist))
729 (delete-region here (point)))))
730
731(defun eshell-get-next-from-history ()
732 "After fetching a line from input history, this fetches the next.
733In other words, this recalls the input line after the line you
734recalled last. You can use this to repeat a sequence of input lines."
735 (interactive)
736 (if eshell-save-history-index
737 (progn
738 (setq eshell-history-index (1+ eshell-save-history-index))
739 (eshell-next-input 1))
740 (message "No previous history command")))
741
742(defun eshell-search-arg (arg)
743 ;; First make sure there is a ring and that we are after the process
744 ;; mark
745 (if (and eshell-hist-move-to-end
746 (< (point) eshell-last-output-end))
747 (goto-char eshell-last-output-end))
748 (cond ((or (null eshell-history-ring)
749 (ring-empty-p eshell-history-ring))
750 (error "Empty input ring"))
751 ((zerop arg)
752 ;; arg of zero resets search from beginning, and uses arg of
753 ;; 1
754 (setq eshell-history-index nil)
755 1)
756 (t
757 arg)))
758
759(defun eshell-search-start (arg)
760 "Index to start a directional search, starting at `eshell-history-index'."
761 (if eshell-history-index
762 ;; If a search is running, offset by 1 in direction of arg
763 (mod (+ eshell-history-index (if (> arg 0) 1 -1))
764 (ring-length eshell-history-ring))
765 ;; For a new search, start from beginning or end, as appropriate
766 (if (>= arg 0)
767 0 ; First elt for forward search
768 ;; Last elt for backward search
769 (1- (ring-length eshell-history-ring)))))
770
771(defun eshell-previous-input-string (arg)
772 "Return the string ARG places along the input ring.
773Moves relative to `eshell-history-index'."
774 (eshell-get-history (if eshell-history-index
775 (mod (+ arg eshell-history-index)
776 (ring-length eshell-history-ring))
777 arg)))
778
779(defun eshell-previous-input (arg)
780 "Cycle backwards through input history."
781 (interactive "*p")
782 (eshell-previous-matching-input "." arg))
783
784(defun eshell-next-input (arg)
785 "Cycle forwards through input history."
786 (interactive "*p")
787 (eshell-previous-input (- arg)))
788
789(defun eshell-previous-matching-input-string (regexp arg)
790 "Return the string matching REGEXP ARG places along the input ring.
791Moves relative to `eshell-history-index'."
792 (let* ((pos (eshell-previous-matching-input-string-position regexp arg)))
793 (if pos (eshell-get-history pos))))
794
795(defun eshell-previous-matching-input-string-position
796 (regexp arg &optional start)
797 "Return the index matching REGEXP ARG places along the input ring.
798Moves relative to START, or `eshell-history-index'."
799 (if (or (not (ring-p eshell-history-ring))
800 (ring-empty-p eshell-history-ring))
801 (error "No history"))
802 (let* ((len (ring-length eshell-history-ring))
803 (motion (if (> arg 0) 1 -1))
804 (n (mod (- (or start (eshell-search-start arg)) motion) len))
805 (tried-each-ring-item nil)
70a06174 806 (case-fold-search (eshell-under-windows-p))
affbf647
GM
807 (prev nil))
808 ;; Do the whole search as many times as the argument says.
809 (while (and (/= arg 0) (not tried-each-ring-item))
810 ;; Step once.
811 (setq prev n
812 n (mod (+ n motion) len))
813 ;; If we haven't reached a match, step some more.
814 (while (and (< n len) (not tried-each-ring-item)
815 (not (string-match regexp (eshell-get-history n))))
816 (setq n (mod (+ n motion) len)
817 ;; If we have gone all the way around in this search.
818 tried-each-ring-item (= n prev)))
819 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
820 ;; Now that we know which ring element to use, if we found it,
821 ;; return that.
822 (if (string-match regexp (eshell-get-history n))
823 n)))
824
825(defun eshell-previous-matching-input (regexp arg)
826 "Search backwards through input history for match for REGEXP.
827\(Previous history elements are earlier commands.)
828With prefix argument N, search for Nth previous match.
829If N is negative, find the next or Nth next match."
830 (interactive (eshell-regexp-arg "Previous input matching (regexp): "))
831 (setq arg (eshell-search-arg arg))
832 (let ((pos (eshell-previous-matching-input-string-position regexp arg)))
833 ;; Has a match been found?
834 (if (null pos)
835 (error "Not found")
836 (setq eshell-history-index pos)
3f75af1b
JW
837 (unless (minibuffer-window-active-p (selected-window))
838 (message "History item: %d" (- (ring-length eshell-history-ring) pos)))
affbf647 839 ;; Can't use kill-region as it sets this-command
de653a63 840 (delete-region eshell-last-output-end (point))
affbf647
GM
841 (insert-and-inherit (eshell-get-history pos)))))
842
843(defun eshell-next-matching-input (regexp arg)
844 "Search forwards through input history for match for REGEXP.
845\(Later history elements are more recent commands.)
846With prefix argument N, search for Nth following match.
847If N is negative, find the previous or Nth previous match."
848 (interactive (eshell-regexp-arg "Next input matching (regexp): "))
849 (eshell-previous-matching-input regexp (- arg)))
850
851(defun eshell-previous-matching-input-from-input (arg)
852 "Search backwards through input history for match for current input.
853\(Previous history elements are earlier commands.)
854With prefix argument N, search for Nth previous match.
855If N is negative, search forwards for the -Nth following match."
856 (interactive "p")
857 (if (not (memq last-command '(eshell-previous-matching-input-from-input
858 eshell-next-matching-input-from-input)))
859 ;; Starting a new search
860 (setq eshell-matching-input-from-input-string
861 (buffer-substring (save-excursion (eshell-bol) (point))
862 (point))
863 eshell-history-index nil))
864 (eshell-previous-matching-input
865 (concat "^" (regexp-quote eshell-matching-input-from-input-string))
866 arg))
867
868(defun eshell-next-matching-input-from-input (arg)
869 "Search forwards through input history for match for current input.
870\(Following history elements are more recent commands.)
871With prefix argument N, search for Nth following match.
872If N is negative, search backwards for the -Nth previous match."
873 (interactive "p")
874 (eshell-previous-matching-input-from-input (- arg)))
875
876(defun eshell-test-imatch ()
877 "If isearch match good, put point at the beginning and return non-nil."
878 (if (get-text-property (point) 'history)
879 (progn (beginning-of-line) t)
880 (let ((before (point)))
881 (eshell-bol)
882 (if (and (not (bolp))
883 (<= (point) before))
884 t
885 (if isearch-forward
886 (progn
887 (end-of-line)
888 (forward-char))
889 (beginning-of-line)
890 (backward-char))))))
891
892(defun eshell-return-to-prompt ()
893 "Once a search string matches, insert it at the end and go there."
894 (setq isearch-other-end nil)
895 (let ((found (eshell-test-imatch)) before)
896 (while (and (not found)
897 (setq before
898 (funcall (if isearch-forward
899 're-search-forward
900 're-search-backward)
901 isearch-string nil t)))
902 (setq found (eshell-test-imatch)))
903 (if (not found)
904 (progn
905 (goto-char eshell-last-output-end)
906 (delete-region (point) (point-max)))
907 (setq before (point))
908 (let ((text (buffer-substring-no-properties
909 (point) (line-end-position)))
910 (orig (marker-position eshell-last-output-end)))
911 (goto-char eshell-last-output-end)
912 (delete-region (point) (point-max))
913 (when (and text (> (length text) 0))
affbf647
GM
914 (insert text)
915 (put-text-property (1- (point)) (point)
916 'last-search-pos before)
917 (set-marker eshell-last-output-end orig)
918 (goto-char eshell-last-output-end))))))
919
920(defun eshell-prepare-for-search ()
921 "Make sure the old history file is at the beginning of the buffer."
922 (unless (get-text-property (point-min) 'history)
923 (save-excursion
924 (goto-char (point-min))
925 (let ((end (copy-marker (point) t)))
926 (insert-file-contents eshell-history-file-name)
927 (set-text-properties (point-min) end
928 '(history t invisible t))))))
929
930(defun eshell-isearch-backward (&optional invert)
931 "Do incremental regexp search backward through past commands."
932 (interactive)
933 (let ((inhibit-read-only t) end)
934 (eshell-prepare-for-search)
935 (goto-char (point-max))
936 (set-marker eshell-last-output-end (point))
937 (delete-region (point) (point-max)))
938 (isearch-mode invert t 'eshell-return-to-prompt))
939
940(defun eshell-isearch-repeat-backward (&optional invert)
941 "Do incremental regexp search backward through past commands."
942 (interactive)
943 (let ((old-pos (get-text-property (1- (point-max))
944 'last-search-pos)))
945 (when old-pos
946 (goto-char old-pos)
947 (if invert
948 (end-of-line)
949 (backward-char)))
950 (setq isearch-forward invert)
951 (isearch-search-and-update)))
952
953(defun eshell-isearch-forward ()
954 "Do incremental regexp search backward through past commands."
955 (interactive)
956 (eshell-isearch-backward t))
957
958(defun eshell-isearch-repeat-forward ()
959 "Do incremental regexp search backward through past commands."
960 (interactive)
961 (eshell-isearch-repeat-backward t))
962
963(defun eshell-isearch-cancel ()
964 (interactive)
965 (goto-char eshell-last-output-end)
966 (delete-region (point) (point-max))
967 (call-interactively 'isearch-cancel))
968
969(defun eshell-isearch-abort ()
970 (interactive)
971 (goto-char eshell-last-output-end)
972 (delete-region (point) (point-max))
973 (call-interactively 'isearch-abort))
974
975(defun eshell-isearch-delete-char ()
976 (interactive)
977 (save-excursion
978 (isearch-delete-char)))
979
980(defun eshell-isearch-return ()
981 (interactive)
982 (isearch-done)
983 (eshell-send-input))
984
dbba8a04
GM
985(provide 'em-hist)
986
cbee283d 987;; arch-tag: 1a847333-f864-4b96-9acd-b549d620b6c6
affbf647 988;;; em-hist.el ends here