savehist.el 12.9 KB
Newer Older
1
;;; savehist.el --- Save minibuffer history  -*- lexical-binding:t -*-
Richard M. Stallman's avatar
Richard M. Stallman committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1997, 2005-2020 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

Paul Eggert's avatar
Paul Eggert committed
5
;; Author: Hrvoje Nikšić <hrvoje.niksic@avl.com>
6
;; Maintainer: emacs-devel@gnu.org
Richard M. Stallman's avatar
Richard M. Stallman committed
7
;; Keywords: minibuffer
8
;; Version: 24
Richard M. Stallman's avatar
Richard M. Stallman committed
9 10 11

;; This file is part of GNU Emacs.

12
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
13
;; it under the terms of the GNU General Public License as published by
14 15
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
16 17 18 19 20 21 22

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
23
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
24 25 26

;;; Commentary:

27 28
;; Many editors (e.g. Vim) have the feature of saving minibuffer
;; history to an external file after exit.  This package provides the
Stefan Monnier's avatar
Stefan Monnier committed
29 30 31 32
;; same feature in Emacs.  When set up, it saves recorded minibuffer
;; histories to a file (`~/.emacs-history' by default).  Additional
;; variables may be specified by customizing
;; `savehist-additional-variables'.
Richard M. Stallman's avatar
Richard M. Stallman committed
33

Stefan Monnier's avatar
Stefan Monnier committed
34 35
;; To use savehist, turn on savehist-mode by putting the following in
;; `~/.emacs':
Richard M. Stallman's avatar
Richard M. Stallman committed
36
;;
Stefan Monnier's avatar
Stefan Monnier committed
37 38 39 40 41
;;     (savehist-mode 1)
;;
;; or with customize: `M-x customize-option RET savehist-mode RET'.
;;
;; You can also explicitly save history with `M-x savehist-save' and
42
;; load it by loading the `savehist-file' with `M-x load-file'.
Richard M. Stallman's avatar
Richard M. Stallman committed
43

Stefan Monnier's avatar
Stefan Monnier committed
44 45 46
;; If you are using a version of Emacs that does not ship with this
;; package, be sure to have `savehist.el' in a directory that is in
;; your load-path, and to byte-compile it.
47

Richard M. Stallman's avatar
Richard M. Stallman committed
48 49
;;; Code:

50 51
(require 'custom)

Richard M. Stallman's avatar
Richard M. Stallman committed
52 53 54 55
;; User variables

(defgroup savehist nil
  "Save minibuffer history."
Reiner Steib's avatar
Reiner Steib committed
56
  :version "22.1"
Richard M. Stallman's avatar
Richard M. Stallman committed
57 58
  :group 'minibuffer)

Stefan Monnier's avatar
Stefan Monnier committed
59
(defcustom savehist-save-minibuffer-history t
60
  "If non-nil, save all recorded minibuffer histories.
61 62
If you want to save only specific histories, use `savehist-save-hook'
to modify the value of `savehist-minibuffer-history-variables'."
63
  :type 'boolean)
Stefan Monnier's avatar
Stefan Monnier committed
64 65

(defcustom savehist-additional-variables ()
66
  "List of additional variables to save.
Stefan Monnier's avatar
Stefan Monnier committed
67
Each element is a symbol whose value will be persisted across Emacs
68
sessions that use Savehist.  The contents of variables should be
Stefan Monnier's avatar
Stefan Monnier committed
69 70 71 72 73
printable with the Lisp printer.  You don't need to add minibuffer
history variables to this list, all minibuffer histories will be
saved automatically as long as `savehist-save-minibuffer-history' is
non-nil.

74
User options should be saved with the Customize interface.  This
Stefan Monnier's avatar
Stefan Monnier committed
75 76
list is useful for saving automatically updated variables that are not
minibuffer histories, such as `compile-command' or `kill-ring'."
77
  :type '(repeat variable))
Richard M. Stallman's avatar
Richard M. Stallman committed
78

Reiner Steib's avatar
Reiner Steib committed
79
(defcustom savehist-ignored-variables nil ;; '(command-history)
80
  "List of additional variables not to save."
81
  :type '(repeat variable))
Reiner Steib's avatar
Reiner Steib committed
82

Stefan Monnier's avatar
Stefan Monnier committed
83
(defcustom savehist-file
84
  (locate-user-emacs-file "history" ".emacs-history")
85
  "File name where minibuffer history is saved to and loaded from.
Stefan Monnier's avatar
Stefan Monnier committed
86
The minibuffer history is a series of Lisp expressions loaded
87
automatically when Savehist mode is turned on.  See `savehist-mode'
88
for more details."
89
  :type 'file)
Richard M. Stallman's avatar
Richard M. Stallman committed
90

Stefan Monnier's avatar
Stefan Monnier committed
91
(defcustom savehist-file-modes #o600
92
  "Default permissions of the history file.
93 94 95 96
This is decimal, not octal.  The default is 384 (0600 in octal).
Set to nil to use the default permissions that Emacs uses, typically
mandated by umask.  The default is a bit more restrictive to protect
the user's privacy."
97
  :type 'integer)
Richard M. Stallman's avatar
Richard M. Stallman committed
98

99
(defcustom savehist-autosave-interval (* 5 60)
100
  "The interval between autosaves of minibuffer history.
Stefan Monnier's avatar
Stefan Monnier committed
101
If set to nil, disables timer-based autosaving."
102
  :type '(choice (const :tag "Disabled" nil)
103
                 (integer :tag "Seconds")))
104

105
(defcustom savehist-mode-hook nil
106
  "Hook called when Savehist mode is turned on."
107
  :type 'hook)
108

Stefan Monnier's avatar
Stefan Monnier committed
109
(defcustom savehist-save-hook nil
110
  "Hook called by `savehist-save' before saving the variables.
111 112
You can use this hook to influence choice and content of variables
to save."
113
  :type 'hook)
Stefan Monnier's avatar
Stefan Monnier committed
114

115 116
;; This should be capable of representing characters used by Emacs.
;; We prefer UTF-8 over ISO 2022 because it is well-known outside
117 118
;; Mule.
(defvar savehist-coding-system 'utf-8-unix
119
  "The coding system Savehist uses for saving the minibuffer history.
120 121 122 123 124 125 126 127 128
Changing this value while Emacs is running is supported, but considered
unwise, unless you know what you are doing.")

;; Internal variables.

(defvar savehist-timer nil)

(defvar savehist-last-checksum nil)

Stefan Monnier's avatar
Stefan Monnier committed
129 130 131 132 133
(defvar savehist-minibuffer-history-variables nil
  "List of minibuffer histories.
The contents of this variable is built while Emacs is running, and saved
along with minibuffer history.  You can change its value off
`savehist-save-hook' to influence which variables are saved.")
Stefan Monnier's avatar
Stefan Monnier committed
134

135 136
(defvar savehist-loaded nil
  "Whether the history has already been loaded.
137
This prevents toggling Savehist mode from destroying existing
138
minibuffer history.")
Stefan Monnier's avatar
Stefan Monnier committed
139

Richard M. Stallman's avatar
Richard M. Stallman committed
140

Stefan Monnier's avatar
Stefan Monnier committed
141 142
;; Functions.

Stefan Monnier's avatar
Stefan Monnier committed
143
;;;###autoload
144
(define-minor-mode savehist-mode
145 146 147
  "Toggle saving of minibuffer history (Savehist mode).

When Savehist mode is enabled, minibuffer history is saved
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
to `savehist-file' periodically and when exiting Emacs.  When
Savehist mode is enabled for the first time in an Emacs session,
it loads the previous minibuffer histories from `savehist-file'.
The variable `savehist-autosave-interval' controls the
periodicity of saving minibuffer histories.

If `savehist-save-minibuffer-history' is non-nil (the default),
all recorded minibuffer histories will be saved.  You can arrange
for additional history variables to be saved and restored by
customizing `savehist-additional-variables', which by default is
an empty list.  For example, to save the history of commands
invoked via \\[execute-extended-command], add `command-history' to the list in
`savehist-additional-variables'.

Alternatively, you could customize `savehist-save-minibuffer-history'
to nil, and add to `savehist-additional-variables' only those
history variables you want to save.

To ignore some history variables, add their symbols to the list
in `savehist-ignored-variables'.
Stefan Monnier's avatar
Stefan Monnier committed
168 169

This mode should normally be turned on from your Emacs init file.
170 171
Calling it at any other time replaces your current minibuffer
histories, which is probably undesirable."
172
  :global t
Stefan Monnier's avatar
Stefan Monnier committed
173 174 175 176 177 178 179 180 181 182
  (if (not savehist-mode)
      (savehist-uninstall)
    (when (and (not savehist-loaded)
	       (file-exists-p savehist-file))
      (condition-case errvar
	  (progn
	    ;; Don't set coding-system-for-read -- we rely on the
	    ;; coding cookie to convey that information.  That way, if
	    ;; the user changes the value of savehist-coding-system,
	    ;; we can still correctly load the old file.
183
	    (load savehist-file nil (not (called-interactively-p 'interactive)))
Stefan Monnier's avatar
Stefan Monnier committed
184 185 186 187 188 189 190
	    (setq savehist-loaded t))
	(error
	 ;; Don't install the mode if reading failed.  Doing so would
	 ;; effectively destroy the user's data at the next save.
	 (setq savehist-mode nil)
	 (savehist-uninstall)
	 (signal (car errvar) (cdr errvar)))))
191
    (savehist-install)))
Stefan Monnier's avatar
Stefan Monnier committed
192

Stefan Monnier's avatar
Stefan Monnier committed
193
(defun savehist-install ()
194
  "Hook Savehist into Emacs.
Stefan Monnier's avatar
Stefan Monnier committed
195
Normally invoked by calling `savehist-mode' to set the minor mode.
196 197
Installs `savehist-autosave' in `kill-emacs-hook' and on a timer.
To undo this, call `savehist-uninstall'."
198 199
  (add-hook 'minibuffer-setup-hook #'savehist-minibuffer-hook)
  (add-hook 'kill-emacs-hook #'savehist-autosave)
Stefan Monnier's avatar
Stefan Monnier committed
200 201 202
  ;; Install an invocation of savehist-autosave on a timer.  This
  ;; should not cause noticeable delays for users -- savehist-autosave
  ;; executes in under 5 ms on my system.
Stefan Monnier's avatar
Stefan Monnier committed
203 204
  (when (and savehist-autosave-interval
	     (null savehist-timer))
Stefan Monnier's avatar
Stefan Monnier committed
205
    (setq savehist-timer
206 207
	  (run-with-timer savehist-autosave-interval
			  savehist-autosave-interval #'savehist-autosave))))
Stefan Monnier's avatar
Stefan Monnier committed
208 209

(defun savehist-uninstall ()
Stefan Monnier's avatar
Stefan Monnier committed
210 211
  "Undo installing savehist.
Normally invoked by calling `savehist-mode' to unset the minor mode."
212 213
  (remove-hook 'minibuffer-setup-hook #'savehist-minibuffer-hook)
  (remove-hook 'kill-emacs-hook #'savehist-autosave)
Stefan Monnier's avatar
Stefan Monnier committed
214
  (when savehist-timer
215
    (cancel-timer savehist-timer)
Stefan Monnier's avatar
Stefan Monnier committed
216
    (setq savehist-timer nil)))
Richard M. Stallman's avatar
Richard M. Stallman committed
217

218
(defun savehist-save (&optional auto-save)
Stefan Monnier's avatar
Stefan Monnier committed
219 220
  "Save the values of minibuffer history variables.
Unbound symbols referenced in `savehist-additional-variables' are ignored.
221 222
If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
 and don't save the buffer if they are the same."
Richard M. Stallman's avatar
Richard M. Stallman committed
223
  (interactive)
224 225
  (with-temp-buffer
    (insert
226 227 228 229 230 231
     (format-message
      (concat
       ";; -*- mode: emacs-lisp; coding: %s -*-\n"
       ";; Minibuffer history file, automatically generated by `savehist'.\n"
       "\n")
      savehist-coding-system))
Stefan Monnier's avatar
Stefan Monnier committed
232
    (run-hooks 'savehist-save-hook)
233 234
    (let ((print-length nil)
	  (print-level nil)
Stefan Monnier's avatar
Stefan Monnier committed
235 236 237 238 239 240 241 242 243
	  (print-quoted t))
      ;; Save the minibuffer histories, along with the value of
      ;; savehist-minibuffer-history-variables itself.
      (when savehist-save-minibuffer-history
	(prin1 `(setq savehist-minibuffer-history-variables
		      ',savehist-minibuffer-history-variables)
	       (current-buffer))
	(insert ?\n)
	(dolist (symbol savehist-minibuffer-history-variables)
244 245
	  (when (and (boundp symbol)
		     (not (memq symbol savehist-ignored-variables)))
246
	    (let ((value (symbol-value symbol))
247 248 249 250 251 252 253 254 255 256 257 258
		  excess-space)
	      (when value		; Don't save empty histories.
		(insert "(setq ")
		(prin1 symbol (current-buffer))
		(insert " '(")
		;; We will print an extra space before the first element.
		;; Record where that is.
		(setq excess-space (point))
		;; Print elements of VALUE one by one, carefully.
		(dolist (elt value)
		  (let ((start (point)))
		    (insert " ")
Glenn Morris's avatar
Glenn Morris committed
259
		    ;; Try to print and then to read an element.
260
		    (condition-case nil
261 262 263 264 265
			(progn
			  (prin1 elt (current-buffer))
			  (save-excursion
			    (goto-char start)
			    (read (current-buffer))))
266
		      (error
Glenn Morris's avatar
Glenn Morris committed
267
		       ;; If writing or reading gave an error, comment it out.
268 269 270 271 272 273 274 275 276 277 278 279 280
		       (goto-char start)
		       (insert "\n")
		       (while (not (eobp))
			 (insert ";;; ")
			 (forward-line 1))
		       (insert "\n")))
		    (goto-char (point-max))))
		;; Delete the extra space before the first element.
		(save-excursion
		  (goto-char excess-space)
		  (if (eq (following-char) ?\s)
		      (delete-region (point) (1+ (point)))))
		(insert "))\n"))))))
Stefan Monnier's avatar
Stefan Monnier committed
281 282 283 284 285 286 287
      ;; Save the additional variables.
      (dolist (symbol savehist-additional-variables)
	(when (boundp symbol)
	  (let ((value (symbol-value symbol)))
	    (when (savehist-printable value)
	      (prin1 `(setq ,symbol ',value) (current-buffer))
	      (insert ?\n))))))
288 289
    ;; If autosaving, avoid writing if nothing has changed since the
    ;; last write.
290
    (let ((checksum (md5 (current-buffer) nil nil savehist-coding-system)))
291 292 293
      (unless (and auto-save (equal checksum savehist-last-checksum))
	;; Set file-precious-flag when saving the buffer because we
	;; don't want a half-finished write ruining the entire
Stefan Monnier's avatar
Stefan Monnier committed
294 295 296
	;; history.  Remember that this is run from a timer and from
	;; kill-emacs-hook, and also that multiple Emacs instances
	;; could write to this file at once.
297
	(let ((file-precious-flag t)
298 299 300 301 302
	      (coding-system-for-write savehist-coding-system)
              (dir (file-name-directory savehist-file)))
          ;; Ensure that the directory exists before saving.
          (unless (file-exists-p dir)
            (make-directory dir t))
303
	  (write-region (point-min) (point-max) savehist-file nil
304
			(unless (called-interactively-p 'interactive) 'quiet)))
Stefan Monnier's avatar
Stefan Monnier committed
305 306
	(when savehist-file-modes
	  (set-file-modes savehist-file savehist-file-modes))
307 308 309
	(setq savehist-last-checksum checksum)))))

(defun savehist-autosave ()
Stefan Monnier's avatar
Stefan Monnier committed
310
  "Save the minibuffer history if it has been modified since the last save.
311
Does nothing if Savehist mode is off."
Stefan Monnier's avatar
Stefan Monnier committed
312 313 314
  (when savehist-mode
    (savehist-save t)))

315
(define-obsolete-function-alias 'savehist-trim-history #'identity "27.1")
316 317

(defun savehist-printable (value)
Stefan Monnier's avatar
Stefan Monnier committed
318
  "Return non-nil if VALUE is printable."
319
  (cond
Stefan Monnier's avatar
Stefan Monnier committed
320
   ;; Quick response for oft-encountered types known to be printable.
321 322
   ((numberp value))
   ((symbolp value))
323 324 325
   ;; String without properties
   ((and (stringp value)
	 (equal-including-properties value (substring-no-properties value))))
326 327
   (t
    ;; For others, check explicitly.
Stefan Monnier's avatar
Stefan Monnier committed
328 329
    (with-temp-buffer
      (condition-case nil
330 331 332 333 334 335 336
	  (let ((print-level nil))
	    ;; Print the value into a buffer...
	    (prin1 value (current-buffer))
	    ;; ...and attempt to read it.
	    (read (point-min-marker))
	    ;; The attempt worked: the object is printable.
	    t)
Stefan Monnier's avatar
Stefan Monnier committed
337 338
	;; The attempt failed: the object is not printable.
	(error nil))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
339

Stefan Monnier's avatar
Stefan Monnier committed
340
(defun savehist-minibuffer-hook ()
341
  (unless (or (eq minibuffer-history-variable t)
342 343 344 345
	      ;; If `read-string' is called with a t HISTORY argument
	      ;; (which `read-password' does),
	      ;; `minibuffer-history-variable' is bound to t to mean
	      ;; "no history is being recorded".
346
	      (memq minibuffer-history-variable savehist-ignored-variables))
347 348
    (add-to-list 'savehist-minibuffer-history-variables
		 minibuffer-history-variable)))
Stefan Monnier's avatar
Stefan Monnier committed
349

Richard M. Stallman's avatar
Richard M. Stallman committed
350
(provide 'savehist)
Stefan Monnier's avatar
Stefan Monnier committed
351 352


Richard M. Stallman's avatar
Richard M. Stallman committed
353
;;; savehist.el ends here