Revert introduction of isearch-filter-predicates.
[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 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
5db9dace
JL
195(defcustom desktop-auto-save-timeout nil
196 "Number of seconds between auto-saves of the desktop.
197Zero or nil means disable timer-based auto-saving."
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)
387 (const :tag "Delete frames in other displays" 'delete))
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.
d5671a82 393If `:all', frames that are partially offscreen are also forced onscren.
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))
673 (mini (window-frame (minibuffer-window this)))) ; in case they difer
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
9421876d
JB
913 (let ((name (concat user-login-name "@" system-name
914 (format-time-string " %Y-%m-%d %T"))))
915 (frameset-save nil
9421876d
JB
916 :predicate #'desktop--check-dont-save
917 :properties (list :app desktop--app-id
918 :name name))))))
39c0e36f 919
11425834 920;;;###autoload
5db9dace 921(defun desktop-save (dirname &optional release auto-save)
6b61353c
KH
922 "Save the desktop in a desktop file.
923Parameter DIRNAME specifies where to save the desktop file.
e88110db 924Optional parameter RELEASE says whether we're done with this desktop.
5db9dace
JL
925If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
926and don't save the buffer if they are the same."
6343ed61 927 (interactive "DDirectory to save desktop file in: ")
e88110db 928 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
6343ed61 929 (save-excursion
e88110db
JB
930 (let ((eager desktop-restore-eager)
931 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
932 (when
933 (or (not new-modtime) ; nothing to overwrite
934 (equal desktop-file-modtime new-modtime)
935 (yes-or-no-p (if desktop-file-modtime
936 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
937 "Desktop file is more recent than the one loaded. Save anyway? "
938 "Desktop file isn't the one loaded. Overwrite it? ")
939 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
940 (unless release (error "Desktop file conflict")))
941
942 ;; If we're done with it, release the lock.
943 ;; Otherwise, claim it if it's unclaimed or if we created it.
944 (if release
945 (desktop-release-lock)
946 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
947
948 (with-temp-buffer
949 (insert
950 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
951 desktop-header
952 ";; Created " (current-time-string) "\n"
953 ";; Desktop file format version " desktop-file-version "\n"
954 ";; Emacs version " emacs-version "\n")
955 (save-excursion (run-hooks 'desktop-save-hook))
956 (goto-char (point-max))
957 (insert "\n;; Global section:\n")
39c0e36f
JB
958 ;; Called here because we save the window/frame state as a global
959 ;; variable for compatibility with previous Emacsen.
9421876d
JB
960 (desktop-save-frameset)
961 (unless (memq 'desktop-saved-frameset desktop-globals-to-save)
962 (desktop-outvar 'desktop-saved-frameset))
e88110db 963 (mapc (function desktop-outvar) desktop-globals-to-save)
9421876d 964 (setq desktop-saved-frameset nil) ; after saving desktop-globals-to-save
e88110db
JB
965 (when (memq 'kill-ring desktop-globals-to-save)
966 (insert
967 "(setq kill-ring-yank-pointer (nthcdr "
968 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
969 " kill-ring))\n"))
970
971 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
972 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
a8049a30
JB
973 (let ((base (pop l)))
974 (when (apply 'desktop-save-buffer-p l)
975 (insert "("
976 (if (or (not (integerp eager))
977 (if (zerop eager)
978 nil
979 (setq eager (1- eager))))
980 "desktop-create-buffer"
981 "desktop-append-buffer-args")
982 " "
983 desktop-file-version)
ae4370a8
JB
984 ;; If there's a non-empty base name, we save it instead of the buffer name
985 (when (and base (not (string= base "")))
986 (setcar (nthcdr 1 l) base))
a8049a30
JB
987 (dolist (e l)
988 (insert "\n " (desktop-value-to-string e)))
989 (insert ")\n\n"))))
e88110db 990
9e29c91c 991 (setq default-directory desktop-dirname)
5db9dace
JL
992 ;; If auto-saving, avoid writing if nothing has changed since the last write.
993 ;; Don't check 300 characters of the header that contains the timestamp.
994 (let ((checksum (and auto-save (md5 (current-buffer)
995 (+ (point-min) 300) (point-max)
996 'emacs-mule))))
997 (unless (and auto-save (equal checksum desktop-file-checksum))
998 (let ((coding-system-for-write 'emacs-mule))
999 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1000 (setq desktop-file-checksum checksum)
1001 ;; We remember when it was modified (which is presumably just now).
1002 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
4a2fce7a 1003
0b9bd504 1004;; ----------------------------------------------------------------------------
11425834 1005;;;###autoload
6343ed61 1006(defun desktop-remove ()
6b61353c
KH
1007 "Delete desktop file in `desktop-dirname'.
1008This function also sets `desktop-dirname' to nil."
6343ed61 1009 (interactive)
6b61353c 1010 (when desktop-dirname
11425834 1011 (let ((filename (desktop-full-file-name)))
6b61353c
KH
1012 (setq desktop-dirname nil)
1013 (when (file-exists-p filename)
73b0b745 1014 (delete-file filename)))))
6b61353c 1015
150f39ee
LH
1016(defvar desktop-buffer-args-list nil
1017 "List of args for `desktop-create-buffer'.")
1018
1019(defvar desktop-lazy-timer nil)
1020
0b9bd504 1021;; ----------------------------------------------------------------------------
9421876d
JB
1022(defun desktop-restoring-frameset-p ()
1023 "True if calling `desktop-restore-frameset' will actually restore it."
1024 (and desktop-restore-frames desktop-saved-frameset t))
1025
1026(defun desktop-restore-frameset ()
1027 "Restore the state of a set of frames.
1028This function depends on the value of `desktop-saved-frameset'
56bc453c 1029being set (usually, by reading it from the desktop)."
9421876d
JB
1030 (when (desktop-restoring-frameset-p)
1031 (frameset-restore desktop-saved-frameset
9421876d
JB
1032 :reuse-frames desktop-restore-reuses-frames
1033 :force-display desktop-restore-in-current-display
1034 :force-onscreen desktop-restore-forces-onscreen)))
1035
1036;; Just to silence the byte compiler.
1037;; Dynamicaly bound in `desktop-read'.
1038(defvar desktop-first-buffer)
1039(defvar desktop-buffer-ok-count)
1040(defvar desktop-buffer-fail-count)
39c0e36f 1041
478653c9 1042;;;###autoload
6b61353c
KH
1043(defun desktop-read (&optional dirname)
1044 "Read and process the desktop file in directory DIRNAME.
1045Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1046directories listed in `desktop-path'. If a desktop file is found, it
cc8b76bf 1047is processed and `desktop-after-read-hook' is run. If no desktop file
6b61353c
KH
1048is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1049This function is a no-op when Emacs is running in batch mode.
1050It returns t if a desktop file was loaded, nil otherwise."
6343ed61 1051 (interactive)
4a2fce7a 1052 (unless noninteractive
6b61353c 1053 (setq desktop-dirname
11425834
LH
1054 (file-name-as-directory
1055 (expand-file-name
1056 (or
1057 ;; If DIRNAME is specified, use it.
1058 (and (< 0 (length dirname)) dirname)
1059 ;; Otherwise search desktop file in desktop-path.
1060 (let ((dirs desktop-path))
1061 (while (and dirs
1062 (not (file-exists-p
1063 (desktop-full-file-name (car dirs)))))
1064 (setq dirs (cdr dirs)))
1065 (and dirs (car dirs)))
1066 ;; If not found and `desktop-path' is non-nil, use its first element.
1067 (and desktop-path (car desktop-path))
6b67c0d4
CY
1068 ;; Default: .emacs.d.
1069 user-emacs-directory))))
11425834 1070 (if (file-exists-p (desktop-full-file-name))
e88110db
JB
1071 ;; Desktop file found, but is it already in use?
1072 (let ((desktop-first-buffer nil)
1073 (desktop-buffer-ok-count 0)
1074 (desktop-buffer-fail-count 0)
1075 (owner (desktop-owner))
1076 ;; Avoid desktop saving during evaluation of desktop buffer.
1077 (desktop-save nil))
1078 (if (and owner
1f7efe1b
JB
1079 (memq desktop-load-locked-desktop '(nil ask))
1080 (or (null desktop-load-locked-desktop)
e76f0800 1081 (daemonp)
1f7efe1b
JB
1082 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1083Using it may cause conflicts. Use it anyway? " owner)))))
c41cf130 1084 (let ((default-directory desktop-dirname))
794855ca 1085 (setq desktop-dirname nil)
c41cf130
JB
1086 (run-hooks 'desktop-not-loaded-hook)
1087 (unless desktop-dirname
1088 (message "Desktop file in use; not loaded.")))
e88110db
JB
1089 (desktop-lazy-abort)
1090 ;; Evaluate desktop buffer and remember when it was modified.
1091 (load (desktop-full-file-name) t t t)
1092 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1093 ;; If it wasn't already, mark it as in-use, to bother other
1094 ;; desktop instances.
1095 (unless owner
1096 (condition-case nil
1097 (desktop-claim-lock)
1098 (file-error (message "Couldn't record use of desktop file")
1099 (sit-for 1))))
1100
9421876d 1101 (unless (desktop-restoring-frameset-p)
56bc453c
JB
1102 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1103 ;; We want buffers existing prior to evaluating the desktop (and
1104 ;; not reused) to be placed at the end of the buffer list, so we
1105 ;; move them here.
1106 (mapc 'bury-buffer
1107 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1108 (switch-to-buffer (car (buffer-list))))
e88110db
JB
1109 (run-hooks 'desktop-delay-hook)
1110 (setq desktop-delay-hook nil)
9421876d 1111 (desktop-restore-frameset)
e88110db 1112 (run-hooks 'desktop-after-read-hook)
9421876d
JB
1113 (message "Desktop: %s%d buffer%s restored%s%s."
1114 (if desktop-saved-frameset
1115 (let ((fn (length (frameset-states desktop-saved-frameset))))
1116 (format "%d frame%s, "
1117 fn (if (= fn 1) "" "s")))
1118 "")
e88110db
JB
1119 desktop-buffer-ok-count
1120 (if (= 1 desktop-buffer-ok-count) "" "s")
1121 (if (< 0 desktop-buffer-fail-count)
1122 (format ", %d failed to restore" desktop-buffer-fail-count)
1123 "")
1124 (if desktop-buffer-args-list
1125 (format ", %d to restore lazily"
1126 (length desktop-buffer-args-list))
1127 ""))
9421876d 1128 (unless (desktop-restoring-frameset-p)
56bc453c
JB
1129 ;; Bury the *Messages* buffer to not reshow it when burying
1130 ;; the buffer we switched to above.
1131 (when (buffer-live-p (get-buffer "*Messages*"))
1132 (bury-buffer "*Messages*"))
1133 ;; Clear all windows' previous and next buffers, these have
1134 ;; been corrupted by the `switch-to-buffer' calls in
1135 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1136 ;; brute force fix and should be replaced by a more subtle
1137 ;; strategy eventually.
1138 (walk-window-tree (lambda (window)
1139 (set-window-prev-buffers window nil)
1140 (set-window-next-buffers window nil))))
5414a283 1141 (setq desktop-saved-frameset nil)
e88110db 1142 t))
6b61353c
KH
1143 ;; No desktop file found.
1144 (desktop-clear)
1145 (let ((default-directory desktop-dirname))
1146 (run-hooks 'desktop-no-desktop-file-hook))
1147 (message "No desktop file.")
1148 nil)))
4a2fce7a 1149
0b9bd504 1150;; ----------------------------------------------------------------------------
6b61353c 1151;; Maintained for backward compatibility
478653c9 1152;;;###autoload
6343ed61 1153(defun desktop-load-default ()
577ed2b2 1154 "Load the `default' start-up library manually.
6b61353c 1155Also inhibit further loading of it."
59f7af81 1156 (declare (obsolete desktop-save-mode "22.1"))
b89c5a72
JB
1157 (unless inhibit-default-init ; safety check
1158 (load "default" t t)
1159 (setq inhibit-default-init t)))
4a2fce7a
RS
1160
1161;; ----------------------------------------------------------------------------
1162;;;###autoload
6b61353c
KH
1163(defun desktop-change-dir (dirname)
1164 "Change to desktop saved in DIRNAME.
1165Kill the desktop as specified by variables `desktop-save-mode' and
1166`desktop-save', then clear the desktop and load the desktop file in
1167directory DIRNAME."
1168 (interactive "DChange to directory: ")
1169 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
4a2fce7a
RS
1170 (desktop-kill)
1171 (desktop-clear)
6b61353c 1172 (desktop-read dirname))
bf247b6e 1173
6b61353c 1174;; ----------------------------------------------------------------------------
4a2fce7a 1175;;;###autoload
6b61353c
KH
1176(defun desktop-save-in-desktop-dir ()
1177 "Save the desktop in directory `desktop-dirname'."
4a2fce7a
RS
1178 (interactive)
1179 (if desktop-dirname
b89c5a72 1180 (desktop-save desktop-dirname)
4a2fce7a 1181 (call-interactively 'desktop-save))
a609d13b 1182 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
4a2fce7a 1183
5db9dace
JL
1184;; ----------------------------------------------------------------------------
1185;; Auto-Saving.
1186(defvar desktop-auto-save-timer nil)
1187
1188(defun desktop-auto-save ()
1189 "Save the desktop periodically.
1190Called by the timer created in `desktop-auto-save-set-timer'."
1191 (when (and desktop-save-mode
1192 (integerp desktop-auto-save-timeout)
1193 (> desktop-auto-save-timeout 0)
1194 ;; Avoid desktop saving during lazy loading.
1195 (not desktop-lazy-timer)
1196 ;; Save only to own desktop file.
1197 (eq (emacs-pid) (desktop-owner))
1198 desktop-dirname)
1199 (desktop-save desktop-dirname nil t))
1200 (desktop-auto-save-set-timer))
1201
1202(defun desktop-auto-save-set-timer ()
1203 "Reset the auto-save timer.
1204Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1205integer, start a new timer to call `desktop-auto-save' in that many seconds."
1206 (when desktop-auto-save-timer
1207 (cancel-timer desktop-auto-save-timer)
1208 (setq desktop-auto-save-timer nil))
1209 (when (and (integerp desktop-auto-save-timeout)
1210 (> desktop-auto-save-timeout 0))
1211 (setq desktop-auto-save-timer
1212 (run-with-timer desktop-auto-save-timeout nil
1213 'desktop-auto-save))))
1214
4a2fce7a
RS
1215;; ----------------------------------------------------------------------------
1216;;;###autoload
1217(defun desktop-revert ()
1218 "Revert to the last loaded desktop."
1219 (interactive)
6b61353c
KH
1220 (unless desktop-dirname
1221 (error "Unknown desktop directory"))
11425834 1222 (unless (file-exists-p (desktop-full-file-name))
6b61353c
KH
1223 (error "No desktop file found"))
1224 (desktop-clear)
1225 (desktop-read desktop-dirname))
4a2fce7a 1226
341c2f07
SM
1227(defvar desktop-buffer-major-mode)
1228(defvar desktop-buffer-locals)
06b60517 1229(defvar auto-insert) ; from autoinsert.el
0b9bd504 1230;; ----------------------------------------------------------------------------
06b60517
JB
1231(defun desktop-restore-file-buffer (buffer-filename
1232 _buffer-name
1233 _buffer-misc)
e5780ae1 1234 "Restore a file buffer."
06b60517
JB
1235 (when buffer-filename
1236 (if (or (file-exists-p buffer-filename)
1f7efe1b 1237 (let ((msg (format "Desktop: File \"%s\" no longer exists."
06b60517 1238 buffer-filename)))
1f7efe1b
JB
1239 (if desktop-missing-file-warning
1240 (y-or-n-p (concat msg " Re-create buffer? "))
1241 (message "%s" msg)
1242 nil)))
1243 (let* ((auto-insert nil) ; Disable auto insertion
1244 (coding-system-for-read
1245 (or coding-system-for-read
1246 (cdr (assq 'buffer-file-coding-system
1247 desktop-buffer-locals))))
06b60517 1248 (buf (find-file-noselect buffer-filename)))
1f7efe1b
JB
1249 (condition-case nil
1250 (switch-to-buffer buf)
1251 (error (pop-to-buffer buf)))
1252 (and (not (eq major-mode desktop-buffer-major-mode))
1253 (functionp desktop-buffer-major-mode)
1254 (funcall desktop-buffer-major-mode))
1255 buf)
1256 nil)))
4a2fce7a 1257
0f4804e7
LH
1258(defun desktop-load-file (function)
1259 "Load the file where auto loaded FUNCTION is defined."
7abaf5cc
SM
1260 (when (fboundp function)
1261 (autoload-do-load (symbol-function function) function)))
0f4804e7 1262
0b9bd504 1263;; ----------------------------------------------------------------------------
eb982898
JL
1264;; Create a buffer, load its file, set its mode, ...;
1265;; called from Desktop file only.
1d500ca6 1266
340db502 1267(defun desktop-create-buffer
06b60517
JB
1268 (file-version
1269 buffer-filename
1270 buffer-name
1271 buffer-majormode
1272 buffer-minormodes
1273 buffer-point
1274 buffer-mark
1275 buffer-readonly
1276 buffer-misc
1277 &optional
1278 buffer-locals)
1279
1280 (let ((desktop-file-version file-version)
1281 (desktop-buffer-file-name buffer-filename)
1282 (desktop-buffer-name buffer-name)
1283 (desktop-buffer-major-mode buffer-majormode)
1284 (desktop-buffer-minor-modes buffer-minormodes)
1285 (desktop-buffer-point buffer-point)
1286 (desktop-buffer-mark buffer-mark)
1287 (desktop-buffer-read-only buffer-readonly)
1288 (desktop-buffer-misc buffer-misc)
1289 (desktop-buffer-locals buffer-locals))
1290 ;; To make desktop files with relative file names possible, we cannot
1291 ;; allow `default-directory' to change. Therefore we save current buffer.
1292 (save-current-buffer
1293 ;; Give major mode module a chance to add a handler.
1294 (desktop-load-file desktop-buffer-major-mode)
1295 (let ((buffer-list (buffer-list))
1296 (result
1be3ca5a 1297 (condition-case-unless-debug err
06b60517
JB
1298 (funcall (or (cdr (assq desktop-buffer-major-mode
1299 desktop-buffer-mode-handlers))
1300 'desktop-restore-file-buffer)
1301 desktop-buffer-file-name
1302 desktop-buffer-name
1303 desktop-buffer-misc)
1304 (error
1305 (message "Desktop: Can't load buffer %s: %s"
1306 desktop-buffer-name
1307 (error-message-string err))
1308 (when desktop-missing-file-warning (sit-for 1))
1309 nil))))
1310 (if (bufferp result)
1311 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1312 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1313 (setq result nil))
1314 ;; Restore buffer list order with new buffer at end. Don't change
91af3942 1315 ;; the order for old desktop files (old desktop module behavior).
06b60517
JB
1316 (unless (< desktop-file-version 206)
1317 (mapc 'bury-buffer buffer-list)
1318 (when result (bury-buffer result)))
1319 (when result
1320 (unless (or desktop-first-buffer (< desktop-file-version 206))
1321 (setq desktop-first-buffer result))
1322 (set-buffer result)
1323 (unless (equal (buffer-name) desktop-buffer-name)
1324 (rename-buffer desktop-buffer-name t))
1325 ;; minor modes
1326 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1327 (auto-fill-mode 1))
1328 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1329 (auto-fill-mode 0))
1330 (t
1331 (dolist (minor-mode desktop-buffer-minor-modes)
1332 ;; Give minor mode module a chance to add a handler.
1333 (desktop-load-file minor-mode)
1334 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1335 (if handler
1336 (funcall handler desktop-buffer-locals)
1337 (when (functionp minor-mode)
1338 (funcall minor-mode 1)))))))
1339 ;; Even though point and mark are non-nil when written by
1340 ;; `desktop-save', they may be modified by handlers wanting to set
1341 ;; point or mark themselves.
1342 (when desktop-buffer-point
1343 (goto-char
1344 (condition-case err
1345 ;; Evaluate point. Thus point can be something like
1346 ;; '(search-forward ...
1347 (eval desktop-buffer-point)
1348 (error (message "%s" (error-message-string err)) 1))))
1349 (when desktop-buffer-mark
1350 (if (consp desktop-buffer-mark)
1f7efe1b 1351 (progn
06b60517
JB
1352 (set-mark (car desktop-buffer-mark))
1353 (setq mark-active (car (cdr desktop-buffer-mark))))
1354 (set-mark desktop-buffer-mark)))
1355 ;; Never override file system if the file really is read-only marked.
1356 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
b61d71e4
JB
1357 (dolist (this desktop-buffer-locals)
1358 (if (consp this)
1359 ;; an entry of this form `(symbol . value)'
1360 (progn
1361 (make-local-variable (car this))
1362 (set (car this) (cdr this)))
1363 ;; an entry of the form `symbol'
1364 (make-local-variable this)
1365 (makunbound this))))))))
ec4c6f22 1366
4a2fce7a 1367;; ----------------------------------------------------------------------------
ec4c6f22 1368;; Backward compatibility -- update parameters to 205 standards.
06b60517
JB
1369(defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1370 mim pt mk ro tl fc cfs cr buffer-misc)
1371 (desktop-create-buffer 205 buffer-filename buffer-name
1372 buffer-majormode (cdr mim) pt mk ro
1373 buffer-misc
ec4c6f22
RS
1374 (list (cons 'truncate-lines tl)
1375 (cons 'fill-column fc)
1376 (cons 'case-fold-search cfs)
1377 (cons 'case-replace cr)
1378 (cons 'overwrite-mode (car mim)))))
84b538ec 1379
150f39ee 1380(defun desktop-append-buffer-args (&rest args)
cc8b76bf 1381 "Append ARGS at end of `desktop-buffer-args-list'.
150f39ee
LH
1382ARGS must be an argument list for `desktop-create-buffer'."
1383 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1384 (unless desktop-lazy-timer
1385 (setq desktop-lazy-timer
1386 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1387
1388(defun desktop-lazy-create-buffer ()
1389 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1390 (when desktop-buffer-args-list
1391 (let* ((remaining (length desktop-buffer-args-list))
1392 (args (pop desktop-buffer-args-list))
1393 (buffer-name (nth 2 args))
1394 (msg (format "Desktop lazily opening %s (%s remaining)..."
1395 buffer-name remaining)))
1396 (when desktop-lazy-verbose
8a26c165 1397 (message "%s" msg))
150f39ee
LH
1398 (let ((desktop-first-buffer nil)
1399 (desktop-buffer-ok-count 0)
1400 (desktop-buffer-fail-count 0))
1401 (apply 'desktop-create-buffer args)
1402 (run-hooks 'desktop-delay-hook)
1403 (setq desktop-delay-hook nil)
1404 (bury-buffer (get-buffer buffer-name))
1405 (when desktop-lazy-verbose
1406 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1407
1408(defun desktop-idle-create-buffers ()
1409 "Create buffers until the user does something, then stop.
1410If there are no buffers left to create, kill the timer."
1411 (let ((repeat 1))
1412 (while (and repeat desktop-buffer-args-list)
1413 (save-window-excursion
1414 (desktop-lazy-create-buffer))
1415 (setq repeat (sit-for 0.2))
1416 (unless desktop-buffer-args-list
1417 (cancel-timer desktop-lazy-timer)
1418 (setq desktop-lazy-timer nil)
1419 (message "Lazy desktop load complete")
1420 (sit-for 3)
1421 (message "")))))
1422
1423(defun desktop-lazy-complete ()
1424 "Run the desktop load to completion."
1425 (interactive)
1426 (let ((desktop-lazy-verbose t))
1427 (while desktop-buffer-args-list
1428 (save-window-excursion
1429 (desktop-lazy-create-buffer)))
1430 (message "Lazy desktop load complete")))
1431
1432(defun desktop-lazy-abort ()
1433 "Abort lazy loading of the desktop."
1434 (interactive)
1435 (when desktop-lazy-timer
1436 (cancel-timer desktop-lazy-timer)
1437 (setq desktop-lazy-timer nil))
1438 (when desktop-buffer-args-list
1439 (setq desktop-buffer-args-list nil)
32226619 1440 (when (called-interactively-p 'interactive)
150f39ee
LH
1441 (message "Lazy desktop load aborted"))))
1442
0b9bd504 1443;; ----------------------------------------------------------------------------
6b61353c 1444;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
4a2fce7a
RS
1445;; command line, we do the rest of what it takes to use desktop, but do it
1446;; after finishing loading the init file.
1447;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1448;; functions are processed after `after-init-hook'.
1449(add-hook
1450 'after-init-hook
341c2f07 1451 (lambda ()
4a2fce7a 1452 (let ((key "--no-desktop"))
4b217d46
LH
1453 (when (member key command-line-args)
1454 (setq command-line-args (delete key command-line-args))
1455 (setq desktop-save-mode nil)))
54d22a6f
JL
1456 (when desktop-save-mode
1457 (desktop-read)
5db9dace 1458 (desktop-auto-save-set-timer)
54d22a6f 1459 (setq inhibit-startup-screen t))))
813dbb2d 1460
f12ad6ec
GM
1461;; So we can restore vc-dir buffers.
1462(autoload 'vc-dir-mode "vc-dir" nil t)
1463
ab1d55ea 1464(provide 'desktop)
6343ed61 1465
80f9f3db 1466;;; desktop.el ends here