Backslash cleanup in Elisp source files
[emacs.git] / lisp / eshell / em-hist.el
blob90dec59670148d7a8bb6538ac8efb031e3c76312
1 ;;; em-hist.el --- history list management -*- lexical-binding:t -*-
3 ;; Copyright (C) 1999-2015 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
123 (function
124 (lambda (str)
125 (not (string-match "\\`\\s-*\\'" str))))
126 "Predicate for filtering additions to input history.
127 Takes one argument, the input. If non-nil, the input may be saved on
128 the input history list. Default is to save anything that isn't all
129 whitespace."
130 :type 'function
131 :group 'eshell-hist)
133 (put 'eshell-input-filter 'risky-local-variable t)
135 (defcustom eshell-hist-match-partial t
136 "If non-nil, movement through history is constrained by current input.
137 Otherwise, typing <M-p> and <M-n> will always go to the next history
138 element, 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)
143 (defcustom eshell-hist-move-to-end t
144 "If non-nil, move to the end of the buffer before cycling history."
145 :type 'boolean
146 :group 'eshell-hist)
148 (defcustom eshell-hist-event-designator
149 "^!\\(!\\|-?[0-9]+\\|\\??[^:^$%*?]+\\??\\|#\\)"
150 "The regexp used to identifier history event designators."
151 :type 'regexp
152 :group 'eshell-hist)
154 (defcustom eshell-hist-word-designator
155 "^:?\\([0-9]+\\|[$^%*]\\)?\\(\\*\\|-[0-9]*\\|[$^%*]\\)?"
156 "The regexp used to identify history word designators."
157 :type 'regexp
158 :group 'eshell-hist)
160 (defcustom eshell-hist-modifier
161 "^\\(:\\([hretpqx&g]\\|s/\\([^/]*\\)/\\([^/]*\\)/\\)\\)*"
162 "The regexp used to identity history modifiers."
163 :type 'regexp
164 :group 'eshell-hist)
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))
179 "History keys to bind differently if point is in input text."
180 :type '(repeat (cons (vector :tag "Keys to bind"
181 (repeat :inline t sexp))
182 (function :tag "Command")))
183 :group 'eshell-hist)
185 ;;; Internal Variables:
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)
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.")
205 (defvar eshell-rebind-keys-alist)
207 ;;; Functions:
209 (defun eshell-hist-initialize ()
210 "Initialize the history management code for one Eshell buffer."
211 (add-hook 'eshell-expand-input-functions
212 'eshell-expand-history-references nil t)
214 (when (eshell-using-module 'eshell-cmpl)
215 (add-hook 'pcomplete-try-first-hook
216 'eshell-complete-history-reference nil t))
218 (if (and (eshell-using-module 'eshell-rebind)
219 (not eshell-non-interactive-p))
220 (let ((rebind-alist eshell-rebind-keys-alist))
221 (make-local-variable 'eshell-rebind-keys-alist)
222 (setq eshell-rebind-keys-alist
223 (append rebind-alist eshell-hist-rebind-keys-alist))
224 (set (make-local-variable 'search-invisible) t)
225 (set (make-local-variable 'search-exit-option) t)
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)
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)))
261 (make-local-variable 'eshell-history-size)
262 (or eshell-history-size
263 (let ((hsize (getenv "HISTSIZE")))
264 (setq eshell-history-size
265 (if (and (stringp hsize)
266 (integerp (setq hsize (string-to-number hsize)))
267 (> hsize 0))
268 hsize
269 128))))
271 (make-local-variable 'eshell-history-file-name)
272 (or eshell-history-file-name
273 (setq eshell-history-file-name (getenv "HISTFILE")))
275 (make-local-variable 'eshell-history-index)
276 (make-local-variable 'eshell-save-history-index)
278 (if (minibuffer-window-active-p (selected-window))
279 (set (make-local-variable 'eshell-save-history-on-exit) nil)
280 (set (make-local-variable 'eshell-history-ring) nil)
281 (if eshell-history-file-name
282 (eshell-read-history nil t))
284 (add-hook 'eshell-exit-hook 'eshell-write-history nil t))
286 (unless eshell-history-ring
287 (setq eshell-history-ring (make-ring eshell-history-size)))
289 (add-hook 'eshell-exit-hook 'eshell-write-history nil t)
291 (add-hook 'kill-emacs-hook 'eshell-save-some-history)
293 (make-local-variable 'eshell-input-filter-functions)
294 (add-hook 'eshell-input-filter-functions 'eshell-add-to-history nil t)
296 (define-key eshell-command-map [(control ?l)] 'eshell-list-history)
297 (define-key eshell-command-map [(control ?x)] 'eshell-get-next-from-history))
299 (defun eshell-save-some-history ()
300 "Save the history for any open Eshell buffers."
301 (dolist (buf (buffer-list))
302 (if (buffer-live-p buf)
303 (with-current-buffer buf
304 (if (and eshell-mode
305 eshell-history-file-name
306 eshell-save-history-on-exit
307 (or (eq eshell-save-history-on-exit t)
308 (y-or-n-p
309 (format-message
310 "Save input history for Eshell buffer `%s'? "
311 (buffer-name buf)))))
312 (eshell-write-history))))))
314 (defun eshell/history (&rest args)
315 "List in help buffer the buffer's input history."
316 (eshell-init-print-buffer)
317 (eshell-eval-using-options
318 "history" args
319 '((?r "read" nil read-history
320 "read from history file to current history list")
321 (?w "write" nil write-history
322 "write current history list to history file")
323 (?a "append" nil append-history
324 "append current history list to history file")
325 (?h "help" nil nil "display this usage message")
326 :usage "[n] [-rwa [filename]]"
327 :post-usage
328 "When Eshell is started, history is read from `eshell-history-file-name'.
329 This is also the location where history info will be saved by this command,
330 unless a different file is specified on the command line.")
331 (and (or (not (ring-p eshell-history-ring))
332 (ring-empty-p eshell-history-ring))
333 (error "No history"))
334 (let (length file)
335 (when (and args (string-match "^[0-9]+$" (car args)))
336 (setq length (min (eshell-convert (car args))
337 (ring-length eshell-history-ring))
338 args (cdr args)))
339 (and length
340 (or read-history write-history append-history)
341 (error "history: extra arguments"))
342 (when (and args (stringp (car args)))
343 (setq file (car args)
344 args (cdr args)))
345 (cond
346 (read-history (eshell-read-history file))
347 (write-history (eshell-write-history file))
348 (append-history (eshell-write-history file t))
350 (let* ((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))
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))
364 (if at-beginning
365 (ring-insert-at-beginning ring input)
366 (ring-insert ring input)))
368 (defun eshell-get-history (index &optional ring)
369 "Get an input line from the history ring."
370 (ring-ref (or ring eshell-history-ring) index))
372 (defun eshell-add-input-to-history (input)
373 "Add the string INPUT to the history ring.
374 Input is entered into the input history ring, if the value of
375 variable `eshell-input-filter' returns non-nil when called on the
376 input."
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))
386 (defun eshell-add-command-to-history ()
387 "Add the command entered at `eshell-command's prompt to the history ring.
388 The command is added to the input history ring, if the value of
389 variable `eshell-input-filter' returns non-nil when called on the
390 command.
392 This function is supposed to be called from the minibuffer, presumably
393 as a minibuffer-exit-hook."
394 (eshell-add-input-to-history
395 (buffer-substring (minibuffer-prompt-end) (point-max))))
397 (defun eshell-add-to-history ()
398 "Add last Eshell command to the history ring.
399 The command is entered into the input history ring, if the value of
400 variable `eshell-input-filter' returns non-nil when called on the
401 command."
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))))
405 (eshell-add-input-to-history input))))
407 (defun eshell-read-history (&optional filename silent)
408 "Sets the buffer's `eshell-history-ring' from a history file.
409 The 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.
414 If the optional argument SILENT is non-nil, we say nothing about a
415 failure to read the history file.
417 This function is useful for major mode commands and mode hooks.
419 The structure of the history file should be one input command per
420 line, 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)))
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)))
447 (ring-insert-at-beginning
448 ring (subst-char-in-string ?\177 ?\n history))))
449 (setq count (1+ count))))
450 (setq eshell-history-ring ring
451 eshell-history-index nil))))))
453 (defun eshell-write-history (&optional filename append)
454 "Writes the buffer's `eshell-history-ring' to a history file.
455 The name of the file is given by the variable
456 `eshell-history-file-name'. The original contents of the file are
457 lost if `eshell-history-ring' is not empty. If
458 `eshell-history-file-name' is nil this function does nothing.
460 Useful within process sentinels.
462 See 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))
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))
480 (let ((start (point)))
481 (insert (ring-ref ring index) ?\n)
482 (subst-char-in-region start (1- (point)) ?\n ?\177)))
483 (eshell-with-private-file-modes
484 (write-region (point-min) (point-max) file append
485 'no-message))))))))
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
513 (display-completion-list
514 (completion-hilit-commonality history (length prefix)))
515 (set-buffer history-buffer)
516 (forward-line 3)
517 (while (search-backward "completion" nil 'move)
518 (replace-match "history reference")))
519 (eshell-redisplay)
520 (message "Hit space to flush")
521 (let ((ch (read-event)))
522 (if (eq ch ?\ )
523 (set-window-configuration conf)
524 (push ch unread-command-events)))))))
526 (defun eshell-hist-word-reference (ref)
527 "Return the word designator index referred to by REF."
528 (cond
529 ((string-match "^[0-9]+$" ref)
530 (string-to-number ref))
531 ((string= "^" ref) 1)
532 ((string= "$" ref) nil)
533 ((string= "%" ref)
534 (error "`%%' history word designator not yet implemented"))))
536 (defun eshell-hist-parse-arguments (&optional b e)
537 "Parse current command arguments in a history-code-friendly way."
538 (let ((end (or e (point)))
539 (begin (or b (save-excursion (eshell-bol) (point))))
540 (posb (list t))
541 (pose (list t))
542 (textargs (list t))
543 hist args)
544 (unless (catch 'eshell-incomplete
545 (ignore
546 (setq args (eshell-parse-arguments begin end))))
547 (save-excursion
548 (goto-char begin)
549 (while (< (point) end)
550 (if (get-text-property (point) 'arg-begin)
551 (nconc posb (list (point))))
552 (if (get-text-property (point) 'arg-end)
553 (nconc pose
554 (list (if (= (1+ (point)) end)
555 (1+ (point))
556 (point)))))
557 (forward-char))
558 (setq posb (cdr posb)
559 pose (cdr pose))
560 (cl-assert (= (length posb) (length args)))
561 (cl-assert (<= (length posb) (length pose))))
562 (setq hist (buffer-substring-no-properties begin end))
563 (let ((b posb) (e pose))
564 (while b
565 (nconc textargs
566 (list (substring hist (- (car b) begin)
567 (- (car e) begin))))
568 (setq b (cdr b)
569 e (cdr e))))
570 (setq textargs (cdr textargs))
571 (cl-assert (= (length textargs) (length args)))
572 (list textargs posb pose))))
574 (defun eshell-expand-history-references (beg end)
575 "Parse and expand any history references in current input."
576 (let ((result (eshell-hist-parse-arguments beg end)))
577 (when result
578 (let ((textargs (nreverse (nth 0 result)))
579 (posb (nreverse (nth 1 result)))
580 (pose (nreverse (nth 2 result))))
581 (save-excursion
582 (while textargs
583 (let ((str (eshell-history-reference (car textargs))))
584 (unless (eq str (car textargs))
585 (goto-char (car posb))
586 (insert-and-inherit str)
587 (delete-char (- (car pose) (car posb)))))
588 (setq textargs (cdr textargs)
589 posb (cdr posb)
590 pose (cdr pose))))))))
592 (defvar pcomplete-stub)
593 (defvar pcomplete-last-completion-raw)
594 (declare-function pcomplete-actual-arg "pcomplete")
596 (defun eshell-complete-history-reference ()
597 "Complete a history reference, by completing the event designator."
598 (let ((arg (pcomplete-actual-arg)))
599 (when (string-match "\\`![^:^$*%]*\\'" arg)
600 (setq pcomplete-stub (substring arg 1)
601 pcomplete-last-completion-raw t)
602 (throw 'pcomplete-completions
603 (let ((history nil)
604 (index (1- (ring-length eshell-history-ring)))
605 (stublen (length pcomplete-stub)))
606 ;; We have to build up a list ourselves from the ring
607 ;; vector.
608 (while (>= index 0)
609 (let ((hist (eshell-get-history index)))
610 (if (and (>= (length hist) stublen)
611 (string= (substring hist 0 stublen)
612 pcomplete-stub)
613 (string-match "^\\([^:^$*% \t\n]+\\)" hist))
614 (setq history (cons (match-string 1 hist)
615 history))))
616 (setq index (1- index)))
617 (let ((fhist (list t)))
618 ;; uniquify the list, but preserve the order
619 (while history
620 (unless (member (car history) fhist)
621 (nconc fhist (list (car history))))
622 (setq history (cdr history)))
623 (cdr fhist)))))))
625 (defun eshell-history-reference (reference)
626 "Expand directory stack REFERENCE.
627 The syntax used here was taken from the Bash info manual.
628 Returns the resultant reference, or the same string REFERENCE if none
629 matched."
630 ;; `^string1^string2^'
631 ;; Quick Substitution. Repeat the last command, replacing
632 ;; STRING1 with STRING2. Equivalent to `!!:s/string1/string2/'
633 (if (and (eshell-using-module 'eshell-pred)
634 (string-match "\\^\\([^^]+\\)\\^\\([^^]+\\)\\^?\\s-*$"
635 reference))
636 (setq reference (format "!!:s/%s/%s/"
637 (match-string 1 reference)
638 (match-string 2 reference))))
639 ;; `!'
640 ;; Start a history substitution, except when followed by a
641 ;; space, tab, the end of the line, = or (.
642 (if (not (string-match "^![^ \t\n=(]" reference))
643 reference
644 (setq eshell-history-index nil)
645 (let ((event (eshell-hist-parse-event-designator reference)))
646 (unless event
647 (error "Could not find history event `%s'" reference))
648 (setq eshell-history-index (car event)
649 reference (substring reference (cdr event))
650 event (eshell-get-history eshell-history-index))
651 (if (not (string-match "^[:^$*%]" reference))
652 event
653 (let ((word (eshell-hist-parse-word-designator
654 event reference)))
655 (unless word
656 (error "Unable to honor word designator `%s'" reference))
657 (unless (string-match "^[:^$*%][[$^*%0-9-]" reference)
658 (setcdr word 0))
659 (setq event (car word)
660 reference (substring reference (cdr word)))
661 (if (not (and (eshell-using-module 'eshell-pred)
662 (string-match "^:" reference)))
663 event
664 (eshell-hist-parse-modifier event reference)))))))
666 (defun eshell-hist-parse-event-designator (reference)
667 "Parse a history event designator beginning in REFERENCE."
668 (let* ((index (string-match eshell-hist-event-designator reference))
669 (end (and index (match-end 0))))
670 (unless index
671 (error "Invalid history event designator `%s'" reference))
672 (let* ((event (match-string 1 reference))
673 (pos
674 (cond
675 ((string= event "!") (ring-length eshell-history-ring))
676 ((string= event "#") (error "!# not yet implemented"))
677 ((string-match "^-?[0-9]+$" event)
678 (let ((num (string-to-number event)))
679 (if (>= num 0)
680 (- (ring-length eshell-history-ring) num)
681 (1- (abs num)))))
682 ((string-match "^\\(\\??\\)\\([^?]+\\)\\??$" event)
683 (let ((pref (if (> (length (match-string 1 event)) 0)
684 "" "^"))
685 (str (match-string 2 event)))
686 (save-match-data
687 (eshell-previous-matching-input-string-position
688 (concat pref (regexp-quote str)) 1))))
690 (error "Failed to parse event designator `%s'" event)))))
691 (and pos (cons pos end)))))
693 (defun eshell-hist-parse-word-designator (hist reference)
694 "Parse a history word designator beginning for HIST in REFERENCE."
695 (let* ((index (string-match eshell-hist-word-designator reference))
696 (end (and index (match-end 0))))
697 (unless (memq (aref reference 0) '(?: ?^ ?$ ?* ?%))
698 (error "Invalid history word designator `%s'" reference))
699 (let ((nth (match-string 1 reference))
700 (mth (match-string 2 reference))
701 (here (point))
702 textargs)
703 (insert hist)
704 (setq textargs (car (eshell-hist-parse-arguments here (point))))
705 (delete-region here (point))
706 (if (string= nth "*")
707 (if mth
708 (error "Invalid history word designator `%s'"
709 reference)
710 (setq nth 1 mth "-$")))
711 (if (not mth)
712 (if nth
713 (setq mth nth)
714 (setq nth 0 mth "$"))
715 (if (string= mth "-")
716 (setq mth (- (length textargs) 2))
717 (if (string= mth "*")
718 (setq mth "$")
719 (if (not (and (> (length mth) 1)
720 (eq (aref mth 0) ?-)))
721 (error "Invalid history word designator `%s'"
722 reference)
723 (setq mth (substring mth 1))))))
724 (unless (numberp nth)
725 (setq nth (eshell-hist-word-reference nth)))
726 (unless (numberp mth)
727 (setq mth (eshell-hist-word-reference mth)))
728 (cons (mapconcat 'identity (eshell-sublist textargs nth mth) " ")
729 end))))
731 (defun eshell-hist-parse-modifier (hist reference)
732 "Parse a history modifier beginning for HIST in REFERENCE."
733 (let ((here (point)))
734 (insert reference)
735 (prog1
736 (save-restriction
737 (narrow-to-region here (point))
738 (goto-char (point-min))
739 (let ((modifiers (cdr (eshell-parse-modifiers))))
740 (dolist (mod modifiers)
741 (setq hist (car (funcall mod (list hist)))))
742 hist))
743 (delete-region here (point)))))
745 (defun eshell-get-next-from-history ()
746 "After fetching a line from input history, this fetches the next.
747 In other words, this recalls the input line after the line you
748 recalled last. You can use this to repeat a sequence of input lines."
749 (interactive)
750 (if eshell-save-history-index
751 (progn
752 (setq eshell-history-index (1+ eshell-save-history-index))
753 (eshell-next-input 1))
754 (message "No previous history command")))
756 (defun eshell-search-arg (arg)
757 ;; First make sure there is a ring and that we are after the process
758 ;; mark
759 (if (and eshell-hist-move-to-end
760 (< (point) eshell-last-output-end))
761 (goto-char eshell-last-output-end))
762 (cond ((or (null eshell-history-ring)
763 (ring-empty-p eshell-history-ring))
764 (error "Empty input ring"))
765 ((zerop arg)
766 ;; arg of zero resets search from beginning, and uses arg of
767 ;; 1
768 (setq eshell-history-index nil)
771 arg)))
773 (defun eshell-search-start (arg)
774 "Index to start a directional search, starting at `eshell-history-index'."
775 (if eshell-history-index
776 ;; If a search is running, offset by 1 in direction of arg
777 (mod (+ eshell-history-index (if (> arg 0) 1 -1))
778 (ring-length eshell-history-ring))
779 ;; For a new search, start from beginning or end, as appropriate
780 (if (>= arg 0)
781 0 ; First elt for forward search
782 ;; Last elt for backward search
783 (1- (ring-length eshell-history-ring)))))
785 (defun eshell-previous-input-string (arg)
786 "Return the string ARG places along the input ring.
787 Moves relative to `eshell-history-index'."
788 (eshell-get-history (if eshell-history-index
789 (mod (+ arg eshell-history-index)
790 (ring-length eshell-history-ring))
791 arg)))
793 (defun eshell-previous-input (arg)
794 "Cycle backwards through input history."
795 (interactive "*p")
796 (eshell-previous-matching-input "." arg))
798 (defun eshell-next-input (arg)
799 "Cycle forwards through input history."
800 (interactive "*p")
801 (eshell-previous-input (- arg)))
803 (defun eshell-previous-matching-input-string (regexp arg)
804 "Return the string matching REGEXP ARG places along the input ring.
805 Moves relative to `eshell-history-index'."
806 (let* ((pos (eshell-previous-matching-input-string-position regexp arg)))
807 (if pos (eshell-get-history pos))))
809 (defun eshell-previous-matching-input-string-position
810 (regexp arg &optional start)
811 "Return the index matching REGEXP ARG places along the input ring.
812 Moves relative to START, or `eshell-history-index'."
813 (if (or (not (ring-p eshell-history-ring))
814 (ring-empty-p eshell-history-ring))
815 (error "No history"))
816 (let* ((len (ring-length eshell-history-ring))
817 (motion (if (> arg 0) 1 -1))
818 (n (mod (- (or start (eshell-search-start arg)) motion) len))
819 (tried-each-ring-item nil)
820 (case-fold-search (eshell-under-windows-p))
821 (prev nil))
822 ;; Do the whole search as many times as the argument says.
823 (while (and (/= arg 0) (not tried-each-ring-item))
824 ;; Step once.
825 (setq prev n
826 n (mod (+ n motion) len))
827 ;; If we haven't reached a match, step some more.
828 (while (and (< n len) (not tried-each-ring-item)
829 (not (string-match regexp (eshell-get-history n))))
830 (setq n (mod (+ n motion) len)
831 ;; If we have gone all the way around in this search.
832 tried-each-ring-item (= n prev)))
833 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
834 ;; Now that we know which ring element to use, if we found it,
835 ;; return that.
836 (if (string-match regexp (eshell-get-history n))
837 n)))
839 (defun eshell-previous-matching-input (regexp arg)
840 "Search backwards through input history for match for REGEXP.
841 \(Previous history elements are earlier commands.)
842 With prefix argument N, search for Nth previous match.
843 If N is negative, find the next or Nth next match."
844 (interactive (eshell-regexp-arg "Previous input matching (regexp): "))
845 (setq arg (eshell-search-arg arg))
846 (if (> eshell-last-output-end (point))
847 (error "Point not located after prompt"))
848 (let ((pos (eshell-previous-matching-input-string-position regexp arg)))
849 ;; Has a match been found?
850 (if (null pos)
851 (error "Not found")
852 (setq eshell-history-index pos)
853 (unless (minibuffer-window-active-p (selected-window))
854 (message "History item: %d" (- (ring-length eshell-history-ring) pos)))
855 ;; Can't use kill-region as it sets this-command
856 (delete-region eshell-last-output-end (point))
857 (insert-and-inherit (eshell-get-history pos)))))
859 (defun eshell-next-matching-input (regexp arg)
860 "Search forwards through input history for match for REGEXP.
861 \(Later history elements are more recent commands.)
862 With prefix argument N, search for Nth following match.
863 If N is negative, find the previous or Nth previous match."
864 (interactive (eshell-regexp-arg "Next input matching (regexp): "))
865 (eshell-previous-matching-input regexp (- arg)))
867 (defun eshell-previous-matching-input-from-input (arg)
868 "Search backwards through input history for match for current input.
869 \(Previous history elements are earlier commands.)
870 With prefix argument N, search for Nth previous match.
871 If N is negative, search forwards for the -Nth following match."
872 (interactive "p")
873 (if (not (memq last-command '(eshell-previous-matching-input-from-input
874 eshell-next-matching-input-from-input)))
875 ;; Starting a new search
876 (setq eshell-matching-input-from-input-string
877 (buffer-substring (save-excursion (eshell-bol) (point))
878 (point))
879 eshell-history-index nil))
880 (eshell-previous-matching-input
881 (concat "^" (regexp-quote eshell-matching-input-from-input-string))
882 arg))
884 (defun eshell-next-matching-input-from-input (arg)
885 "Search forwards through input history for match for current input.
886 \(Following history elements are more recent commands.)
887 With prefix argument N, search for Nth following match.
888 If N is negative, search backwards for the -Nth previous match."
889 (interactive "p")
890 (eshell-previous-matching-input-from-input (- arg)))
892 (defun eshell-test-imatch ()
893 "If isearch match good, put point at the beginning and return non-nil."
894 (if (get-text-property (point) 'history)
895 (progn (beginning-of-line) t)
896 (let ((before (point)))
897 (eshell-bol)
898 (if (and (not (bolp))
899 (<= (point) before))
901 (if isearch-forward
902 (progn
903 (end-of-line)
904 (forward-char))
905 (beginning-of-line)
906 (backward-char))))))
908 (defun eshell-return-to-prompt ()
909 "Once a search string matches, insert it at the end and go there."
910 (setq isearch-other-end nil)
911 (let ((found (eshell-test-imatch)) before)
912 (while (and (not found)
913 (setq before
914 (funcall (if isearch-forward
915 're-search-forward
916 're-search-backward)
917 isearch-string nil t)))
918 (setq found (eshell-test-imatch)))
919 (if (not found)
920 (progn
921 (goto-char eshell-last-output-end)
922 (delete-region (point) (point-max)))
923 (setq before (point))
924 (let ((text (buffer-substring-no-properties
925 (point) (line-end-position)))
926 (orig (marker-position eshell-last-output-end)))
927 (goto-char eshell-last-output-end)
928 (delete-region (point) (point-max))
929 (when (and text (> (length text) 0))
930 (insert text)
931 (put-text-property (1- (point)) (point)
932 'last-search-pos before)
933 (set-marker eshell-last-output-end orig)
934 (goto-char eshell-last-output-end))))))
936 (defun eshell-prepare-for-search ()
937 "Make sure the old history file is at the beginning of the buffer."
938 (unless (get-text-property (point-min) 'history)
939 (save-excursion
940 (goto-char (point-min))
941 (let ((end (copy-marker (point) t)))
942 (insert-file-contents eshell-history-file-name)
943 (set-text-properties (point-min) end
944 '(history t invisible t))))))
946 (defun eshell-isearch-backward (&optional invert)
947 "Do incremental regexp search backward through past commands."
948 (interactive)
949 (let ((inhibit-read-only t))
950 (eshell-prepare-for-search)
951 (goto-char (point-max))
952 (set-marker eshell-last-output-end (point))
953 (delete-region (point) (point-max)))
954 (isearch-mode invert t 'eshell-return-to-prompt))
956 (defun eshell-isearch-repeat-backward (&optional invert)
957 "Do incremental regexp search backward through past commands."
958 (interactive)
959 (let ((old-pos (get-text-property (1- (point-max))
960 'last-search-pos)))
961 (when old-pos
962 (goto-char old-pos)
963 (if invert
964 (end-of-line)
965 (backward-char)))
966 (setq isearch-forward invert)
967 (isearch-search-and-update)))
969 (defun eshell-isearch-forward ()
970 "Do incremental regexp search backward through past commands."
971 (interactive)
972 (eshell-isearch-backward t))
974 (defun eshell-isearch-repeat-forward ()
975 "Do incremental regexp search backward through past commands."
976 (interactive)
977 (eshell-isearch-repeat-backward t))
979 (defun eshell-isearch-cancel ()
980 (interactive)
981 (goto-char eshell-last-output-end)
982 (delete-region (point) (point-max))
983 (call-interactively 'isearch-cancel))
985 (defun eshell-isearch-abort ()
986 (interactive)
987 (goto-char eshell-last-output-end)
988 (delete-region (point) (point-max))
989 (call-interactively 'isearch-abort))
991 (defun eshell-isearch-delete-char ()
992 (interactive)
993 (save-excursion
994 (isearch-delete-char)))
996 (defun eshell-isearch-return ()
997 (interactive)
998 (isearch-done)
999 (eshell-send-input))
1001 (provide 'em-hist)
1003 ;; Local Variables:
1004 ;; generated-autoload-file: "esh-groups.el"
1005 ;; End:
1007 ;;; em-hist.el ends here