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