Elisp interactive function with input history

2019-07-16 06:47发布

问题:

there is a bunch of interactive functions which take string input as an argument:

(defun zb/run-cmd-X (arg1 argN)
  (interactive "Marg1: Marg2: ")
  ;;; some logic

How to make each of such functions zb/run-cmd-1..zb/run-cmd-N have own independent history of input arguments arg1...argN? And it would be perfect if this history was persistent between Emacs launches (ideally somewhere in an external file; for sync).

Is there any ready solution for this?

Thanks

回答1:

Basically you want to read the documentation for read-from-minibuffer and completing-read regarding the HIST argument which each of those functions accepts. There are other functions with history support of course, but these two are the standard/basic options.

Persistence is provided for by the savehist library, which writes to the file in savehist-file (which by default is ~/.emacs.d/history, but the old ~/.emacs-history will be used instead if that file exists -- in which case you might want to rename it to the modern preferred path).

Here's an example:

(defvar my-ssh-history nil)

(eval-after-load "savehist"
  '(add-to-list 'savehist-additional-variables 'my-ssh-history))

(defun my-ssh (args)
  "Connect to a remote host by SSH."
  (interactive
   (list (read-from-minibuffer "ssh " nil nil nil 'my-ssh-history)))
  (let* ((switches (split-string-and-unquote args))
         (name (concat "ssh " args))
         (termbuf (apply 'make-term name "ssh" nil switches)))
    (set-buffer termbuf)
    (term-mode)
    (term-char-mode)
    (switch-to-buffer termbuf)))

(savehist-mode 1)


标签: emacs elisp