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
b958c0ad 36;; - frame and window configuration
6343ed61 37
6b61353c 38;; To use this, use customize to turn on desktop-save-mode or add the
865fe16f 39;; following line somewhere in your init file:
0b9bd504 40;;
6b61353c 41;; (desktop-save-mode 1)
0b9bd504 42;;
6b61353c 43;; For further usage information, look at the section
20535d5b 44;; (info "(emacs)Saving Emacs Sessions") in the GNU Emacs Manual.
6b61353c
KH
45
46;; When the desktop module is loaded, the function `desktop-kill' is
341c2f07 47;; added to the `kill-emacs-hook'. This function is responsible for
6b61353c 48;; saving the desktop when Emacs is killed. Furthermore an anonymous
341c2f07 49;; function is added to the `after-init-hook'. This function is
6b61353c 50;; responsible for loading the desktop when Emacs is started.
ec4c6f22 51
0f4804e7
LH
52;; Special handling.
53;; -----------------
54;; Variables `desktop-buffer-mode-handlers' and `desktop-minor-mode-handlers'
55;; are supplied to handle special major and minor modes respectively.
56;; `desktop-buffer-mode-handlers' is an alist of major mode specific functions
341c2f07 57;; to restore a desktop buffer. Elements must have the form
be617bbf 58;;
0f4804e7 59;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
be617bbf 60;;
0f4804e7 61;; Functions listed are called by `desktop-create-buffer' when `desktop-read'
341c2f07 62;; evaluates the desktop file. Buffers with a major mode not specified here,
0f4804e7
LH
63;; are restored by the default handler `desktop-restore-file-buffer'.
64;; `desktop-minor-mode-handlers' is an alist of functions to restore
65;; non-standard minor modes. Elements must have the form
be617bbf 66;;
0f4804e7 67;; (MINOR-MODE . RESTORE-FUNCTION).
be617bbf 68;;
0f4804e7
LH
69;; Functions are called by `desktop-create-buffer' to restore minor modes.
70;; Minor modes not specified here, are restored by the standard minor mode
71;; function. If you write a module that defines a major or minor mode that
72;; needs a special handler, then place code like
73
74;; (defun foo-restore-desktop-buffer
75;; ...
76;; (add-to-list 'desktop-buffer-mode-handlers
77;; '(foo-mode . foo-restore-desktop-buffer))
78
79;; or
80
81;; (defun bar-desktop-restore
82;; ...
83;; (add-to-list 'desktop-minor-mode-handlers
84;; '(bar-mode . bar-desktop-restore))
85
fb8a6326 86;; in the module itself, and make sure that the mode function is
341c2f07 87;; autoloaded. See the docstrings of `desktop-buffer-mode-handlers' and
0f4804e7
LH
88;; `desktop-minor-mode-handlers' for more info.
89
90;; Minor modes.
91;; ------------
92;; Conventional minor modes (see node "Minor Mode Conventions" in the elisp
93;; manual) are handled in the following way:
94;; When `desktop-save' saves the state of a buffer to the desktop file, it
95;; saves as `desktop-minor-modes' the list of names of those variables in
96;; `minor-mode-alist' that have a non-nil value.
97;; When `desktop-create' restores the buffer, each of the symbols in
98;; `desktop-minor-modes' is called as function with parameter 1.
99;; The variables `desktop-minor-mode-table' and `desktop-minor-mode-handlers'
100;; are used to handle non-conventional minor modes. `desktop-save' uses
101;; `desktop-minor-mode-table' to map minor mode variables to minor mode
341c2f07 102;; functions before writing `desktop-minor-modes'. If a minor mode has a
0f4804e7
LH
103;; variable name that is different form its function name, an entry
104
105;; (NAME RESTORE-FUNCTION)
106
107;; should be added to `desktop-minor-mode-table'. If a minor mode should not
108;; be restored, RESTORE-FUNCTION should be set to nil. `desktop-create' uses
109;; `desktop-minor-mode-handlers' to lookup minor modes that needs a restore
110;; function different from the usual minor mode function.
111;; ---------------------------------------------------------------------------
47640244 112
ec4c6f22
RS
113;; By the way: don't use desktop.el to customize Emacs -- the file .emacs
114;; in your home directory is used for that. Saving global default values
115;; for buffers is an example of misuse.
116
0b9bd504
RS
117;; PLEASE NOTE: The kill ring can be saved as specified by the variable
118;; `desktop-globals-to-save' (by default it isn't). This may result in saving
119;; things you did not mean to keep. Use M-x desktop-clear RET.
ec4c6f22 120
fa379636
KH
121;; Thanks to hetrick@phys.uva.nl (Jim Hetrick) for useful ideas.
122;; avk@rtsg.mot.com (Andrew V. Klein) for a dired tip.
123;; chris@tecc.co.uk (Chris Boucher) for a mark tip.
124;; f89-kam@nada.kth.se (Klas Mellbourn) for a mh-e tip.
125;; kifer@sbkifer.cs.sunysb.edu (M. Kifer) for a bug hunt.
f4c73d07 126;; treese@lcs.mit.edu (Win Treese) for ange-ftp tips.
253406b9 127;; pot@cnuce.cnr.it (Francesco Potorti`) for misc. tips.
0b9bd504
RS
128;; ---------------------------------------------------------------------------
129;; TODO:
130;;
0b9bd504
RS
131;; Recognize more minor modes.
132;; Save mark rings.
6343ed61
RS
133
134;;; Code:
135
a1c80d9d
JB
136(require 'cl-lib)
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
CY
155 "Toggle desktop saving (Desktop Save mode).
156With a prefix argument ARG, enable Desktop Save mode if ARG is
157positive, and disable it otherwise. If called from Lisp, enable
158the mode if ARG is omitted or nil.
159
160If Desktop Save mode is enabled, the state of Emacs is saved from
161one session to another. See variable `desktop-save' and function
162`desktop-read' for details."
6b61353c
KH
163 :global t
164 :group 'desktop)
165
e88110db
JB
166(defun desktop-save-mode-off ()
167 "Disable `desktop-save-mode'. Provided for use in hooks."
168 (desktop-save-mode 0))
169
4a2fce7a 170(defcustom desktop-save 'ask-if-new
9201cc28 171 "Specifies whether the desktop should be saved when it is killed.
6b61353c
KH
172A desktop is killed when the user changes desktop or quits Emacs.
173Possible values are:
4a2fce7a
RS
174 t -- always save.
175 ask -- always ask.
176 ask-if-new -- ask if no desktop file exists, otherwise just save.
177 ask-if-exists -- ask if desktop file exists, otherwise don't save.
178 if-exists -- save if desktop file exists, otherwise don't save.
179 nil -- never save.
6b61353c 180The desktop is never saved when `desktop-save-mode' is nil.
cc8b76bf 181The variables `desktop-dirname' and `desktop-base-file-name'
6b61353c 182determine where the desktop is saved."
11425834
LH
183 :type
184 '(choice
4a2fce7a
RS
185 (const :tag "Always save" t)
186 (const :tag "Always ask" ask)
187 (const :tag "Ask if desktop file is new, else do save" ask-if-new)
188 (const :tag "Ask if desktop file exists, else don't save" ask-if-exists)
189 (const :tag "Save if desktop file exists, else don't" if-exists)
190 (const :tag "Never save" nil))
af61551b 191 :group 'desktop
bf247b6e 192 :version "22.1")
4a2fce7a 193
5db9dace
JL
194(defcustom desktop-auto-save-timeout nil
195 "Number of seconds between auto-saves of the desktop.
196Zero or nil means disable timer-based auto-saving."
197 :type '(choice (const :tag "Off" nil)
198 (integer :tag "Seconds"))
199 :set (lambda (symbol value)
200 (set-default symbol value)
acfcc8c5 201 (ignore-errors (desktop-auto-save-set-timer)))
5db9dace
JL
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
b958c0ad 374(defcustom desktop-restore-frames t
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 380(defcustom desktop-restore-in-current-display nil
b958c0ad
JB
381 "If t, frames are restored in the current display.
382If nil, frames are restored, if possible, in their original displays.
383If `delete', frames on other displays are deleted instead of restored."
384 :type '(choice (const :tag "Restore in current display" t)
385 (const :tag "Restore in original display" nil)
386 (const :tag "Delete frames in other displays" 'delete))
387 :group 'desktop
388 :version "24.4")
389
390(defcustom desktop-restoring-reuses-frames t
391 "If t, restoring frames reuses existing frames.
392If nil, existing frames are deleted.
393If `keep', existing frames are kept and not reused."
394 :type '(choice (const :tag "Reuse existing frames" t)
395 (const :tag "Delete existing frames" nil)
396 (const :tag "Keep existing frames" 'keep))
2addf922
JB
397 :group 'desktop
398 :version "24.4")
399
a1c80d9d
JB
400(defcustom desktop-before-saving-frames-functions nil
401 "Abnormal hook run before saving frames.
402Functions in this hook are called with one argument, a live frame."
403 :type 'hook
404 :group 'desktop
405 :version "24.4")
406
4a2fce7a 407(defcustom desktop-file-name-format 'absolute
9201cc28 408 "Format in which desktop file names should be saved.
4a2fce7a
RS
409Possible values are:
410 absolute -- Absolute file name.
411 tilde -- Relative to ~.
412 local -- Relative to directory of desktop file."
413 :type '(choice (const absolute) (const tilde) (const local))
af61551b 414 :group 'desktop
bf247b6e 415 :version "22.1")
569c754e 416
150f39ee
LH
417(defcustom desktop-restore-eager t
418 "Number of buffers to restore immediately.
419Remaining buffers are restored lazily (when Emacs is idle).
420If value is t, all buffers are restored immediately."
0ba9bc53 421 :type '(choice (const t) integer)
150f39ee 422 :group 'desktop
bf247b6e 423 :version "22.1")
150f39ee
LH
424
425(defcustom desktop-lazy-verbose t
426 "Verbose reporting of lazily created buffers."
427 :type 'boolean
428 :group 'desktop
bf247b6e 429 :version "22.1")
150f39ee
LH
430
431(defcustom desktop-lazy-idle-delay 5
432 "Idle delay before starting to create buffers.
433See `desktop-restore-eager'."
434 :type 'integer
435 :group 'desktop
bf247b6e 436 :version "22.1")
150f39ee 437
e5780ae1 438;;;###autoload
acfcc8c5 439(defvar-local desktop-save-buffer nil
ebb39555 440 "When non-nil, save buffer status in desktop file.
ebb39555 441
b89c5a72
JB
442If the value is a function, it is called by `desktop-save' with argument
443DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
ebb39555 444file along with the state of the buffer for which it was called.
b6b70cda 445
6b61353c 446When file names are returned, they should be formatted using the call
e5780ae1 447\"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
4a2fce7a 448
0f4804e7
LH
449Later, when `desktop-read' evaluates the desktop file, auxiliary information
450is passed as the argument DESKTOP-BUFFER-MISC to functions in
451`desktop-buffer-mode-handlers'.")
ebb39555 452(make-obsolete-variable 'desktop-buffer-modes-to-save
cc8b76bf 453 'desktop-save-buffer "22.1")
e5780ae1 454(make-obsolete-variable 'desktop-buffer-misc-functions
cc8b76bf 455 'desktop-save-buffer "22.1")
b6b70cda 456
0f4804e7 457;;;###autoload
e76f0800 458(defvar desktop-buffer-mode-handlers nil
e5780ae1 459 "Alist of major mode specific functions to restore a desktop buffer.
0f4804e7
LH
460Functions listed are called by `desktop-create-buffer' when `desktop-read'
461evaluates the desktop file. List elements must have the form
462
463 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
e5780ae1
LH
464
465Buffers with a major mode not specified here, are restored by the default
466handler `desktop-restore-file-buffer'.
467
55775448 468Handlers are called with argument list
4a2fce7a 469
9bcabb45 470 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
e5780ae1
LH
471
472Furthermore, they may use the following variables:
4a2fce7a
RS
473
474 desktop-file-version
4a2fce7a
RS
475 desktop-buffer-major-mode
476 desktop-buffer-minor-modes
477 desktop-buffer-point
478 desktop-buffer-mark
479 desktop-buffer-read-only
4a2fce7a
RS
480 desktop-buffer-locals
481
e5780ae1 482If a handler returns a buffer, then the saved mode settings
0f4804e7
LH
483and variable values for that buffer are copied into it.
484
485Modules that define a major mode that needs a special handler should contain
486code like
ec4c6f22 487
0f4804e7
LH
488 (defun foo-restore-desktop-buffer
489 ...
490 (add-to-list 'desktop-buffer-mode-handlers
491 '(foo-mode . foo-restore-desktop-buffer))
492
493Furthermore the major mode function must be autoloaded.")
ec4c6f22 494
498eb267 495;;;###autoload
e5780ae1
LH
496(put 'desktop-buffer-mode-handlers 'risky-local-variable t)
497(make-obsolete-variable 'desktop-buffer-handlers
cc8b76bf 498 'desktop-buffer-mode-handlers "22.1")
b6b70cda 499
47640244
GM
500(defcustom desktop-minor-mode-table
501 '((auto-fill-function auto-fill-mode)
5fff0265 502 (vc-mode nil)
f2168a4c 503 (vc-dired-mode nil)
fb8a6326
JB
504 (erc-track-minor-mode nil)
505 (savehist-mode nil))
47640244
GM
506 "Table mapping minor mode variables to minor mode functions.
507Each entry has the form (NAME RESTORE-FUNCTION).
508NAME is the name of the buffer-local variable indicating that the minor
509mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
7d6ee4df 510RESTORE-FUNCTION nil means don't try to restore the minor mode.
47640244 511Only minor modes for which the name of the buffer-local variable
7bfa55b3 512and the name of the minor mode function are different have to be added to
0f4804e7 513this table. See also `desktop-minor-mode-handlers'."
47640244
GM
514 :type 'sexp
515 :group 'desktop)
516
0f4804e7 517;;;###autoload
e76f0800 518(defvar desktop-minor-mode-handlers nil
0f4804e7
LH
519 "Alist of functions to restore non-standard minor modes.
520Functions are called by `desktop-create-buffer' to restore minor modes.
521List elements must have the form
522
523 (MINOR-MODE . RESTORE-FUNCTION).
524
525Minor modes not specified here, are restored by the standard minor mode
526function.
527
528Handlers are called with argument list
529
530 (DESKTOP-BUFFER-LOCALS)
531
532Furthermore, they may use the following variables:
533
534 desktop-file-version
535 desktop-buffer-file-name
536 desktop-buffer-name
537 desktop-buffer-major-mode
538 desktop-buffer-minor-modes
539 desktop-buffer-point
540 desktop-buffer-mark
541 desktop-buffer-read-only
542 desktop-buffer-misc
543
544When a handler is called, the buffer has been created and the major mode has
545been set, but local variables listed in desktop-buffer-locals has not yet been
546created and set.
547
548Modules that define a minor mode that needs a special handler should contain
549code like
550
551 (defun foo-desktop-restore
552 ...
553 (add-to-list 'desktop-minor-mode-handlers
554 '(foo-mode . foo-desktop-restore))
555
556Furthermore the minor mode function must be autoloaded.
557
558See also `desktop-minor-mode-table'.")
559
498eb267 560;;;###autoload
0f4804e7
LH
561(put 'desktop-minor-mode-handlers 'risky-local-variable t)
562
0b9bd504
RS
563;; ----------------------------------------------------------------------------
564(defvar desktop-dirname nil
6b61353c 565 "The directory in which the desktop file should be saved.")
6343ed61 566
11425834
LH
567(defun desktop-full-file-name (&optional dirname)
568 "Return the full name of the desktop file in DIRNAME.
569DIRNAME omitted or nil means use `desktop-dirname'."
570 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
571
e88110db
JB
572(defun desktop-full-lock-name (&optional dirname)
573 "Return the full name of the desktop lock file in DIRNAME.
574DIRNAME omitted or nil means use `desktop-dirname'."
575 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
576
6343ed61 577(defconst desktop-header
0b9bd504
RS
578";; --------------------------------------------------------------------------
579;; Desktop File for Emacs
580;; --------------------------------------------------------------------------
6343ed61 581" "*Header to place in Desktop file.")
de9e2828
RS
582
583(defvar desktop-delay-hook nil
584 "Hooks run after all buffers are loaded; intended for internal use.")
813dbb2d 585
5db9dace
JL
586(defvar desktop-file-checksum nil
587 "Checksum of the last auto-saved contents of the desktop file.
588Used to avoid writing contents unchanged between auto-saves.")
589
56bc453c
JB
590(defvar desktop-saved-frame-states nil
591 "Saved state of all frames.
592Only valid during frame saving & restoring; intended for internal use.")
39c0e36f 593
e88110db
JB
594;; ----------------------------------------------------------------------------
595;; Desktop file conflict detection
596(defvar desktop-file-modtime nil
597 "When the desktop file was last modified to the knowledge of this Emacs.
598Used to detect desktop file conflicts.")
599
600(defun desktop-owner (&optional dirname)
601 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
602Return nil if no desktop file found or no Emacs process is using it.
603DIRNAME omitted or nil means use `desktop-dirname'."
acfcc8c5
JB
604 (let (owner
605 (file (desktop-full-lock-name dirname)))
606 (and (file-exists-p file)
607 (ignore-errors
608 (with-temp-buffer
609 (insert-file-contents-literally file)
610 (goto-char (point-min))
611 (setq owner (read (current-buffer)))
612 (integerp owner)))
e88110db
JB
613 owner)))
614
615(defun desktop-claim-lock (&optional dirname)
616 "Record this Emacs process as the owner of the desktop file in DIRNAME.
617DIRNAME omitted or nil means use `desktop-dirname'."
618 (write-region (number-to-string (emacs-pid)) nil
619 (desktop-full-lock-name dirname)))
620
621(defun desktop-release-lock (&optional dirname)
622 "Remove the lock file for the desktop in DIRNAME.
623DIRNAME omitted or nil means use `desktop-dirname'."
624 (let ((file (desktop-full-lock-name dirname)))
625 (when (file-exists-p file) (delete-file file))))
626
0b9bd504 627;; ----------------------------------------------------------------------------
6b61353c 628(defun desktop-truncate (list n)
ec4c6f22 629 "Truncate LIST to at most N elements destructively."
6b61353c 630 (let ((here (nthcdr (1- n) list)))
1f7efe1b
JB
631 (when (consp here)
632 (setcdr here nil))))
f9be4574 633
4a2fce7a 634;; ----------------------------------------------------------------------------
11425834 635;;;###autoload
f9be4574
RS
636(defun desktop-clear ()
637 "Empty the Desktop.
0f4804e7
LH
638This kills all buffers except for internal ones and those with names matched by
639a regular expression in the list `desktop-clear-preserve-buffers'.
640Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
6343ed61 641 (interactive)
150f39ee 642 (desktop-lazy-abort)
4a2fce7a
RS
643 (dolist (var desktop-globals-to-clear)
644 (if (symbolp var)
1f7efe1b 645 (eval `(setq-default ,var nil))
4a2fce7a 646 (eval `(setq-default ,(car var) ,(cdr var)))))
b61d71e4 647 (let ((preserve-regexp (concat "^\\("
0f4804e7
LH
648 (mapconcat (lambda (regexp)
649 (concat "\\(" regexp "\\)"))
650 desktop-clear-preserve-buffers
651 "\\|")
652 "\\)$")))
b61d71e4
JB
653 (dolist (buffer (buffer-list))
654 (let ((bufname (buffer-name buffer)))
655 (unless (or (eq (aref bufname 0) ?s) ;; Don't kill internal buffers
656 (string-match-p preserve-regexp bufname))
657 (kill-buffer buffer)))))
b6105c76 658 (delete-other-windows))
4a2fce7a 659
0b9bd504 660;; ----------------------------------------------------------------------------
845fc5e5
JB
661(unless noninteractive
662 (add-hook 'kill-emacs-hook 'desktop-kill))
ec4c6f22 663
6343ed61 664(defun desktop-kill ()
6b61353c 665 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
4a2fce7a
RS
666If the desktop should be saved and `desktop-dirname'
667is nil, ask the user where to save the desktop."
11425834
LH
668 (when (and desktop-save-mode
669 (let ((exists (file-exists-p (desktop-full-file-name))))
670 (or (eq desktop-save t)
7dd7fbb9
JD
671 (and exists (eq desktop-save 'if-exists))
672 ;; If it exists, but we aren't using it, we are going
673 ;; to ask for a new directory below.
674 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
11425834
LH
675 (and
676 (or (memq desktop-save '(ask ask-if-new))
677 (and exists (eq desktop-save 'ask-if-exists)))
678 (y-or-n-p "Save desktop? ")))))
4a2fce7a
RS
679 (unless desktop-dirname
680 (setq desktop-dirname
11425834
LH
681 (file-name-as-directory
682 (expand-file-name
794855ca 683 (read-directory-name "Directory for desktop file: " nil nil t)))))
4a2fce7a 684 (condition-case err
e88110db 685 (desktop-save desktop-dirname t)
4a2fce7a 686 (file-error
11425834 687 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
e88110db
JB
688 (signal (car err) (cdr err))))))
689 ;; If we own it, we don't anymore.
690 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
4a2fce7a 691
0b9bd504 692;; ----------------------------------------------------------------------------
ed2f7fc8 693(defun desktop-list* (&rest args)
b61d71e4 694 (and args (cl-list* args)))
ed2f7fc8 695
e88110db
JB
696;; ----------------------------------------------------------------------------
697(defun desktop-buffer-info (buffer)
698 (set-buffer buffer)
699 (list
a8049a30
JB
700 ;; base name of the buffer; replaces the buffer name if managed by uniquify
701 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
e88110db 702 ;; basic information
9e29c91c 703 (desktop-file-name (buffer-file-name) desktop-dirname)
a8049a30 704 (buffer-name)
e88110db
JB
705 major-mode
706 ;; minor modes
707 (let (ret)
708 (mapc
709 #'(lambda (minor-mode)
710 (and (boundp minor-mode)
711 (symbol-value minor-mode)
712 (let* ((special (assq minor-mode desktop-minor-mode-table))
713 (value (cond (special (cadr special))
714 ((functionp minor-mode) minor-mode))))
715 (when value (add-to-list 'ret value)))))
716 (mapcar #'car minor-mode-alist))
717 ret)
718 ;; point and mark, and read-only status
719 (point)
720 (list (mark t) mark-active)
721 buffer-read-only
722 ;; auxiliary information
723 (when (functionp desktop-save-buffer)
9e29c91c 724 (funcall desktop-save-buffer desktop-dirname))
e88110db 725 ;; local variables
b61d71e4
JB
726 (let ((loclist (buffer-local-variables))
727 (ll nil))
728 (dolist (local desktop-locals-to-save)
729 (let ((here (assq local loclist)))
730 (cond (here
731 (push here ll))
732 ((member local loclist)
733 (push local ll)))))
e88110db
JB
734 ll)))
735
4a2fce7a 736;; ----------------------------------------------------------------------------
69b2c07e
SM
737(defun desktop--v2s (value)
738 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
739SEXP is an sexp that when evaluated yields VALUE.
577ed2b2 740QUOTE may be `may' (value may be quoted),
60ff536c 741`must' (value must be quoted), or nil (value must not be quoted)."
de9e2828 742 (cond
1f7efe1b 743 ((or (numberp value) (null value) (eq t value) (keywordp value))
69b2c07e 744 (cons 'may value))
1f7efe1b
JB
745 ((stringp value)
746 (let ((copy (copy-sequence value)))
747 (set-text-properties 0 (length copy) nil copy)
69b2c07e
SM
748 ;; Get rid of text properties because we cannot read them.
749 (cons 'may copy)))
1f7efe1b 750 ((symbolp value)
69b2c07e 751 (cons 'must value))
1f7efe1b 752 ((vectorp value)
69b2c07e
SM
753 (let* ((pass1 (mapcar #'desktop--v2s value))
754 (special (assq nil pass1)))
1f7efe1b 755 (if special
69b2c07e
SM
756 (cons nil `(vector
757 ,@(mapcar (lambda (el)
758 (if (eq (car el) 'must)
759 `',(cdr el) (cdr el)))
760 pass1)))
761 (cons 'may `[,@(mapcar #'cdr pass1)]))))
1f7efe1b
JB
762 ((consp value)
763 (let ((p value)
764 newlist
acfcc8c5 765 use-list*)
1f7efe1b 766 (while (consp p)
69b2c07e
SM
767 (let ((q.sexp (desktop--v2s (car p))))
768 (push q.sexp newlist))
1f7efe1b 769 (setq p (cdr p)))
69b2c07e
SM
770 (when p
771 (let ((last (desktop--v2s p)))
772 (setq use-list* t)
773 (push last newlist)))
774 (if (assq nil newlist)
1f7efe1b 775 (cons nil
69b2c07e
SM
776 `(,(if use-list* 'desktop-list* 'list)
777 ,@(mapcar (lambda (el)
778 (if (eq (car el) 'must)
779 `',(cdr el) (cdr el)))
780 (nreverse newlist))))
1f7efe1b 781 (cons 'must
69b2c07e
SM
782 `(,@(mapcar #'cdr
783 (nreverse (if use-list* (cdr newlist) newlist)))
784 ,@(if use-list* (cdar newlist)))))))
1f7efe1b 785 ((subrp value)
69b2c07e
SM
786 (cons nil `(symbol-function
787 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
1f7efe1b 788 ((markerp value)
69b2c07e
SM
789 (let ((pos (marker-position value))
790 (buf (buffer-name (marker-buffer value))))
791 (cons nil
792 `(let ((mk (make-marker)))
793 (add-hook 'desktop-delay-hook
794 `(lambda ()
795 (set-marker ,mk ,,pos (get-buffer ,,buf))))
796 mk))))
797 (t ; Save as text.
798 (cons 'may "Unprintable entity"))))
de9e2828 799
4a2fce7a 800;; ----------------------------------------------------------------------------
6b61353c 801(defun desktop-value-to-string (value)
577ed2b2
RS
802 "Convert VALUE to a string that when read evaluates to the same value.
803Not all types of values are supported."
de9e2828
RS
804 (let* ((print-escape-newlines t)
805 (float-output-format nil)
69b2c07e
SM
806 (quote.sexp (desktop--v2s value))
807 (quote (car quote.sexp))
808 (txt
809 (let ((print-quoted t))
810 (prin1-to-string (cdr quote.sexp)))))
de9e2828
RS
811 (if (eq quote 'must)
812 (concat "'" txt)
813 txt)))
4a2fce7a 814
ec4c6f22 815;; ----------------------------------------------------------------------------
0e7c8611
RS
816(defun desktop-outvar (varspec)
817 "Output a setq statement for variable VAR to the desktop file.
818The argument VARSPEC may be the variable name VAR (a symbol),
be617bbf 819or a cons cell of the form (VAR . MAX-SIZE),
0e7c8611
RS
820which means to truncate VAR's value to at most MAX-SIZE elements
821\(if the value is a list) before saving the value."
822 (let (var size)
823 (if (consp varspec)
824 (setq var (car varspec) size (cdr varspec))
825 (setq var varspec))
1f7efe1b
JB
826 (when (boundp var)
827 (when (and (integerp size)
828 (> size 0)
829 (listp (eval var)))
830 (desktop-truncate (eval var) size))
831 (insert "(setq "
832 (symbol-name var)
833 " "
834 (desktop-value-to-string (symbol-value var))
835 ")\n"))))
4a2fce7a 836
0b9bd504 837;; ----------------------------------------------------------------------------
06b60517 838(defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
ebb39555 839 "Return t if buffer should have its state saved in the desktop file.
0b9bd504 840FILENAME is the visited file name, BUFNAME is the buffer name, and
be617bbf
JB
841MODE is the major mode.
842\n\(fn FILENAME BUFNAME MODE)"
b23caf75
GM
843 (let ((case-fold-search nil)
844 dired-skip)
a6c2c80c
EZ
845 (and (not (and (stringp desktop-buffers-not-to-save)
846 (not filename)
acfcc8c5 847 (string-match-p desktop-buffers-not-to-save bufname)))
ebb39555 848 (not (memq mode desktop-modes-not-to-save))
b23caf75 849 ;; FIXME this is broken if desktop-files-not-to-save is nil.
ebb39555 850 (or (and filename
a6c2c80c 851 (stringp desktop-files-not-to-save)
acfcc8c5 852 (not (string-match-p desktop-files-not-to-save filename)))
4ad900d9 853 (and (memq mode '(dired-mode vc-dir-mode))
ebb39555 854 (with-current-buffer bufname
b23caf75 855 (not (setq dired-skip
acfcc8c5
JB
856 (string-match-p desktop-files-not-to-save
857 default-directory)))))
ebb39555 858 (and (null filename)
b23caf75 859 (null dired-skip) ; bug#5755
ebb39555 860 (with-current-buffer bufname desktop-save-buffer))))))
4a2fce7a 861
0b9bd504 862;; ----------------------------------------------------------------------------
4a2fce7a
RS
863(defun desktop-file-name (filename dirname)
864 "Convert FILENAME to format specified in `desktop-file-name-format'.
865DIRNAME must be the directory in which the desktop file will be saved."
866 (cond
867 ((not filename) nil)
868 ((eq desktop-file-name-format 'tilde)
869 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
870 (cond
871 ((file-name-absolute-p relative-name) relative-name)
872 ((string= "./" relative-name) "~/")
873 ((string= "." relative-name) "~")
874 (t (concat "~/" relative-name)))))
875 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
876 (t (expand-file-name filename))))
e5714620 877
b3615392 878
4a2fce7a 879;; ----------------------------------------------------------------------------
b958c0ad
JB
880(defvar desktop-filter-parameters-alist
881 '((background-color . desktop--filter-*-color)
882 (buffer-list . t)
883 (buffer-predicate . t)
884 (buried-buffer-list . t)
885 (desktop-font . desktop--filter-restore-desktop-parm)
886 (desktop-fullscreen . desktop--filter-restore-desktop-parm)
887 (desktop-height . desktop--filter-restore-desktop-parm)
888 (desktop-width . desktop--filter-restore-desktop-parm)
889 (font . desktop--filter-save-desktop-parm)
890 (font-backend . t)
891 (foreground-color . desktop--filter-*-color)
892 (fullscreen . desktop--filter-save-desktop-parm)
893 (height . desktop--filter-save-desktop-parm)
728dc3cc 894 (left . desktop--filter-iconified-position)
b958c0ad
JB
895 (minibuffer . desktop--filter-minibuffer)
896 (name . t)
897 (outer-window-id . t)
898 (parent-id . t)
728dc3cc 899 (top . desktop--filter-iconified-position)
b958c0ad
JB
900 (tty . desktop--filter-tty*)
901 (tty-type . desktop--filter-tty*)
902 (width . desktop--filter-save-desktop-parm)
903 (window-id . t)
904 (window-system . t))
905 "Alist of frame parameters and filtering functions.
906
907Each element is a cons (PARAM . FILTER), where PARAM is a parameter
908name (a symbol identifying a frame parameter), and FILTER can be t
909\(meaning the parameter is removed from the parameter list on saving
910and restoring), or a function that will be called with three args:
911
912 CURRENT a cons (PARAM . VALUE), where PARAM is the one being
913 filtered and VALUE is its current value
914 PARAMETERS the complete alist of parameters being filtered
915 SAVING non-nil if filtering before saving state, nil otherwise
916
917The FILTER function must return:
918 nil CURRENT is removed from the list
919 t CURRENT is left as is
920 (PARAM' . VALUE') replace CURRENT with this
921
922Frame parameters not on this list are passed intact.")
923
924(defvar desktop--target-display nil
925 "Either (minibuffer . VALUE) or nil.
926This refers to the current frame config being processed inside
927`frame--restore-frames' and its auxiliary functions (like filtering).
928If nil, there is no need to change the display.
929If non-nil, display parameter to use when creating the frame.
930Internal use only.")
931
932(defun desktop-switch-to-gui-p (parameters)
933 "True when switching to a graphic display.
934Return t if PARAMETERS describes a text-only terminal and
935the target is a graphic display; otherwise return nil.
936Only meaningful when called from a filtering function in
937`desktop-filter-parameters-alist'."
938 (and desktop--target-display ; we're switching
939 (null (cdr (assq 'display parameters))) ; from a tty
940 (cdr desktop--target-display))) ; to a GUI display
941
942(defun desktop-switch-to-tty-p (parameters)
943 "True when switching to a text-only terminal.
944Return t if PARAMETERS describes a graphic display and
945the target is a text-only terminal; otherwise return nil.
946Only meaningful when called from a filtering function in
947`desktop-filter-parameters-alist'."
948 (and desktop--target-display ; we're switching
949 (cdr (assq 'display parameters)) ; from a GUI display
950 (null (cdr desktop--target-display)))) ; to a tty
951
952(defun desktop--filter-tty* (_current parameters saving)
953 ;; Remove tty and tty-type parameters when switching
954 ;; to a GUI frame.
955 (or saving
956 (not (desktop-switch-to-gui-p parameters))))
957
958(defun desktop--filter-*-color (current parameters saving)
959 ;; Remove (foreground|background)-color parameters
960 ;; when switching to a GUI frame if they denote an
961 ;; "unspecified" color.
962 (or saving
963 (not (desktop-switch-to-gui-p parameters))
964 (not (stringp (cdr current)))
965 (not (string-match-p "^unspecified-[fb]g$" (cdr current)))))
966
967(defun desktop--filter-minibuffer (current _parameters saving)
968 ;; When minibuffer is a window, save it as minibuffer . t
969 (or (not saving)
970 (if (windowp (cdr current))
971 '(minibuffer . t)
972 t)))
973
974(defun desktop--filter-restore-desktop-parm (current parameters saving)
975 ;; When switching to a GUI frame, convert desktop-XXX parameter to XXX
976 (or saving
977 (not (desktop-switch-to-gui-p parameters))
978 (let ((val (cdr current)))
979 (if (eq val :desktop-processed)
980 nil
981 (cons (intern (substring (symbol-name (car current))
982 8)) ;; (length "desktop-")
983 val)))))
984
985(defun desktop--filter-save-desktop-parm (current parameters saving)
986 ;; When switching to a tty frame, save parameter XXX as desktop-XXX so it
987 ;; can be restored in a subsequent GUI session, unless it already exists.
988 (cond (saving t)
989 ((desktop-switch-to-tty-p parameters)
990 (let ((sym (intern (format "desktop-%s" (car current)))))
991 (if (assq sym parameters)
992 nil
993 (cons sym (cdr current)))))
994 ((desktop-switch-to-gui-p parameters)
995 (let* ((dtp (assq (intern (format "desktop-%s" (car current)))
996 parameters))
997 (val (cdr dtp)))
998 (if (eq val :desktop-processed)
999 nil
1000 (setcdr dtp :desktop-processed)
1001 (cons (car current) val))))
1002 (t t)))
1003
728dc3cc
JB
1004(defun desktop--filter-iconified-position (_current parameters saving)
1005 ;; When saving an iconified frame, top & left are meaningless,
1006 ;; so remove them to allow restoring to a default position.
1007 (not (and saving (eq (cdr (assq 'visibility parameters)) 'icon))))
1008
b958c0ad
JB
1009(defun desktop-restore-in-original-display-p ()
1010 "True if saved frames' displays should be honored."
1011 (cond ((daemonp) t)
1012 ((eq system-type 'windows-nt) nil)
1013 (t (null desktop-restore-in-current-display))))
1014
1015(defun desktop--filter-frame-parms (parameters saving)
1016 "Filter frame parameters and return filtered list.
1017PARAMETERS is a parameter alist as returned by `frame-parameters'.
1018If SAVING is non-nil, filtering is happening before saving frame state;
1019otherwise, filtering is being done before restoring frame state.
1020Parameters are filtered according to the setting of
1021`desktop-filter-parameters-alist' (which see).
39c0e36f 1022Internal use only."
b958c0ad
JB
1023 (let ((filtered nil))
1024 (dolist (param parameters)
1025 (let ((filter (cdr (assq (car param) desktop-filter-parameters-alist)))
1026 this)
1027 (cond (;; no filter: pass param
1028 (null filter)
1029 (push param filtered))
1030 (;; filter = t; skip param
1031 (eq filter t))
1032 (;; filter func returns nil: skip param
1033 (null (setq this (funcall filter param parameters saving))))
1034 (;; filter func returns t: pass param
1035 (eq this t)
1036 (push param filtered))
1037 (;; filter func returns a new param: use it
1038 t
1039 (push this filtered)))))
1040 ;; Set the display parameter after filtering, so that filter functions
1041 ;; have access to its original value.
1042 (when desktop--target-display
1043 (let ((display (assq 'display filtered)))
1044 (if display
1045 (setcdr display (cdr desktop--target-display))
1046 (push desktop--target-display filtered))))
1047 filtered))
1048
a1c80d9d 1049(defun desktop--process-minibuffer-frames (frames)
b958c0ad
JB
1050 ;; Adds a desktop-mini parameter to frames
1051 ;; desktop-mini is a list (MINIBUFFER NUMBER DEFAULT?) where
1052 ;; MINIBUFFER t if the frame (including minibuffer-only) owns a minibuffer
1053 ;; NUMBER if MINIBUFFER = t, an ID for the frame; if nil, the ID of
1054 ;; the frame containing the minibuffer used by this frame
1055 ;; DEFAULT? if t, this frame is the value of default-minibuffer-frame
a1c80d9d 1056 (let ((count 0))
b958c0ad 1057 ;; Reset desktop-mini for all frames
a1c80d9d 1058 (dolist (frame (frame-list))
b958c0ad
JB
1059 (set-frame-parameter frame 'desktop-mini nil))
1060 ;; Number all frames with its own minibuffer
1061 (dolist (frame (minibuffer-frame-list))
1062 (set-frame-parameter frame 'desktop-mini
1063 (list t
a1c80d9d 1064 (cl-incf count)
b958c0ad
JB
1065 (eq frame default-minibuffer-frame))))
1066 ;; Now link minibufferless frames with their minibuffer frames
1067 (dolist (frame frames)
1068 (unless (frame-parameter frame 'desktop-mini)
a1c80d9d
JB
1069 (let ((mb-frame (window-frame (minibuffer-window frame))))
1070 ;; Frames whose minibuffer frame has been filtered out will have
1071 ;; desktop-mini = nil, so desktop-restore-frames will restore them
1072 ;; according to their minibuffer parameter. Set up desktop-mini
1073 ;; for the rest.
1074 (when (memq mb-frame frames)
1075 (set-frame-parameter frame 'desktop-mini
1076 (list nil
1077 (cl-second (frame-parameter mb-frame 'desktop-mini))
1078 nil))))))))
39c0e36f 1079
56bc453c 1080(defun desktop-save-frames ()
a1c80d9d
JB
1081 "Save frame state in `desktop-saved-frame-states'.
1082Runs the hook `desktop-before-saving-frames-functions'.
1083Frames with a non-nil `desktop-dont-save' parameter are not saved."
56bc453c 1084 (setq desktop-saved-frame-states
2addf922 1085 (and desktop-restore-frames
a1c80d9d
JB
1086 (let ((frames (cl-delete-if
1087 (lambda (frame)
1088 (run-hook-with-args 'desktop-before-saving-frames-functions frame)
1089 (frame-parameter frame 'desktop-dont-save))
1090 (frame-list))))
1091 ;; In case some frame was deleted by a hook function
1092 (setq frames (cl-delete-if-not #'frame-live-p frames))
1093 (desktop--process-minibuffer-frames frames)
b958c0ad
JB
1094 (mapcar (lambda (frame)
1095 (cons (desktop--filter-frame-parms (frame-parameters frame) t)
1096 (window-state-get (frame-root-window frame) t)))
a1c80d9d 1097 frames)))))
39c0e36f 1098
11425834 1099;;;###autoload
5db9dace 1100(defun desktop-save (dirname &optional release auto-save)
6b61353c
KH
1101 "Save the desktop in a desktop file.
1102Parameter DIRNAME specifies where to save the desktop file.
e88110db 1103Optional parameter RELEASE says whether we're done with this desktop.
5db9dace
JL
1104If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
1105and don't save the buffer if they are the same."
6343ed61 1106 (interactive "DDirectory to save desktop file in: ")
e88110db 1107 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
6343ed61 1108 (save-excursion
e88110db
JB
1109 (let ((eager desktop-restore-eager)
1110 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1111 (when
1112 (or (not new-modtime) ; nothing to overwrite
1113 (equal desktop-file-modtime new-modtime)
1114 (yes-or-no-p (if desktop-file-modtime
1115 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
1116 "Desktop file is more recent than the one loaded. Save anyway? "
1117 "Desktop file isn't the one loaded. Overwrite it? ")
1118 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1119 (unless release (error "Desktop file conflict")))
1120
1121 ;; If we're done with it, release the lock.
1122 ;; Otherwise, claim it if it's unclaimed or if we created it.
1123 (if release
1124 (desktop-release-lock)
1125 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
1126
1127 (with-temp-buffer
1128 (insert
1129 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
1130 desktop-header
1131 ";; Created " (current-time-string) "\n"
1132 ";; Desktop file format version " desktop-file-version "\n"
1133 ";; Emacs version " emacs-version "\n")
1134 (save-excursion (run-hooks 'desktop-save-hook))
1135 (goto-char (point-max))
1136 (insert "\n;; Global section:\n")
39c0e36f
JB
1137 ;; Called here because we save the window/frame state as a global
1138 ;; variable for compatibility with previous Emacsen.
56bc453c
JB
1139 (desktop-save-frames)
1140 (unless (memq 'desktop-saved-frame-states desktop-globals-to-save)
1141 (desktop-outvar 'desktop-saved-frame-states))
e88110db 1142 (mapc (function desktop-outvar) desktop-globals-to-save)
56bc453c 1143 (setq desktop-saved-frame-states nil) ; after saving desktop-globals-to-save
e88110db
JB
1144 (when (memq 'kill-ring desktop-globals-to-save)
1145 (insert
1146 "(setq kill-ring-yank-pointer (nthcdr "
1147 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
1148 " kill-ring))\n"))
1149
1150 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
1151 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
a8049a30
JB
1152 (let ((base (pop l)))
1153 (when (apply 'desktop-save-buffer-p l)
1154 (insert "("
1155 (if (or (not (integerp eager))
1156 (if (zerop eager)
1157 nil
1158 (setq eager (1- eager))))
1159 "desktop-create-buffer"
1160 "desktop-append-buffer-args")
1161 " "
1162 desktop-file-version)
ae4370a8
JB
1163 ;; If there's a non-empty base name, we save it instead of the buffer name
1164 (when (and base (not (string= base "")))
1165 (setcar (nthcdr 1 l) base))
a8049a30
JB
1166 (dolist (e l)
1167 (insert "\n " (desktop-value-to-string e)))
1168 (insert ")\n\n"))))
e88110db 1169
9e29c91c 1170 (setq default-directory desktop-dirname)
5db9dace
JL
1171 ;; If auto-saving, avoid writing if nothing has changed since the last write.
1172 ;; Don't check 300 characters of the header that contains the timestamp.
1173 (let ((checksum (and auto-save (md5 (current-buffer)
1174 (+ (point-min) 300) (point-max)
1175 'emacs-mule))))
1176 (unless (and auto-save (equal checksum desktop-file-checksum))
1177 (let ((coding-system-for-write 'emacs-mule))
1178 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1179 (setq desktop-file-checksum checksum)
1180 ;; We remember when it was modified (which is presumably just now).
1181 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
4a2fce7a 1182
0b9bd504 1183;; ----------------------------------------------------------------------------
11425834 1184;;;###autoload
6343ed61 1185(defun desktop-remove ()
6b61353c
KH
1186 "Delete desktop file in `desktop-dirname'.
1187This function also sets `desktop-dirname' to nil."
6343ed61 1188 (interactive)
6b61353c 1189 (when desktop-dirname
11425834 1190 (let ((filename (desktop-full-file-name)))
6b61353c
KH
1191 (setq desktop-dirname nil)
1192 (when (file-exists-p filename)
73b0b745 1193 (delete-file filename)))))
6b61353c 1194
150f39ee
LH
1195(defvar desktop-buffer-args-list nil
1196 "List of args for `desktop-create-buffer'.")
1197
1198(defvar desktop-lazy-timer nil)
1199
0b9bd504 1200;; ----------------------------------------------------------------------------
b958c0ad
JB
1201(defvar desktop--reuse-list nil
1202 "Internal use only.")
1203
1204(defun desktop--find-frame (predicate display &rest args)
1205 "Find a suitable frame in `desktop--reuse-list'.
1206Look through frames whose display property matches DISPLAY and
1207return the first one for which (PREDICATE frame ARGS) returns t.
1208If PREDICATE is nil, it is always satisfied. Internal use only.
1209This is an auxiliary function for `desktop--select-frame'."
a1c80d9d
JB
1210 (cl-find-if (lambda (frame)
1211 (and (equal (frame-parameter frame 'display) display)
1212 (or (null predicate)
1213 (apply predicate frame args))))
1214 desktop--reuse-list))
b958c0ad
JB
1215
1216(defun desktop--select-frame (display frame-cfg)
1217 "Look for an existing frame to reuse.
1218DISPLAY is the display where the frame will be shown, and FRAME-CFG
1219is the parameter list of the frame being restored. Internal use only."
1220 (if (eq desktop-restoring-reuses-frames t)
1221 (let ((frame nil)
1222 mini)
1223 ;; There are no fancy heuristics there. We could implement some
1224 ;; based on frame size and/or position, etc., but it is not clear
1225 ;; that any "gain" (in the sense of reduced flickering, etc.) is
1226 ;; worth the added complexity. In fact, the code below mainly
1227 ;; tries to work nicely when M-x desktop-read is used after a desktop
1228 ;; session has already been loaded. The other main use case, which
1229 ;; is the initial desktop-read upon starting Emacs, should usually
1230 ;; only have one, or very few, frame(s) to reuse.
1231 (cond (;; When the target is tty, every existing frame is reusable.
1232 (null display)
1233 (setq frame (desktop--find-frame nil display)))
1234 (;; If the frame has its own minibuffer, let's see whether
1235 ;; that frame has already been loaded (which can happen after
1236 ;; M-x desktop-read).
1237 (car (setq mini (cdr (assq 'desktop-mini frame-cfg))))
1238 (setq frame (or (desktop--find-frame
1239 (lambda (f m)
1240 (equal (frame-parameter f 'desktop-mini) m))
1241 display mini))))
1242 (;; For minibufferless frames, check whether they already exist,
1243 ;; and that they are linked to the right minibuffer frame.
1244 mini
1245 (setq frame (desktop--find-frame
1246 (lambda (f n)
1247 (let ((m (frame-parameter f 'desktop-mini)))
1248 (and m
a1c80d9d
JB
1249 (null (cl-first m))
1250 (= (cl-second m) n)
1251 (equal (cl-second (frame-parameter
1252 (window-frame (minibuffer-window f))
1253 'desktop-mini))
b958c0ad 1254 n))))
a1c80d9d 1255 display (cl-second mini))))
b958c0ad
JB
1256 (;; Default to just finding a frame in the same display.
1257 t
1258 (setq frame (desktop--find-frame nil display))))
1259 ;; If found, remove from the list.
1260 (when frame
1261 (setq desktop--reuse-list (delq frame desktop--reuse-list)))
a47cbd64 1262 frame)
b958c0ad
JB
1263 nil))
1264
1265(defun desktop--make-frame (frame-cfg window-cfg)
1266 "Set up a frame according to its saved state.
1267That means either creating a new frame or reusing an existing one.
1268FRAME-CFG is the parameter list of the new frame; WINDOW-CFG is
1269its window state. Internal use only."
1270 (let* ((fullscreen (cdr (assq 'fullscreen frame-cfg)))
1271 (lines (assq 'tool-bar-lines frame-cfg))
1272 (filtered-cfg (desktop--filter-frame-parms frame-cfg nil))
1273 (display (cdr (assq 'display filtered-cfg))) ;; post-filtering
1274 alt-cfg frame)
1275
1276 ;; This works around bug#14795 (or feature#14795, if not a bug :-)
1277 (setq filtered-cfg (assq-delete-all 'tool-bar-lines filtered-cfg))
1278 (push '(tool-bar-lines . 0) filtered-cfg)
1279
1280 (when fullscreen
1281 ;; Currently Emacs has the limitation that it does not record the size
1282 ;; and position of a frame before maximizing it, so we cannot save &
1283 ;; restore that info. Instead, when restoring, we resort to creating
1284 ;; invisible "fullscreen" frames of default size and then maximizing them
1285 ;; (and making them visible) which at least is somewhat user-friendly
1286 ;; when these frames are later de-maximized.
1287 (let ((width (and (eq fullscreen 'fullheight) (cdr (assq 'width filtered-cfg))))
1288 (height (and (eq fullscreen 'fullwidth) (cdr (assq 'height filtered-cfg))))
1289 (visible (assq 'visibility filtered-cfg)))
a1c80d9d
JB
1290 (setq filtered-cfg (cl-delete-if (lambda (p)
1291 (memq p '(visibility fullscreen width height)))
1292 filtered-cfg))
b958c0ad
JB
1293 (when width
1294 (setq filtered-cfg (append `((user-size . t) (width . ,width))
1295 filtered-cfg)))
1296 (when height
1297 (setq filtered-cfg (append `((user-size . t) (height . ,height))
1298 filtered-cfg)))
1299 ;; These are parameters to apply after creating/setting the frame.
1300 (push visible alt-cfg)
1301 (push (cons 'fullscreen fullscreen) alt-cfg)))
1302
1303 ;; Time to select or create a frame an apply the big bunch of parameters
1304 (if (setq frame (desktop--select-frame display filtered-cfg))
1305 (modify-frame-parameters frame filtered-cfg)
1306 (setq frame (make-frame-on-display display filtered-cfg)))
1307
1308 ;; Let's give the finishing touches (visibility, tool-bar, maximization).
1309 (when lines (push lines alt-cfg))
1310 (when alt-cfg (modify-frame-parameters frame alt-cfg))
1311 ;; Now restore window state.
1312 (window-state-put window-cfg (frame-root-window frame) 'safe)
a47cbd64
JB
1313 frame))
1314
b958c0ad
JB
1315(defun desktop--sort-states (state1 state2)
1316 ;; Order: default minibuffer frame
1317 ;; other frames with minibuffer, ascending ID
1318 ;; minibufferless frames, ascending ID
1319 (let ((dm1 (cdr (assq 'desktop-mini (car state1))))
1320 (dm2 (cdr (assq 'desktop-mini (car state2)))))
a1c80d9d
JB
1321 (cond ((cl-third dm1) t)
1322 ((cl-third dm2) nil)
1323 ((eq (cl-first dm1) (cl-first dm2))
1324 (< (cl-second dm1) (cl-second dm2)))
1325 (t
1326 (cl-first dm1)))))
b958c0ad 1327
56bc453c
JB
1328(defun desktop-restoring-frames-p ()
1329 "True if calling `desktop-restore-frames' will actually restore frames."
1330 (and desktop-restore-frames desktop-saved-frame-states))
1331
1332(defun desktop-restore-frames ()
39c0e36f 1333 "Restore window/frame configuration.
56bc453c
JB
1334This function depends on the value of `desktop-saved-frame-states'
1335being set (usually, by reading it from the desktop)."
1336 (when (desktop-restoring-frames-p)
b958c0ad 1337 (let* ((frame-mb-map nil) ;; Alist of frames with their own minibuffer
b958c0ad
JB
1338 (delete-saved (eq desktop-restore-in-current-display 'delete))
1339 (forcing (not (desktop-restore-in-original-display-p)))
1340 (target (and forcing (cons 'display (frame-parameter nil 'display)))))
1341
1342 ;; Sorting saved states allows us to easily restore minibuffer-owning frames
1343 ;; before minibufferless ones.
56bc453c
JB
1344 (setq desktop-saved-frame-states (sort desktop-saved-frame-states
1345 #'desktop--sort-states))
b958c0ad
JB
1346 ;; Potentially all existing frames are reusable. Later we will decide which ones
1347 ;; to reuse, and how to deal with any leftover.
1348 (setq desktop--reuse-list (frame-list))
1349
56bc453c 1350 (dolist (state desktop-saved-frame-states)
a47cbd64 1351 (condition-case err
b958c0ad
JB
1352 (let* ((frame-cfg (car state))
1353 (window-cfg (cdr state))
1354 (d-mini (cdr (assq 'desktop-mini frame-cfg)))
1355 num frame to-tty)
1356 ;; Only set target if forcing displays and the target display is different.
1357 (if (or (not forcing)
1358 (equal target (or (assq 'display frame-cfg) '(display . nil))))
1359 (setq desktop--target-display nil)
1360 (setq desktop--target-display target
1361 to-tty (null (cdr target))))
1362 ;; Time to restore frames and set up their minibuffers as they were.
1363 ;; We only skip a frame (thus deleting it) if either:
1364 ;; - we're switching displays, and the user chose the option to delete, or
1365 ;; - we're switching to tty, and the frame to restore is minibuffer-only.
1366 (unless (and desktop--target-display
1367 (or delete-saved
1368 (and to-tty
1369 (eq (cdr (assq 'minibuffer frame-cfg)) 'only))))
1370
1371 ;; Restore minibuffers. Some of this stuff could be done in a filter
1372 ;; function, but it would be messy because restoring minibuffers affects
1373 ;; global state; it's best to do it here than add a bunch of global
1374 ;; variables to pass info back-and-forth to/from the filter function.
1375 (cond
1376 ((null d-mini)) ;; No desktop-mini. Process as normal frame.
1377 (to-tty) ;; Ignore minibuffer stuff and process as normal frame.
a1c80d9d
JB
1378 ((cl-first d-mini) ;; Frame has minibuffer (or it is minibuffer-only).
1379 (setq num (cl-second d-mini))
b958c0ad
JB
1380 (when (eq (cdr (assq 'minibuffer frame-cfg)) 'only)
1381 (setq frame-cfg (append '((tool-bar-lines . 0) (menu-bar-lines . 0))
1382 frame-cfg))))
02c66599 1383 (t ;; Frame depends on other frame's minibuffer window.
a1c80d9d 1384 (let ((mb-frame (cdr (assq (cl-second d-mini) frame-mb-map))))
b958c0ad 1385 (unless (frame-live-p mb-frame)
a1c80d9d 1386 (error "Minibuffer frame %s not found" (cl-second d-mini)))
b958c0ad
JB
1387 (let ((mb-param (assq 'minibuffer frame-cfg))
1388 (mb-window (minibuffer-window mb-frame)))
1389 (unless (and (window-live-p mb-window)
1390 (window-minibuffer-p mb-window))
1391 (error "Not a minibuffer window %s" mb-window))
1392 (if mb-param
1393 (setcdr mb-param mb-window)
1394 (push (cons 'minibuffer mb-window) frame-cfg))))))
1395 ;; OK, we're ready at last to create (or reuse) a frame and
1396 ;; restore the window config.
1397 (setq frame (desktop--make-frame frame-cfg window-cfg))
1398 ;; Set default-minibuffer if required.
a1c80d9d 1399 (when (cl-third d-mini) (setq default-minibuffer-frame frame))
b958c0ad 1400 ;; Store frame/NUM to assign to minibufferless frames.
a1c80d9d 1401 (when num (push (cons num frame) frame-mb-map))))
a47cbd64 1402 (error
b958c0ad
JB
1403 (delay-warning 'desktop (error-message-string err) :error))))
1404
1405 ;; Delete remaining frames, but do not fail if some resist being deleted.
1406 (unless (eq desktop-restoring-reuses-frames 'keep)
1407 (dolist (frame desktop--reuse-list)
1408 (ignore-errors (delete-frame frame))))
1409 (setq desktop--reuse-list nil)
1410 ;; Make sure there's at least one visible frame, and select it.
a1c80d9d
JB
1411 (unless (or (daemonp)
1412 (cl-find-if #'frame-visible-p (frame-list)))
1413 (let ((visible (if (frame-live-p default-minibuffer-frame)
1414 default-minibuffer-frame
1415 (car (frame-list)))))
1416 (make-frame-visible visible)
1417 (select-frame-set-input-focus visible))))))
39c0e36f 1418
478653c9 1419;;;###autoload
6b61353c
KH
1420(defun desktop-read (&optional dirname)
1421 "Read and process the desktop file in directory DIRNAME.
1422Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1423directories listed in `desktop-path'. If a desktop file is found, it
cc8b76bf 1424is processed and `desktop-after-read-hook' is run. If no desktop file
6b61353c
KH
1425is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1426This function is a no-op when Emacs is running in batch mode.
1427It returns t if a desktop file was loaded, nil otherwise."
6343ed61 1428 (interactive)
4a2fce7a 1429 (unless noninteractive
6b61353c 1430 (setq desktop-dirname
11425834
LH
1431 (file-name-as-directory
1432 (expand-file-name
1433 (or
1434 ;; If DIRNAME is specified, use it.
1435 (and (< 0 (length dirname)) dirname)
1436 ;; Otherwise search desktop file in desktop-path.
1437 (let ((dirs desktop-path))
1438 (while (and dirs
1439 (not (file-exists-p
1440 (desktop-full-file-name (car dirs)))))
1441 (setq dirs (cdr dirs)))
1442 (and dirs (car dirs)))
1443 ;; If not found and `desktop-path' is non-nil, use its first element.
1444 (and desktop-path (car desktop-path))
6b67c0d4
CY
1445 ;; Default: .emacs.d.
1446 user-emacs-directory))))
11425834 1447 (if (file-exists-p (desktop-full-file-name))
e88110db
JB
1448 ;; Desktop file found, but is it already in use?
1449 (let ((desktop-first-buffer nil)
1450 (desktop-buffer-ok-count 0)
1451 (desktop-buffer-fail-count 0)
1452 (owner (desktop-owner))
1453 ;; Avoid desktop saving during evaluation of desktop buffer.
1454 (desktop-save nil))
1455 (if (and owner
1f7efe1b
JB
1456 (memq desktop-load-locked-desktop '(nil ask))
1457 (or (null desktop-load-locked-desktop)
e76f0800 1458 (daemonp)
1f7efe1b
JB
1459 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1460Using it may cause conflicts. Use it anyway? " owner)))))
c41cf130 1461 (let ((default-directory desktop-dirname))
794855ca 1462 (setq desktop-dirname nil)
c41cf130
JB
1463 (run-hooks 'desktop-not-loaded-hook)
1464 (unless desktop-dirname
1465 (message "Desktop file in use; not loaded.")))
e88110db
JB
1466 (desktop-lazy-abort)
1467 ;; Evaluate desktop buffer and remember when it was modified.
1468 (load (desktop-full-file-name) t t t)
1469 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1470 ;; If it wasn't already, mark it as in-use, to bother other
1471 ;; desktop instances.
1472 (unless owner
1473 (condition-case nil
1474 (desktop-claim-lock)
1475 (file-error (message "Couldn't record use of desktop file")
1476 (sit-for 1))))
1477
56bc453c
JB
1478 (unless (desktop-restoring-frames-p)
1479 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1480 ;; We want buffers existing prior to evaluating the desktop (and
1481 ;; not reused) to be placed at the end of the buffer list, so we
1482 ;; move them here.
1483 (mapc 'bury-buffer
1484 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1485 (switch-to-buffer (car (buffer-list))))
e88110db
JB
1486 (run-hooks 'desktop-delay-hook)
1487 (setq desktop-delay-hook nil)
56bc453c 1488 (desktop-restore-frames)
e88110db
JB
1489 (run-hooks 'desktop-after-read-hook)
1490 (message "Desktop: %d buffer%s restored%s%s."
1491 desktop-buffer-ok-count
1492 (if (= 1 desktop-buffer-ok-count) "" "s")
1493 (if (< 0 desktop-buffer-fail-count)
1494 (format ", %d failed to restore" desktop-buffer-fail-count)
1495 "")
1496 (if desktop-buffer-args-list
1497 (format ", %d to restore lazily"
1498 (length desktop-buffer-args-list))
1499 ""))
56bc453c
JB
1500 (unless (desktop-restoring-frames-p)
1501 ;; Bury the *Messages* buffer to not reshow it when burying
1502 ;; the buffer we switched to above.
1503 (when (buffer-live-p (get-buffer "*Messages*"))
1504 (bury-buffer "*Messages*"))
1505 ;; Clear all windows' previous and next buffers, these have
1506 ;; been corrupted by the `switch-to-buffer' calls in
1507 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1508 ;; brute force fix and should be replaced by a more subtle
1509 ;; strategy eventually.
1510 (walk-window-tree (lambda (window)
1511 (set-window-prev-buffers window nil)
1512 (set-window-next-buffers window nil))))
e88110db 1513 t))
6b61353c
KH
1514 ;; No desktop file found.
1515 (desktop-clear)
1516 (let ((default-directory desktop-dirname))
1517 (run-hooks 'desktop-no-desktop-file-hook))
1518 (message "No desktop file.")
1519 nil)))
4a2fce7a 1520
0b9bd504 1521;; ----------------------------------------------------------------------------
6b61353c 1522;; Maintained for backward compatibility
478653c9 1523;;;###autoload
6343ed61 1524(defun desktop-load-default ()
577ed2b2 1525 "Load the `default' start-up library manually.
6b61353c 1526Also inhibit further loading of it."
59f7af81 1527 (declare (obsolete desktop-save-mode "22.1"))
b89c5a72
JB
1528 (unless inhibit-default-init ; safety check
1529 (load "default" t t)
1530 (setq inhibit-default-init t)))
4a2fce7a
RS
1531
1532;; ----------------------------------------------------------------------------
1533;;;###autoload
6b61353c
KH
1534(defun desktop-change-dir (dirname)
1535 "Change to desktop saved in DIRNAME.
1536Kill the desktop as specified by variables `desktop-save-mode' and
1537`desktop-save', then clear the desktop and load the desktop file in
1538directory DIRNAME."
1539 (interactive "DChange to directory: ")
1540 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
4a2fce7a
RS
1541 (desktop-kill)
1542 (desktop-clear)
6b61353c 1543 (desktop-read dirname))
bf247b6e 1544
6b61353c 1545;; ----------------------------------------------------------------------------
4a2fce7a 1546;;;###autoload
6b61353c
KH
1547(defun desktop-save-in-desktop-dir ()
1548 "Save the desktop in directory `desktop-dirname'."
4a2fce7a
RS
1549 (interactive)
1550 (if desktop-dirname
b89c5a72 1551 (desktop-save desktop-dirname)
4a2fce7a 1552 (call-interactively 'desktop-save))
a609d13b 1553 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
4a2fce7a 1554
5db9dace
JL
1555;; ----------------------------------------------------------------------------
1556;; Auto-Saving.
1557(defvar desktop-auto-save-timer nil)
1558
1559(defun desktop-auto-save ()
1560 "Save the desktop periodically.
1561Called by the timer created in `desktop-auto-save-set-timer'."
1562 (when (and desktop-save-mode
1563 (integerp desktop-auto-save-timeout)
1564 (> desktop-auto-save-timeout 0)
1565 ;; Avoid desktop saving during lazy loading.
1566 (not desktop-lazy-timer)
1567 ;; Save only to own desktop file.
1568 (eq (emacs-pid) (desktop-owner))
1569 desktop-dirname)
1570 (desktop-save desktop-dirname nil t))
1571 (desktop-auto-save-set-timer))
1572
1573(defun desktop-auto-save-set-timer ()
1574 "Reset the auto-save timer.
1575Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1576integer, start a new timer to call `desktop-auto-save' in that many seconds."
1577 (when desktop-auto-save-timer
1578 (cancel-timer desktop-auto-save-timer)
1579 (setq desktop-auto-save-timer nil))
1580 (when (and (integerp desktop-auto-save-timeout)
1581 (> desktop-auto-save-timeout 0))
1582 (setq desktop-auto-save-timer
1583 (run-with-timer desktop-auto-save-timeout nil
1584 'desktop-auto-save))))
1585
4a2fce7a
RS
1586;; ----------------------------------------------------------------------------
1587;;;###autoload
1588(defun desktop-revert ()
1589 "Revert to the last loaded desktop."
1590 (interactive)
6b61353c
KH
1591 (unless desktop-dirname
1592 (error "Unknown desktop directory"))
11425834 1593 (unless (file-exists-p (desktop-full-file-name))
6b61353c
KH
1594 (error "No desktop file found"))
1595 (desktop-clear)
1596 (desktop-read desktop-dirname))
4a2fce7a 1597
341c2f07
SM
1598(defvar desktop-buffer-major-mode)
1599(defvar desktop-buffer-locals)
06b60517 1600(defvar auto-insert) ; from autoinsert.el
0b9bd504 1601;; ----------------------------------------------------------------------------
06b60517
JB
1602(defun desktop-restore-file-buffer (buffer-filename
1603 _buffer-name
1604 _buffer-misc)
e5780ae1 1605 "Restore a file buffer."
06b60517
JB
1606 (when buffer-filename
1607 (if (or (file-exists-p buffer-filename)
1f7efe1b 1608 (let ((msg (format "Desktop: File \"%s\" no longer exists."
06b60517 1609 buffer-filename)))
1f7efe1b
JB
1610 (if desktop-missing-file-warning
1611 (y-or-n-p (concat msg " Re-create buffer? "))
1612 (message "%s" msg)
1613 nil)))
1614 (let* ((auto-insert nil) ; Disable auto insertion
1615 (coding-system-for-read
1616 (or coding-system-for-read
1617 (cdr (assq 'buffer-file-coding-system
1618 desktop-buffer-locals))))
06b60517 1619 (buf (find-file-noselect buffer-filename)))
1f7efe1b
JB
1620 (condition-case nil
1621 (switch-to-buffer buf)
1622 (error (pop-to-buffer buf)))
1623 (and (not (eq major-mode desktop-buffer-major-mode))
1624 (functionp desktop-buffer-major-mode)
1625 (funcall desktop-buffer-major-mode))
1626 buf)
1627 nil)))
4a2fce7a 1628
0f4804e7
LH
1629(defun desktop-load-file (function)
1630 "Load the file where auto loaded FUNCTION is defined."
7abaf5cc
SM
1631 (when (fboundp function)
1632 (autoload-do-load (symbol-function function) function)))
0f4804e7 1633
0b9bd504 1634;; ----------------------------------------------------------------------------
eb982898
JL
1635;; Create a buffer, load its file, set its mode, ...;
1636;; called from Desktop file only.
1d500ca6 1637
0f4804e7 1638;; Just to silence the byte compiler.
341c2f07
SM
1639
1640(defvar desktop-first-buffer) ; Dynamically bound in `desktop-read'
1641
1642;; Bound locally in `desktop-read'.
1643(defvar desktop-buffer-ok-count)
1644(defvar desktop-buffer-fail-count)
4a2fce7a 1645
340db502 1646(defun desktop-create-buffer
06b60517
JB
1647 (file-version
1648 buffer-filename
1649 buffer-name
1650 buffer-majormode
1651 buffer-minormodes
1652 buffer-point
1653 buffer-mark
1654 buffer-readonly
1655 buffer-misc
1656 &optional
1657 buffer-locals)
1658
1659 (let ((desktop-file-version file-version)
1660 (desktop-buffer-file-name buffer-filename)
1661 (desktop-buffer-name buffer-name)
1662 (desktop-buffer-major-mode buffer-majormode)
1663 (desktop-buffer-minor-modes buffer-minormodes)
1664 (desktop-buffer-point buffer-point)
1665 (desktop-buffer-mark buffer-mark)
1666 (desktop-buffer-read-only buffer-readonly)
1667 (desktop-buffer-misc buffer-misc)
1668 (desktop-buffer-locals buffer-locals))
1669 ;; To make desktop files with relative file names possible, we cannot
1670 ;; allow `default-directory' to change. Therefore we save current buffer.
1671 (save-current-buffer
1672 ;; Give major mode module a chance to add a handler.
1673 (desktop-load-file desktop-buffer-major-mode)
1674 (let ((buffer-list (buffer-list))
1675 (result
1be3ca5a 1676 (condition-case-unless-debug err
06b60517
JB
1677 (funcall (or (cdr (assq desktop-buffer-major-mode
1678 desktop-buffer-mode-handlers))
1679 'desktop-restore-file-buffer)
1680 desktop-buffer-file-name
1681 desktop-buffer-name
1682 desktop-buffer-misc)
1683 (error
1684 (message "Desktop: Can't load buffer %s: %s"
1685 desktop-buffer-name
1686 (error-message-string err))
1687 (when desktop-missing-file-warning (sit-for 1))
1688 nil))))
1689 (if (bufferp result)
1690 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1691 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1692 (setq result nil))
1693 ;; Restore buffer list order with new buffer at end. Don't change
91af3942 1694 ;; the order for old desktop files (old desktop module behavior).
06b60517
JB
1695 (unless (< desktop-file-version 206)
1696 (mapc 'bury-buffer buffer-list)
1697 (when result (bury-buffer result)))
1698 (when result
1699 (unless (or desktop-first-buffer (< desktop-file-version 206))
1700 (setq desktop-first-buffer result))
1701 (set-buffer result)
1702 (unless (equal (buffer-name) desktop-buffer-name)
1703 (rename-buffer desktop-buffer-name t))
1704 ;; minor modes
1705 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1706 (auto-fill-mode 1))
1707 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1708 (auto-fill-mode 0))
1709 (t
1710 (dolist (minor-mode desktop-buffer-minor-modes)
1711 ;; Give minor mode module a chance to add a handler.
1712 (desktop-load-file minor-mode)
1713 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1714 (if handler
1715 (funcall handler desktop-buffer-locals)
1716 (when (functionp minor-mode)
1717 (funcall minor-mode 1)))))))
1718 ;; Even though point and mark are non-nil when written by
1719 ;; `desktop-save', they may be modified by handlers wanting to set
1720 ;; point or mark themselves.
1721 (when desktop-buffer-point
1722 (goto-char
1723 (condition-case err
1724 ;; Evaluate point. Thus point can be something like
1725 ;; '(search-forward ...
1726 (eval desktop-buffer-point)
1727 (error (message "%s" (error-message-string err)) 1))))
1728 (when desktop-buffer-mark
1729 (if (consp desktop-buffer-mark)
1f7efe1b 1730 (progn
06b60517
JB
1731 (set-mark (car desktop-buffer-mark))
1732 (setq mark-active (car (cdr desktop-buffer-mark))))
1733 (set-mark desktop-buffer-mark)))
1734 ;; Never override file system if the file really is read-only marked.
1735 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
b61d71e4
JB
1736 (dolist (this desktop-buffer-locals)
1737 (if (consp this)
1738 ;; an entry of this form `(symbol . value)'
1739 (progn
1740 (make-local-variable (car this))
1741 (set (car this) (cdr this)))
1742 ;; an entry of the form `symbol'
1743 (make-local-variable this)
1744 (makunbound this))))))))
ec4c6f22 1745
4a2fce7a 1746;; ----------------------------------------------------------------------------
ec4c6f22 1747;; Backward compatibility -- update parameters to 205 standards.
06b60517
JB
1748(defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1749 mim pt mk ro tl fc cfs cr buffer-misc)
1750 (desktop-create-buffer 205 buffer-filename buffer-name
1751 buffer-majormode (cdr mim) pt mk ro
1752 buffer-misc
ec4c6f22
RS
1753 (list (cons 'truncate-lines tl)
1754 (cons 'fill-column fc)
1755 (cons 'case-fold-search cfs)
1756 (cons 'case-replace cr)
1757 (cons 'overwrite-mode (car mim)))))
84b538ec 1758
150f39ee 1759(defun desktop-append-buffer-args (&rest args)
cc8b76bf 1760 "Append ARGS at end of `desktop-buffer-args-list'.
150f39ee
LH
1761ARGS must be an argument list for `desktop-create-buffer'."
1762 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1763 (unless desktop-lazy-timer
1764 (setq desktop-lazy-timer
1765 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1766
1767(defun desktop-lazy-create-buffer ()
1768 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1769 (when desktop-buffer-args-list
1770 (let* ((remaining (length desktop-buffer-args-list))
1771 (args (pop desktop-buffer-args-list))
1772 (buffer-name (nth 2 args))
1773 (msg (format "Desktop lazily opening %s (%s remaining)..."
1774 buffer-name remaining)))
1775 (when desktop-lazy-verbose
8a26c165 1776 (message "%s" msg))
150f39ee
LH
1777 (let ((desktop-first-buffer nil)
1778 (desktop-buffer-ok-count 0)
1779 (desktop-buffer-fail-count 0))
1780 (apply 'desktop-create-buffer args)
1781 (run-hooks 'desktop-delay-hook)
1782 (setq desktop-delay-hook nil)
1783 (bury-buffer (get-buffer buffer-name))
1784 (when desktop-lazy-verbose
1785 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1786
1787(defun desktop-idle-create-buffers ()
1788 "Create buffers until the user does something, then stop.
1789If there are no buffers left to create, kill the timer."
1790 (let ((repeat 1))
1791 (while (and repeat desktop-buffer-args-list)
1792 (save-window-excursion
1793 (desktop-lazy-create-buffer))
1794 (setq repeat (sit-for 0.2))
1795 (unless desktop-buffer-args-list
1796 (cancel-timer desktop-lazy-timer)
1797 (setq desktop-lazy-timer nil)
1798 (message "Lazy desktop load complete")
1799 (sit-for 3)
1800 (message "")))))
1801
1802(defun desktop-lazy-complete ()
1803 "Run the desktop load to completion."
1804 (interactive)
1805 (let ((desktop-lazy-verbose t))
1806 (while desktop-buffer-args-list
1807 (save-window-excursion
1808 (desktop-lazy-create-buffer)))
1809 (message "Lazy desktop load complete")))
1810
1811(defun desktop-lazy-abort ()
1812 "Abort lazy loading of the desktop."
1813 (interactive)
1814 (when desktop-lazy-timer
1815 (cancel-timer desktop-lazy-timer)
1816 (setq desktop-lazy-timer nil))
1817 (when desktop-buffer-args-list
1818 (setq desktop-buffer-args-list nil)
32226619 1819 (when (called-interactively-p 'interactive)
150f39ee
LH
1820 (message "Lazy desktop load aborted"))))
1821
0b9bd504 1822;; ----------------------------------------------------------------------------
6b61353c 1823;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
4a2fce7a
RS
1824;; command line, we do the rest of what it takes to use desktop, but do it
1825;; after finishing loading the init file.
1826;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1827;; functions are processed after `after-init-hook'.
1828(add-hook
1829 'after-init-hook
341c2f07 1830 (lambda ()
4a2fce7a 1831 (let ((key "--no-desktop"))
4b217d46
LH
1832 (when (member key command-line-args)
1833 (setq command-line-args (delete key command-line-args))
1834 (setq desktop-save-mode nil)))
54d22a6f
JL
1835 (when desktop-save-mode
1836 (desktop-read)
5db9dace 1837 (desktop-auto-save-set-timer)
54d22a6f 1838 (setq inhibit-startup-screen t))))
813dbb2d 1839
f12ad6ec
GM
1840;; So we can restore vc-dir buffers.
1841(autoload 'vc-dir-mode "vc-dir" nil t)
1842
ab1d55ea 1843(provide 'desktop)
6343ed61 1844
80f9f3db 1845;;; desktop.el ends here