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