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