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