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