winner.el 15.5 KB
Newer Older
1
;;; winner.el --- Restore old window configurations
Richard M. Stallman's avatar
Richard M. Stallman committed
2

3
;; Copyright (C) 1997, 1998, 2001, 2002, 2003, 2004,
Glenn Morris's avatar
Glenn Morris committed
4
;;   2005, 2006, 2007 Free Software Foundation. Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
5

Dave Love's avatar
Dave Love committed
6
;; Author: Ivar Rummelhoff <ivarru@math.uio.no>
Richard M. Stallman's avatar
Richard M. Stallman committed
7
;; Created: 27 Feb 1997
8
;; Keywords: convenience frames
Richard M. Stallman's avatar
Richard M. Stallman committed
9

Richard M. Stallman's avatar
Richard M. Stallman committed
10 11 12
;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
13
;; it under the terms of the GNU General Public License as published by
14
;; the Free Software Foundation; either version 3, or (at your option)
Richard M. Stallman's avatar
Richard M. Stallman committed
15 16
;; any later version.

Richard M. Stallman's avatar
Richard M. Stallman committed
17
;; GNU Emacs is distributed in the hope that it will be useful,
Richard M. Stallman's avatar
Richard M. Stallman committed
18 19 20 21 22 23
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
Lute Kamstra's avatar
Lute Kamstra committed
24 25
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
Richard M. Stallman's avatar
Richard M. Stallman committed
26 27

;;; Commentary:
28

29 30
;; Winner mode is a global minor mode that records the changes in the
;; window configuration (i.e. how the frames are partitioned into
31
;; windows) so that the changes can be "undone" using the command
32
;; `winner-undo'.  By default this one is bound to the key sequence
33 34
;; ctrl-c left.  If you change your mind (while undoing), you can
;; press ctrl-c right (calling `winner-redo').  Even though it uses
35 36 37 38
;; some features of Emacs20.3, winner.el should also work with
;; Emacs19.34 and XEmacs20, provided that the installed version of
;; custom is not obsolete.

39 40
;; Winner mode was improved August 1998.
;; Further improvements February 2002.
41 42 43 44

;;; Code:

