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