international/characters.el: Fix simple mistake ((car chars) -> elt), delete duplicat...
[emacs.git] / lisp / savehist.el
blobcca958ff0a167e834a20ecd337393ed132f074b5
1 ;;; savehist.el --- Save minibuffer history
3 ;; Copyright (C) 1997, 2005-2012 Free Software Foundation, Inc.
5 ;; Author: Hrvoje Niksic <hniksic@xemacs.org>
6 ;; Maintainer: FSF
7 ;; Keywords: minibuffer
8 ;; Version: 24
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Many editors (e.g. Vim) have the feature of saving minibuffer
28 ;; history to an external file after exit. This package provides the
29 ;; same feature in Emacs. When set up, it saves recorded minibuffer
30 ;; histories to a file (`~/.emacs-history' by default). Additional
31 ;; variables may be specified by customizing
32 ;; `savehist-additional-variables'.
34 ;; To use savehist, turn on savehist-mode by putting the following in
35 ;; `~/.emacs':
37 ;; (savehist-mode 1)
39 ;; or with customize: `M-x customize-option RET savehist-mode RET'.
41 ;; 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'.
44 ;; If you are using a version of Emacs that does not ship with this
45 ;; package, be sure to have `savehist.el' in a directory that is in
46 ;; your load-path, and to byte-compile it.
48 ;;; Code:
50 (require 'custom)
51 (eval-when-compile
52 (require 'cl))
54 ;; User variables
56 (defgroup savehist nil
57 "Save minibuffer history."
58 :version "22.1"
59 :group 'minibuffer)
61 (defcustom savehist-save-minibuffer-history t
62 "If non-nil, save all recorded minibuffer histories.
63 If you want to save only specific histories, use `savehist-save-hook' to
64 modify the value of `savehist-minibuffer-history-variables'."
65 :type 'boolean
66 :group 'savehist)
68 (defcustom savehist-additional-variables ()
69 "List of additional variables to save.
70 Each element is a symbol whose value will be persisted across Emacs
71 sessions that use savehist. The contents of variables should be
72 printable with the Lisp printer. You don't need to add minibuffer
73 history variables to this list, all minibuffer histories will be
74 saved automatically as long as `savehist-save-minibuffer-history' is
75 non-nil.
77 User options should be saved with the customize interface. This
78 list is useful for saving automatically updated variables that are not
79 minibuffer histories, such as `compile-command' or `kill-ring'."
80 :type '(repeat variable)
81 :group 'savehist)
83 (defcustom savehist-ignored-variables nil ;; '(command-history)
84 "List of additional variables not to save."
85 :type '(repeat variable)
86 :group 'savehist)
88 (defcustom savehist-file
89 (locate-user-emacs-file "history" ".emacs-history")
90 "File name where minibuffer history is saved to and loaded from.
91 The minibuffer history is a series of Lisp expressions loaded
92 automatically when `savehist-mode' is turned on. See `savehist-mode'
93 for more details.
95 If you want your minibuffer history shared between Emacs and XEmacs,
96 customize this value and make sure that `savehist-coding-system' is
97 set to a coding system that exists in both emacsen."
98 :type 'file
99 :group 'savehist)
101 (defcustom savehist-file-modes #o600
102 "Default permissions of the history file.
103 This is decimal, not octal. The default is 384 (0600 in octal).
104 Set to nil to use the default permissions that Emacs uses, typically
105 mandated by umask. The default is a bit more restrictive to protect
106 the user's privacy."
107 :type 'integer
108 :group 'savehist)
110 (defcustom savehist-autosave-interval (* 5 60)
111 "The interval between autosaves of minibuffer history.
112 If set to nil, disables timer-based autosaving."
113 :type '(choice (const :tag "Disabled" nil)
114 (integer :tag "Seconds"))
115 :group 'savehist)
117 (defcustom savehist-mode-hook nil
118 "Hook called when `savehist-mode' is turned on."
119 :type 'hook
120 :group 'savehist)
122 (defcustom savehist-save-hook nil
123 "Hook called by `savehist-save' before saving the variables.
124 You can use this hook to influence choice and content of variables to
125 save."
126 :type 'hook
127 :group 'savehist)
129 ;; This should be capable of representing characters used by Emacs.
130 ;; We prefer UTF-8 over ISO 2022 because it is well-known outside
131 ;; Mule. XEmacs prior to 21.5 had UTF-8 provided by an external
132 ;; package which may not be loaded, which is why we check for version.
133 (defvar savehist-coding-system (if (and (featurep 'xemacs)
134 (<= emacs-major-version 21)
135 (< emacs-minor-version 5))
136 'iso-2022-8 'utf-8-unix)
137 "The coding system savehist uses for saving the minibuffer history.
138 Changing this value while Emacs is running is supported, but considered
139 unwise, unless you know what you are doing.")
141 ;; Internal variables.
143 (defvar savehist-timer nil)
145 (defvar savehist-last-checksum nil)
147 (defvar savehist-minibuffer-history-variables nil
148 "List of minibuffer histories.
149 The contents of this variable is built while Emacs is running, and saved
150 along with minibuffer history. You can change its value off
151 `savehist-save-hook' to influence which variables are saved.")
153 (defconst savehist-no-conversion (if (featurep 'xemacs) 'binary 'no-conversion)
154 "Coding system without any conversion.
155 This is used for calculating an internal checksum. Should be as fast
156 as possible, ideally simply exposing the internal representation of
157 buffer text.")
159 (defvar savehist-loaded nil
160 "Whether the history has already been loaded.
161 This prevents toggling `savehist-mode' from destroying existing
162 minibuffer history.")
164 (when (featurep 'xemacs)
165 ;; Must declare this under XEmacs, which doesn't have built-in
166 ;; minibuffer history truncation.
167 (defvar history-length 100))
169 ;; Functions.
171 ;;;###autoload
172 (define-minor-mode savehist-mode
173 "Toggle saving of minibuffer history (Savehist mode).
174 With a prefix argument ARG, enable Savehist mode if ARG is
175 positive, and disable it otherwise. If called from Lisp, enable
176 the mode if ARG is omitted or nil.
178 When Savehist mode is enabled, minibuffer history is saved
179 periodically and when exiting Emacs. When Savehist mode is
180 enabled for the first time in an Emacs session, it loads the
181 previous minibuffer history from `savehist-file'.
183 This mode should normally be turned on from your Emacs init file.
184 Calling it at any other time replaces your current minibuffer
185 histories, which is probably undesirable."
186 :global t
187 (if (not savehist-mode)
188 (savehist-uninstall)
189 (when (and (not savehist-loaded)
190 (file-exists-p savehist-file))
191 (condition-case errvar
192 (progn
193 ;; Don't set coding-system-for-read -- we rely on the
194 ;; coding cookie to convey that information. That way, if
195 ;; the user changes the value of savehist-coding-system,
196 ;; we can still correctly load the old file.
197 (load savehist-file nil (not (called-interactively-p 'interactive)))
198 (setq savehist-loaded t))
199 (error
200 ;; Don't install the mode if reading failed. Doing so would
201 ;; effectively destroy the user's data at the next save.
202 (setq savehist-mode nil)
203 (savehist-uninstall)
204 (signal (car errvar) (cdr errvar)))))
205 (savehist-install)))
207 (defun savehist-load ()
208 "Load the variables stored in `savehist-file' and turn on `savehist-mode'.
209 If `savehist-file' is in the old format that doesn't record
210 the value of `savehist-minibuffer-history-variables', that
211 value is deducted from the contents of the file."
212 (declare (obsolete savehist-mode "22.1"))
213 (savehist-mode 1)
214 ;; Old versions of savehist distributed with XEmacs didn't save
215 ;; savehist-minibuffer-history-variables. If that variable is nil
216 ;; after loading the file, try to intuit the intended value.
217 (when (null savehist-minibuffer-history-variables)
218 (setq savehist-minibuffer-history-variables
219 (with-temp-buffer
220 (ignore-errors
221 (insert-file-contents savehist-file))
222 (let ((vars ()) form)
223 (while (setq form (condition-case nil
224 (read (current-buffer)) (error nil)))
225 ;; Each form read is of the form (setq VAR VALUE).
226 ;; Collect VAR, i.e. (nth form 1).
227 (push (nth 1 form) vars))
228 vars)))))
230 (defun savehist-install ()
231 "Hook savehist into Emacs.
232 Normally invoked by calling `savehist-mode' to set the minor mode.
233 Installs `savehist-autosave' in `kill-emacs-hook' and on a timer.
234 To undo this, call `savehist-uninstall'."
235 (add-hook 'minibuffer-setup-hook 'savehist-minibuffer-hook)
236 (add-hook 'kill-emacs-hook 'savehist-autosave)
237 ;; Install an invocation of savehist-autosave on a timer. This
238 ;; should not cause noticeable delays for users -- savehist-autosave
239 ;; executes in under 5 ms on my system.
240 (when (and savehist-autosave-interval
241 (null savehist-timer))
242 (setq savehist-timer
243 (if (featurep 'xemacs)
244 (start-itimer
245 "savehist" 'savehist-autosave savehist-autosave-interval
246 savehist-autosave-interval)
247 (run-with-timer savehist-autosave-interval
248 savehist-autosave-interval 'savehist-autosave)))))
250 (defun savehist-uninstall ()
251 "Undo installing savehist.
252 Normally invoked by calling `savehist-mode' to unset the minor mode."
253 (remove-hook 'minibuffer-setup-hook 'savehist-minibuffer-hook)
254 (remove-hook 'kill-emacs-hook 'savehist-autosave)
255 (when savehist-timer
256 (if (featurep 'xemacs)
257 (delete-itimer savehist-timer)
258 (cancel-timer savehist-timer))
259 (setq savehist-timer nil)))
261 ;; From XEmacs?
262 (defvar print-readably)
263 (defvar print-string-length)
265 (defun savehist-save (&optional auto-save)
266 "Save the values of minibuffer history variables.
267 Unbound symbols referenced in `savehist-additional-variables' are ignored.
268 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
269 and don't save the buffer if they are the same."
270 (interactive)
271 (with-temp-buffer
272 (insert
273 (format ";; -*- mode: emacs-lisp; coding: %s -*-\n" savehist-coding-system)
274 ";; Minibuffer history file, automatically generated by `savehist'.\n\n")
275 (run-hooks 'savehist-save-hook)
276 (let ((print-length nil)
277 (print-string-length nil)
278 (print-level nil)
279 (print-readably t)
280 (print-quoted t))
281 ;; During the 24.3 development, read-passwd had a bug which resulted in
282 ;; the passwords being saved by savehist. Trim them, retroactively.
283 ;; This code can be removed after the 24.3 release.
284 (dolist (sym savehist-minibuffer-history-variables)
285 (if (and (symbolp sym) (equal (symbol-name sym) "forget-history"))
286 (setq savehist-minibuffer-history-variables
287 (delq sym savehist-minibuffer-history-variables))))
288 ;; Save the minibuffer histories, along with the value of
289 ;; savehist-minibuffer-history-variables itself.
290 (when savehist-save-minibuffer-history
291 (prin1 `(setq savehist-minibuffer-history-variables
292 ',savehist-minibuffer-history-variables)
293 (current-buffer))
294 (insert ?\n)
295 (dolist (symbol savehist-minibuffer-history-variables)
296 (when (and (boundp symbol)
297 (not (memq symbol savehist-ignored-variables)))
298 (let ((value (savehist-trim-history (symbol-value symbol)))
299 excess-space)
300 (when value ; Don't save empty histories.
301 (insert "(setq ")
302 (prin1 symbol (current-buffer))
303 (insert " '(")
304 ;; We will print an extra space before the first element.
305 ;; Record where that is.
306 (setq excess-space (point))
307 ;; Print elements of VALUE one by one, carefully.
308 (dolist (elt value)
309 (let ((start (point)))
310 (insert " ")
311 ;; Try to print and then to read an element.
312 (condition-case nil
313 (progn
314 (prin1 elt (current-buffer))
315 (save-excursion
316 (goto-char start)
317 (read (current-buffer))))
318 (error
319 ;; If writing or reading gave an error, comment it out.
320 (goto-char start)
321 (insert "\n")
322 (while (not (eobp))
323 (insert ";;; ")
324 (forward-line 1))
325 (insert "\n")))
326 (goto-char (point-max))))
327 ;; Delete the extra space before the first element.
328 (save-excursion
329 (goto-char excess-space)
330 (if (eq (following-char) ?\s)
331 (delete-region (point) (1+ (point)))))
332 (insert "))\n"))))))
333 ;; Save the additional variables.
334 (dolist (symbol savehist-additional-variables)
335 (when (boundp symbol)
336 (let ((value (symbol-value symbol)))
337 (when (savehist-printable value)
338 (prin1 `(setq ,symbol ',value) (current-buffer))
339 (insert ?\n))))))
340 ;; If autosaving, avoid writing if nothing has changed since the
341 ;; last write.
342 (let ((checksum (md5 (current-buffer) nil nil savehist-no-conversion)))
343 (unless (and auto-save (equal checksum savehist-last-checksum))
344 ;; Set file-precious-flag when saving the buffer because we
345 ;; don't want a half-finished write ruining the entire
346 ;; history. Remember that this is run from a timer and from
347 ;; kill-emacs-hook, and also that multiple Emacs instances
348 ;; could write to this file at once.
349 (let ((file-precious-flag t)
350 (coding-system-for-write savehist-coding-system))
351 (write-region (point-min) (point-max) savehist-file nil
352 (unless (called-interactively-p 'interactive) 'quiet)))
353 (when savehist-file-modes
354 (set-file-modes savehist-file savehist-file-modes))
355 (setq savehist-last-checksum checksum)))))
357 (defun savehist-autosave ()
358 "Save the minibuffer history if it has been modified since the last save.
359 Does nothing if `savehist-mode' is off."
360 (when savehist-mode
361 (savehist-save t)))
363 (defun savehist-trim-history (value)
364 "Retain only the first `history-length' items in VALUE.
365 Only used under XEmacs, which doesn't (yet) implement automatic
366 trimming of history lists to `history-length' items."
367 (if (and (featurep 'xemacs)
368 (natnump history-length)
369 (> (length value) history-length))
370 ;; Equivalent to `(subseq value 0 history-length)', but doesn't
371 ;; need cl-extra at run-time.
372 (loop repeat history-length collect (pop value))
373 value))
375 (defun savehist-printable (value)
376 "Return non-nil if VALUE is printable."
377 (cond
378 ;; Quick response for oft-encountered types known to be printable.
379 ((numberp value))
380 ((symbolp value))
381 ;; String without properties
382 ((and (stringp value)
383 (equal-including-properties value (substring-no-properties value))))
385 ;; For others, check explicitly.
386 (with-temp-buffer
387 (condition-case nil
388 (let ((print-readably t) (print-level nil))
389 ;; Print the value into a buffer...
390 (prin1 value (current-buffer))
391 ;; ...and attempt to read it.
392 (read (point-min-marker))
393 ;; The attempt worked: the object is printable.
395 ;; The attempt failed: the object is not printable.
396 (error nil))))))
398 (defun savehist-minibuffer-hook ()
399 (unless (or (eq minibuffer-history-variable t)
400 ;; XEmacs sets minibuffer-history-variable to t to mean "no
401 ;; history is being recorded".
402 (memq minibuffer-history-variable savehist-ignored-variables))
403 (add-to-list 'savehist-minibuffer-history-variables
404 minibuffer-history-variable)))
406 (provide 'savehist)
409 ;;; savehist.el ends here