(eval-when-compile
45
  (require 'cl))
46

47 48 49 50 51 52 53 54

(defmacro winner-active-region ()
  (if (fboundp 'region-active-p)
      '(region-active-p)
    'mark-active))

(defsetf winner-active-region () (store)
  (if (fboundp 'zmacs-activate-region)
55
      `(if ,store (zmacs-activate-region)
56 57
	 (zmacs-deactivate-region))
    `(setq mark-active ,store)))
Richard M. Stallman's avatar
Richard M. Stallman committed
58

59 60 61 62 63 64
(defalias 'winner-edges
  (if (featurep 'xemacs) 'window-pixel-edges 'window-edges))
(defalias 'winner-window-list
  (if (featurep 'xemacs)
      (lambda () (delq (minibuffer-window) (window-list nil 0)))
    (lambda () (window-list nil 0))))
65

66
(require 'ring)
Richard M. Stallman's avatar
Richard M. Stallman committed
67

68 69 70 71 72 73
(unless (fboundp 'defgroup)
  (defmacro defgroup (&rest rest)))

(defgroup winner nil
  "Restoring window configurations."
  :group 'windows)
74 75 76 77 78

(unless (fboundp 'defcustom)
  (defmacro defcustom (symbol &optional initvalue docs &rest rest)
    (list 'defvar symbol initvalue docs)))

79
;;;###autoload
Dave Love's avatar
Dave Love committed
80
(defcustom winner-mode nil
81
  "Toggle Winner mode.
Dave Love's avatar
Dave Love committed
82 83
Setting this variable directly does not take effect;
use either \\[customize] or the function `winner-mode'."
84
  :set #'(lambda (symbol value) (funcall symbol (or value 0)))
Dave Love's avatar
Dave Love committed
85
  :initialize 'custom-initialize-default
86 87
  :type    'boolean
  :group   'winner
Dave Love's avatar
Dave Love committed
88 89 90 91
  :require 'winner)

(defcustom winner-dont-bind-my-keys nil
  "If non-nil: Do not use `winner-mode-map' in Winner mode."
92
  :type  'boolean
Dave Love's avatar
Dave Love committed
93
  :group 'winner)
Richard M. Stallman's avatar
Richard M. Stallman committed
94

95 96 97
(defcustom winner-ring-size 200
  "Maximum number of stored window configurations per frame."
  :type  'integer
Dave Love's avatar
Dave Love committed
98
  :group 'winner)
Richard M. Stallman's avatar
Richard M. Stallman committed
99

100
(defcustom winner-boring-buffers '("*Completions*")
101
  "`winner-undo' will not restore windows displaying any of these buffers.
102 103 104 105 106 107 108
You may want to include buffer names such as *Help*, *Apropos*,
*Buffer List*, *info* and *Compile-Log*."
  :type '(repeat string)
  :group 'winner)



Richard M. Stallman's avatar
Richard M. Stallman committed
109

110 111

;;;; Saving old configurations (internal variables and subroutines)
Richard M. Stallman's avatar
Richard M. Stallman committed
112

113

114
;;; Current configuration
115

116 117 118 119 120 121 122 123 124
;; List the windows according to their edges.
(defun winner-sorted-window-list ()
  (sort (winner-window-list)
        (lambda (x y)
          (loop for a in (winner-edges x)
                for b in (winner-edges y)
                while (= a b)
                finally return (< a b)))))

125
(defun winner-win-data ()
126 127 128
  ;; Essential properties of the windows in the selected frame.
  (loop for win in (winner-sorted-window-list)
        collect (cons (winner-edges win) (window-buffer win))))
129

130
;; This variable is updated with the current window configuration
131
;; every time it changes.
132 133 134 135
(defvar winner-currents nil)

;; The current configuration (+ the buffers involved).
(defsubst winner-conf ()
136 137 138
  (cons (current-window-configuration)
        (winner-win-data)))

139 140

;; Save current configuration.
141
;; (Called below by `winner-save-old-configurations').
142 143 144 145 146 147 148 149 150 151 152 153
(defun winner-remember ()
  (let ((entry (assq (selected-frame) winner-currents)))
    (if entry (setcdr entry (winner-conf))
      (push (cons (selected-frame) (winner-conf))
	    winner-currents))))

;; Consult `winner-currents'.
(defun winner-configuration (&optional frame)
  (or (cdr (assq (or frame (selected-frame)) winner-currents))
      (letf (((selected-frame) frame))
	(winner-conf))))

154 155


156 157
;;; Saved configurations

158 159
;; This variable contains the window cofiguration rings.
;; The key in this alist is the frame.
160
(defvar winner-ring-alist nil)
Richard M. Stallman's avatar
Richard M. Stallman committed
161

162
;; Find the right ring.  If it does not exist, create one.
163 164
(defsubst winner-ring (frame)
  (or (cdr (assq frame winner-ring-alist))
165 166 167 168
      (let ((ring (make-ring winner-ring-size)))
        (ring-insert ring (winner-configuration frame))
        (push (cons frame ring) winner-ring-alist)
        ring)))
169

170 171

;; If the same command is called several times in a row,
172 173
;; we only save one window configuration.
(defvar winner-last-command nil)
Richard M. Stallman's avatar
Richard M. Stallman committed
174

175 176
;; Frames affected by the previous command.
(defvar winner-last-frames nil)
Richard M. Stallman's avatar
Richard M. Stallman committed
177

178

179
(defsubst winner-equal (a b)
180 181 182
  "Check whether two Winner configurations (as produced by
`winner-conf') are equal."
  (equal (cdr a) (cdr b)))
183 184


185
;; Save the current window configuration, if it has changed.
186
;; If so return frame, otherwise return nil.
187 188 189 190 191 192 193
(defun winner-insert-if-new (frame)
  (unless (or (memq frame winner-last-frames)
	      (eq this-command 'winner-redo))
    (let ((conf (winner-configuration frame))
	  (ring (winner-ring frame)))
      (when (and (not (ring-empty-p ring))
		 (winner-equal conf (ring-ref ring 0)))
194 195
        ;; When the previous configuration was very similar,
        ;; keep only the latest.
196 197 198 199 200
	(ring-remove ring 0))
      (ring-insert ring conf)
      (push frame winner-last-frames)
      frame)))

201 202 203 204


;;; Hooks

205 206 207 208 209
;; Frames affected by the current command.
(defvar winner-modified-list nil)

;; Called whenever the window configuration changes
;; (a `window-configuration-change-hook').
210
(defun winner-change-fun ()
211 212
  (unless (or (memq (selected-frame) winner-modified-list)
              (/= 0 (minibuffer-depth)))
213
    (push (selected-frame) winner-modified-list)))
Richard M. Stallman's avatar
Richard M. Stallman committed
214

215 216
;; A `post-command-hook' for emacsen with
;; `window-configuration-change-hook'.
217
(defun winner-save-old-configurations ()
218 219 220 221 222 223 224 225 226 227
  (when (zerop (minibuffer-depth))
    (unless (eq this-command winner-last-command)
      (setq winner-last-frames nil)
      (setq winner-last-command this-command))
    (dolist (frame winner-modified-list)
      (winner-insert-if-new frame))
    (setq winner-modified-list nil)
    (winner-remember)))

;; A `minibuffer-setup-hook'.
228
(defun winner-save-unconditionally ()
229 230 231 232 233
  (unless (eq this-command winner-last-command)
    (setq winner-last-frames nil)
    (setq winner-last-command this-command))
  (winner-insert-if-new (selected-frame))
  (winner-remember))
234

235 236 237 238 239
;; A `post-command-hook' for other emacsen.
;; Also called by `winner-undo' before "undoing".
(defun winner-save-conditionally ()
  (when (zerop (minibuffer-depth))
    (winner-save-unconditionally)))
240 241 242



243 244

;;;; Restoring configurations
245 246

;; Works almost as `set-window-configuration',
247 248
;; but does not change the contents or the size of the minibuffer,
;; and tries to preserve the selected window.
249
(defun winner-set-conf (winconf)
250 251 252 253 254 255 256 257 258 259
  (let* ((miniwin  (minibuffer-window))
         (chosen   (selected-window))
         (minisize (window-height miniwin)))
    (letf (((window-buffer miniwin))
           ((window-point  miniwin)))
      (set-window-configuration winconf))
    (cond
     ((window-live-p chosen) (select-window chosen))
     ((window-minibuffer-p (selected-window))
      (other-window 1)))
260
    (when (/= minisize (window-height miniwin))
261 262 263
      (letf (((selected-window) miniwin) )
        (setf (window-height) minisize)))))

264 265 266 267 268 269 270 271 272 273 274 275


(defvar winner-point-alist nil)
;; `set-window-configuration' restores old points and marks.  This is
;; not what we want, so we make a list of the "real" (i.e. new) points
;; and marks before undoing window configurations.
;;
;; Format of entries: (buffer (mark . mark-active) (window . point) ..)

(defun winner-make-point-alist ()
  (letf (((current-buffer)))
    (loop with alist
276
	  for win in (winner-window-list)
277
	  for entry =
278 279 280 281 282 283
          (or (assq (window-buffer win) alist)
              (car (push (list (set-buffer (window-buffer win))
                               (cons (mark t) (winner-active-region)))
                         alist)))
	  do (push (cons win (window-point win))
                   (cddr entry))
284 285 286 287
	  finally return alist)))

(defun winner-get-point (buf win)
  ;; Consult (and possibly extend) `winner-point-alist'.
Glenn Morris's avatar
Glenn Morris committed
288
  ;; Returns nil if buf no longer exists.
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  (when (buffer-name buf)
    (let ((entry (assq buf winner-point-alist)))
      (cond
       (entry
	(or (cdr (assq win (cddr entry)))
	    (cdr (assq nil (cddr entry)))
	    (letf (((current-buffer) buf))
	      (push (cons nil (point)) (cddr entry))
	      (point))))
       (t (letf (((current-buffer) buf))
	    (push (list buf
			(cons (mark t) (winner-active-region))
			(cons nil (point)))
		  winner-point-alist)
	    (point)))))))

305 306

;; Make sure point does not end up in the minibuffer and delete
307
;; windows displaying dead or boring buffers
Glenn Morris's avatar
Glenn Morris committed
308
;; (c.f. `winner-boring-buffers').  Return nil if all the windows
309
;; should be deleted.  Preserve correct points and marks.
310
(defun winner-set (conf)
311
  ;; For the format of `conf', see `winner-conf'.
312
  (let* ((buffers nil)
313 314 315
	 (alive
          ;; Possibly update `winner-point-alist'
	  (loop for buf in (mapcar 'cdr (cdr conf))
316 317 318 319
		for pos = (winner-get-point buf nil)
		if (and pos (not (memq buf buffers)))
		do (push buf buffers)
		collect pos)))
320
    (winner-set-conf (car conf))
321 322 323 324 325 326 327 328 329 330 331 332
    (let (xwins)                        ; to be deleted

      ;; Restore points
      (dolist (win (winner-sorted-window-list))
        (unless (and (pop alive)
                     (setf (window-point win)
                           (winner-get-point (window-buffer win) win))
                     (not (member (buffer-name (window-buffer win))
                                  winner-boring-buffers)))
          (push win xwins)))            ; delete this window

      ;; Restore marks
333
      (letf (((current-buffer)))
334
	(loop for buf in buffers
335 336 337 338
	      for entry = (cadr (assq buf winner-point-alist))
	      do (progn (set-buffer buf)
			(set-mark (car entry))
			(setf (winner-active-region) (cdr entry)))))
339
      ;; Delete windows, whose buffers are dead or boring.
340 341
      ;; Return t if this is still a possible configuration.
      (or (null xwins)
342 343 344 345 346
	  (progn
            (mapc 'delete-window (cdr xwins)) ; delete all but one
            (unless (one-window-p t)
              (delete-window (car xwins))
              t))))))
347 348 349 350



;;;; Winner mode  (a minor mode)
Richard M. Stallman's avatar
Richard M. Stallman committed
351

Dave Love's avatar
Dave Love committed
352 353 354
(defcustom winner-mode-hook nil
  "Functions to run whenever Winner mode is turned on."
  :type 'hook
Dan Nicolaescu's avatar
Dan Nicolaescu committed
355
  :group 'winner)
Richard M. Stallman's avatar
Richard M. Stallman committed
356

Dan Nicolaescu's avatar
Dan Nicolaescu committed
357
(defcustom winner-mode-leave-hook nil
Dave Love's avatar
Dave Love committed
358 359
  "Functions to run whenever Winner mode is turned off."
  :type 'hook
Dan Nicolaescu's avatar
Dan Nicolaescu committed
360
  :group 'winner)
361

362 363 364 365 366 367
(defvar winner-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map [(control c) left] 'winner-undo)
    (define-key map [(control c) right] 'winner-redo)
    map)
  "Keymap for Winner mode.")
Richard M. Stallman's avatar
Richard M. Stallman committed
368

369
;; Check if `window-configuration-change-hook' is working.
370 371 372 373 374 375 376 377
(defun winner-hook-installed-p ()
  (save-window-excursion
    (let ((winner-var nil)
	  (window-configuration-change-hook
	   '((lambda () (setq winner-var t)))))
      (split-window)
      winner-var)))

378 379

;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
380 381 382 383 384 385 386
(defun winner-mode (&optional arg)
  "Toggle Winner mode.
With arg, turn Winner mode on if and only if arg is positive."
  (interactive "P")
  (let ((on-p (if arg (> (prefix-numeric-value arg) 0)
		(not winner-mode))))
    (cond
387
     ;; Turn mode on
388
     (on-p
389
      (setq winner-mode t)
390 391 392
      (cond
       ((winner-hook-installed-p)
	(add-hook 'window-configuration-change-hook 'winner-change-fun)
393
      (add-hook 'post-command-hook 'winner-save-old-configurations))
394 395
       (t (add-hook 'post-command-hook 'winner-save-conditionally)))
      (add-hook 'minibuffer-setup-hook 'winner-save-unconditionally)
396
      (setq winner-modified-list (frame-list))
397
      (winner-save-old-configurations)
398 399
      (run-hooks 'winner-mode-hook)
      (when (interactive-p) (message "Winner mode enabled")))
400 401 402
     ;; Turn mode off
     (winner-mode
      (setq winner-mode nil)
403
      (remove-hook 'window-configuration-change-hook 'winner-change-fun)
404
      (remove-hook 'post-command-hook 'winner-save-old-configurations)
405 406 407 408
      (remove-hook 'post-command-hook 'winner-save-conditionally)
      (remove-hook 'minibuffer-setup-hook 'winner-save-unconditionally)
      (run-hooks 'winner-mode-leave-hook)
      (when (interactive-p) (message "Winner mode disabled"))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
409

410
;; Inspired by undo (simple.el)
Richard M. Stallman's avatar
Richard M. Stallman committed
411

412 413
(defvar winner-undo-frame nil)

Richard M. Stallman's avatar
Richard M. Stallman committed
414
(defvar winner-pending-undo-ring nil
415
  "The ring currently used by `winner-undo'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
416 417 418
(defvar winner-undo-counter nil)
(defvar winner-undone-data  nil) ; There confs have been passed.

419
(defun winner-undo ()
420
  "Switch back to an earlier window configuration saved by Winner mode.
421 422
In other words, \"undo\" changes in window configuration."
  (interactive)
423 424
  (cond
   ((not winner-mode) (error "Winner mode is turned off"))
425 426
   (t (unless (and (eq last-command 'winner-undo)
 		   (eq winner-undo-frame (selected-frame)))
427
	(winner-save-conditionally)     ; current configuration->stack
428 429 430 431 432 433 434 435 436 437 438
 	(setq winner-undo-frame (selected-frame))
 	(setq winner-point-alist (winner-make-point-alist))
 	(setq winner-pending-undo-ring (winner-ring (selected-frame)))
 	(setq winner-undo-counter 0)
 	(setq winner-undone-data (list (winner-win-data))))
      (incf winner-undo-counter)	; starting at 1
      (when (and (winner-undo-this)
 		 (not (window-minibuffer-p (selected-window))))
 	(message "Winner undo (%d / %d)"
 		 winner-undo-counter
 		 (1- (ring-length winner-pending-undo-ring)))))))
439 440 441



442 443

(defun winner-undo-this ()		; The heart of winner undo.
444
  (loop
445 446 447 448
   (cond
    ((>= winner-undo-counter (ring-length winner-pending-undo-ring))
     (message "No further window configuration undo information")
     (return nil))
449

450 451 452
    ((and				; If possible configuration
      (winner-set (ring-ref winner-pending-undo-ring
 			    winner-undo-counter))
453
                                        ; .. and new configuration
454 455 456
      (let ((data (winner-win-data)))
 	(and (not (member data winner-undone-data))
 	     (push data winner-undone-data))))
457 458
     (return t))			; .. then everything is fine.
    (t ;; Otherwise, discharge it (and try the next one).
459
     (ring-remove winner-pending-undo-ring winner-undo-counter)))))
460

461 462

(defun winner-redo ()			; If you change your mind.
463 464 465 466 467
  "Restore a more recent window configuration saved by Winner mode."
  (interactive)
  (cond
   ((eq last-command 'winner-undo)
    (winner-set
468 469 470
     (if (zerop (minibuffer-depth))
         (ring-remove winner-pending-undo-ring 0)
       (ring-ref winner-pending-undo-ring 0)))
471 472
    (unless (eq (selected-window) (minibuffer-window))
      (message "Winner undid undo")))
473
   (t (error "Previous command was not a `winner-undo'"))))
474

475
;;; To be evaluated when the package is loaded:
476

Richard M. Stallman's avatar
Richard M. Stallman committed
477 478 479 480 481 482
(unless (or (assq 'winner-mode minor-mode-map-alist)
	    winner-dont-bind-my-keys)
  (push (cons 'winner-mode winner-mode-map)
	minor-mode-map-alist))

(provide 'winner)
483
;; arch-tag: 686d1c1b-010e-42ca-a192-b5685112418f
Richard M. Stallman's avatar
Richard M. Stallman committed
484
;;; winner.el ends here