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