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