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