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