Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / lisp / desktop.el
blob78ecc2f53769bf8f6e9ac89c2edc8a83cff1b502
1 ;;; desktop.el --- save partial status of Emacs when killed -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993-1995, 1997, 2000-2014 Free Software Foundation,
4 ;; Inc.
6 ;; Author: Morten Welinder <terra@diku.dk>
7 ;; Keywords: convenience
8 ;; Favorite-brand-of-beer: None, I hate beer.
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 ;; Save the Desktop, i.e.,
28 ;; - some global variables
29 ;; - the list of buffers with associated files. For each buffer also
30 ;; - the major mode
31 ;; - the default directory
32 ;; - the point
33 ;; - the mark & mark-active
34 ;; - buffer-read-only
35 ;; - some local variables
36 ;; - frame and window configuration
38 ;; To use this, use customize to turn on desktop-save-mode or add the
39 ;; following line somewhere in your init file:
41 ;; (desktop-save-mode 1)
43 ;; For further usage information, look at the section
44 ;; (info "(emacs)Saving Emacs Sessions") in the GNU Emacs Manual.
46 ;; When the desktop module is loaded, the function `desktop-kill' is
47 ;; added to the `kill-emacs-hook'. This function is responsible for
48 ;; saving the desktop when Emacs is killed. Furthermore an anonymous
49 ;; function is added to the `after-init-hook'. This function is
50 ;; responsible for loading the desktop when Emacs is started.
52 ;; Special handling.
53 ;; -----------------
54 ;; Variables `desktop-buffer-mode-handlers' and `desktop-minor-mode-handlers'
55 ;; are supplied to handle special major and minor modes respectively.
56 ;; `desktop-buffer-mode-handlers' is an alist of major mode specific functions
57 ;; to restore a desktop buffer. Elements must have the form
59 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
61 ;; Functions listed are called by `desktop-create-buffer' when `desktop-read'
62 ;; evaluates the desktop file. Buffers with a major mode not specified here,
63 ;; are restored by the default handler `desktop-restore-file-buffer'.
64 ;; `desktop-minor-mode-handlers' is an alist of functions to restore
65 ;; non-standard minor modes. Elements must have the form
67 ;; (MINOR-MODE . RESTORE-FUNCTION).
69 ;; Functions are called by `desktop-create-buffer' to restore minor modes.
70 ;; Minor modes not specified here, are restored by the standard minor mode
71 ;; function. If you write a module that defines a major or minor mode that
72 ;; needs a special handler, then place code like
74 ;; (defun foo-restore-desktop-buffer
75 ;; ...
76 ;; (add-to-list 'desktop-buffer-mode-handlers
77 ;; '(foo-mode . foo-restore-desktop-buffer))
79 ;; or
81 ;; (defun bar-desktop-restore
82 ;; ...
83 ;; (add-to-list 'desktop-minor-mode-handlers
84 ;; '(bar-mode . bar-desktop-restore))
86 ;; in the module itself, and make sure that the mode function is
87 ;; autoloaded. See the docstrings of `desktop-buffer-mode-handlers' and
88 ;; `desktop-minor-mode-handlers' for more info.
90 ;; Minor modes.
91 ;; ------------
92 ;; Conventional minor modes (see node "Minor Mode Conventions" in the elisp
93 ;; manual) are handled in the following way:
94 ;; When `desktop-save' saves the state of a buffer to the desktop file, it
95 ;; saves as `desktop-minor-modes' the list of names of those variables in
96 ;; `minor-mode-alist' that have a non-nil value.
97 ;; When `desktop-create' restores the buffer, each of the symbols in
98 ;; `desktop-minor-modes' is called as function with parameter 1.
99 ;; The variables `desktop-minor-mode-table' and `desktop-minor-mode-handlers'
100 ;; are used to handle non-conventional minor modes. `desktop-save' uses
101 ;; `desktop-minor-mode-table' to map minor mode variables to minor mode
102 ;; functions before writing `desktop-minor-modes'. If a minor mode has a
103 ;; variable name that is different form its function name, an entry
105 ;; (NAME RESTORE-FUNCTION)
107 ;; should be added to `desktop-minor-mode-table'. If a minor mode should not
108 ;; be restored, RESTORE-FUNCTION should be set to nil. `desktop-create' uses
109 ;; `desktop-minor-mode-handlers' to lookup minor modes that needs a restore
110 ;; function different from the usual minor mode function.
111 ;; ---------------------------------------------------------------------------
113 ;; By the way: don't use desktop.el to customize Emacs -- the file .emacs
114 ;; in your home directory is used for that. Saving global default values
115 ;; for buffers is an example of misuse.
117 ;; PLEASE NOTE: The kill ring can be saved as specified by the variable
118 ;; `desktop-globals-to-save' (by default it isn't). This may result in saving
119 ;; things you did not mean to keep. Use M-x desktop-clear RET.
121 ;; Thanks to hetrick@phys.uva.nl (Jim Hetrick) for useful ideas.
122 ;; avk@rtsg.mot.com (Andrew V. Klein) for a dired tip.
123 ;; chris@tecc.co.uk (Chris Boucher) for a mark tip.
124 ;; f89-kam@nada.kth.se (Klas Mellbourn) for a mh-e tip.
125 ;; kifer@sbkifer.cs.sunysb.edu (M. Kifer) for a bug hunt.
126 ;; treese@lcs.mit.edu (Win Treese) for ange-ftp tips.
127 ;; pot@cnuce.cnr.it (Francesco Potortì) for misc. tips.
128 ;; ---------------------------------------------------------------------------
129 ;; TODO:
131 ;; Recognize more minor modes.
132 ;; Save mark rings.
134 ;;; Code:
136 (require 'cl-lib)
137 (require 'frameset)
139 (defvar desktop-file-version "206"
140 "Version number of desktop file format.
141 Written into the desktop file and used at desktop read to provide
142 backward compatibility.")
144 ;; ----------------------------------------------------------------------------
145 ;; USER OPTIONS -- settings you might want to play with.
146 ;; ----------------------------------------------------------------------------
148 (defgroup desktop nil
149 "Save status of Emacs when you exit."
150 :group 'frames)
152 ;; Maintained for backward compatibility
153 (define-obsolete-variable-alias 'desktop-enable 'desktop-save-mode "22.1")
154 ;;;###autoload
155 (define-minor-mode desktop-save-mode
156 "Toggle desktop saving (Desktop Save mode).
157 With a prefix argument ARG, enable Desktop Save mode if ARG is
158 positive, and disable it otherwise. If called from Lisp, enable
159 the mode if ARG is omitted or nil.
161 If Desktop Save mode is enabled, the state of Emacs is saved from
162 one session to another. See variable `desktop-save' and function
163 `desktop-read' for details."
164 :global t
165 :group 'desktop)
167 (defun desktop-save-mode-off ()
168 "Disable `desktop-save-mode'. Provided for use in hooks."
169 (desktop-save-mode 0))
171 (defcustom desktop-save 'ask-if-new
172 "Specifies whether the desktop should be saved when it is killed.
173 A desktop is killed when the user changes desktop or quits Emacs.
174 Possible values are:
175 t -- always save.
176 ask -- always ask.
177 ask-if-new -- ask if no desktop file exists, otherwise just save.
178 ask-if-exists -- ask if desktop file exists, otherwise don't save.
179 if-exists -- save if desktop file exists, otherwise don't save.
180 nil -- never save.
181 The desktop is never saved when `desktop-save-mode' is nil.
182 The variables `desktop-dirname' and `desktop-base-file-name'
183 determine where the desktop is saved."
184 :type
185 '(choice
186 (const :tag "Always save" t)
187 (const :tag "Always ask" ask)
188 (const :tag "Ask if desktop file is new, else do save" ask-if-new)
189 (const :tag "Ask if desktop file exists, else don't save" ask-if-exists)
190 (const :tag "Save if desktop file exists, else don't" if-exists)
191 (const :tag "Never save" nil))
192 :group 'desktop
193 :version "22.1")
195 (defcustom desktop-auto-save-timeout auto-save-timeout
196 "Number of seconds idle time before auto-save of the desktop.
197 Zero or nil means disable auto-saving due to idleness."
198 :type '(choice (const :tag "Off" nil)
199 (integer :tag "Seconds"))
200 :set (lambda (symbol value)
201 (set-default symbol value)
202 (ignore-errors (desktop-auto-save-set-timer)))
203 :group 'desktop
204 :version "24.4")
206 (defcustom desktop-load-locked-desktop 'ask
207 "Specifies whether the desktop should be loaded if locked.
208 Possible values are:
209 t -- load anyway.
210 nil -- don't load.
211 ask -- ask the user.
212 If the value is nil, or `ask' and the user chooses not to load the desktop,
213 the normal hook `desktop-not-loaded-hook' is run."
214 :type
215 '(choice
216 (const :tag "Load anyway" t)
217 (const :tag "Don't load" nil)
218 (const :tag "Ask the user" ask))
219 :group 'desktop
220 :version "22.2")
222 (define-obsolete-variable-alias 'desktop-basefilename
223 'desktop-base-file-name "22.1")
225 (defcustom desktop-base-file-name
226 (convert-standard-filename ".emacs.desktop")
227 "Name of file for Emacs desktop, excluding the directory part."
228 :type 'file
229 :group 'desktop)
231 (defcustom desktop-base-lock-name
232 (convert-standard-filename ".emacs.desktop.lock")
233 "Name of lock file for Emacs desktop, excluding the directory part."
234 :type 'file
235 :group 'desktop
236 :version "22.2")
238 (defcustom desktop-path (list user-emacs-directory "~")
239 "List of directories to search for the desktop file.
240 The base name of the file is specified in `desktop-base-file-name'."
241 :type '(repeat directory)
242 :group 'desktop
243 :version "23.2") ; user-emacs-directory added
245 (defcustom desktop-missing-file-warning nil
246 "If non-nil, offer to recreate the buffer of a deleted file.
247 Also pause for a moment to display message about errors signaled in
248 `desktop-buffer-mode-handlers'.
250 If nil, just print error messages in the message buffer."
251 :type 'boolean
252 :group 'desktop
253 :version "22.1")
255 (defcustom desktop-no-desktop-file-hook nil
256 "Normal hook run when `desktop-read' can't find a desktop file.
257 Run in the directory in which the desktop file was sought.
258 May be used to show a dired buffer."
259 :type 'hook
260 :group 'desktop
261 :version "22.1")
263 (defcustom desktop-not-loaded-hook nil
264 "Normal hook run when the user declines to re-use a desktop file.
265 Run in the directory in which the desktop file was found.
266 May be used to deal with accidental multiple Emacs jobs."
267 :type 'hook
268 :group 'desktop
269 :options '(desktop-save-mode-off save-buffers-kill-emacs)
270 :version "22.2")
272 (defcustom desktop-after-read-hook nil
273 "Normal hook run after a successful `desktop-read'.
274 May be used to show a buffer list."
275 :type 'hook
276 :group 'desktop
277 :options '(list-buffers)
278 :version "22.1")
280 (defcustom desktop-save-hook nil
281 "Normal hook run before the desktop is saved in a desktop file.
282 Run with the desktop buffer current with only the header present.
283 May be used to add to the desktop code or to truncate history lists,
284 for example."
285 :type 'hook
286 :group 'desktop)
288 (defcustom desktop-globals-to-save
289 '(desktop-missing-file-warning
290 tags-file-name
291 tags-table-list
292 search-ring
293 regexp-search-ring
294 register-alist
295 file-name-history)
296 "List of global variables saved by `desktop-save'.
297 An element may be variable name (a symbol) or a cons cell of the form
298 \(VAR . MAX-SIZE), which means to truncate VAR's value to at most
299 MAX-SIZE elements (if the value is a list) before saving the value.
300 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
301 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
302 :group 'desktop)
304 (defcustom desktop-globals-to-clear
305 '(kill-ring
306 kill-ring-yank-pointer
307 search-ring
308 search-ring-yank-pointer
309 regexp-search-ring
310 regexp-search-ring-yank-pointer)
311 "List of global variables that `desktop-clear' will clear.
312 An element may be variable name (a symbol) or a cons cell of the form
313 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
314 to the value obtained by evaluating FORM."
315 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
316 :group 'desktop
317 :version "22.1")
319 (defcustom desktop-clear-preserve-buffers
320 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*"
321 "\\*Warnings\\*")
322 "List of buffers that `desktop-clear' should not delete.
323 Each element is a regular expression. Buffers with a name matched by any of
324 these won't be deleted."
325 :version "23.3" ; added Warnings - bug#6336
326 :type '(repeat string)
327 :group 'desktop)
329 ;;;###autoload
330 (defcustom desktop-locals-to-save
331 '(desktop-locals-to-save ; Itself! Think it over.
332 truncate-lines
333 case-fold-search
334 case-replace
335 fill-column
336 overwrite-mode
337 change-log-default-name
338 line-number-mode
339 column-number-mode
340 size-indication-mode
341 buffer-file-coding-system
342 indent-tabs-mode
343 tab-width
344 indicate-buffer-boundaries
345 indicate-empty-lines
346 show-trailing-whitespace)
347 "List of local variables to save for each buffer.
348 The variables are saved only when they really are local. Conventional minor
349 modes are restored automatically; they should not be listed here."
350 :type '(repeat symbol)
351 :group 'desktop)
353 (defcustom desktop-buffers-not-to-save nil
354 "Regexp identifying buffers that are to be excluded from saving."
355 :type '(choice (const :tag "None" nil)
356 regexp)
357 :version "23.2" ; set to nil
358 :group 'desktop)
360 ;; Skip tramp and ange-ftp files
361 (defcustom desktop-files-not-to-save
362 "\\(^/[^/:]*:\\|(ftp)$\\)"
363 "Regexp identifying files whose buffers are to be excluded from saving."
364 :type '(choice (const :tag "None" nil)
365 regexp)
366 :group 'desktop)
368 ;; We skip TAGS files to save time (tags-file-name is saved instead).
369 (defcustom desktop-modes-not-to-save
370 '(tags-table-mode)
371 "List of major modes whose buffers should not be saved."
372 :type '(repeat symbol)
373 :group 'desktop)
375 (defcustom desktop-restore-frames t
376 "When non-nil, save frames to desktop file."
377 :type 'boolean
378 :group 'desktop
379 :version "24.4")
381 (defcustom desktop-restore-in-current-display nil
382 "If t, frames are restored in the current display.
383 If nil, frames are restored, if possible, in their original displays.
384 If `delete', frames on other displays are deleted instead of restored."
385 :type '(choice (const :tag "Restore in current display" t)
386 (const :tag "Restore in original display" nil)
387 (const :tag "Delete frames in other displays" delete))
388 :group 'desktop
389 :version "24.4")
391 (defcustom desktop-restore-forces-onscreen t
392 "If t, offscreen frames are restored onscreen instead.
393 If `:all', frames that are partially offscreen are also forced onscreen.
394 NOTE: Checking of frame boundaries is only approximate and can fail
395 to reliably detect frames whose onscreen/offscreen state depends on a
396 few pixels, especially near the right / bottom borders of the screen."
397 :type '(choice (const :tag "Only fully offscreen frames" t)
398 (const :tag "Also partially offscreen frames" :all)
399 (const :tag "Do not force frames onscreen" nil))
400 :group 'desktop
401 :version "24.4")
403 (defcustom desktop-restore-reuses-frames t
404 "If t, restoring frames reuses existing frames.
405 If nil, existing frames are deleted.
406 If `:keep', existing frames are kept and not reused."
407 :type '(choice (const :tag "Reuse existing frames" t)
408 (const :tag "Delete existing frames" nil)
409 (const :tag "Keep existing frames" :keep))
410 :group 'desktop
411 :version "24.4")
413 (defcustom desktop-file-name-format 'absolute
414 "Format in which desktop file names should be saved.
415 Possible values are:
416 absolute -- Absolute file name.
417 tilde -- Relative to ~.
418 local -- Relative to directory of desktop file."
419 :type '(choice (const absolute) (const tilde) (const local))
420 :group 'desktop
421 :version "22.1")
423 (defcustom desktop-restore-eager t
424 "Number of buffers to restore immediately.
425 Remaining buffers are restored lazily (when Emacs is idle).
426 If value is t, all buffers are restored immediately."
427 :type '(choice (const t) integer)
428 :group 'desktop
429 :version "22.1")
431 (defcustom desktop-lazy-verbose t
432 "Verbose reporting of lazily created buffers."
433 :type 'boolean
434 :group 'desktop
435 :version "22.1")
437 (defcustom desktop-lazy-idle-delay 5
438 "Idle delay before starting to create buffers.
439 See `desktop-restore-eager'."
440 :type 'integer
441 :group 'desktop
442 :version "22.1")
444 ;;;###autoload
445 (defvar-local desktop-save-buffer nil
446 "When non-nil, save buffer status in desktop file.
448 If the value is a function, it is called by `desktop-save' with argument
449 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
450 file along with the state of the buffer for which it was called.
452 When file names are returned, they should be formatted using the call
453 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
455 Later, when `desktop-read' evaluates the desktop file, auxiliary information
456 is passed as the argument DESKTOP-BUFFER-MISC to functions in
457 `desktop-buffer-mode-handlers'.")
458 (make-obsolete-variable 'desktop-buffer-modes-to-save
459 'desktop-save-buffer "22.1")
460 (make-obsolete-variable 'desktop-buffer-misc-functions
461 'desktop-save-buffer "22.1")
463 ;;;###autoload
464 (defvar desktop-buffer-mode-handlers nil
465 "Alist of major mode specific functions to restore a desktop buffer.
466 Functions listed are called by `desktop-create-buffer' when `desktop-read'
467 evaluates the desktop file. List elements must have the form
469 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
471 Buffers with a major mode not specified here, are restored by the default
472 handler `desktop-restore-file-buffer'.
474 Handlers are called with argument list
476 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
478 Furthermore, they may use the following variables:
480 desktop-file-version
481 desktop-buffer-major-mode
482 desktop-buffer-minor-modes
483 desktop-buffer-point
484 desktop-buffer-mark
485 desktop-buffer-read-only
486 desktop-buffer-locals
488 If a handler returns a buffer, then the saved mode settings
489 and variable values for that buffer are copied into it.
491 Modules that define a major mode that needs a special handler should contain
492 code like
494 (defun foo-restore-desktop-buffer
496 (add-to-list 'desktop-buffer-mode-handlers
497 '(foo-mode . foo-restore-desktop-buffer))
499 Furthermore the major mode function must be autoloaded.")
501 ;;;###autoload
502 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
503 (make-obsolete-variable 'desktop-buffer-handlers
504 'desktop-buffer-mode-handlers "22.1")
506 (defcustom desktop-minor-mode-table
507 '((auto-fill-function auto-fill-mode)
508 (vc-mode nil)
509 (vc-dired-mode nil)
510 (erc-track-minor-mode nil)
511 (savehist-mode nil))
512 "Table mapping minor mode variables to minor mode functions.
513 Each entry has the form (NAME RESTORE-FUNCTION).
514 NAME is the name of the buffer-local variable indicating that the minor
515 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
516 RESTORE-FUNCTION nil means don't try to restore the minor mode.
517 Only minor modes for which the name of the buffer-local variable
518 and the name of the minor mode function are different have to be added to
519 this table. See also `desktop-minor-mode-handlers'."
520 :type 'sexp
521 :group 'desktop)
523 ;;;###autoload
524 (defvar desktop-minor-mode-handlers nil
525 "Alist of functions to restore non-standard minor modes.
526 Functions are called by `desktop-create-buffer' to restore minor modes.
527 List elements must have the form
529 (MINOR-MODE . RESTORE-FUNCTION).
531 Minor modes not specified here, are restored by the standard minor mode
532 function.
534 Handlers are called with argument list
536 (DESKTOP-BUFFER-LOCALS)
538 Furthermore, they may use the following variables:
540 desktop-file-version
541 desktop-buffer-file-name
542 desktop-buffer-name
543 desktop-buffer-major-mode
544 desktop-buffer-minor-modes
545 desktop-buffer-point
546 desktop-buffer-mark
547 desktop-buffer-read-only
548 desktop-buffer-misc
550 When a handler is called, the buffer has been created and the major mode has
551 been set, but local variables listed in desktop-buffer-locals has not yet been
552 created and set.
554 Modules that define a minor mode that needs a special handler should contain
555 code like
557 (defun foo-desktop-restore
559 (add-to-list 'desktop-minor-mode-handlers
560 '(foo-mode . foo-desktop-restore))
562 Furthermore the minor mode function must be autoloaded.
564 See also `desktop-minor-mode-table'.")
566 ;;;###autoload
567 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
569 ;; ----------------------------------------------------------------------------
570 (defvar desktop-dirname nil
571 "The directory in which the desktop file should be saved.")
573 (defun desktop-full-file-name (&optional dirname)
574 "Return the full name of the desktop file in DIRNAME.
575 DIRNAME omitted or nil means use `desktop-dirname'."
576 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
578 (defun desktop-full-lock-name (&optional dirname)
579 "Return the full name of the desktop lock file in DIRNAME.
580 DIRNAME omitted or nil means use `desktop-dirname'."
581 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
583 (defconst desktop-header
584 ";; --------------------------------------------------------------------------
585 ;; Desktop File for Emacs
586 ;; --------------------------------------------------------------------------
587 " "*Header to place in Desktop file.")
589 (defvar desktop-delay-hook nil
590 "Hooks run after all buffers are loaded; intended for internal use.")
592 (defvar desktop-file-checksum nil
593 "Checksum of the last auto-saved contents of the desktop file.
594 Used to avoid writing contents unchanged between auto-saves.")
596 (defvar desktop-saved-frameset nil
597 "Saved state of all frames.
598 Only valid during frame saving & restoring; intended for internal use.")
600 ;; ----------------------------------------------------------------------------
601 ;; Desktop file conflict detection
602 (defvar desktop-file-modtime nil
603 "When the desktop file was last modified to the knowledge of this Emacs.
604 Used to detect desktop file conflicts.")
606 (defun desktop-owner (&optional dirname)
607 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
608 Return nil if no desktop file found or no Emacs process is using it.
609 DIRNAME omitted or nil means use `desktop-dirname'."
610 (let (owner
611 (file (desktop-full-lock-name dirname)))
612 (and (file-exists-p file)
613 (ignore-errors
614 (with-temp-buffer
615 (insert-file-contents-literally file)
616 (goto-char (point-min))
617 (setq owner (read (current-buffer)))
618 (integerp owner)))
619 owner)))
621 (defun desktop-claim-lock (&optional dirname)
622 "Record this Emacs process as the owner of the desktop file in DIRNAME.
623 DIRNAME omitted or nil means use `desktop-dirname'."
624 (write-region (number-to-string (emacs-pid)) nil
625 (desktop-full-lock-name dirname)))
627 (defun desktop-release-lock (&optional dirname)
628 "Remove the lock file for the desktop in DIRNAME.
629 DIRNAME omitted or nil means use `desktop-dirname'."
630 (let ((file (desktop-full-lock-name dirname)))
631 (when (file-exists-p file) (delete-file file))))
633 ;; ----------------------------------------------------------------------------
634 (defun desktop-truncate (list n)
635 "Truncate LIST to at most N elements destructively."
636 (let ((here (nthcdr (1- n) list)))
637 (when (consp here)
638 (setcdr here nil))))
640 ;; ----------------------------------------------------------------------------
641 ;;;###autoload
642 (defun desktop-clear ()
643 "Empty the Desktop.
644 This kills all buffers except for internal ones and those with names matched by
645 a regular expression in the list `desktop-clear-preserve-buffers'.
646 Furthermore, it clears the variables listed in `desktop-globals-to-clear'.
647 When called interactively and `desktop-restore-frames' is non-nil, it also
648 deletes all frames except the selected one (and its minibuffer frame,
649 if different)."
650 (interactive)
651 (desktop-lazy-abort)
652 (dolist (var desktop-globals-to-clear)
653 (if (symbolp var)
654 (eval `(setq-default ,var nil))
655 (eval `(setq-default ,(car var) ,(cdr var)))))
656 (let ((preserve-regexp (concat "^\\("
657 (mapconcat (lambda (regexp)
658 (concat "\\(" regexp "\\)"))
659 desktop-clear-preserve-buffers
660 "\\|")
661 "\\)$")))
662 (dolist (buffer (buffer-list))
663 (let ((bufname (buffer-name buffer)))
664 (unless (or (eq (aref bufname 0) ?\s) ;; Don't kill internal buffers
665 (string-match-p preserve-regexp bufname))
666 (kill-buffer buffer)))))
667 (delete-other-windows)
668 (when (and desktop-restore-frames
669 ;; Non-interactive calls to desktop-clear happen before desktop-read
670 ;; which already takes care of frame restoration and deletion.
671 (called-interactively-p 'any))
672 (let* ((this (selected-frame))
673 (mini (window-frame (minibuffer-window this)))) ; in case they differ
674 (dolist (frame (sort (frame-list) #'frameset-minibufferless-first-p))
675 (condition-case err
676 (unless (or (eq frame this)
677 (eq frame mini)
678 (frame-parameter frame 'desktop-dont-clear))
679 (delete-frame frame))
680 (error
681 (delay-warning 'desktop (error-message-string err))))))))
683 ;; ----------------------------------------------------------------------------
684 (unless noninteractive
685 (add-hook 'kill-emacs-hook 'desktop-kill))
687 (defun desktop-kill ()
688 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
689 If the desktop should be saved and `desktop-dirname'
690 is nil, ask the user where to save the desktop."
691 (when (and desktop-save-mode
692 (let ((exists (file-exists-p (desktop-full-file-name))))
693 (or (eq desktop-save t)
694 (and exists (eq desktop-save 'if-exists))
695 ;; If it exists, but we aren't using it, we are going
696 ;; to ask for a new directory below.
697 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
698 (and
699 (or (memq desktop-save '(ask ask-if-new))
700 (and exists (eq desktop-save 'ask-if-exists)))
701 (y-or-n-p "Save desktop? ")))))
702 (unless desktop-dirname
703 (setq desktop-dirname
704 (file-name-as-directory
705 (expand-file-name
706 (read-directory-name "Directory for desktop file: " nil nil t)))))
707 (condition-case err
708 (desktop-save desktop-dirname t)
709 (file-error
710 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
711 (signal (car err) (cdr err))))))
712 ;; If we own it, we don't anymore.
713 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
715 ;; ----------------------------------------------------------------------------
716 (defun desktop-list* (&rest args)
717 (and args (apply #'cl-list* args)))
719 ;; ----------------------------------------------------------------------------
720 (defun desktop-buffer-info (buffer)
721 (set-buffer buffer)
722 (list
723 ;; base name of the buffer; replaces the buffer name if managed by uniquify
724 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
725 ;; basic information
726 (desktop-file-name (buffer-file-name) desktop-dirname)
727 (buffer-name)
728 major-mode
729 ;; minor modes
730 (let (ret)
731 (mapc
732 #'(lambda (minor-mode)
733 (and (boundp minor-mode)
734 (symbol-value minor-mode)
735 (let* ((special (assq minor-mode desktop-minor-mode-table))
736 (value (cond (special (cadr special))
737 ((functionp minor-mode) minor-mode))))
738 (when value (add-to-list 'ret value)))))
739 (mapcar #'car minor-mode-alist))
740 ret)
741 ;; point and mark, and read-only status
742 (point)
743 (list (mark t) mark-active)
744 buffer-read-only
745 ;; auxiliary information
746 (when (functionp desktop-save-buffer)
747 (funcall desktop-save-buffer desktop-dirname))
748 ;; local variables
749 (let ((loclist (buffer-local-variables))
750 (ll nil))
751 (dolist (local desktop-locals-to-save)
752 (let ((here (assq local loclist)))
753 (cond (here
754 (push here ll))
755 ((member local loclist)
756 (push local ll)))))
757 ll)))
759 ;; ----------------------------------------------------------------------------
760 (defun desktop--v2s (value)
761 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
762 SEXP is an sexp that when evaluated yields VALUE.
763 QUOTE may be `may' (value may be quoted),
764 `must' (value must be quoted), or nil (value must not be quoted)."
765 (cond
766 ((or (numberp value) (null value) (eq t value) (keywordp value))
767 (cons 'may value))
768 ((stringp value)
769 (let ((copy (copy-sequence value)))
770 (set-text-properties 0 (length copy) nil copy)
771 ;; Get rid of text properties because we cannot read them.
772 (cons 'may copy)))
773 ((symbolp value)
774 (cons 'must value))
775 ((vectorp value)
776 (let* ((pass1 (mapcar #'desktop--v2s value))
777 (special (assq nil pass1)))
778 (if special
779 (cons nil `(vector
780 ,@(mapcar (lambda (el)
781 (if (eq (car el) 'must)
782 `',(cdr el) (cdr el)))
783 pass1)))
784 (cons 'may `[,@(mapcar #'cdr pass1)]))))
785 ((consp value)
786 (let ((p value)
787 newlist
788 use-list*)
789 (while (consp p)
790 (let ((q.sexp (desktop--v2s (car p))))
791 (push q.sexp newlist))
792 (setq p (cdr p)))
793 (when p
794 (let ((last (desktop--v2s p)))
795 (setq use-list* t)
796 (push last newlist)))
797 (if (assq nil newlist)
798 (cons nil
799 `(,(if use-list* 'desktop-list* 'list)
800 ,@(mapcar (lambda (el)
801 (if (eq (car el) 'must)
802 `',(cdr el) (cdr el)))
803 (nreverse newlist))))
804 (cons 'must
805 `(,@(mapcar #'cdr
806 (nreverse (if use-list* (cdr newlist) newlist)))
807 ,@(if use-list* (cdar newlist)))))))
808 ((subrp value)
809 (cons nil `(symbol-function
810 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
811 ((markerp value)
812 (let ((pos (marker-position value))
813 (buf (buffer-name (marker-buffer value))))
814 (cons nil
815 `(let ((mk (make-marker)))
816 (add-hook 'desktop-delay-hook
817 `(lambda ()
818 (set-marker ,mk ,,pos (get-buffer ,,buf))))
819 mk))))
820 (t ; Save as text.
821 (cons 'may "Unprintable entity"))))
823 ;; ----------------------------------------------------------------------------
824 (defun desktop-value-to-string (value)
825 "Convert VALUE to a string that when read evaluates to the same value.
826 Not all types of values are supported."
827 (let* ((print-escape-newlines t)
828 (float-output-format nil)
829 (quote.sexp (desktop--v2s value))
830 (quote (car quote.sexp))
831 (txt
832 (let ((print-quoted t))
833 (prin1-to-string (cdr quote.sexp)))))
834 (if (eq quote 'must)
835 (concat "'" txt)
836 txt)))
838 ;; ----------------------------------------------------------------------------
839 (defun desktop-outvar (varspec)
840 "Output a setq statement for variable VAR to the desktop file.
841 The argument VARSPEC may be the variable name VAR (a symbol),
842 or a cons cell of the form (VAR . MAX-SIZE),
843 which means to truncate VAR's value to at most MAX-SIZE elements
844 \(if the value is a list) before saving the value."
845 (let (var size)
846 (if (consp varspec)
847 (setq var (car varspec) size (cdr varspec))
848 (setq var varspec))
849 (when (boundp var)
850 (when (and (integerp size)
851 (> size 0)
852 (listp (eval var)))
853 (desktop-truncate (eval var) size))
854 (insert "(setq "
855 (symbol-name var)
857 (desktop-value-to-string (symbol-value var))
858 ")\n"))))
860 ;; ----------------------------------------------------------------------------
861 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
862 "Return t if buffer should have its state saved in the desktop file.
863 FILENAME is the visited file name, BUFNAME is the buffer name, and
864 MODE is the major mode.
865 \n\(fn FILENAME BUFNAME MODE)"
866 (let ((case-fold-search nil)
867 dired-skip)
868 (and (not (and (stringp desktop-buffers-not-to-save)
869 (not filename)
870 (string-match-p desktop-buffers-not-to-save bufname)))
871 (not (memq mode desktop-modes-not-to-save))
872 ;; FIXME this is broken if desktop-files-not-to-save is nil.
873 (or (and filename
874 (stringp desktop-files-not-to-save)
875 (not (string-match-p desktop-files-not-to-save filename)))
876 (and (memq mode '(dired-mode vc-dir-mode))
877 (with-current-buffer bufname
878 (not (setq dired-skip
879 (string-match-p desktop-files-not-to-save
880 default-directory)))))
881 (and (null filename)
882 (null dired-skip) ; bug#5755
883 (with-current-buffer bufname desktop-save-buffer))))))
885 ;; ----------------------------------------------------------------------------
886 (defun desktop-file-name (filename dirname)
887 "Convert FILENAME to format specified in `desktop-file-name-format'.
888 DIRNAME must be the directory in which the desktop file will be saved."
889 (cond
890 ((not filename) nil)
891 ((eq desktop-file-name-format 'tilde)
892 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
893 (cond
894 ((file-name-absolute-p relative-name) relative-name)
895 ((string= "./" relative-name) "~/")
896 ((string= "." relative-name) "~")
897 (t (concat "~/" relative-name)))))
898 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
899 (t (expand-file-name filename))))
902 ;; ----------------------------------------------------------------------------
903 (defun desktop--check-dont-save (frame)
904 (not (frame-parameter frame 'desktop-dont-save)))
906 (defconst desktop--app-id `(desktop . ,desktop-file-version))
908 (defun desktop-save-frameset ()
909 "Save the state of existing frames in `desktop-saved-frameset'.
910 Frames with a non-nil `desktop-dont-save' parameter are not saved."
911 (setq desktop-saved-frameset
912 (and desktop-restore-frames
913 (frameset-save nil
914 :app desktop--app-id
915 :name (concat user-login-name "@" system-name)
916 :predicate #'desktop--check-dont-save))))
918 ;;;###autoload
919 (defun desktop-save (dirname &optional release auto-save)
920 "Save the desktop in a desktop file.
921 Parameter DIRNAME specifies where to save the desktop file.
922 Optional parameter RELEASE says whether we're done with this desktop.
923 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
924 and don't save the buffer if they are the same."
925 (interactive (list
926 ;; Or should we just use (car desktop-path)?
927 (let ((default (if (member "." desktop-path)
928 default-directory
929 user-emacs-directory)))
930 (read-directory-name "Directory to save desktop file in: "
931 default default t))))
932 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
933 (save-excursion
934 (let ((eager desktop-restore-eager)
935 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
936 (when
937 (or (not new-modtime) ; nothing to overwrite
938 (equal desktop-file-modtime new-modtime)
939 (yes-or-no-p (if desktop-file-modtime
940 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
941 "Desktop file is more recent than the one loaded. Save anyway? "
942 "Desktop file isn't the one loaded. Overwrite it? ")
943 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
944 (unless release (error "Desktop file conflict")))
946 ;; If we're done with it, release the lock.
947 ;; Otherwise, claim it if it's unclaimed or if we created it.
948 (if release
949 (desktop-release-lock)
950 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
952 (with-temp-buffer
953 (insert
954 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
955 desktop-header
956 ";; Created " (current-time-string) "\n"
957 ";; Desktop file format version " desktop-file-version "\n"
958 ";; Emacs version " emacs-version "\n")
959 (save-excursion (run-hooks 'desktop-save-hook))
960 (goto-char (point-max))
961 (insert "\n;; Global section:\n")
962 ;; Called here because we save the window/frame state as a global
963 ;; variable for compatibility with previous Emacsen.
964 (desktop-save-frameset)
965 (unless (memq 'desktop-saved-frameset desktop-globals-to-save)
966 (desktop-outvar 'desktop-saved-frameset))
967 (mapc (function desktop-outvar) desktop-globals-to-save)
968 (setq desktop-saved-frameset nil) ; after saving desktop-globals-to-save
969 (when (memq 'kill-ring desktop-globals-to-save)
970 (insert
971 "(setq kill-ring-yank-pointer (nthcdr "
972 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
973 " kill-ring))\n"))
975 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
976 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
977 (let ((base (pop l)))
978 (when (apply 'desktop-save-buffer-p l)
979 (insert "("
980 (if (or (not (integerp eager))
981 (if (zerop eager)
983 (setq eager (1- eager))))
984 "desktop-create-buffer"
985 "desktop-append-buffer-args")
987 desktop-file-version)
988 ;; If there's a non-empty base name, we save it instead of the buffer name
989 (when (and base (not (string= base "")))
990 (setcar (nthcdr 1 l) base))
991 (dolist (e l)
992 (insert "\n " (desktop-value-to-string e)))
993 (insert ")\n\n"))))
995 (setq default-directory desktop-dirname)
996 ;; When auto-saving, avoid writing if nothing has changed since the last write.
997 (let* ((beg (and auto-save
998 (save-excursion
999 (goto-char (point-min))
1000 ;; Don't check the header with changing timestamp
1001 (and (search-forward "Global section" nil t)
1002 ;; Also skip the timestamp in desktop-saved-frameset
1003 ;; if it's saved in the first non-header line
1004 (search-forward "desktop-saved-frameset"
1005 (line-beginning-position 3) t)
1006 ;; This is saved after the timestamp
1007 (search-forward (format "%S" desktop--app-id) nil t))
1008 (point))))
1009 (checksum (and beg (md5 (current-buffer) beg (point-max) 'emacs-mule))))
1010 (unless (and checksum (equal checksum desktop-file-checksum))
1011 (let ((coding-system-for-write 'emacs-mule))
1012 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1013 (setq desktop-file-checksum checksum)
1014 ;; We remember when it was modified (which is presumably just now).
1015 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
1017 ;; ----------------------------------------------------------------------------
1018 ;;;###autoload
1019 (defun desktop-remove ()
1020 "Delete desktop file in `desktop-dirname'.
1021 This function also sets `desktop-dirname' to nil."
1022 (interactive)
1023 (when desktop-dirname
1024 (let ((filename (desktop-full-file-name)))
1025 (setq desktop-dirname nil)
1026 (when (file-exists-p filename)
1027 (delete-file filename)))))
1029 (defvar desktop-buffer-args-list nil
1030 "List of args for `desktop-create-buffer'.")
1032 (defvar desktop-lazy-timer nil)
1034 ;; ----------------------------------------------------------------------------
1035 (defun desktop-restoring-frameset-p ()
1036 "True if calling `desktop-restore-frameset' will actually restore it."
1037 (and desktop-restore-frames desktop-saved-frameset t))
1039 (defun desktop-restore-frameset ()
1040 "Restore the state of a set of frames.
1041 This function depends on the value of `desktop-saved-frameset'
1042 being set (usually, by reading it from the desktop)."
1043 (when (desktop-restoring-frameset-p)
1044 (frameset-restore desktop-saved-frameset
1045 :reuse-frames desktop-restore-reuses-frames
1046 :force-display desktop-restore-in-current-display
1047 :force-onscreen desktop-restore-forces-onscreen)))
1049 ;; Just to silence the byte compiler.
1050 ;; Dynamically bound in `desktop-read'.
1051 (defvar desktop-first-buffer)
1052 (defvar desktop-buffer-ok-count)
1053 (defvar desktop-buffer-fail-count)
1055 ;;;###autoload
1056 (defun desktop-read (&optional dirname)
1057 "Read and process the desktop file in directory DIRNAME.
1058 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1059 directories listed in `desktop-path'. If a desktop file is found, it
1060 is processed and `desktop-after-read-hook' is run. If no desktop file
1061 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1062 This function is a no-op when Emacs is running in batch mode.
1063 It returns t if a desktop file was loaded, nil otherwise."
1064 (interactive)
1065 (unless noninteractive
1066 (setq desktop-dirname
1067 (file-name-as-directory
1068 (expand-file-name
1070 ;; If DIRNAME is specified, use it.
1071 (and (< 0 (length dirname)) dirname)
1072 ;; Otherwise search desktop file in desktop-path.
1073 (let ((dirs desktop-path))
1074 (while (and dirs
1075 (not (file-exists-p
1076 (desktop-full-file-name (car dirs)))))
1077 (setq dirs (cdr dirs)))
1078 (and dirs (car dirs)))
1079 ;; If not found and `desktop-path' is non-nil, use its first element.
1080 (and desktop-path (car desktop-path))
1081 ;; Default: .emacs.d.
1082 user-emacs-directory))))
1083 (if (file-exists-p (desktop-full-file-name))
1084 ;; Desktop file found, but is it already in use?
1085 (let ((desktop-first-buffer nil)
1086 (desktop-buffer-ok-count 0)
1087 (desktop-buffer-fail-count 0)
1088 (owner (desktop-owner))
1089 ;; Avoid desktop saving during evaluation of desktop buffer.
1090 (desktop-save nil))
1091 (if (and owner
1092 (memq desktop-load-locked-desktop '(nil ask))
1093 (or (null desktop-load-locked-desktop)
1094 (daemonp)
1095 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1096 Using it may cause conflicts. Use it anyway? " owner)))))
1097 (let ((default-directory desktop-dirname))
1098 (setq desktop-dirname nil)
1099 (run-hooks 'desktop-not-loaded-hook)
1100 (unless desktop-dirname
1101 (message "Desktop file in use; not loaded.")))
1102 (desktop-lazy-abort)
1103 ;; Evaluate desktop buffer and remember when it was modified.
1104 (load (desktop-full-file-name) t t t)
1105 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1106 ;; If it wasn't already, mark it as in-use, to bother other
1107 ;; desktop instances.
1108 (unless owner
1109 (condition-case nil
1110 (desktop-claim-lock)
1111 (file-error (message "Couldn't record use of desktop file")
1112 (sit-for 1))))
1114 (unless (desktop-restoring-frameset-p)
1115 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1116 ;; We want buffers existing prior to evaluating the desktop (and
1117 ;; not reused) to be placed at the end of the buffer list, so we
1118 ;; move them here.
1119 (mapc 'bury-buffer
1120 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1121 (switch-to-buffer (car (buffer-list))))
1122 (run-hooks 'desktop-delay-hook)
1123 (setq desktop-delay-hook nil)
1124 (desktop-restore-frameset)
1125 (run-hooks 'desktop-after-read-hook)
1126 (message "Desktop: %s%d buffer%s restored%s%s."
1127 (if desktop-saved-frameset
1128 (let ((fn (length (frameset-states desktop-saved-frameset))))
1129 (format "%d frame%s, "
1130 fn (if (= fn 1) "" "s")))
1132 desktop-buffer-ok-count
1133 (if (= 1 desktop-buffer-ok-count) "" "s")
1134 (if (< 0 desktop-buffer-fail-count)
1135 (format ", %d failed to restore" desktop-buffer-fail-count)
1137 (if desktop-buffer-args-list
1138 (format ", %d to restore lazily"
1139 (length desktop-buffer-args-list))
1140 ""))
1141 (unless (desktop-restoring-frameset-p)
1142 ;; Bury the *Messages* buffer to not reshow it when burying
1143 ;; the buffer we switched to above.
1144 (when (buffer-live-p (get-buffer "*Messages*"))
1145 (bury-buffer "*Messages*"))
1146 ;; Clear all windows' previous and next buffers, these have
1147 ;; been corrupted by the `switch-to-buffer' calls in
1148 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1149 ;; brute force fix and should be replaced by a more subtle
1150 ;; strategy eventually.
1151 (walk-window-tree (lambda (window)
1152 (set-window-prev-buffers window nil)
1153 (set-window-next-buffers window nil))))
1154 (setq desktop-saved-frameset nil)
1156 ;; No desktop file found.
1157 (desktop-clear)
1158 (let ((default-directory desktop-dirname))
1159 (run-hooks 'desktop-no-desktop-file-hook))
1160 (message "No desktop file.")
1161 nil)))
1163 ;; ----------------------------------------------------------------------------
1164 ;; Maintained for backward compatibility
1165 ;;;###autoload
1166 (defun desktop-load-default ()
1167 "Load the `default' start-up library manually.
1168 Also inhibit further loading of it."
1169 (declare (obsolete desktop-save-mode "22.1"))
1170 (unless inhibit-default-init ; safety check
1171 (load "default" t t)
1172 (setq inhibit-default-init t)))
1174 ;; ----------------------------------------------------------------------------
1175 ;;;###autoload
1176 (defun desktop-change-dir (dirname)
1177 "Change to desktop saved in DIRNAME.
1178 Kill the desktop as specified by variables `desktop-save-mode' and
1179 `desktop-save', then clear the desktop and load the desktop file in
1180 directory DIRNAME."
1181 (interactive "DChange to directory: ")
1182 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1183 (desktop-kill)
1184 (desktop-clear)
1185 (desktop-read dirname))
1187 ;; ----------------------------------------------------------------------------
1188 ;;;###autoload
1189 (defun desktop-save-in-desktop-dir ()
1190 "Save the desktop in directory `desktop-dirname'."
1191 (interactive)
1192 (if desktop-dirname
1193 (desktop-save desktop-dirname)
1194 (call-interactively 'desktop-save))
1195 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1197 ;; ----------------------------------------------------------------------------
1198 ;; Auto-Saving.
1199 (defvar desktop-auto-save-timer nil)
1201 (defun desktop-auto-save ()
1202 "Save the desktop periodically.
1203 Called by the timer created in `desktop-auto-save-set-timer'."
1204 (when (and desktop-save-mode
1205 (integerp desktop-auto-save-timeout)
1206 (> desktop-auto-save-timeout 0)
1207 ;; Avoid desktop saving during lazy loading.
1208 (not desktop-lazy-timer)
1209 ;; Save only to own desktop file.
1210 (eq (emacs-pid) (desktop-owner))
1211 desktop-dirname)
1212 (desktop-save desktop-dirname nil t)))
1214 (defun desktop-auto-save-set-timer ()
1215 "Set the auto-save timer.
1216 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1217 integer, start a new idle timer to call `desktop-auto-save' repeatedly
1218 after that many seconds of idle time."
1219 (when desktop-auto-save-timer
1220 (cancel-timer desktop-auto-save-timer)
1221 (setq desktop-auto-save-timer nil))
1222 (when (and (integerp desktop-auto-save-timeout)
1223 (> desktop-auto-save-timeout 0))
1224 (setq desktop-auto-save-timer
1225 (run-with-idle-timer desktop-auto-save-timeout t
1226 'desktop-auto-save))))
1228 ;; ----------------------------------------------------------------------------
1229 ;;;###autoload
1230 (defun desktop-revert ()
1231 "Revert to the last loaded desktop."
1232 (interactive)
1233 (unless desktop-dirname
1234 (error "Unknown desktop directory"))
1235 (unless (file-exists-p (desktop-full-file-name))
1236 (error "No desktop file found"))
1237 (desktop-clear)
1238 (desktop-read desktop-dirname))
1240 (defvar desktop-buffer-major-mode)
1241 (defvar desktop-buffer-locals)
1242 (defvar auto-insert) ; from autoinsert.el
1243 ;; ----------------------------------------------------------------------------
1244 (defun desktop-restore-file-buffer (buffer-filename
1245 _buffer-name
1246 _buffer-misc)
1247 "Restore a file buffer."
1248 (when buffer-filename
1249 (if (or (file-exists-p buffer-filename)
1250 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1251 buffer-filename)))
1252 (if desktop-missing-file-warning
1253 (y-or-n-p (concat msg " Re-create buffer? "))
1254 (message "%s" msg)
1255 nil)))
1256 (let* ((auto-insert nil) ; Disable auto insertion
1257 (coding-system-for-read
1258 (or coding-system-for-read
1259 (cdr (assq 'buffer-file-coding-system
1260 desktop-buffer-locals))))
1261 (buf (find-file-noselect buffer-filename)))
1262 (condition-case nil
1263 (switch-to-buffer buf)
1264 (error (pop-to-buffer buf)))
1265 (and (not (eq major-mode desktop-buffer-major-mode))
1266 (functionp desktop-buffer-major-mode)
1267 (funcall desktop-buffer-major-mode))
1268 buf)
1269 nil)))
1271 (defun desktop-load-file (function)
1272 "Load the file where auto loaded FUNCTION is defined."
1273 (when (fboundp function)
1274 (autoload-do-load (symbol-function function) function)))
1276 ;; ----------------------------------------------------------------------------
1277 ;; Create a buffer, load its file, set its mode, ...;
1278 ;; called from Desktop file only.
1280 (defun desktop-create-buffer
1281 (file-version
1282 buffer-filename
1283 buffer-name
1284 buffer-majormode
1285 buffer-minormodes
1286 buffer-point
1287 buffer-mark
1288 buffer-readonly
1289 buffer-misc
1290 &optional
1291 buffer-locals)
1293 (let ((desktop-file-version file-version)
1294 (desktop-buffer-file-name buffer-filename)
1295 (desktop-buffer-name buffer-name)
1296 (desktop-buffer-major-mode buffer-majormode)
1297 (desktop-buffer-minor-modes buffer-minormodes)
1298 (desktop-buffer-point buffer-point)
1299 (desktop-buffer-mark buffer-mark)
1300 (desktop-buffer-read-only buffer-readonly)
1301 (desktop-buffer-misc buffer-misc)
1302 (desktop-buffer-locals buffer-locals))
1303 ;; To make desktop files with relative file names possible, we cannot
1304 ;; allow `default-directory' to change. Therefore we save current buffer.
1305 (save-current-buffer
1306 ;; Give major mode module a chance to add a handler.
1307 (desktop-load-file desktop-buffer-major-mode)
1308 (let ((buffer-list (buffer-list))
1309 (result
1310 (condition-case-unless-debug err
1311 (funcall (or (cdr (assq desktop-buffer-major-mode
1312 desktop-buffer-mode-handlers))
1313 'desktop-restore-file-buffer)
1314 desktop-buffer-file-name
1315 desktop-buffer-name
1316 desktop-buffer-misc)
1317 (error
1318 (message "Desktop: Can't load buffer %s: %s"
1319 desktop-buffer-name
1320 (error-message-string err))
1321 (when desktop-missing-file-warning (sit-for 1))
1322 nil))))
1323 (if (bufferp result)
1324 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1325 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1326 (setq result nil))
1327 ;; Restore buffer list order with new buffer at end. Don't change
1328 ;; the order for old desktop files (old desktop module behavior).
1329 (unless (< desktop-file-version 206)
1330 (mapc 'bury-buffer buffer-list)
1331 (when result (bury-buffer result)))
1332 (when result
1333 (unless (or desktop-first-buffer (< desktop-file-version 206))
1334 (setq desktop-first-buffer result))
1335 (set-buffer result)
1336 (unless (equal (buffer-name) desktop-buffer-name)
1337 (rename-buffer desktop-buffer-name t))
1338 ;; minor modes
1339 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1340 (auto-fill-mode 1))
1341 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1342 (auto-fill-mode 0))
1344 (dolist (minor-mode desktop-buffer-minor-modes)
1345 ;; Give minor mode module a chance to add a handler.
1346 (desktop-load-file minor-mode)
1347 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1348 (if handler
1349 (funcall handler desktop-buffer-locals)
1350 (when (functionp minor-mode)
1351 (funcall minor-mode 1)))))))
1352 ;; Even though point and mark are non-nil when written by
1353 ;; `desktop-save', they may be modified by handlers wanting to set
1354 ;; point or mark themselves.
1355 (when desktop-buffer-point
1356 (goto-char
1357 (condition-case err
1358 ;; Evaluate point. Thus point can be something like
1359 ;; '(search-forward ...
1360 (eval desktop-buffer-point)
1361 (error (message "%s" (error-message-string err)) 1))))
1362 (when desktop-buffer-mark
1363 (if (consp desktop-buffer-mark)
1364 (progn
1365 (set-mark (car desktop-buffer-mark))
1366 (setq mark-active (car (cdr desktop-buffer-mark))))
1367 (set-mark desktop-buffer-mark)))
1368 ;; Never override file system if the file really is read-only marked.
1369 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1370 (dolist (this desktop-buffer-locals)
1371 (if (consp this)
1372 ;; an entry of this form `(symbol . value)'
1373 (progn
1374 (make-local-variable (car this))
1375 (set (car this) (cdr this)))
1376 ;; an entry of the form `symbol'
1377 (make-local-variable this)
1378 (makunbound this))))))))
1380 ;; ----------------------------------------------------------------------------
1381 ;; Backward compatibility -- update parameters to 205 standards.
1382 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1383 mim pt mk ro tl fc cfs cr buffer-misc)
1384 (desktop-create-buffer 205 buffer-filename buffer-name
1385 buffer-majormode (cdr mim) pt mk ro
1386 buffer-misc
1387 (list (cons 'truncate-lines tl)
1388 (cons 'fill-column fc)
1389 (cons 'case-fold-search cfs)
1390 (cons 'case-replace cr)
1391 (cons 'overwrite-mode (car mim)))))
1393 (defun desktop-append-buffer-args (&rest args)
1394 "Append ARGS at end of `desktop-buffer-args-list'.
1395 ARGS must be an argument list for `desktop-create-buffer'."
1396 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1397 (unless desktop-lazy-timer
1398 (setq desktop-lazy-timer
1399 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1401 (defun desktop-lazy-create-buffer ()
1402 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1403 (when desktop-buffer-args-list
1404 (let* ((remaining (length desktop-buffer-args-list))
1405 (args (pop desktop-buffer-args-list))
1406 (buffer-name (nth 2 args))
1407 (msg (format "Desktop lazily opening %s (%s remaining)..."
1408 buffer-name remaining)))
1409 (when desktop-lazy-verbose
1410 (message "%s" msg))
1411 (let ((desktop-first-buffer nil)
1412 (desktop-buffer-ok-count 0)
1413 (desktop-buffer-fail-count 0))
1414 (apply 'desktop-create-buffer args)
1415 (run-hooks 'desktop-delay-hook)
1416 (setq desktop-delay-hook nil)
1417 (bury-buffer (get-buffer buffer-name))
1418 (when desktop-lazy-verbose
1419 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1421 (defun desktop-idle-create-buffers ()
1422 "Create buffers until the user does something, then stop.
1423 If there are no buffers left to create, kill the timer."
1424 (let ((repeat 1))
1425 (while (and repeat desktop-buffer-args-list)
1426 (save-window-excursion
1427 (desktop-lazy-create-buffer))
1428 (setq repeat (sit-for 0.2))
1429 (unless desktop-buffer-args-list
1430 (cancel-timer desktop-lazy-timer)
1431 (setq desktop-lazy-timer nil)
1432 (message "Lazy desktop load complete")
1433 (sit-for 3)
1434 (message "")))))
1436 (defun desktop-lazy-complete ()
1437 "Run the desktop load to completion."
1438 (interactive)
1439 (let ((desktop-lazy-verbose t))
1440 (while desktop-buffer-args-list
1441 (save-window-excursion
1442 (desktop-lazy-create-buffer)))
1443 (message "Lazy desktop load complete")))
1445 (defun desktop-lazy-abort ()
1446 "Abort lazy loading of the desktop."
1447 (interactive)
1448 (when desktop-lazy-timer
1449 (cancel-timer desktop-lazy-timer)
1450 (setq desktop-lazy-timer nil))
1451 (when desktop-buffer-args-list
1452 (setq desktop-buffer-args-list nil)
1453 (when (called-interactively-p 'interactive)
1454 (message "Lazy desktop load aborted"))))
1456 ;; ----------------------------------------------------------------------------
1457 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1458 ;; command line, we do the rest of what it takes to use desktop, but do it
1459 ;; after finishing loading the init file.
1460 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1461 ;; functions are processed after `after-init-hook'.
1462 (add-hook
1463 'after-init-hook
1464 (lambda ()
1465 (let ((key "--no-desktop"))
1466 (when (member key command-line-args)
1467 (setq command-line-args (delete key command-line-args))
1468 (setq desktop-save-mode nil)))
1469 (when desktop-save-mode
1470 (desktop-read)
1471 (desktop-auto-save-set-timer)
1472 (setq inhibit-startup-screen t))))
1474 ;; So we can restore vc-dir buffers.
1475 (autoload 'vc-dir-mode "vc-dir" nil t)
1477 (provide 'desktop)
1479 ;;; desktop.el ends here
1481 ;; Local Variables:
1482 ;; coding: utf-8
1483 ;; End: