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