lisp/desktop.el: Fix problem creating minibuffer(less,only) frames.
[emacs.git] / lisp / desktop.el
blob299bdc0eeb47381c4e6003d263c83af0cd28d89e
1 ;;; desktop.el --- save partial status of Emacs when killed
3 ;; Copyright (C) 1993-1995, 1997, 2000-2013 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 Potorti`) for misc. tips.
128 ;; ---------------------------------------------------------------------------
129 ;; TODO:
131 ;; Recognize more minor modes.
132 ;; Save mark rings.
134 ;;; Code:
136 (require 'cl-lib)
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 nil
195 "Number of seconds between auto-saves of the desktop.
196 Zero or nil means disable timer-based auto-saving."
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 window/frame configuration 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 onscren.
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-restoring-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-before-saving-frames-functions nil
413 "Abnormal hook run before saving frames.
414 Functions in this hook are called with one argument, a live frame."
415 :type 'hook
416 :group 'desktop
417 :version "24.4")
419 (defcustom desktop-file-name-format 'absolute
420 "Format in which desktop file names should be saved.
421 Possible values are:
422 absolute -- Absolute file name.
423 tilde -- Relative to ~.
424 local -- Relative to directory of desktop file."
425 :type '(choice (const absolute) (const tilde) (const local))
426 :group 'desktop
427 :version "22.1")
429 (defcustom desktop-restore-eager t
430 "Number of buffers to restore immediately.
431 Remaining buffers are restored lazily (when Emacs is idle).
432 If value is t, all buffers are restored immediately."
433 :type '(choice (const t) integer)
434 :group 'desktop
435 :version "22.1")
437 (defcustom desktop-lazy-verbose t
438 "Verbose reporting of lazily created buffers."
439 :type 'boolean
440 :group 'desktop
441 :version "22.1")
443 (defcustom desktop-lazy-idle-delay 5
444 "Idle delay before starting to create buffers.
445 See `desktop-restore-eager'."
446 :type 'integer
447 :group 'desktop
448 :version "22.1")
450 ;;;###autoload
451 (defvar-local desktop-save-buffer nil
452 "When non-nil, save buffer status in desktop file.
454 If the value is a function, it is called by `desktop-save' with argument
455 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
456 file along with the state of the buffer for which it was called.
458 When file names are returned, they should be formatted using the call
459 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
461 Later, when `desktop-read' evaluates the desktop file, auxiliary information
462 is passed as the argument DESKTOP-BUFFER-MISC to functions in
463 `desktop-buffer-mode-handlers'.")
464 (make-obsolete-variable 'desktop-buffer-modes-to-save
465 'desktop-save-buffer "22.1")
466 (make-obsolete-variable 'desktop-buffer-misc-functions
467 'desktop-save-buffer "22.1")
469 ;;;###autoload
470 (defvar desktop-buffer-mode-handlers nil
471 "Alist of major mode specific functions to restore a desktop buffer.
472 Functions listed are called by `desktop-create-buffer' when `desktop-read'
473 evaluates the desktop file. List elements must have the form
475 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
477 Buffers with a major mode not specified here, are restored by the default
478 handler `desktop-restore-file-buffer'.
480 Handlers are called with argument list
482 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
484 Furthermore, they may use the following variables:
486 desktop-file-version
487 desktop-buffer-major-mode
488 desktop-buffer-minor-modes
489 desktop-buffer-point
490 desktop-buffer-mark
491 desktop-buffer-read-only
492 desktop-buffer-locals
494 If a handler returns a buffer, then the saved mode settings
495 and variable values for that buffer are copied into it.
497 Modules that define a major mode that needs a special handler should contain
498 code like
500 (defun foo-restore-desktop-buffer
502 (add-to-list 'desktop-buffer-mode-handlers
503 '(foo-mode . foo-restore-desktop-buffer))
505 Furthermore the major mode function must be autoloaded.")
507 ;;;###autoload
508 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
509 (make-obsolete-variable 'desktop-buffer-handlers
510 'desktop-buffer-mode-handlers "22.1")
512 (defcustom desktop-minor-mode-table
513 '((auto-fill-function auto-fill-mode)
514 (vc-mode nil)
515 (vc-dired-mode nil)
516 (erc-track-minor-mode nil)
517 (savehist-mode nil))
518 "Table mapping minor mode variables to minor mode functions.
519 Each entry has the form (NAME RESTORE-FUNCTION).
520 NAME is the name of the buffer-local variable indicating that the minor
521 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
522 RESTORE-FUNCTION nil means don't try to restore the minor mode.
523 Only minor modes for which the name of the buffer-local variable
524 and the name of the minor mode function are different have to be added to
525 this table. See also `desktop-minor-mode-handlers'."
526 :type 'sexp
527 :group 'desktop)
529 ;;;###autoload
530 (defvar desktop-minor-mode-handlers nil
531 "Alist of functions to restore non-standard minor modes.
532 Functions are called by `desktop-create-buffer' to restore minor modes.
533 List elements must have the form
535 (MINOR-MODE . RESTORE-FUNCTION).
537 Minor modes not specified here, are restored by the standard minor mode
538 function.
540 Handlers are called with argument list
542 (DESKTOP-BUFFER-LOCALS)
544 Furthermore, they may use the following variables:
546 desktop-file-version
547 desktop-buffer-file-name
548 desktop-buffer-name
549 desktop-buffer-major-mode
550 desktop-buffer-minor-modes
551 desktop-buffer-point
552 desktop-buffer-mark
553 desktop-buffer-read-only
554 desktop-buffer-misc
556 When a handler is called, the buffer has been created and the major mode has
557 been set, but local variables listed in desktop-buffer-locals has not yet been
558 created and set.
560 Modules that define a minor mode that needs a special handler should contain
561 code like
563 (defun foo-desktop-restore
565 (add-to-list 'desktop-minor-mode-handlers
566 '(foo-mode . foo-desktop-restore))
568 Furthermore the minor mode function must be autoloaded.
570 See also `desktop-minor-mode-table'.")
572 ;;;###autoload
573 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
575 ;; ----------------------------------------------------------------------------
576 (defvar desktop-dirname nil
577 "The directory in which the desktop file should be saved.")
579 (defun desktop-full-file-name (&optional dirname)
580 "Return the full name of the desktop file in DIRNAME.
581 DIRNAME omitted or nil means use `desktop-dirname'."
582 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
584 (defun desktop-full-lock-name (&optional dirname)
585 "Return the full name of the desktop lock file in DIRNAME.
586 DIRNAME omitted or nil means use `desktop-dirname'."
587 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
589 (defconst desktop-header
590 ";; --------------------------------------------------------------------------
591 ;; Desktop File for Emacs
592 ;; --------------------------------------------------------------------------
593 " "*Header to place in Desktop file.")
595 (defvar desktop-delay-hook nil
596 "Hooks run after all buffers are loaded; intended for internal use.")
598 (defvar desktop-file-checksum nil
599 "Checksum of the last auto-saved contents of the desktop file.
600 Used to avoid writing contents unchanged between auto-saves.")
602 (defvar desktop-saved-frame-states nil
603 "Saved state of all frames.
604 Only valid during frame saving & restoring; intended for internal use.")
606 ;; ----------------------------------------------------------------------------
607 ;; Desktop file conflict detection
608 (defvar desktop-file-modtime nil
609 "When the desktop file was last modified to the knowledge of this Emacs.
610 Used to detect desktop file conflicts.")
612 (defun desktop-owner (&optional dirname)
613 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
614 Return nil if no desktop file found or no Emacs process is using it.
615 DIRNAME omitted or nil means use `desktop-dirname'."
616 (let (owner
617 (file (desktop-full-lock-name dirname)))
618 (and (file-exists-p file)
619 (ignore-errors
620 (with-temp-buffer
621 (insert-file-contents-literally file)
622 (goto-char (point-min))
623 (setq owner (read (current-buffer)))
624 (integerp owner)))
625 owner)))
627 (defun desktop-claim-lock (&optional dirname)
628 "Record this Emacs process as the owner of the desktop file in DIRNAME.
629 DIRNAME omitted or nil means use `desktop-dirname'."
630 (write-region (number-to-string (emacs-pid)) nil
631 (desktop-full-lock-name dirname)))
633 (defun desktop-release-lock (&optional dirname)
634 "Remove the lock file for the desktop in DIRNAME.
635 DIRNAME omitted or nil means use `desktop-dirname'."
636 (let ((file (desktop-full-lock-name dirname)))
637 (when (file-exists-p file) (delete-file file))))
639 ;; ----------------------------------------------------------------------------
640 (defun desktop-truncate (list n)
641 "Truncate LIST to at most N elements destructively."
642 (let ((here (nthcdr (1- n) list)))
643 (when (consp here)
644 (setcdr here nil))))
646 ;; ----------------------------------------------------------------------------
647 ;;;###autoload
648 (defun desktop-clear ()
649 "Empty the Desktop.
650 This kills all buffers except for internal ones and those with names matched by
651 a regular expression in the list `desktop-clear-preserve-buffers'.
652 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
653 (interactive)
654 (desktop-lazy-abort)
655 (dolist (var desktop-globals-to-clear)
656 (if (symbolp var)
657 (eval `(setq-default ,var nil))
658 (eval `(setq-default ,(car var) ,(cdr var)))))
659 (let ((preserve-regexp (concat "^\\("
660 (mapconcat (lambda (regexp)
661 (concat "\\(" regexp "\\)"))
662 desktop-clear-preserve-buffers
663 "\\|")
664 "\\)$")))
665 (dolist (buffer (buffer-list))
666 (let ((bufname (buffer-name buffer)))
667 (unless (or (eq (aref bufname 0) ?\s) ;; Don't kill internal buffers
668 (string-match-p preserve-regexp bufname))
669 (kill-buffer buffer)))))
670 (delete-other-windows))
672 ;; ----------------------------------------------------------------------------
673 (unless noninteractive
674 (add-hook 'kill-emacs-hook 'desktop-kill))
676 (defun desktop-kill ()
677 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
678 If the desktop should be saved and `desktop-dirname'
679 is nil, ask the user where to save the desktop."
680 (when (and desktop-save-mode
681 (let ((exists (file-exists-p (desktop-full-file-name))))
682 (or (eq desktop-save t)
683 (and exists (eq desktop-save 'if-exists))
684 ;; If it exists, but we aren't using it, we are going
685 ;; to ask for a new directory below.
686 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
687 (and
688 (or (memq desktop-save '(ask ask-if-new))
689 (and exists (eq desktop-save 'ask-if-exists)))
690 (y-or-n-p "Save desktop? ")))))
691 (unless desktop-dirname
692 (setq desktop-dirname
693 (file-name-as-directory
694 (expand-file-name
695 (read-directory-name "Directory for desktop file: " nil nil t)))))
696 (condition-case err
697 (desktop-save desktop-dirname t)
698 (file-error
699 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
700 (signal (car err) (cdr err))))))
701 ;; If we own it, we don't anymore.
702 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
704 ;; ----------------------------------------------------------------------------
705 (defun desktop-list* (&rest args)
706 (and args (apply #'cl-list* args)))
708 ;; ----------------------------------------------------------------------------
709 (defun desktop-buffer-info (buffer)
710 (set-buffer buffer)
711 (list
712 ;; base name of the buffer; replaces the buffer name if managed by uniquify
713 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
714 ;; basic information
715 (desktop-file-name (buffer-file-name) desktop-dirname)
716 (buffer-name)
717 major-mode
718 ;; minor modes
719 (let (ret)
720 (mapc
721 #'(lambda (minor-mode)
722 (and (boundp minor-mode)
723 (symbol-value minor-mode)
724 (let* ((special (assq minor-mode desktop-minor-mode-table))
725 (value (cond (special (cadr special))
726 ((functionp minor-mode) minor-mode))))
727 (when value (add-to-list 'ret value)))))
728 (mapcar #'car minor-mode-alist))
729 ret)
730 ;; point and mark, and read-only status
731 (point)
732 (list (mark t) mark-active)
733 buffer-read-only
734 ;; auxiliary information
735 (when (functionp desktop-save-buffer)
736 (funcall desktop-save-buffer desktop-dirname))
737 ;; local variables
738 (let ((loclist (buffer-local-variables))
739 (ll nil))
740 (dolist (local desktop-locals-to-save)
741 (let ((here (assq local loclist)))
742 (cond (here
743 (push here ll))
744 ((member local loclist)
745 (push local ll)))))
746 ll)))
748 ;; ----------------------------------------------------------------------------
749 (defun desktop--v2s (value)
750 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
751 SEXP is an sexp that when evaluated yields VALUE.
752 QUOTE may be `may' (value may be quoted),
753 `must' (value must be quoted), or nil (value must not be quoted)."
754 (cond
755 ((or (numberp value) (null value) (eq t value) (keywordp value))
756 (cons 'may value))
757 ((stringp value)
758 (let ((copy (copy-sequence value)))
759 (set-text-properties 0 (length copy) nil copy)
760 ;; Get rid of text properties because we cannot read them.
761 (cons 'may copy)))
762 ((symbolp value)
763 (cons 'must value))
764 ((vectorp value)
765 (let* ((pass1 (mapcar #'desktop--v2s value))
766 (special (assq nil pass1)))
767 (if special
768 (cons nil `(vector
769 ,@(mapcar (lambda (el)
770 (if (eq (car el) 'must)
771 `',(cdr el) (cdr el)))
772 pass1)))
773 (cons 'may `[,@(mapcar #'cdr pass1)]))))
774 ((consp value)
775 (let ((p value)
776 newlist
777 use-list*)
778 (while (consp p)
779 (let ((q.sexp (desktop--v2s (car p))))
780 (push q.sexp newlist))
781 (setq p (cdr p)))
782 (when p
783 (let ((last (desktop--v2s p)))
784 (setq use-list* t)
785 (push last newlist)))
786 (if (assq nil newlist)
787 (cons nil
788 `(,(if use-list* 'desktop-list* 'list)
789 ,@(mapcar (lambda (el)
790 (if (eq (car el) 'must)
791 `',(cdr el) (cdr el)))
792 (nreverse newlist))))
793 (cons 'must
794 `(,@(mapcar #'cdr
795 (nreverse (if use-list* (cdr newlist) newlist)))
796 ,@(if use-list* (cdar newlist)))))))
797 ((subrp value)
798 (cons nil `(symbol-function
799 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
800 ((markerp value)
801 (let ((pos (marker-position value))
802 (buf (buffer-name (marker-buffer value))))
803 (cons nil
804 `(let ((mk (make-marker)))
805 (add-hook 'desktop-delay-hook
806 `(lambda ()
807 (set-marker ,mk ,,pos (get-buffer ,,buf))))
808 mk))))
809 (t ; Save as text.
810 (cons 'may "Unprintable entity"))))
812 ;; ----------------------------------------------------------------------------
813 (defun desktop-value-to-string (value)
814 "Convert VALUE to a string that when read evaluates to the same value.
815 Not all types of values are supported."
816 (let* ((print-escape-newlines t)
817 (float-output-format nil)
818 (quote.sexp (desktop--v2s value))
819 (quote (car quote.sexp))
820 (txt
821 (let ((print-quoted t))
822 (prin1-to-string (cdr quote.sexp)))))
823 (if (eq quote 'must)
824 (concat "'" txt)
825 txt)))
827 ;; ----------------------------------------------------------------------------
828 (defun desktop-outvar (varspec)
829 "Output a setq statement for variable VAR to the desktop file.
830 The argument VARSPEC may be the variable name VAR (a symbol),
831 or a cons cell of the form (VAR . MAX-SIZE),
832 which means to truncate VAR's value to at most MAX-SIZE elements
833 \(if the value is a list) before saving the value."
834 (let (var size)
835 (if (consp varspec)
836 (setq var (car varspec) size (cdr varspec))
837 (setq var varspec))
838 (when (boundp var)
839 (when (and (integerp size)
840 (> size 0)
841 (listp (eval var)))
842 (desktop-truncate (eval var) size))
843 (insert "(setq "
844 (symbol-name var)
846 (desktop-value-to-string (symbol-value var))
847 ")\n"))))
849 ;; ----------------------------------------------------------------------------
850 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
851 "Return t if buffer should have its state saved in the desktop file.
852 FILENAME is the visited file name, BUFNAME is the buffer name, and
853 MODE is the major mode.
854 \n\(fn FILENAME BUFNAME MODE)"
855 (let ((case-fold-search nil)
856 dired-skip)
857 (and (not (and (stringp desktop-buffers-not-to-save)
858 (not filename)
859 (string-match-p desktop-buffers-not-to-save bufname)))
860 (not (memq mode desktop-modes-not-to-save))
861 ;; FIXME this is broken if desktop-files-not-to-save is nil.
862 (or (and filename
863 (stringp desktop-files-not-to-save)
864 (not (string-match-p desktop-files-not-to-save filename)))
865 (and (memq mode '(dired-mode vc-dir-mode))
866 (with-current-buffer bufname
867 (not (setq dired-skip
868 (string-match-p desktop-files-not-to-save
869 default-directory)))))
870 (and (null filename)
871 (null dired-skip) ; bug#5755
872 (with-current-buffer bufname desktop-save-buffer))))))
874 ;; ----------------------------------------------------------------------------
875 (defun desktop-file-name (filename dirname)
876 "Convert FILENAME to format specified in `desktop-file-name-format'.
877 DIRNAME must be the directory in which the desktop file will be saved."
878 (cond
879 ((not filename) nil)
880 ((eq desktop-file-name-format 'tilde)
881 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
882 (cond
883 ((file-name-absolute-p relative-name) relative-name)
884 ((string= "./" relative-name) "~/")
885 ((string= "." relative-name) "~")
886 (t (concat "~/" relative-name)))))
887 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
888 (t (expand-file-name filename))))
891 ;; ----------------------------------------------------------------------------
892 (defvar desktop-filter-parameters-alist
893 '((background-color . desktop--filter-*-color)
894 (buffer-list . t)
895 (buffer-predicate . t)
896 (buried-buffer-list . t)
897 (desktop--font . desktop--filter-restore-desktop-parm)
898 (desktop--fullscreen . desktop--filter-restore-desktop-parm)
899 (desktop--height . desktop--filter-restore-desktop-parm)
900 (desktop--width . desktop--filter-restore-desktop-parm)
901 (font . desktop--filter-save-desktop-parm)
902 (font-backend . t)
903 (foreground-color . desktop--filter-*-color)
904 (fullscreen . desktop--filter-save-desktop-parm)
905 (height . desktop--filter-save-desktop-parm)
906 (left . desktop--filter-iconified-position)
907 (minibuffer . desktop--filter-minibuffer)
908 (name . t)
909 (outer-window-id . t)
910 (parent-id . t)
911 (top . desktop--filter-iconified-position)
912 (tty . desktop--filter-tty*)
913 (tty-type . desktop--filter-tty*)
914 (width . desktop--filter-save-desktop-parm)
915 (window-id . t)
916 (window-system . t))
917 "Alist of frame parameters and filtering functions.
919 Each element is a cons (PARAM . FILTER), where PARAM is a parameter
920 name (a symbol identifying a frame parameter), and FILTER can be t
921 \(meaning the parameter is removed from the parameter list on saving
922 and restoring), or a function that will be called with three args:
924 CURRENT a cons (PARAM . VALUE), where PARAM is the one being
925 filtered and VALUE is its current value
926 PARAMETERS the complete alist of parameters being filtered
927 SAVING non-nil if filtering before saving state, nil otherwise
929 The FILTER function must return:
930 nil CURRENT is removed from the list
931 t CURRENT is left as is
932 (PARAM' . VALUE') replace CURRENT with this
934 Frame parameters not on this list are passed intact.")
936 (defvar desktop--target-display nil
937 "Either (minibuffer . VALUE) or nil.
938 This refers to the current frame config being processed inside
939 `frame--restore-frames' and its auxiliary functions (like filtering).
940 If nil, there is no need to change the display.
941 If non-nil, display parameter to use when creating the frame.
942 Internal use only.")
944 (defun desktop-switch-to-gui-p (parameters)
945 "True when switching to a graphic display.
946 Return t if PARAMETERS describes a text-only terminal and
947 the target is a graphic display; otherwise return nil.
948 Only meaningful when called from a filtering function in
949 `desktop-filter-parameters-alist'."
950 (and desktop--target-display ; we're switching
951 (null (cdr (assq 'display parameters))) ; from a tty
952 (cdr desktop--target-display))) ; to a GUI display
954 (defun desktop-switch-to-tty-p (parameters)
955 "True when switching to a text-only terminal.
956 Return t if PARAMETERS describes a graphic display and
957 the target is a text-only terminal; otherwise return nil.
958 Only meaningful when called from a filtering function in
959 `desktop-filter-parameters-alist'."
960 (and desktop--target-display ; we're switching
961 (cdr (assq 'display parameters)) ; from a GUI display
962 (null (cdr desktop--target-display)))) ; to a tty
964 (defun desktop--filter-tty* (_current parameters saving)
965 ;; Remove tty and tty-type parameters when switching
966 ;; to a GUI frame.
967 (or saving
968 (not (desktop-switch-to-gui-p parameters))))
970 (defun desktop--filter-*-color (current parameters saving)
971 ;; Remove (foreground|background)-color parameters
972 ;; when switching to a GUI frame if they denote an
973 ;; "unspecified" color.
974 (or saving
975 (not (desktop-switch-to-gui-p parameters))
976 (not (stringp (cdr current)))
977 (not (string-match-p "^unspecified-[fb]g$" (cdr current)))))
979 (defun desktop--filter-minibuffer (current _parameters saving)
980 ;; When minibuffer is a window, save it as minibuffer . t
981 (or (not saving)
982 (if (windowp (cdr current))
983 '(minibuffer . t)
984 t)))
986 (defun desktop--filter-restore-desktop-parm (current parameters saving)
987 ;; When switching to a GUI frame, convert desktop--XXX parameter to XXX
988 (or saving
989 (not (desktop-switch-to-gui-p parameters))
990 (let ((val (cdr current)))
991 (if (eq val :desktop-processed)
993 (cons (intern (substring (symbol-name (car current))
994 9)) ;; (length "desktop--")
995 val)))))
997 (defun desktop--filter-save-desktop-parm (current parameters saving)
998 ;; When switching to a tty frame, save parameter XXX as desktop--XXX so it
999 ;; can be restored in a subsequent GUI session, unless it already exists.
1000 (cond (saving t)
1001 ((desktop-switch-to-tty-p parameters)
1002 (let ((sym (intern (format "desktop--%s" (car current)))))
1003 (if (assq sym parameters)
1005 (cons sym (cdr current)))))
1006 ((desktop-switch-to-gui-p parameters)
1007 (let* ((dtp (assq (intern (format "desktop--%s" (car current)))
1008 parameters))
1009 (val (cdr dtp)))
1010 (if (eq val :desktop-processed)
1012 (setcdr dtp :desktop-processed)
1013 (cons (car current) val))))
1014 (t t)))
1016 (defun desktop--filter-iconified-position (_current parameters saving)
1017 ;; When saving an iconified frame, top & left are meaningless,
1018 ;; so remove them to allow restoring to a default position.
1019 (not (and saving (eq (cdr (assq 'visibility parameters)) 'icon))))
1021 (defun desktop-restore-in-original-display-p ()
1022 "True if saved frames' displays should be honored."
1023 (cond ((daemonp) t)
1024 ((eq system-type 'windows-nt) nil)
1025 (t (null desktop-restore-in-current-display))))
1027 (defun desktop--filter-frame-parms (parameters saving)
1028 "Filter frame parameters and return filtered list.
1029 PARAMETERS is a parameter alist as returned by `frame-parameters'.
1030 If SAVING is non-nil, filtering is happening before saving frame state;
1031 otherwise, filtering is being done before restoring frame state.
1032 Parameters are filtered according to the setting of
1033 `desktop-filter-parameters-alist' (which see).
1034 Internal use only."
1035 (let ((filtered nil))
1036 (dolist (param parameters)
1037 (let ((filter (cdr (assq (car param) desktop-filter-parameters-alist)))
1038 this)
1039 (cond (;; no filter: pass param
1040 (null filter)
1041 (push param filtered))
1042 (;; filter = t; skip param
1043 (eq filter t))
1044 (;; filter func returns nil: skip param
1045 (null (setq this (funcall filter param parameters saving))))
1046 (;; filter func returns t: pass param
1047 (eq this t)
1048 (push param filtered))
1049 (;; filter func returns a new param: use it
1051 (push this filtered)))))
1052 ;; Set the display parameter after filtering, so that filter functions
1053 ;; have access to its original value.
1054 (when desktop--target-display
1055 (let ((display (assq 'display filtered)))
1056 (if display
1057 (setcdr display (cdr desktop--target-display))
1058 (push desktop--target-display filtered))))
1059 filtered))
1061 (defun desktop--process-minibuffer-frames (frames)
1062 ;; Adds a desktop--mini parameter to frames
1063 ;; desktop--mini is a list (MINIBUFFER NUMBER DEFAULT?) where
1064 ;; MINIBUFFER t if the frame (including minibuffer-only) owns a minibuffer
1065 ;; NUMBER if MINIBUFFER = t, an ID for the frame; if nil, the ID of
1066 ;; the frame containing the minibuffer used by this frame
1067 ;; DEFAULT? if t, this frame is the value of default-minibuffer-frame
1068 (let ((count 0))
1069 ;; Reset desktop--mini for all frames
1070 (dolist (frame (frame-list))
1071 (set-frame-parameter frame 'desktop--mini nil))
1072 ;; Number all frames with its own minibuffer
1073 (dolist (frame (minibuffer-frame-list))
1074 (set-frame-parameter frame 'desktop--mini
1075 (list t
1076 (cl-incf count)
1077 (eq frame default-minibuffer-frame))))
1078 ;; Now link minibufferless frames with their minibuffer frames
1079 (dolist (frame frames)
1080 (unless (frame-parameter frame 'desktop--mini)
1081 (let ((mb-frame (window-frame (minibuffer-window frame))))
1082 ;; Frames whose minibuffer frame has been filtered out will have
1083 ;; desktop--mini = nil, so desktop-restore-frames will restore them
1084 ;; according to their minibuffer parameter. Set up desktop--mini
1085 ;; for the rest.
1086 (when (memq mb-frame frames)
1087 (set-frame-parameter frame 'desktop--mini
1088 (list nil
1089 (cl-second (frame-parameter mb-frame 'desktop--mini))
1090 nil))))))))
1092 (defun desktop-save-frames ()
1093 "Save frame state in `desktop-saved-frame-states'.
1094 Runs the hook `desktop-before-saving-frames-functions'.
1095 Frames with a non-nil `desktop-dont-save' parameter are not saved."
1096 (setq desktop-saved-frame-states
1097 (and desktop-restore-frames
1098 (let ((frames (cl-delete-if
1099 (lambda (frame)
1100 (run-hook-with-args 'desktop-before-saving-frames-functions frame)
1101 (frame-parameter frame 'desktop-dont-save))
1102 (frame-list))))
1103 ;; In case some frame was deleted by a hook function
1104 (setq frames (cl-delete-if-not #'frame-live-p frames))
1105 (desktop--process-minibuffer-frames frames)
1106 (mapcar (lambda (frame)
1107 (cons (desktop--filter-frame-parms (frame-parameters frame) t)
1108 (window-state-get (frame-root-window frame) t)))
1109 frames)))))
1111 ;;;###autoload
1112 (defun desktop-save (dirname &optional release auto-save)
1113 "Save the desktop in a desktop file.
1114 Parameter DIRNAME specifies where to save the desktop file.
1115 Optional parameter RELEASE says whether we're done with this desktop.
1116 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
1117 and don't save the buffer if they are the same."
1118 (interactive "DDirectory to save desktop file in: ")
1119 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
1120 (save-excursion
1121 (let ((eager desktop-restore-eager)
1122 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1123 (when
1124 (or (not new-modtime) ; nothing to overwrite
1125 (equal desktop-file-modtime new-modtime)
1126 (yes-or-no-p (if desktop-file-modtime
1127 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
1128 "Desktop file is more recent than the one loaded. Save anyway? "
1129 "Desktop file isn't the one loaded. Overwrite it? ")
1130 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1131 (unless release (error "Desktop file conflict")))
1133 ;; If we're done with it, release the lock.
1134 ;; Otherwise, claim it if it's unclaimed or if we created it.
1135 (if release
1136 (desktop-release-lock)
1137 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
1139 (with-temp-buffer
1140 (insert
1141 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
1142 desktop-header
1143 ";; Created " (current-time-string) "\n"
1144 ";; Desktop file format version " desktop-file-version "\n"
1145 ";; Emacs version " emacs-version "\n")
1146 (save-excursion (run-hooks 'desktop-save-hook))
1147 (goto-char (point-max))
1148 (insert "\n;; Global section:\n")
1149 ;; Called here because we save the window/frame state as a global
1150 ;; variable for compatibility with previous Emacsen.
1151 (desktop-save-frames)
1152 (unless (memq 'desktop-saved-frame-states desktop-globals-to-save)
1153 (desktop-outvar 'desktop-saved-frame-states))
1154 (mapc (function desktop-outvar) desktop-globals-to-save)
1155 (setq desktop-saved-frame-states nil) ; after saving desktop-globals-to-save
1156 (when (memq 'kill-ring desktop-globals-to-save)
1157 (insert
1158 "(setq kill-ring-yank-pointer (nthcdr "
1159 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
1160 " kill-ring))\n"))
1162 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
1163 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
1164 (let ((base (pop l)))
1165 (when (apply 'desktop-save-buffer-p l)
1166 (insert "("
1167 (if (or (not (integerp eager))
1168 (if (zerop eager)
1170 (setq eager (1- eager))))
1171 "desktop-create-buffer"
1172 "desktop-append-buffer-args")
1174 desktop-file-version)
1175 ;; If there's a non-empty base name, we save it instead of the buffer name
1176 (when (and base (not (string= base "")))
1177 (setcar (nthcdr 1 l) base))
1178 (dolist (e l)
1179 (insert "\n " (desktop-value-to-string e)))
1180 (insert ")\n\n"))))
1182 (setq default-directory desktop-dirname)
1183 ;; If auto-saving, avoid writing if nothing has changed since the last write.
1184 ;; Don't check 300 characters of the header that contains the timestamp.
1185 (let ((checksum (and auto-save (md5 (current-buffer)
1186 (+ (point-min) 300) (point-max)
1187 'emacs-mule))))
1188 (unless (and auto-save (equal checksum desktop-file-checksum))
1189 (let ((coding-system-for-write 'emacs-mule))
1190 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1191 (setq desktop-file-checksum checksum)
1192 ;; We remember when it was modified (which is presumably just now).
1193 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
1195 ;; ----------------------------------------------------------------------------
1196 ;;;###autoload
1197 (defun desktop-remove ()
1198 "Delete desktop file in `desktop-dirname'.
1199 This function also sets `desktop-dirname' to nil."
1200 (interactive)
1201 (when desktop-dirname
1202 (let ((filename (desktop-full-file-name)))
1203 (setq desktop-dirname nil)
1204 (when (file-exists-p filename)
1205 (delete-file filename)))))
1207 (defvar desktop-buffer-args-list nil
1208 "List of args for `desktop-create-buffer'.")
1210 (defvar desktop-lazy-timer nil)
1212 ;; ----------------------------------------------------------------------------
1213 (defvar desktop--reuse-list nil
1214 "Internal use only.")
1216 (defun desktop--compute-pos (value left/top right/bottom)
1217 (pcase value
1218 (`(+ ,val) (+ left/top val))
1219 (`(- ,val) (+ right/bottom val))
1220 (val val)))
1222 (defun desktop--move-onscreen (frame)
1223 "If FRAME is offscreen, move it back onscreen and, if necessary, resize it.
1224 When forced onscreen, frames wider than the monitor's workarea are converted
1225 to fullwidth, and frames taller than the workarea are converted to fullheight.
1226 NOTE: This only works for non-iconified frames."
1227 (pcase-let* ((`(,left ,top ,width ,height) (cl-cdadr (frame-monitor-attributes frame)))
1228 (right (+ left width -1))
1229 (bottom (+ top height -1))
1230 (fr-left (desktop--compute-pos (frame-parameter frame 'left) left right))
1231 (fr-top (desktop--compute-pos (frame-parameter frame 'top) top bottom))
1232 (ch-width (frame-char-width frame))
1233 (ch-height (frame-char-height frame))
1234 (fr-width (max (frame-pixel-width frame) (* ch-width (frame-width frame))))
1235 (fr-height (max (frame-pixel-height frame) (* ch-height (frame-height frame))))
1236 (fr-right (+ fr-left fr-width -1))
1237 (fr-bottom (+ fr-top fr-height -1)))
1238 (when (pcase desktop-restore-forces-onscreen
1239 ;; Any corner is outside the screen.
1240 (`all (or (< fr-bottom top) (> fr-bottom bottom)
1241 (< fr-left left) (> fr-left right)
1242 (< fr-right left) (> fr-right right)
1243 (< fr-top top) (> fr-top bottom)))
1244 ;; Displaced to the left, right, above or below the screen.
1245 (`t (or (> fr-left right)
1246 (< fr-right left)
1247 (> fr-top bottom)
1248 (< fr-bottom top)))
1249 (_ nil))
1250 (let ((fullwidth (> fr-width width))
1251 (fullheight (> fr-height height))
1252 (params nil))
1253 ;; Position frame horizontally.
1254 (cond (fullwidth
1255 (push `(left . ,left) params))
1256 ((> fr-right right)
1257 (push `(left . ,(+ left (- width fr-width))) params))
1258 ((< fr-left left)
1259 (push `(left . ,left) params)))
1260 ;; Position frame vertically.
1261 (cond (fullheight
1262 (push `(top . ,top) params))
1263 ((> fr-bottom bottom)
1264 (push `(top . ,(+ top (- height fr-height))) params))
1265 ((< fr-top top)
1266 (push `(top . ,top) params)))
1267 ;; Compute fullscreen state, if required.
1268 (when (or fullwidth fullheight)
1269 (push (cons 'fullscreen
1270 (cond ((not fullwidth) 'fullheight)
1271 ((not fullheight) 'fullwidth)
1272 (t 'maximized)))
1273 params))
1274 ;; Finally, move the frame back onscreen.
1275 (when params
1276 (modify-frame-parameters frame params))))))
1278 (defun desktop--find-frame (predicate display &rest args)
1279 "Find a suitable frame in `desktop--reuse-list'.
1280 Look through frames whose display property matches DISPLAY and
1281 return the first one for which (PREDICATE frame ARGS) returns t.
1282 If PREDICATE is nil, it is always satisfied. Internal use only.
1283 This is an auxiliary function for `desktop--select-frame'."
1284 (cl-find-if (lambda (frame)
1285 (and (equal (frame-parameter frame 'display) display)
1286 (or (null predicate)
1287 (apply predicate frame args))))
1288 desktop--reuse-list))
1290 (defun desktop--select-frame (display frame-cfg)
1291 "Look for an existing frame to reuse.
1292 DISPLAY is the display where the frame will be shown, and FRAME-CFG
1293 is the parameter list of the frame being restored. Internal use only."
1294 (if (eq desktop-restoring-reuses-frames t)
1295 (let ((frame nil)
1296 mini)
1297 ;; There are no fancy heuristics there. We could implement some
1298 ;; based on frame size and/or position, etc., but it is not clear
1299 ;; that any "gain" (in the sense of reduced flickering, etc.) is
1300 ;; worth the added complexity. In fact, the code below mainly
1301 ;; tries to work nicely when M-x desktop-read is used after a desktop
1302 ;; session has already been loaded. The other main use case, which
1303 ;; is the initial desktop-read upon starting Emacs, should usually
1304 ;; only have one, or very few, frame(s) to reuse.
1305 (cond ((null display)
1306 ;; When the target is tty, every existing frame is reusable.
1307 (setq frame (desktop--find-frame nil display)))
1308 ((car (setq mini (cdr (assq 'desktop--mini frame-cfg))))
1309 ;; If the frame has its own minibuffer, let's see whether
1310 ;; that frame has already been loaded (which can happen after
1311 ;; M-x desktop-read).
1312 (setq frame (desktop--find-frame
1313 (lambda (f m)
1314 (equal (frame-parameter f 'desktop--mini) m))
1315 display mini))
1316 ;; If it has not been loaded, and it is not a minibuffer-only frame,
1317 ;; let's look for an existing non-minibuffer-only frame to reuse.
1318 (unless (or frame (eq (cdr (assq 'minibuffer frame-cfg)) 'only))
1319 (setq frame (desktop--find-frame
1320 (lambda (f)
1321 (let ((w (frame-parameter f 'minibuffer)))
1322 (and (window-live-p w)
1323 (window-minibuffer-p w)
1324 (eq (window-frame w) f))))
1325 display))))
1326 (mini
1327 ;; For minibufferless frames, check whether they already exist,
1328 ;; and that they are linked to the right minibuffer frame.
1329 (setq frame (desktop--find-frame
1330 (lambda (f n)
1331 (pcase-let (((and m `(,hasmini ,num))
1332 (frame-parameter f 'desktop--mini)))
1333 (and m
1334 (null hasmini)
1335 (= num n)
1336 (equal (cl-second (frame-parameter
1337 (window-frame (minibuffer-window f))
1338 'desktop--mini))
1339 n))))
1340 display (cl-second mini))))
1342 ;; Default to just finding a frame in the same display.
1343 (setq frame (desktop--find-frame nil display))))
1344 ;; If found, remove from the list.
1345 (when frame
1346 (setq desktop--reuse-list (delq frame desktop--reuse-list)))
1347 frame)
1348 nil))
1350 (defun desktop--make-frame (frame-cfg window-cfg)
1351 "Set up a frame according to its saved state.
1352 That means either creating a new frame or reusing an existing one.
1353 FRAME-CFG is the parameter list of the new frame; WINDOW-CFG is
1354 its window state. Internal use only."
1355 (let* ((fullscreen (cdr (assq 'fullscreen frame-cfg)))
1356 (lines (assq 'tool-bar-lines frame-cfg))
1357 (filtered-cfg (desktop--filter-frame-parms frame-cfg nil))
1358 (display (cdr (assq 'display filtered-cfg))) ;; post-filtering
1359 alt-cfg frame)
1361 ;; This works around bug#14795 (or feature#14795, if not a bug :-)
1362 (setq filtered-cfg (assq-delete-all 'tool-bar-lines filtered-cfg))
1363 (push '(tool-bar-lines . 0) filtered-cfg)
1365 (when fullscreen
1366 ;; Currently Emacs has the limitation that it does not record the size
1367 ;; and position of a frame before maximizing it, so we cannot save &
1368 ;; restore that info. Instead, when restoring, we resort to creating
1369 ;; invisible "fullscreen" frames of default size and then maximizing them
1370 ;; (and making them visible) which at least is somewhat user-friendly
1371 ;; when these frames are later de-maximized.
1372 (let ((width (and (eq fullscreen 'fullheight) (cdr (assq 'width filtered-cfg))))
1373 (height (and (eq fullscreen 'fullwidth) (cdr (assq 'height filtered-cfg))))
1374 (visible (assq 'visibility filtered-cfg)))
1375 (setq filtered-cfg (cl-delete-if (lambda (p)
1376 (memq p '(visibility fullscreen width height)))
1377 filtered-cfg :key #'car))
1378 (when width
1379 (setq filtered-cfg (append `((user-size . t) (width . ,width))
1380 filtered-cfg)))
1381 (when height
1382 (setq filtered-cfg (append `((user-size . t) (height . ,height))
1383 filtered-cfg)))
1384 ;; These are parameters to apply after creating/setting the frame.
1385 (push visible alt-cfg)
1386 (push (cons 'fullscreen fullscreen) alt-cfg)))
1388 ;; Time to find or create a frame an apply the big bunch of parameters.
1389 ;; If a frame needs to be created and it falls partially or wholly offscreen,
1390 ;; sometimes it gets "pushed back" onscreen; however, moving it afterwards is
1391 ;; allowed. So we create the frame as invisible and then reapply the full
1392 ;; parameter list (including position and size parameters).
1393 (setq frame (or (desktop--select-frame display filtered-cfg)
1394 (make-frame-on-display display
1395 (cons '(visibility)
1396 (cl-loop
1397 for param in '(left top width height minibuffer)
1398 collect (assq param filtered-cfg))))))
1399 (modify-frame-parameters frame
1400 (if (eq (frame-parameter frame 'fullscreen) fullscreen)
1401 ;; Workaround for bug#14949
1402 (assq-delete-all 'fullscreen filtered-cfg)
1403 filtered-cfg))
1405 ;; If requested, force frames to be onscreen.
1406 (when (and desktop-restore-forces-onscreen
1407 ;; FIXME: iconified frames should be checked too,
1408 ;; but it is impossible without deiconifying them.
1409 (not (eq (frame-parameter frame 'visibility) 'icon)))
1410 (desktop--move-onscreen frame))
1412 ;; Let's give the finishing touches (visibility, tool-bar, maximization).
1413 (when lines (push lines alt-cfg))
1414 (when alt-cfg (modify-frame-parameters frame alt-cfg))
1415 ;; Now restore window state.
1416 (window-state-put window-cfg (frame-root-window frame) 'safe)
1417 frame))
1419 (defun desktop--sort-states (state1 state2)
1420 ;; Order: default minibuffer frame
1421 ;; other frames with minibuffer, ascending ID
1422 ;; minibufferless frames, ascending ID
1423 (pcase-let ((`(,_p1 ,hasmini1 ,num1 ,default1) (assq 'desktop--mini (car state1)))
1424 (`(,_p2 ,hasmini2 ,num2 ,default2) (assq 'desktop--mini (car state2))))
1425 (cond (default1 t)
1426 (default2 nil)
1427 ((eq hasmini1 hasmini2) (< num1 num2))
1428 (t hasmini1))))
1430 (defun desktop-restoring-frames-p ()
1431 "True if calling `desktop-restore-frames' will actually restore frames."
1432 (and desktop-restore-frames desktop-saved-frame-states t))
1434 (defun desktop-restore-frames ()
1435 "Restore window/frame configuration.
1436 This function depends on the value of `desktop-saved-frame-states'
1437 being set (usually, by reading it from the desktop)."
1438 (when (desktop-restoring-frames-p)
1439 (let* ((frame-mb-map nil) ;; Alist of frames with their own minibuffer
1440 (delete-saved (eq desktop-restore-in-current-display 'delete))
1441 (forcing (not (desktop-restore-in-original-display-p)))
1442 (target (and forcing (cons 'display (frame-parameter nil 'display)))))
1444 ;; Sorting saved states allows us to easily restore minibuffer-owning frames
1445 ;; before minibufferless ones.
1446 (setq desktop-saved-frame-states (sort desktop-saved-frame-states
1447 #'desktop--sort-states))
1448 ;; Potentially all existing frames are reusable. Later we will decide which ones
1449 ;; to reuse, and how to deal with any leftover.
1450 (setq desktop--reuse-list (frame-list))
1452 (dolist (state desktop-saved-frame-states)
1453 (condition-case err
1454 (pcase-let* ((`(,frame-cfg . ,window-cfg) state)
1455 ((and d-mini `(,hasmini ,num ,default))
1456 (cdr (assq 'desktop--mini frame-cfg)))
1457 (frame nil) (to-tty nil))
1458 ;; Only set target if forcing displays and the target display is different.
1459 (if (or (not forcing)
1460 (equal target (or (assq 'display frame-cfg) '(display . nil))))
1461 (setq desktop--target-display nil)
1462 (setq desktop--target-display target
1463 to-tty (null (cdr target))))
1464 ;; Time to restore frames and set up their minibuffers as they were.
1465 ;; We only skip a frame (thus deleting it) if either:
1466 ;; - we're switching displays, and the user chose the option to delete, or
1467 ;; - we're switching to tty, and the frame to restore is minibuffer-only.
1468 (unless (and desktop--target-display
1469 (or delete-saved
1470 (and to-tty
1471 (eq (cdr (assq 'minibuffer frame-cfg)) 'only))))
1473 ;; Restore minibuffers. Some of this stuff could be done in a filter
1474 ;; function, but it would be messy because restoring minibuffers affects
1475 ;; global state; it's best to do it here than add a bunch of global
1476 ;; variables to pass info back-and-forth to/from the filter function.
1477 (cond
1478 ((null d-mini)) ;; No desktop--mini. Process as normal frame.
1479 (to-tty) ;; Ignore minibuffer stuff and process as normal frame.
1480 (hasmini ;; Frame has minibuffer (or it is minibuffer-only).
1481 (when (eq (cdr (assq 'minibuffer frame-cfg)) 'only)
1482 (setq frame-cfg (append '((tool-bar-lines . 0) (menu-bar-lines . 0))
1483 frame-cfg))))
1484 (t ;; Frame depends on other frame's minibuffer window.
1485 (let ((mb-frame (cdr (assq num frame-mb-map))))
1486 (unless (frame-live-p mb-frame)
1487 (error "Minibuffer frame %s not found" num))
1488 (let ((mb-param (assq 'minibuffer frame-cfg))
1489 (mb-window (minibuffer-window mb-frame)))
1490 (unless (and (window-live-p mb-window)
1491 (window-minibuffer-p mb-window))
1492 (error "Not a minibuffer window %s" mb-window))
1493 (if mb-param
1494 (setcdr mb-param mb-window)
1495 (push (cons 'minibuffer mb-window) frame-cfg))))))
1496 ;; OK, we're ready at last to create (or reuse) a frame and
1497 ;; restore the window config.
1498 (setq frame (desktop--make-frame frame-cfg window-cfg))
1499 ;; Set default-minibuffer if required.
1500 (when default (setq default-minibuffer-frame frame))
1501 ;; Store NUM/frame to assign to minibufferless frames.
1502 (when hasmini (push (cons num frame) frame-mb-map))))
1503 (error
1504 (delay-warning 'desktop (error-message-string err) :error))))
1506 ;; In case we try to delete the initial frame, we want to make sure that
1507 ;; other frames are already visible (discussed in thread for bug#14841).
1508 (sit-for 0 t)
1510 ;; Delete remaining frames, but do not fail if some resist being deleted.
1511 (unless (eq desktop-restoring-reuses-frames 'keep)
1512 (dolist (frame desktop--reuse-list)
1513 (condition-case err
1514 (delete-frame frame)
1515 (error
1516 (delay-warning 'desktop (error-message-string err))))))
1517 (setq desktop--reuse-list nil)
1518 ;; Make sure there's at least one visible frame, and select it.
1519 (unless (or (daemonp)
1520 (cl-find-if #'frame-visible-p (frame-list)))
1521 (let ((visible (if (frame-live-p default-minibuffer-frame)
1522 default-minibuffer-frame
1523 (car (frame-list)))))
1524 (make-frame-visible visible)
1525 (select-frame-set-input-focus visible))))))
1527 ;;;###autoload
1528 (defun desktop-read (&optional dirname)
1529 "Read and process the desktop file in directory DIRNAME.
1530 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1531 directories listed in `desktop-path'. If a desktop file is found, it
1532 is processed and `desktop-after-read-hook' is run. If no desktop file
1533 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1534 This function is a no-op when Emacs is running in batch mode.
1535 It returns t if a desktop file was loaded, nil otherwise."
1536 (interactive)
1537 (unless noninteractive
1538 (setq desktop-dirname
1539 (file-name-as-directory
1540 (expand-file-name
1542 ;; If DIRNAME is specified, use it.
1543 (and (< 0 (length dirname)) dirname)
1544 ;; Otherwise search desktop file in desktop-path.
1545 (let ((dirs desktop-path))
1546 (while (and dirs
1547 (not (file-exists-p
1548 (desktop-full-file-name (car dirs)))))
1549 (setq dirs (cdr dirs)))
1550 (and dirs (car dirs)))
1551 ;; If not found and `desktop-path' is non-nil, use its first element.
1552 (and desktop-path (car desktop-path))
1553 ;; Default: .emacs.d.
1554 user-emacs-directory))))
1555 (if (file-exists-p (desktop-full-file-name))
1556 ;; Desktop file found, but is it already in use?
1557 (let ((desktop-first-buffer nil)
1558 (desktop-buffer-ok-count 0)
1559 (desktop-buffer-fail-count 0)
1560 (owner (desktop-owner))
1561 ;; Avoid desktop saving during evaluation of desktop buffer.
1562 (desktop-save nil))
1563 (if (and owner
1564 (memq desktop-load-locked-desktop '(nil ask))
1565 (or (null desktop-load-locked-desktop)
1566 (daemonp)
1567 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1568 Using it may cause conflicts. Use it anyway? " owner)))))
1569 (let ((default-directory desktop-dirname))
1570 (setq desktop-dirname nil)
1571 (run-hooks 'desktop-not-loaded-hook)
1572 (unless desktop-dirname
1573 (message "Desktop file in use; not loaded.")))
1574 (desktop-lazy-abort)
1575 ;; Evaluate desktop buffer and remember when it was modified.
1576 (load (desktop-full-file-name) t t t)
1577 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1578 ;; If it wasn't already, mark it as in-use, to bother other
1579 ;; desktop instances.
1580 (unless owner
1581 (condition-case nil
1582 (desktop-claim-lock)
1583 (file-error (message "Couldn't record use of desktop file")
1584 (sit-for 1))))
1586 (unless (desktop-restoring-frames-p)
1587 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1588 ;; We want buffers existing prior to evaluating the desktop (and
1589 ;; not reused) to be placed at the end of the buffer list, so we
1590 ;; move them here.
1591 (mapc 'bury-buffer
1592 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1593 (switch-to-buffer (car (buffer-list))))
1594 (run-hooks 'desktop-delay-hook)
1595 (setq desktop-delay-hook nil)
1596 (desktop-restore-frames)
1597 (run-hooks 'desktop-after-read-hook)
1598 (message "Desktop: %d buffer%s restored%s%s."
1599 desktop-buffer-ok-count
1600 (if (= 1 desktop-buffer-ok-count) "" "s")
1601 (if (< 0 desktop-buffer-fail-count)
1602 (format ", %d failed to restore" desktop-buffer-fail-count)
1604 (if desktop-buffer-args-list
1605 (format ", %d to restore lazily"
1606 (length desktop-buffer-args-list))
1607 ""))
1608 (unless (desktop-restoring-frames-p)
1609 ;; Bury the *Messages* buffer to not reshow it when burying
1610 ;; the buffer we switched to above.
1611 (when (buffer-live-p (get-buffer "*Messages*"))
1612 (bury-buffer "*Messages*"))
1613 ;; Clear all windows' previous and next buffers, these have
1614 ;; been corrupted by the `switch-to-buffer' calls in
1615 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1616 ;; brute force fix and should be replaced by a more subtle
1617 ;; strategy eventually.
1618 (walk-window-tree (lambda (window)
1619 (set-window-prev-buffers window nil)
1620 (set-window-next-buffers window nil))))
1622 ;; No desktop file found.
1623 (desktop-clear)
1624 (let ((default-directory desktop-dirname))
1625 (run-hooks 'desktop-no-desktop-file-hook))
1626 (message "No desktop file.")
1627 nil)))
1629 ;; ----------------------------------------------------------------------------
1630 ;; Maintained for backward compatibility
1631 ;;;###autoload
1632 (defun desktop-load-default ()
1633 "Load the `default' start-up library manually.
1634 Also inhibit further loading of it."
1635 (declare (obsolete desktop-save-mode "22.1"))
1636 (unless inhibit-default-init ; safety check
1637 (load "default" t t)
1638 (setq inhibit-default-init t)))
1640 ;; ----------------------------------------------------------------------------
1641 ;;;###autoload
1642 (defun desktop-change-dir (dirname)
1643 "Change to desktop saved in DIRNAME.
1644 Kill the desktop as specified by variables `desktop-save-mode' and
1645 `desktop-save', then clear the desktop and load the desktop file in
1646 directory DIRNAME."
1647 (interactive "DChange to directory: ")
1648 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1649 (desktop-kill)
1650 (desktop-clear)
1651 (desktop-read dirname))
1653 ;; ----------------------------------------------------------------------------
1654 ;;;###autoload
1655 (defun desktop-save-in-desktop-dir ()
1656 "Save the desktop in directory `desktop-dirname'."
1657 (interactive)
1658 (if desktop-dirname
1659 (desktop-save desktop-dirname)
1660 (call-interactively 'desktop-save))
1661 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1663 ;; ----------------------------------------------------------------------------
1664 ;; Auto-Saving.
1665 (defvar desktop-auto-save-timer nil)
1667 (defun desktop-auto-save ()
1668 "Save the desktop periodically.
1669 Called by the timer created in `desktop-auto-save-set-timer'."
1670 (when (and desktop-save-mode
1671 (integerp desktop-auto-save-timeout)
1672 (> desktop-auto-save-timeout 0)
1673 ;; Avoid desktop saving during lazy loading.
1674 (not desktop-lazy-timer)
1675 ;; Save only to own desktop file.
1676 (eq (emacs-pid) (desktop-owner))
1677 desktop-dirname)
1678 (desktop-save desktop-dirname nil t))
1679 (desktop-auto-save-set-timer))
1681 (defun desktop-auto-save-set-timer ()
1682 "Reset the auto-save timer.
1683 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1684 integer, start a new timer to call `desktop-auto-save' in that many seconds."
1685 (when desktop-auto-save-timer
1686 (cancel-timer desktop-auto-save-timer)
1687 (setq desktop-auto-save-timer nil))
1688 (when (and (integerp desktop-auto-save-timeout)
1689 (> desktop-auto-save-timeout 0))
1690 (setq desktop-auto-save-timer
1691 (run-with-timer desktop-auto-save-timeout nil
1692 'desktop-auto-save))))
1694 ;; ----------------------------------------------------------------------------
1695 ;;;###autoload
1696 (defun desktop-revert ()
1697 "Revert to the last loaded desktop."
1698 (interactive)
1699 (unless desktop-dirname
1700 (error "Unknown desktop directory"))
1701 (unless (file-exists-p (desktop-full-file-name))
1702 (error "No desktop file found"))
1703 (desktop-clear)
1704 (desktop-read desktop-dirname))
1706 (defvar desktop-buffer-major-mode)
1707 (defvar desktop-buffer-locals)
1708 (defvar auto-insert) ; from autoinsert.el
1709 ;; ----------------------------------------------------------------------------
1710 (defun desktop-restore-file-buffer (buffer-filename
1711 _buffer-name
1712 _buffer-misc)
1713 "Restore a file buffer."
1714 (when buffer-filename
1715 (if (or (file-exists-p buffer-filename)
1716 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1717 buffer-filename)))
1718 (if desktop-missing-file-warning
1719 (y-or-n-p (concat msg " Re-create buffer? "))
1720 (message "%s" msg)
1721 nil)))
1722 (let* ((auto-insert nil) ; Disable auto insertion
1723 (coding-system-for-read
1724 (or coding-system-for-read
1725 (cdr (assq 'buffer-file-coding-system
1726 desktop-buffer-locals))))
1727 (buf (find-file-noselect buffer-filename)))
1728 (condition-case nil
1729 (switch-to-buffer buf)
1730 (error (pop-to-buffer buf)))
1731 (and (not (eq major-mode desktop-buffer-major-mode))
1732 (functionp desktop-buffer-major-mode)
1733 (funcall desktop-buffer-major-mode))
1734 buf)
1735 nil)))
1737 (defun desktop-load-file (function)
1738 "Load the file where auto loaded FUNCTION is defined."
1739 (when (fboundp function)
1740 (autoload-do-load (symbol-function function) function)))
1742 ;; ----------------------------------------------------------------------------
1743 ;; Create a buffer, load its file, set its mode, ...;
1744 ;; called from Desktop file only.
1746 ;; Just to silence the byte compiler.
1748 (defvar desktop-first-buffer) ; Dynamically bound in `desktop-read'
1750 ;; Bound locally in `desktop-read'.
1751 (defvar desktop-buffer-ok-count)
1752 (defvar desktop-buffer-fail-count)
1754 (defun desktop-create-buffer
1755 (file-version
1756 buffer-filename
1757 buffer-name
1758 buffer-majormode
1759 buffer-minormodes
1760 buffer-point
1761 buffer-mark
1762 buffer-readonly
1763 buffer-misc
1764 &optional
1765 buffer-locals)
1767 (let ((desktop-file-version file-version)
1768 (desktop-buffer-file-name buffer-filename)
1769 (desktop-buffer-name buffer-name)
1770 (desktop-buffer-major-mode buffer-majormode)
1771 (desktop-buffer-minor-modes buffer-minormodes)
1772 (desktop-buffer-point buffer-point)
1773 (desktop-buffer-mark buffer-mark)
1774 (desktop-buffer-read-only buffer-readonly)
1775 (desktop-buffer-misc buffer-misc)
1776 (desktop-buffer-locals buffer-locals))
1777 ;; To make desktop files with relative file names possible, we cannot
1778 ;; allow `default-directory' to change. Therefore we save current buffer.
1779 (save-current-buffer
1780 ;; Give major mode module a chance to add a handler.
1781 (desktop-load-file desktop-buffer-major-mode)
1782 (let ((buffer-list (buffer-list))
1783 (result
1784 (condition-case-unless-debug err
1785 (funcall (or (cdr (assq desktop-buffer-major-mode
1786 desktop-buffer-mode-handlers))
1787 'desktop-restore-file-buffer)
1788 desktop-buffer-file-name
1789 desktop-buffer-name
1790 desktop-buffer-misc)
1791 (error
1792 (message "Desktop: Can't load buffer %s: %s"
1793 desktop-buffer-name
1794 (error-message-string err))
1795 (when desktop-missing-file-warning (sit-for 1))
1796 nil))))
1797 (if (bufferp result)
1798 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1799 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1800 (setq result nil))
1801 ;; Restore buffer list order with new buffer at end. Don't change
1802 ;; the order for old desktop files (old desktop module behavior).
1803 (unless (< desktop-file-version 206)
1804 (mapc 'bury-buffer buffer-list)
1805 (when result (bury-buffer result)))
1806 (when result
1807 (unless (or desktop-first-buffer (< desktop-file-version 206))
1808 (setq desktop-first-buffer result))
1809 (set-buffer result)
1810 (unless (equal (buffer-name) desktop-buffer-name)
1811 (rename-buffer desktop-buffer-name t))
1812 ;; minor modes
1813 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1814 (auto-fill-mode 1))
1815 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1816 (auto-fill-mode 0))
1818 (dolist (minor-mode desktop-buffer-minor-modes)
1819 ;; Give minor mode module a chance to add a handler.
1820 (desktop-load-file minor-mode)
1821 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1822 (if handler
1823 (funcall handler desktop-buffer-locals)
1824 (when (functionp minor-mode)
1825 (funcall minor-mode 1)))))))
1826 ;; Even though point and mark are non-nil when written by
1827 ;; `desktop-save', they may be modified by handlers wanting to set
1828 ;; point or mark themselves.
1829 (when desktop-buffer-point
1830 (goto-char
1831 (condition-case err
1832 ;; Evaluate point. Thus point can be something like
1833 ;; '(search-forward ...
1834 (eval desktop-buffer-point)
1835 (error (message "%s" (error-message-string err)) 1))))
1836 (when desktop-buffer-mark
1837 (if (consp desktop-buffer-mark)
1838 (progn
1839 (set-mark (car desktop-buffer-mark))
1840 (setq mark-active (car (cdr desktop-buffer-mark))))
1841 (set-mark desktop-buffer-mark)))
1842 ;; Never override file system if the file really is read-only marked.
1843 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1844 (dolist (this desktop-buffer-locals)
1845 (if (consp this)
1846 ;; an entry of this form `(symbol . value)'
1847 (progn
1848 (make-local-variable (car this))
1849 (set (car this) (cdr this)))
1850 ;; an entry of the form `symbol'
1851 (make-local-variable this)
1852 (makunbound this))))))))
1854 ;; ----------------------------------------------------------------------------
1855 ;; Backward compatibility -- update parameters to 205 standards.
1856 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1857 mim pt mk ro tl fc cfs cr buffer-misc)
1858 (desktop-create-buffer 205 buffer-filename buffer-name
1859 buffer-majormode (cdr mim) pt mk ro
1860 buffer-misc
1861 (list (cons 'truncate-lines tl)
1862 (cons 'fill-column fc)
1863 (cons 'case-fold-search cfs)
1864 (cons 'case-replace cr)
1865 (cons 'overwrite-mode (car mim)))))
1867 (defun desktop-append-buffer-args (&rest args)
1868 "Append ARGS at end of `desktop-buffer-args-list'.
1869 ARGS must be an argument list for `desktop-create-buffer'."
1870 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1871 (unless desktop-lazy-timer
1872 (setq desktop-lazy-timer
1873 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1875 (defun desktop-lazy-create-buffer ()
1876 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1877 (when desktop-buffer-args-list
1878 (let* ((remaining (length desktop-buffer-args-list))
1879 (args (pop desktop-buffer-args-list))
1880 (buffer-name (nth 2 args))
1881 (msg (format "Desktop lazily opening %s (%s remaining)..."
1882 buffer-name remaining)))
1883 (when desktop-lazy-verbose
1884 (message "%s" msg))
1885 (let ((desktop-first-buffer nil)
1886 (desktop-buffer-ok-count 0)
1887 (desktop-buffer-fail-count 0))
1888 (apply 'desktop-create-buffer args)
1889 (run-hooks 'desktop-delay-hook)
1890 (setq desktop-delay-hook nil)
1891 (bury-buffer (get-buffer buffer-name))
1892 (when desktop-lazy-verbose
1893 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1895 (defun desktop-idle-create-buffers ()
1896 "Create buffers until the user does something, then stop.
1897 If there are no buffers left to create, kill the timer."
1898 (let ((repeat 1))
1899 (while (and repeat desktop-buffer-args-list)
1900 (save-window-excursion
1901 (desktop-lazy-create-buffer))
1902 (setq repeat (sit-for 0.2))
1903 (unless desktop-buffer-args-list
1904 (cancel-timer desktop-lazy-timer)
1905 (setq desktop-lazy-timer nil)
1906 (message "Lazy desktop load complete")
1907 (sit-for 3)
1908 (message "")))))
1910 (defun desktop-lazy-complete ()
1911 "Run the desktop load to completion."
1912 (interactive)
1913 (let ((desktop-lazy-verbose t))
1914 (while desktop-buffer-args-list
1915 (save-window-excursion
1916 (desktop-lazy-create-buffer)))
1917 (message "Lazy desktop load complete")))
1919 (defun desktop-lazy-abort ()
1920 "Abort lazy loading of the desktop."
1921 (interactive)
1922 (when desktop-lazy-timer
1923 (cancel-timer desktop-lazy-timer)
1924 (setq desktop-lazy-timer nil))
1925 (when desktop-buffer-args-list
1926 (setq desktop-buffer-args-list nil)
1927 (when (called-interactively-p 'interactive)
1928 (message "Lazy desktop load aborted"))))
1930 ;; ----------------------------------------------------------------------------
1931 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1932 ;; command line, we do the rest of what it takes to use desktop, but do it
1933 ;; after finishing loading the init file.
1934 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1935 ;; functions are processed after `after-init-hook'.
1936 (add-hook
1937 'after-init-hook
1938 (lambda ()
1939 (let ((key "--no-desktop"))
1940 (when (member key command-line-args)
1941 (setq command-line-args (delete key command-line-args))
1942 (setq desktop-save-mode nil)))
1943 (when desktop-save-mode
1944 (desktop-read)
1945 (desktop-auto-save-set-timer)
1946 (setq inhibit-startup-screen t))))
1948 ;; So we can restore vc-dir buffers.
1949 (autoload 'vc-dir-mode "vc-dir" nil t)
1951 (provide 'desktop)
1953 ;;; desktop.el ends here