lisp/desktop.el: Move code related to saving frames to frameset.el.
[bpt/emacs.git] / lisp / desktop.el
1 ;;; desktop.el --- save partial status of Emacs when killed
2
3 ;; Copyright (C) 1993-1995, 1997, 2000-2013 Free Software Foundation,
4 ;; Inc.
5
6 ;; Author: Morten Welinder <terra@diku.dk>
7 ;; Keywords: convenience
8 ;; Favorite-brand-of-beer: None, I hate beer.
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
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
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
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
35 ;; - some local variables
36 ;; - frame and window configuration
37
38 ;; To use this, use customize to turn on desktop-save-mode or add the
39 ;; following line somewhere in your init file:
40 ;;
41 ;; (desktop-save-mode 1)
42 ;;
43 ;; For further usage information, look at the section
44 ;; (info "(emacs)Saving Emacs Sessions") in the GNU Emacs Manual.
45
46 ;; When the desktop module is loaded, the function `desktop-kill' is
47 ;; added to the `kill-emacs-hook'. This function is responsible for
48 ;; saving the desktop when Emacs is killed. Furthermore an anonymous
49 ;; function is added to the `after-init-hook'. This function is
50 ;; responsible for loading the desktop when Emacs is started.
51
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
57 ;; to restore a desktop buffer. Elements must have the form
58 ;;
59 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
60 ;;
61 ;; Functions listed are called by `desktop-create-buffer' when `desktop-read'
62 ;; evaluates the desktop file. Buffers with a major mode not specified here,
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
66 ;;
67 ;; (MINOR-MODE . RESTORE-FUNCTION).
68 ;;
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
86 ;; in the module itself, and make sure that the mode function is
87 ;; autoloaded. See the docstrings of `desktop-buffer-mode-handlers' and
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
102 ;; functions before writing `desktop-minor-modes'. If a minor mode has a
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 ;; ---------------------------------------------------------------------------
112
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
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.
120
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.
126 ;; treese@lcs.mit.edu (Win Treese) for ange-ftp tips.
127 ;; pot@cnuce.cnr.it (Francesco Potorti`) for misc. tips.
128 ;; ---------------------------------------------------------------------------
129 ;; TODO:
130 ;;
131 ;; Recognize more minor modes.
132 ;; Save mark rings.
133
134 ;;; Code:
135
136 (require 'cl-lib)
137 (require 'frameset)
138
139 (defvar desktop-file-version "206"
140 "Version number of desktop file format.
141 Written into the desktop file and used at desktop read to provide
142 backward compatibility.")
143
144 ;; ----------------------------------------------------------------------------
145 ;; USER OPTIONS -- settings you might want to play with.
146 ;; ----------------------------------------------------------------------------
147
148 (defgroup desktop nil
149 "Save status of Emacs when you exit."
150 :group 'frames)
151
152 ;; Maintained for backward compatibility
153 (define-obsolete-variable-alias 'desktop-enable 'desktop-save-mode "22.1")
154 ;;;###autoload
155 (define-minor-mode desktop-save-mode
156 "Toggle desktop saving (Desktop Save mode).
157 With a prefix argument ARG, enable Desktop Save mode if ARG is
158 positive, and disable it otherwise. If called from Lisp, enable
159 the mode if ARG is omitted or nil.
160
161 If Desktop Save mode is enabled, the state of Emacs is saved from
162 one session to another. See variable `desktop-save' and function
163 `desktop-read' for details."
164 :global t
165 :group 'desktop)
166
167 (defun desktop-save-mode-off ()
168 "Disable `desktop-save-mode'. Provided for use in hooks."
169 (desktop-save-mode 0))
170
171 (defcustom desktop-save 'ask-if-new
172 "Specifies whether the desktop should be saved when it is killed.
173 A desktop is killed when the user changes desktop or quits Emacs.
174 Possible values are:
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.
181 The desktop is never saved when `desktop-save-mode' is nil.
182 The variables `desktop-dirname' and `desktop-base-file-name'
183 determine where the desktop is saved."
184 :type
185 '(choice
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))
192 :group 'desktop
193 :version "22.1")
194
195 (defcustom desktop-auto-save-timeout nil
196 "Number of seconds between auto-saves of the desktop.
197 Zero 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)
202 (ignore-errors (desktop-auto-save-set-timer)))
203 :group 'desktop
204 :version "24.4")
205
206 (defcustom desktop-load-locked-desktop 'ask
207 "Specifies whether the desktop should be loaded if locked.
208 Possible values are:
209 t -- load anyway.
210 nil -- don't load.
211 ask -- ask the user.
212 If the value is nil, or `ask' and the user chooses not to load the desktop,
213 the 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
220 :version "22.2")
221
222 (define-obsolete-variable-alias 'desktop-basefilename
223 'desktop-base-file-name "22.1")
224
225 (defcustom desktop-base-file-name
226 (convert-standard-filename ".emacs.desktop")
227 "Name of file for Emacs desktop, excluding the directory part."
228 :type 'file
229 :group 'desktop)
230
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
236 :version "22.2")
237
238 (defcustom desktop-path (list user-emacs-directory "~")
239 "List of directories to search for the desktop file.
240 The base name of the file is specified in `desktop-base-file-name'."
241 :type '(repeat directory)
242 :group 'desktop
243 :version "23.2") ; user-emacs-directory added
244
245 (defcustom desktop-missing-file-warning nil
246 "If non-nil, offer to recreate the buffer of a deleted file.
247 Also pause for a moment to display message about errors signaled in
248 `desktop-buffer-mode-handlers'.
249
250 If nil, just print error messages in the message buffer."
251 :type 'boolean
252 :group 'desktop
253 :version "22.1")
254
255 (defcustom desktop-no-desktop-file-hook nil
256 "Normal hook run when `desktop-read' can't find a desktop file.
257 Run in the directory in which the desktop file was sought.
258 May be used to show a dired buffer."
259 :type 'hook
260 :group 'desktop
261 :version "22.1")
262
263 (defcustom desktop-not-loaded-hook nil
264 "Normal hook run when the user declines to re-use a desktop file.
265 Run in the directory in which the desktop file was found.
266 May 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)
270 :version "22.2")
271
272 (defcustom desktop-after-read-hook nil
273 "Normal hook run after a successful `desktop-read'.
274 May be used to show a buffer list."
275 :type 'hook
276 :group 'desktop
277 :options '(list-buffers)
278 :version "22.1")
279
280 (defcustom desktop-save-hook nil
281 "Normal hook run before the desktop is saved in a desktop file.
282 Run with the desktop buffer current with only the header present.
283 May be used to add to the desktop code or to truncate history lists,
284 for example."
285 :type 'hook
286 :group 'desktop)
287
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
294 register-alist
295 file-name-history)
296 "List of global variables saved by `desktop-save'.
297 An 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
299 MAX-SIZE elements (if the value is a list) before saving the value.
300 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
301 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
302 :group 'desktop)
303
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)
311 "List of global variables that `desktop-clear' will clear.
312 An element may be variable name (a symbol) or a cons cell of the form
313 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
314 to the value obtained by evaluating FORM."
315 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
316 :group 'desktop
317 :version "22.1")
318
319 (defcustom desktop-clear-preserve-buffers
320 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*"
321 "\\*Warnings\\*")
322 "List of buffers that `desktop-clear' should not delete.
323 Each element is a regular expression. Buffers with a name matched by any of
324 these won't be deleted."
325 :version "23.3" ; added Warnings - bug#6336
326 :type '(repeat string)
327 :group 'desktop)
328
329 ;;;###autoload
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
339 column-number-mode
340 size-indication-mode
341 buffer-file-coding-system
342 indent-tabs-mode
343 tab-width
344 indicate-buffer-boundaries
345 indicate-empty-lines
346 show-trailing-whitespace)
347 "List of local variables to save for each buffer.
348 The variables are saved only when they really are local. Conventional minor
349 modes are restored automatically; they should not be listed here."
350 :type '(repeat symbol)
351 :group 'desktop)
352
353 (defcustom desktop-buffers-not-to-save nil
354 "Regexp identifying buffers that are to be excluded from saving."
355 :type '(choice (const :tag "None" nil)
356 regexp)
357 :version "23.2" ; set to nil
358 :group 'desktop)
359
360 ;; Skip tramp and ange-ftp files
361 (defcustom desktop-files-not-to-save
362 "\\(^/[^/:]*:\\|(ftp)$\\)"
363 "Regexp identifying files whose buffers are to be excluded from saving."
364 :type '(choice (const :tag "None" nil)
365 regexp)
366 :group 'desktop)
367
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)
371 "List of major modes whose buffers should not be saved."
372 :type '(repeat symbol)
373 :group 'desktop)
374
375 (defcustom desktop-restore-frames t
376 "When non-nil, save frames to desktop file."
377 :type 'boolean
378 :group 'desktop
379 :version "24.4")
380
381 (defcustom desktop-restore-in-current-display nil
382 "If t, frames are restored in the current display.
383 If nil, frames are restored, if possible, in their original displays.
384 If `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
391 (defcustom desktop-restore-forces-onscreen t
392 "If t, offscreen frames are restored onscreen instead.
393 If `all', frames that are partially offscreen are also forced onscren.
394 NOTE: Checking of frame boundaries is only approximate and can fail
395 to reliably detect frames whose onscreen/offscreen state depends on a
396 few pixels, especially near the right / bottom borders of the screen."
397 :type '(choice (const :tag "Only fully offscreen frames" t)
398 (const :tag "Also partially offscreen frames" 'all)
399 (const :tag "Do not force frames onscreen" nil))
400 :group 'desktop
401 :version "24.4")
402
403 (defcustom desktop-restore-reuses-frames t
404 "If t, restoring frames reuses existing frames.
405 If nil, existing frames are deleted.
406 If `keep', existing frames are kept and not reused."
407 :type '(choice (const :tag "Reuse existing frames" t)
408 (const :tag "Delete existing frames" nil)
409 (const :tag "Keep existing frames" 'keep))
410 :group 'desktop
411 :version "24.4")
412
413 (defcustom desktop-file-name-format 'absolute
414 "Format in which desktop file names should be saved.
415 Possible 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))
420 :group 'desktop
421 :version "22.1")
422
423 (defcustom desktop-restore-eager t
424 "Number of buffers to restore immediately.
425 Remaining buffers are restored lazily (when Emacs is idle).
426 If value is t, all buffers are restored immediately."
427 :type '(choice (const t) integer)
428 :group 'desktop
429 :version "22.1")
430
431 (defcustom desktop-lazy-verbose t
432 "Verbose reporting of lazily created buffers."
433 :type 'boolean
434 :group 'desktop
435 :version "22.1")
436
437 (defcustom desktop-lazy-idle-delay 5
438 "Idle delay before starting to create buffers.
439 See `desktop-restore-eager'."
440 :type 'integer
441 :group 'desktop
442 :version "22.1")
443
444 ;;;###autoload
445 (defvar-local desktop-save-buffer nil
446 "When non-nil, save buffer status in desktop file.
447
448 If the value is a function, it is called by `desktop-save' with argument
449 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
450 file along with the state of the buffer for which it was called.
451
452 When file names are returned, they should be formatted using the call
453 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
454
455 Later, when `desktop-read' evaluates the desktop file, auxiliary information
456 is passed as the argument DESKTOP-BUFFER-MISC to functions in
457 `desktop-buffer-mode-handlers'.")
458 (make-obsolete-variable 'desktop-buffer-modes-to-save
459 'desktop-save-buffer "22.1")
460 (make-obsolete-variable 'desktop-buffer-misc-functions
461 'desktop-save-buffer "22.1")
462
463 ;;;###autoload
464 (defvar desktop-buffer-mode-handlers nil
465 "Alist of major mode specific functions to restore a desktop buffer.
466 Functions listed are called by `desktop-create-buffer' when `desktop-read'
467 evaluates the desktop file. List elements must have the form
468
469 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
470
471 Buffers with a major mode not specified here, are restored by the default
472 handler `desktop-restore-file-buffer'.
473
474 Handlers are called with argument list
475
476 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
477
478 Furthermore, they may use the following variables:
479
480 desktop-file-version
481 desktop-buffer-major-mode
482 desktop-buffer-minor-modes
483 desktop-buffer-point
484 desktop-buffer-mark
485 desktop-buffer-read-only
486 desktop-buffer-locals
487
488 If a handler returns a buffer, then the saved mode settings
489 and variable values for that buffer are copied into it.
490
491 Modules that define a major mode that needs a special handler should contain
492 code like
493
494 (defun foo-restore-desktop-buffer
495 ...
496 (add-to-list 'desktop-buffer-mode-handlers
497 '(foo-mode . foo-restore-desktop-buffer))
498
499 Furthermore the major mode function must be autoloaded.")
500
501 ;;;###autoload
502 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
503 (make-obsolete-variable 'desktop-buffer-handlers
504 'desktop-buffer-mode-handlers "22.1")
505
506 (defcustom desktop-minor-mode-table
507 '((auto-fill-function auto-fill-mode)
508 (vc-mode nil)
509 (vc-dired-mode nil)
510 (erc-track-minor-mode nil)
511 (savehist-mode nil))
512 "Table mapping minor mode variables to minor mode functions.
513 Each entry has the form (NAME RESTORE-FUNCTION).
514 NAME is the name of the buffer-local variable indicating that the minor
515 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
516 RESTORE-FUNCTION nil means don't try to restore the minor mode.
517 Only minor modes for which the name of the buffer-local variable
518 and the name of the minor mode function are different have to be added to
519 this table. See also `desktop-minor-mode-handlers'."
520 :type 'sexp
521 :group 'desktop)
522
523 ;;;###autoload
524 (defvar desktop-minor-mode-handlers nil
525 "Alist of functions to restore non-standard minor modes.
526 Functions are called by `desktop-create-buffer' to restore minor modes.
527 List elements must have the form
528
529 (MINOR-MODE . RESTORE-FUNCTION).
530
531 Minor modes not specified here, are restored by the standard minor mode
532 function.
533
534 Handlers are called with argument list
535
536 (DESKTOP-BUFFER-LOCALS)
537
538 Furthermore, 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
550 When a handler is called, the buffer has been created and the major mode has
551 been set, but local variables listed in desktop-buffer-locals has not yet been
552 created and set.
553
554 Modules that define a minor mode that needs a special handler should contain
555 code like
556
557 (defun foo-desktop-restore
558 ...
559 (add-to-list 'desktop-minor-mode-handlers
560 '(foo-mode . foo-desktop-restore))
561
562 Furthermore the minor mode function must be autoloaded.
563
564 See also `desktop-minor-mode-table'.")
565
566 ;;;###autoload
567 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
568
569 ;; ----------------------------------------------------------------------------
570 (defvar desktop-dirname nil
571 "The directory in which the desktop file should be saved.")
572
573 (defun desktop-full-file-name (&optional dirname)
574 "Return the full name of the desktop file in DIRNAME.
575 DIRNAME omitted or nil means use `desktop-dirname'."
576 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
577
578 (defun desktop-full-lock-name (&optional dirname)
579 "Return the full name of the desktop lock file in DIRNAME.
580 DIRNAME omitted or nil means use `desktop-dirname'."
581 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
582
583 (defconst desktop-header
584 ";; --------------------------------------------------------------------------
585 ;; Desktop File for Emacs
586 ;; --------------------------------------------------------------------------
587 " "*Header to place in Desktop file.")
588
589 (defvar desktop-delay-hook nil
590 "Hooks run after all buffers are loaded; intended for internal use.")
591
592 (defvar desktop-file-checksum nil
593 "Checksum of the last auto-saved contents of the desktop file.
594 Used to avoid writing contents unchanged between auto-saves.")
595
596 (defvar desktop-saved-frameset nil
597 "Saved state of all frames.
598 Only valid during frame saving & restoring; intended for internal use.")
599
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.
604 Used 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.
608 Return nil if no desktop file found or no Emacs process is using it.
609 DIRNAME omitted or nil means use `desktop-dirname'."
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)))
619 owner)))
620
621 (defun desktop-claim-lock (&optional dirname)
622 "Record this Emacs process as the owner of the desktop file in DIRNAME.
623 DIRNAME 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.
629 DIRNAME 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
633 ;; ----------------------------------------------------------------------------
634 (defun desktop-truncate (list n)
635 "Truncate LIST to at most N elements destructively."
636 (let ((here (nthcdr (1- n) list)))
637 (when (consp here)
638 (setcdr here nil))))
639
640 ;; ----------------------------------------------------------------------------
641 ;;;###autoload
642 (defun desktop-clear ()
643 "Empty the Desktop.
644 This kills all buffers except for internal ones and those with names matched by
645 a regular expression in the list `desktop-clear-preserve-buffers'.
646 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
647 (interactive)
648 (desktop-lazy-abort)
649 (dolist (var desktop-globals-to-clear)
650 (if (symbolp var)
651 (eval `(setq-default ,var nil))
652 (eval `(setq-default ,(car var) ,(cdr var)))))
653 (let ((preserve-regexp (concat "^\\("
654 (mapconcat (lambda (regexp)
655 (concat "\\(" regexp "\\)"))
656 desktop-clear-preserve-buffers
657 "\\|")
658 "\\)$")))
659 (dolist (buffer (buffer-list))
660 (let ((bufname (buffer-name buffer)))
661 (unless (or (eq (aref bufname 0) ?\s) ;; Don't kill internal buffers
662 (string-match-p preserve-regexp bufname))
663 (kill-buffer buffer)))))
664 (delete-other-windows)
665 (let* ((this (selected-frame))
666 (mini (window-frame (minibuffer-window this)))) ; in case they difer
667 (dolist (frame (sort (frame-list) #'frameset-sort-frames-for-deletion))
668 (condition-case err
669 (unless (or (eq frame this)
670 (eq frame mini)
671 (frame-parameter frame 'desktop-dont-clear))
672 (delete-frame frame))
673 (error
674 (delay-warning 'desktop (error-message-string err)))))))
675
676 ;; ----------------------------------------------------------------------------
677 (unless noninteractive
678 (add-hook 'kill-emacs-hook 'desktop-kill))
679
680 (defun desktop-kill ()
681 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
682 If the desktop should be saved and `desktop-dirname'
683 is nil, ask the user where to save the desktop."
684 (when (and desktop-save-mode
685 (let ((exists (file-exists-p (desktop-full-file-name))))
686 (or (eq desktop-save t)
687 (and exists (eq desktop-save 'if-exists))
688 ;; If it exists, but we aren't using it, we are going
689 ;; to ask for a new directory below.
690 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
691 (and
692 (or (memq desktop-save '(ask ask-if-new))
693 (and exists (eq desktop-save 'ask-if-exists)))
694 (y-or-n-p "Save desktop? ")))))
695 (unless desktop-dirname
696 (setq desktop-dirname
697 (file-name-as-directory
698 (expand-file-name
699 (read-directory-name "Directory for desktop file: " nil nil t)))))
700 (condition-case err
701 (desktop-save desktop-dirname t)
702 (file-error
703 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
704 (signal (car err) (cdr err))))))
705 ;; If we own it, we don't anymore.
706 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
707
708 ;; ----------------------------------------------------------------------------
709 (defun desktop-list* (&rest args)
710 (and args (apply #'cl-list* args)))
711
712 ;; ----------------------------------------------------------------------------
713 (defun desktop-buffer-info (buffer)
714 (set-buffer buffer)
715 (list
716 ;; base name of the buffer; replaces the buffer name if managed by uniquify
717 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
718 ;; basic information
719 (desktop-file-name (buffer-file-name) desktop-dirname)
720 (buffer-name)
721 major-mode
722 ;; minor modes
723 (let (ret)
724 (mapc
725 #'(lambda (minor-mode)
726 (and (boundp minor-mode)
727 (symbol-value minor-mode)
728 (let* ((special (assq minor-mode desktop-minor-mode-table))
729 (value (cond (special (cadr special))
730 ((functionp minor-mode) minor-mode))))
731 (when value (add-to-list 'ret value)))))
732 (mapcar #'car minor-mode-alist))
733 ret)
734 ;; point and mark, and read-only status
735 (point)
736 (list (mark t) mark-active)
737 buffer-read-only
738 ;; auxiliary information
739 (when (functionp desktop-save-buffer)
740 (funcall desktop-save-buffer desktop-dirname))
741 ;; local variables
742 (let ((loclist (buffer-local-variables))
743 (ll nil))
744 (dolist (local desktop-locals-to-save)
745 (let ((here (assq local loclist)))
746 (cond (here
747 (push here ll))
748 ((member local loclist)
749 (push local ll)))))
750 ll)))
751
752 ;; ----------------------------------------------------------------------------
753 (defun desktop--v2s (value)
754 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
755 SEXP is an sexp that when evaluated yields VALUE.
756 QUOTE may be `may' (value may be quoted),
757 `must' (value must be quoted), or nil (value must not be quoted)."
758 (cond
759 ((or (numberp value) (null value) (eq t value) (keywordp value))
760 (cons 'may value))
761 ((stringp value)
762 (let ((copy (copy-sequence value)))
763 (set-text-properties 0 (length copy) nil copy)
764 ;; Get rid of text properties because we cannot read them.
765 (cons 'may copy)))
766 ((symbolp value)
767 (cons 'must value))
768 ((vectorp value)
769 (let* ((pass1 (mapcar #'desktop--v2s value))
770 (special (assq nil pass1)))
771 (if special
772 (cons nil `(vector
773 ,@(mapcar (lambda (el)
774 (if (eq (car el) 'must)
775 `',(cdr el) (cdr el)))
776 pass1)))
777 (cons 'may `[,@(mapcar #'cdr pass1)]))))
778 ((consp value)
779 (let ((p value)
780 newlist
781 use-list*)
782 (while (consp p)
783 (let ((q.sexp (desktop--v2s (car p))))
784 (push q.sexp newlist))
785 (setq p (cdr p)))
786 (when p
787 (let ((last (desktop--v2s p)))
788 (setq use-list* t)
789 (push last newlist)))
790 (if (assq nil newlist)
791 (cons nil
792 `(,(if use-list* 'desktop-list* 'list)
793 ,@(mapcar (lambda (el)
794 (if (eq (car el) 'must)
795 `',(cdr el) (cdr el)))
796 (nreverse newlist))))
797 (cons 'must
798 `(,@(mapcar #'cdr
799 (nreverse (if use-list* (cdr newlist) newlist)))
800 ,@(if use-list* (cdar newlist)))))))
801 ((subrp value)
802 (cons nil `(symbol-function
803 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
804 ((markerp value)
805 (let ((pos (marker-position value))
806 (buf (buffer-name (marker-buffer value))))
807 (cons nil
808 `(let ((mk (make-marker)))
809 (add-hook 'desktop-delay-hook
810 `(lambda ()
811 (set-marker ,mk ,,pos (get-buffer ,,buf))))
812 mk))))
813 (t ; Save as text.
814 (cons 'may "Unprintable entity"))))
815
816 ;; ----------------------------------------------------------------------------
817 (defun desktop-value-to-string (value)
818 "Convert VALUE to a string that when read evaluates to the same value.
819 Not all types of values are supported."
820 (let* ((print-escape-newlines t)
821 (float-output-format nil)
822 (quote.sexp (desktop--v2s value))
823 (quote (car quote.sexp))
824 (txt
825 (let ((print-quoted t))
826 (prin1-to-string (cdr quote.sexp)))))
827 (if (eq quote 'must)
828 (concat "'" txt)
829 txt)))
830
831 ;; ----------------------------------------------------------------------------
832 (defun desktop-outvar (varspec)
833 "Output a setq statement for variable VAR to the desktop file.
834 The argument VARSPEC may be the variable name VAR (a symbol),
835 or a cons cell of the form (VAR . MAX-SIZE),
836 which means to truncate VAR's value to at most MAX-SIZE elements
837 \(if the value is a list) before saving the value."
838 (let (var size)
839 (if (consp varspec)
840 (setq var (car varspec) size (cdr varspec))
841 (setq var varspec))
842 (when (boundp var)
843 (when (and (integerp size)
844 (> size 0)
845 (listp (eval var)))
846 (desktop-truncate (eval var) size))
847 (insert "(setq "
848 (symbol-name var)
849 " "
850 (desktop-value-to-string (symbol-value var))
851 ")\n"))))
852
853 ;; ----------------------------------------------------------------------------
854 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
855 "Return t if buffer should have its state saved in the desktop file.
856 FILENAME is the visited file name, BUFNAME is the buffer name, and
857 MODE is the major mode.
858 \n\(fn FILENAME BUFNAME MODE)"
859 (let ((case-fold-search nil)
860 dired-skip)
861 (and (not (and (stringp desktop-buffers-not-to-save)
862 (not filename)
863 (string-match-p desktop-buffers-not-to-save bufname)))
864 (not (memq mode desktop-modes-not-to-save))
865 ;; FIXME this is broken if desktop-files-not-to-save is nil.
866 (or (and filename
867 (stringp desktop-files-not-to-save)
868 (not (string-match-p desktop-files-not-to-save filename)))
869 (and (memq mode '(dired-mode vc-dir-mode))
870 (with-current-buffer bufname
871 (not (setq dired-skip
872 (string-match-p desktop-files-not-to-save
873 default-directory)))))
874 (and (null filename)
875 (null dired-skip) ; bug#5755
876 (with-current-buffer bufname desktop-save-buffer))))))
877
878 ;; ----------------------------------------------------------------------------
879 (defun desktop-file-name (filename dirname)
880 "Convert FILENAME to format specified in `desktop-file-name-format'.
881 DIRNAME must be the directory in which the desktop file will be saved."
882 (cond
883 ((not filename) nil)
884 ((eq desktop-file-name-format 'tilde)
885 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
886 (cond
887 ((file-name-absolute-p relative-name) relative-name)
888 ((string= "./" relative-name) "~/")
889 ((string= "." relative-name) "~")
890 (t (concat "~/" relative-name)))))
891 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
892 (t (expand-file-name filename))))
893
894
895 ;; ----------------------------------------------------------------------------
896 (defvar desktop-filter-parameters-alist
897 (append '((font-backend . t)
898 (name . t)
899 (outer-window-id . t)
900 (parent-id . t)
901 (tty . desktop--filter-tty*)
902 (tty-type . desktop--filter-tty*)
903 (window-id . t)
904 (window-system . t))
905 frameset-filter-alist)
906 "Alist of frame parameters and filtering functions.
907 Its format is identical to `frameset-filter-alist' (which see).")
908
909 (defun desktop--filter-tty* (_current parameters saving)
910 ;; Remove tty and tty-type parameters when switching
911 ;; to a GUI frame.
912 (or saving
913 (not (frameset-switch-to-gui-p parameters))))
914
915 (defun desktop--check-dont-save (frame)
916 (not (frame-parameter frame 'desktop-dont-save)))
917
918 (defconst desktop--app-id `(desktop . ,desktop-file-version))
919
920 (defun desktop-save-frameset ()
921 "Save the state of existing frames in `desktop-saved-frameset'.
922 Frames with a non-nil `desktop-dont-save' parameter are not saved."
923 (setq desktop-saved-frameset
924 (and desktop-restore-frames
925 (let ((name (concat user-login-name "@" system-name
926 (format-time-string " %Y-%m-%d %T"))))
927 (frameset-save nil
928 :filters desktop-filter-parameters-alist
929 :predicate #'desktop--check-dont-save
930 :properties (list :app desktop--app-id
931 :name name))))))
932
933 ;;;###autoload
934 (defun desktop-save (dirname &optional release auto-save)
935 "Save the desktop in a desktop file.
936 Parameter DIRNAME specifies where to save the desktop file.
937 Optional parameter RELEASE says whether we're done with this desktop.
938 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
939 and don't save the buffer if they are the same."
940 (interactive "DDirectory to save desktop file in: ")
941 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
942 (save-excursion
943 (let ((eager desktop-restore-eager)
944 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
945 (when
946 (or (not new-modtime) ; nothing to overwrite
947 (equal desktop-file-modtime new-modtime)
948 (yes-or-no-p (if desktop-file-modtime
949 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
950 "Desktop file is more recent than the one loaded. Save anyway? "
951 "Desktop file isn't the one loaded. Overwrite it? ")
952 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
953 (unless release (error "Desktop file conflict")))
954
955 ;; If we're done with it, release the lock.
956 ;; Otherwise, claim it if it's unclaimed or if we created it.
957 (if release
958 (desktop-release-lock)
959 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
960
961 (with-temp-buffer
962 (insert
963 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
964 desktop-header
965 ";; Created " (current-time-string) "\n"
966 ";; Desktop file format version " desktop-file-version "\n"
967 ";; Emacs version " emacs-version "\n")
968 (save-excursion (run-hooks 'desktop-save-hook))
969 (goto-char (point-max))
970 (insert "\n;; Global section:\n")
971 ;; Called here because we save the window/frame state as a global
972 ;; variable for compatibility with previous Emacsen.
973 (desktop-save-frameset)
974 (unless (memq 'desktop-saved-frameset desktop-globals-to-save)
975 (desktop-outvar 'desktop-saved-frameset))
976 (mapc (function desktop-outvar) desktop-globals-to-save)
977 (setq desktop-saved-frameset nil) ; after saving desktop-globals-to-save
978 (when (memq 'kill-ring desktop-globals-to-save)
979 (insert
980 "(setq kill-ring-yank-pointer (nthcdr "
981 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
982 " kill-ring))\n"))
983
984 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
985 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
986 (let ((base (pop l)))
987 (when (apply 'desktop-save-buffer-p l)
988 (insert "("
989 (if (or (not (integerp eager))
990 (if (zerop eager)
991 nil
992 (setq eager (1- eager))))
993 "desktop-create-buffer"
994 "desktop-append-buffer-args")
995 " "
996 desktop-file-version)
997 ;; If there's a non-empty base name, we save it instead of the buffer name
998 (when (and base (not (string= base "")))
999 (setcar (nthcdr 1 l) base))
1000 (dolist (e l)
1001 (insert "\n " (desktop-value-to-string e)))
1002 (insert ")\n\n"))))
1003
1004 (setq default-directory desktop-dirname)
1005 ;; If auto-saving, avoid writing if nothing has changed since the last write.
1006 ;; Don't check 300 characters of the header that contains the timestamp.
1007 (let ((checksum (and auto-save (md5 (current-buffer)
1008 (+ (point-min) 300) (point-max)
1009 'emacs-mule))))
1010 (unless (and auto-save (equal checksum desktop-file-checksum))
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)))))))))))
1016
1017 ;; ----------------------------------------------------------------------------
1018 ;;;###autoload
1019 (defun desktop-remove ()
1020 "Delete desktop file in `desktop-dirname'.
1021 This function also sets `desktop-dirname' to nil."
1022 (interactive)
1023 (when desktop-dirname
1024 (let ((filename (desktop-full-file-name)))
1025 (setq desktop-dirname nil)
1026 (when (file-exists-p filename)
1027 (delete-file filename)))))
1028
1029 (defvar desktop-buffer-args-list nil
1030 "List of args for `desktop-create-buffer'.")
1031
1032 (defvar desktop-lazy-timer nil)
1033
1034 ;; ----------------------------------------------------------------------------
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.
1041 This function depends on the value of `desktop-saved-frameset'
1042 being set (usually, by reading it from the desktop)."
1043 (when (desktop-restoring-frameset-p)
1044 (frameset-restore desktop-saved-frameset
1045 :filters desktop-filter-parameters-alist
1046 :reuse-frames desktop-restore-reuses-frames
1047 :force-display desktop-restore-in-current-display
1048 :force-onscreen desktop-restore-forces-onscreen)))
1049
1050 ;; Just to silence the byte compiler.
1051 ;; Dynamicaly bound in `desktop-read'.
1052 (defvar desktop-first-buffer)
1053 (defvar desktop-buffer-ok-count)
1054 (defvar desktop-buffer-fail-count)
1055
1056 ;;;###autoload
1057 (defun desktop-read (&optional dirname)
1058 "Read and process the desktop file in directory DIRNAME.
1059 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1060 directories listed in `desktop-path'. If a desktop file is found, it
1061 is processed and `desktop-after-read-hook' is run. If no desktop file
1062 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1063 This function is a no-op when Emacs is running in batch mode.
1064 It returns t if a desktop file was loaded, nil otherwise."
1065 (interactive)
1066 (unless noninteractive
1067 (setq desktop-dirname
1068 (file-name-as-directory
1069 (expand-file-name
1070 (or
1071 ;; If DIRNAME is specified, use it.
1072 (and (< 0 (length dirname)) dirname)
1073 ;; Otherwise search desktop file in desktop-path.
1074 (let ((dirs desktop-path))
1075 (while (and dirs
1076 (not (file-exists-p
1077 (desktop-full-file-name (car dirs)))))
1078 (setq dirs (cdr dirs)))
1079 (and dirs (car dirs)))
1080 ;; If not found and `desktop-path' is non-nil, use its first element.
1081 (and desktop-path (car desktop-path))
1082 ;; Default: .emacs.d.
1083 user-emacs-directory))))
1084 (if (file-exists-p (desktop-full-file-name))
1085 ;; Desktop file found, but is it already in use?
1086 (let ((desktop-first-buffer nil)
1087 (desktop-buffer-ok-count 0)
1088 (desktop-buffer-fail-count 0)
1089 (owner (desktop-owner))
1090 ;; Avoid desktop saving during evaluation of desktop buffer.
1091 (desktop-save nil))
1092 (if (and owner
1093 (memq desktop-load-locked-desktop '(nil ask))
1094 (or (null desktop-load-locked-desktop)
1095 (daemonp)
1096 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1097 Using it may cause conflicts. Use it anyway? " owner)))))
1098 (let ((default-directory desktop-dirname))
1099 (setq desktop-dirname nil)
1100 (run-hooks 'desktop-not-loaded-hook)
1101 (unless desktop-dirname
1102 (message "Desktop file in use; not loaded.")))
1103 (desktop-lazy-abort)
1104 ;; Evaluate desktop buffer and remember when it was modified.
1105 (load (desktop-full-file-name) t t t)
1106 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1107 ;; If it wasn't already, mark it as in-use, to bother other
1108 ;; desktop instances.
1109 (unless owner
1110 (condition-case nil
1111 (desktop-claim-lock)
1112 (file-error (message "Couldn't record use of desktop file")
1113 (sit-for 1))))
1114
1115 (unless (desktop-restoring-frameset-p)
1116 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1117 ;; We want buffers existing prior to evaluating the desktop (and
1118 ;; not reused) to be placed at the end of the buffer list, so we
1119 ;; move them here.
1120 (mapc 'bury-buffer
1121 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1122 (switch-to-buffer (car (buffer-list))))
1123 (run-hooks 'desktop-delay-hook)
1124 (setq desktop-delay-hook nil)
1125 (desktop-restore-frameset)
1126 (run-hooks 'desktop-after-read-hook)
1127 (message "Desktop: %s%d buffer%s restored%s%s."
1128 (if desktop-saved-frameset
1129 (let ((fn (length (frameset-states desktop-saved-frameset))))
1130 (format "%d frame%s, "
1131 fn (if (= fn 1) "" "s")))
1132 "")
1133 desktop-buffer-ok-count
1134 (if (= 1 desktop-buffer-ok-count) "" "s")
1135 (if (< 0 desktop-buffer-fail-count)
1136 (format ", %d failed to restore" desktop-buffer-fail-count)
1137 "")
1138 (if desktop-buffer-args-list
1139 (format ", %d to restore lazily"
1140 (length desktop-buffer-args-list))
1141 ""))
1142 (unless (desktop-restoring-frameset-p)
1143 ;; Bury the *Messages* buffer to not reshow it when burying
1144 ;; the buffer we switched to above.
1145 (when (buffer-live-p (get-buffer "*Messages*"))
1146 (bury-buffer "*Messages*"))
1147 ;; Clear all windows' previous and next buffers, these have
1148 ;; been corrupted by the `switch-to-buffer' calls in
1149 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1150 ;; brute force fix and should be replaced by a more subtle
1151 ;; strategy eventually.
1152 (walk-window-tree (lambda (window)
1153 (set-window-prev-buffers window nil)
1154 (set-window-next-buffers window nil))))
1155 t))
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)))
1162
1163 ;; ----------------------------------------------------------------------------
1164 ;; Maintained for backward compatibility
1165 ;;;###autoload
1166 (defun desktop-load-default ()
1167 "Load the `default' start-up library manually.
1168 Also inhibit further loading of it."
1169 (declare (obsolete desktop-save-mode "22.1"))
1170 (unless inhibit-default-init ; safety check
1171 (load "default" t t)
1172 (setq inhibit-default-init t)))
1173
1174 ;; ----------------------------------------------------------------------------
1175 ;;;###autoload
1176 (defun desktop-change-dir (dirname)
1177 "Change to desktop saved in DIRNAME.
1178 Kill the desktop as specified by variables `desktop-save-mode' and
1179 `desktop-save', then clear the desktop and load the desktop file in
1180 directory DIRNAME."
1181 (interactive "DChange to directory: ")
1182 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1183 (desktop-kill)
1184 (desktop-clear)
1185 (desktop-read dirname))
1186
1187 ;; ----------------------------------------------------------------------------
1188 ;;;###autoload
1189 (defun desktop-save-in-desktop-dir ()
1190 "Save the desktop in directory `desktop-dirname'."
1191 (interactive)
1192 (if desktop-dirname
1193 (desktop-save desktop-dirname)
1194 (call-interactively 'desktop-save))
1195 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1196
1197 ;; ----------------------------------------------------------------------------
1198 ;; Auto-Saving.
1199 (defvar desktop-auto-save-timer nil)
1200
1201 (defun desktop-auto-save ()
1202 "Save the desktop periodically.
1203 Called 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)
1212 (desktop-save desktop-dirname nil t))
1213 (desktop-auto-save-set-timer))
1214
1215 (defun desktop-auto-save-set-timer ()
1216 "Reset the auto-save timer.
1217 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1218 integer, start a new timer to call `desktop-auto-save' in that many seconds."
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
1225 (run-with-timer desktop-auto-save-timeout nil
1226 'desktop-auto-save))))
1227
1228 ;; ----------------------------------------------------------------------------
1229 ;;;###autoload
1230 (defun desktop-revert ()
1231 "Revert to the last loaded desktop."
1232 (interactive)
1233 (unless desktop-dirname
1234 (error "Unknown desktop directory"))
1235 (unless (file-exists-p (desktop-full-file-name))
1236 (error "No desktop file found"))
1237 (desktop-clear)
1238 (desktop-read desktop-dirname))
1239
1240 (defvar desktop-buffer-major-mode)
1241 (defvar desktop-buffer-locals)
1242 (defvar auto-insert) ; from autoinsert.el
1243 ;; ----------------------------------------------------------------------------
1244 (defun desktop-restore-file-buffer (buffer-filename
1245 _buffer-name
1246 _buffer-misc)
1247 "Restore a file buffer."
1248 (when buffer-filename
1249 (if (or (file-exists-p buffer-filename)
1250 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1251 buffer-filename)))
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))))
1261 (buf (find-file-noselect buffer-filename)))
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)))
1270
1271 (defun desktop-load-file (function)
1272 "Load the file where auto loaded FUNCTION is defined."
1273 (when (fboundp function)
1274 (autoload-do-load (symbol-function function) function)))
1275
1276 ;; ----------------------------------------------------------------------------
1277 ;; Create a buffer, load its file, set its mode, ...;
1278 ;; called from Desktop file only.
1279
1280 (defun desktop-create-buffer
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
1310 (condition-case-unless-debug err
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
1328 ;; the order for old desktop files (old desktop module behavior).
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)
1364 (progn
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))
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))))))))
1379
1380 ;; ----------------------------------------------------------------------------
1381 ;; Backward compatibility -- update parameters to 205 standards.
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
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)))))
1392
1393 (defun desktop-append-buffer-args (&rest args)
1394 "Append ARGS at end of `desktop-buffer-args-list'.
1395 ARGS 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
1410 (message "%s" msg))
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.
1423 If 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)
1453 (when (called-interactively-p 'interactive)
1454 (message "Lazy desktop load aborted"))))
1455
1456 ;; ----------------------------------------------------------------------------
1457 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
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
1464 (lambda ()
1465 (let ((key "--no-desktop"))
1466 (when (member key command-line-args)
1467 (setq command-line-args (delete key command-line-args))
1468 (setq desktop-save-mode nil)))
1469 (when desktop-save-mode
1470 (desktop-read)
1471 (desktop-auto-save-set-timer)
1472 (setq inhibit-startup-screen t))))
1473
1474 ;; So we can restore vc-dir buffers.
1475 (autoload 'vc-dir-mode "vc-dir" nil t)
1476
1477 (provide 'desktop)
1478
1479 ;;; desktop.el ends here