Switch to recommended form of GPLv3 permissions notice.
[bpt/emacs.git] / lisp / savehist.el
1 ;;; savehist.el --- Save minibuffer history.
2
3 ;; Copyright (C) 1997, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5 ;; Author: Hrvoje Niksic <hniksic@xemacs.org>
6 ;; Keywords: minibuffer
7 ;; Version: 24
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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/>.
23
24 ;;; Commentary:
25
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'.
32
33 ;; To use savehist, turn on savehist-mode by putting the following in
34 ;; `~/.emacs':
35 ;;
36 ;; (savehist-mode 1)
37 ;;
38 ;; or with customize: `M-x customize-option RET savehist-mode RET'.
39 ;;
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'.
42
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.
46
47 ;;; Code:
48
49 (require 'custom)
50 (eval-when-compile
51 (require 'cl))
52
53 ;; User variables
54
55 (defgroup savehist nil
56 "Save minibuffer history."
57 :version "22.1"
58 :group 'minibuffer)
59
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)
70
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)
77
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.
86
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)
92
93 (defcustom savehist-ignored-variables nil ;; '(command-history)
94 "*List of additional variables not to save."
95 :type '(repeat variable)
96 :group 'savehist)
97
98 (defcustom savehist-file
99 (cond
100 ;; Backward compatibility with previous versions of savehist.
101 ((file-exists-p "~/.emacs-history") "~/.emacs-history")
102 ((and (not (featurep 'xemacs)) (file-directory-p user-emacs-directory))
103 (concat user-emacs-directory "history"))
104 ((and (featurep 'xemacs) (file-directory-p "~/.xemacs/"))
105 "~/.xemacs/history")
106 ;; For users without `~/.emacs.d/' or `~/.xemacs/'.
107 (t "~/.emacs-history"))
108 "*File name where minibuffer history is saved to and loaded from.
109 The minibuffer history is a series of Lisp expressions loaded
110 automatically when `savehist-mode' is turned on. See `savehist-mode'
111 for more details.
112
113 If you want your minibuffer history shared between Emacs and XEmacs,
114 customize this value and make sure that `savehist-coding-system' is
115 set to a coding system that exists in both emacsen."
116 :type 'file
117 :group 'savehist)
118
119 (defcustom savehist-file-modes #o600
120 "*Default permissions of the history file.
121 This is decimal, not octal. The default is 384 (0600 in octal).
122 Set to nil to use the default permissions that Emacs uses, typically
123 mandated by umask. The default is a bit more restrictive to protect
124 the user's privacy."
125 :type 'integer
126 :group 'savehist)
127
128 (defcustom savehist-autosave-interval (* 5 60)
129 "*The interval between autosaves of minibuffer history.
130 If set to nil, disables timer-based autosaving."
131 :type 'integer
132 :group 'savehist)
133
134 (defcustom savehist-mode-hook nil
135 "Hook called when `savehist-mode' is turned on."
136 :type 'hook
137 :group 'savehist)
138
139 (defcustom savehist-save-hook nil
140 "Hook called by `savehist-save' before saving the variables.
141 You can use this hook to influence choice and content of variables to
142 save."
143 :type 'hook
144 :group 'savehist)
145
146 ;; This should be capable of representing characters used by Emacs.
147 ;; We prefer UTF-8 over ISO 2022 because it is well-known outside
148 ;; Mule. XEmacs prior to 21.5 had UTF-8 provided by an external
149 ;; package which may not be loaded, which is why we check for version.
150 (defvar savehist-coding-system (if (and (featurep 'xemacs)
151 (<= emacs-major-version 21)
152 (< emacs-minor-version 5))
153 'iso-2022-8 'utf-8-unix)
154 "The coding system savehist uses for saving the minibuffer history.
155 Changing this value while Emacs is running is supported, but considered
156 unwise, unless you know what you are doing.")
157
158 ;; Internal variables.
159
160 (defvar savehist-timer nil)
161
162 (defvar savehist-last-checksum nil)
163
164 (defvar savehist-minibuffer-history-variables nil
165 "List of minibuffer histories.
166 The contents of this variable is built while Emacs is running, and saved
167 along with minibuffer history. You can change its value off
168 `savehist-save-hook' to influence which variables are saved.")
169
170 (defconst savehist-no-conversion (if (featurep 'xemacs) 'binary 'no-conversion)
171 "Coding system without any conversion.
172 This is used for calculating an internal checksum. Should be as fast
173 as possible, ideally simply exposing the internal representation of
174 buffer text.")
175
176 (defvar savehist-loaded nil
177 "Whether the history has already been loaded.
178 This prevents toggling `savehist-mode' from destroying existing
179 minibuffer history.")
180
181 (when (featurep 'xemacs)
182 ;; Must declare this under XEmacs, which doesn't have built-in
183 ;; minibuffer history truncation.
184 (defvar history-length 100))
185 \f
186 ;; Functions.
187
188 ;;;###autoload
189 (defun savehist-mode (arg)
190 "Toggle savehist-mode.
191 Positive ARG turns on `savehist-mode'. When on, savehist-mode causes
192 minibuffer history to be saved periodically and when exiting Emacs.
193 When turned on for the first time in an Emacs session, it causes the
194 previous minibuffer history to be loaded from `savehist-file'.
195
196 This mode should normally be turned on from your Emacs init file.
197 Calling it at any other time replaces your current minibuffer histories,
198 which is probably undesirable."
199 (interactive "P")
200 (setq savehist-mode
201 (if (null arg)
202 (not savehist-mode)
203 (> (prefix-numeric-value arg) 0)))
204 (if (not savehist-mode)
205 (savehist-uninstall)
206 (when (and (not savehist-loaded)
207 (file-exists-p savehist-file))
208 (condition-case errvar
209 (progn
210 ;; Don't set coding-system-for-read -- we rely on the
211 ;; coding cookie to convey that information. That way, if
212 ;; the user changes the value of savehist-coding-system,
213 ;; we can still correctly load the old file.
214 (load savehist-file nil (not (interactive-p)))
215 (setq savehist-loaded t))
216 (error
217 ;; Don't install the mode if reading failed. Doing so would
218 ;; effectively destroy the user's data at the next save.
219 (setq savehist-mode nil)
220 (savehist-uninstall)
221 (signal (car errvar) (cdr errvar)))))
222 (savehist-install)
223 (run-hooks 'savehist-mode-hook))
224 ;; Return the new setting.
225 savehist-mode)
226 (add-minor-mode 'savehist-mode "")
227
228 (defun savehist-load ()
229 "Load the variables stored in `savehist-file' and turn on `savehist-mode'.
230 If `savehist-file' is in the old format that doesn't record
231 the value of `savehist-minibuffer-history-variables', that
232 value is deducted from the contents of the file."
233 (savehist-mode 1)
234 ;; Old versions of savehist distributed with XEmacs didn't save
235 ;; savehist-minibuffer-history-variables. If that variable is nil
236 ;; after loading the file, try to intuit the intended value.
237 (when (null savehist-minibuffer-history-variables)
238 (setq savehist-minibuffer-history-variables
239 (with-temp-buffer
240 (ignore-errors
241 (insert-file-contents savehist-file))
242 (let ((vars ()) form)
243 (while (setq form (condition-case nil
244 (read (current-buffer)) (error nil)))
245 ;; Each form read is of the form (setq VAR VALUE).
246 ;; Collect VAR, i.e. (nth form 1).
247 (push (nth 1 form) vars))
248 vars)))))
249 (make-obsolete 'savehist-load 'savehist-mode "22.1")
250
251 (defun savehist-install ()
252 "Hook savehist into Emacs.
253 Normally invoked by calling `savehist-mode' to set the minor mode.
254 Installs `savehist-autosave' in `kill-emacs-hook' and on a timer.
255 To undo this, call `savehist-uninstall'."
256 (add-hook 'minibuffer-setup-hook 'savehist-minibuffer-hook)
257 (add-hook 'kill-emacs-hook 'savehist-autosave)
258 ;; Install an invocation of savehist-autosave on a timer. This
259 ;; should not cause noticeable delays for users -- savehist-autosave
260 ;; executes in under 5 ms on my system.
261 (when (and savehist-autosave-interval
262 (null savehist-timer))
263 (setq savehist-timer
264 (if (featurep 'xemacs)
265 (start-itimer
266 "savehist" 'savehist-autosave savehist-autosave-interval
267 savehist-autosave-interval)
268 (run-with-timer savehist-autosave-interval
269 savehist-autosave-interval 'savehist-autosave)))))
270
271 (defun savehist-uninstall ()
272 "Undo installing savehist.
273 Normally invoked by calling `savehist-mode' to unset the minor mode."
274 (remove-hook 'minibuffer-setup-hook 'savehist-minibuffer-hook)
275 (remove-hook 'kill-emacs-hook 'savehist-autosave)
276 (when savehist-timer
277 (if (featurep 'xemacs)
278 (delete-itimer savehist-timer)
279 (cancel-timer savehist-timer))
280 (setq savehist-timer nil)))
281
282 (defun savehist-save (&optional auto-save)
283 "Save the values of minibuffer history variables.
284 Unbound symbols referenced in `savehist-additional-variables' are ignored.
285 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
286 and don't save the buffer if they are the same."
287 (interactive)
288 (with-temp-buffer
289 (insert
290 (format ";; -*- mode: emacs-lisp; coding: %s -*-\n" savehist-coding-system)
291 ";; Minibuffer history file, automatically generated by `savehist'.\n\n")
292 (run-hooks 'savehist-save-hook)
293 (let ((print-length nil)
294 (print-string-length nil)
295 (print-level nil)
296 (print-readably t)
297 (print-quoted t))
298 ;; Save the minibuffer histories, along with the value of
299 ;; savehist-minibuffer-history-variables itself.
300 (when savehist-save-minibuffer-history
301 (prin1 `(setq savehist-minibuffer-history-variables
302 ',savehist-minibuffer-history-variables)
303 (current-buffer))
304 (insert ?\n)
305 (dolist (symbol savehist-minibuffer-history-variables)
306 (when (and (boundp symbol)
307 (not (memq symbol savehist-ignored-variables)))
308 (let ((value (savehist-trim-history (symbol-value symbol)))
309 excess-space)
310 (when value ; Don't save empty histories.
311 (insert "(setq ")
312 (prin1 symbol (current-buffer))
313 (insert " '(")
314 ;; We will print an extra space before the first element.
315 ;; Record where that is.
316 (setq excess-space (point))
317 ;; Print elements of VALUE one by one, carefully.
318 (dolist (elt value)
319 (let ((start (point)))
320 (insert " ")
321 (prin1 elt (current-buffer))
322 ;; Try to read the element we just printed.
323 (condition-case nil
324 (save-excursion
325 (goto-char start)
326 (read (current-buffer)))
327 (error
328 ;; If reading it gets an error, comment it out.
329 (goto-char start)
330 (insert "\n")
331 (while (not (eobp))
332 (insert ";;; ")
333 (forward-line 1))
334 (insert "\n")))
335 (goto-char (point-max))))
336 ;; Delete the extra space before the first element.
337 (save-excursion
338 (goto-char excess-space)
339 (if (eq (following-char) ?\s)
340 (delete-region (point) (1+ (point)))))
341 (insert "))\n"))))))
342 ;; Save the additional variables.
343 (dolist (symbol savehist-additional-variables)
344 (when (boundp symbol)
345 (let ((value (symbol-value symbol)))
346 (when (savehist-printable value)
347 (prin1 `(setq ,symbol ',value) (current-buffer))
348 (insert ?\n))))))
349 ;; If autosaving, avoid writing if nothing has changed since the
350 ;; last write.
351 (let ((checksum (md5 (current-buffer) nil nil savehist-no-conversion)))
352 (unless (and auto-save (equal checksum savehist-last-checksum))
353 ;; Set file-precious-flag when saving the buffer because we
354 ;; don't want a half-finished write ruining the entire
355 ;; history. Remember that this is run from a timer and from
356 ;; kill-emacs-hook, and also that multiple Emacs instances
357 ;; could write to this file at once.
358 (let ((file-precious-flag t)
359 (coding-system-for-write savehist-coding-system))
360 (write-region (point-min) (point-max) savehist-file nil
361 (unless (interactive-p) 'quiet)))
362 (when savehist-file-modes
363 (set-file-modes savehist-file savehist-file-modes))
364 (setq savehist-last-checksum checksum)))))
365
366 (defun savehist-autosave ()
367 "Save the minibuffer history if it has been modified since the last save.
368 Does nothing if `savehist-mode' is off."
369 (when savehist-mode
370 (savehist-save t)))
371
372 (defun savehist-trim-history (value)
373 "Retain only the first `history-length' items in VALUE.
374 Only used under XEmacs, which doesn't (yet) implement automatic
375 trimming of history lists to `history-length' items."
376 (if (and (featurep 'xemacs)
377 (natnump history-length)
378 (> (length value) history-length))
379 ;; Equivalent to `(subseq value 0 history-length)', but doesn't
380 ;; need cl-extra at run-time.
381 (loop repeat history-length collect (pop value))
382 value))
383
384 (defun savehist-printable (value)
385 "Return non-nil if VALUE is printable."
386 (cond
387 ;; Quick response for oft-encountered types known to be printable.
388 ((stringp value))
389 ((numberp value))
390 ((symbolp value))
391 (t
392 ;; For others, check explicitly.
393 (with-temp-buffer
394 (condition-case nil
395 (let ((print-readably t) (print-level nil))
396 ;; Print the value into a buffer...
397 (prin1 value (current-buffer))
398 ;; ...and attempt to read it.
399 (read (point-min-marker))
400 ;; The attempt worked: the object is printable.
401 t)
402 ;; The attempt failed: the object is not printable.
403 (error nil))))))
404
405 (defun savehist-minibuffer-hook ()
406 (unless (or (eq minibuffer-history-variable t)
407 ;; XEmacs sets minibuffer-history-variable to t to mean "no
408 ;; history is being recorded".
409 (memq minibuffer-history-variable savehist-ignored-variables))
410 (add-to-list 'savehist-minibuffer-history-variables
411 minibuffer-history-variable)))
412
413 (provide 'savehist)
414 \f
415 ;; arch-tag: b3ce47f4-c5ad-4ebc-ad02-73aba705cf9f
416
417 ;;; savehist.el ends here