aboutsummaryrefslogtreecommitdiffhomepage
path: root/lib/bufhist.el
blob: 4c24ca42078525db46be6a64d419c30b731302c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
;; bufhist.el --- keep read-only history of buffer contents for browsing

;; This file is part of Proof General.

;; Portions © Copyright 1994-2012  David Aspinall and University of Edinburgh
;; Portions © Copyright 2003, 2012, 2014  Free Software Foundation, Inc.
;; Portions © Copyright 2001-2017  Pierre Courtieu
;; Portions © Copyright 2010, 2016  Erik Martin-Dorel
;; Portions © Copyright 2011-2013, 2016-2017  Hendrik Tews
;; Portions © Copyright 2015-2017  Clément Pit-Claudel

;; Author:     David Aspinall <David.Aspinall@ed.ac.uk>
;; Keywords:   tools

;; License:    GPL (GNU GENERAL PUBLIC LICENSE)

;; This file is distributed under the terms of the GNU General Public
;; License, Version 2.  Find a copy of the GPL with your version of
;; GNU Emacs or Texinfo.

;;; Commentary:
;;
;; This library implements a minor mode for which keeps a ring history of
;; buffer contents.  Intended to be used for small buffers which are
;; intermittently updated (e.g. status panels/displays), for which history
;; browsing is useful.
;;

;; TODO: this will be replaced by a more PG-specific and efficient
;; approach which keep regions within a single buffer rather than
;; copying strings in and out.  That way we can use cloned (indirect)
;; buffers which allow independent browsing of the history.
;;
;; FIXMEs: - autoloading this doesn't work too well.
;;         - advice on erase-buffer doesn't work
;;         - duplicated first item in ring after clear (& on startup).
;;         - buttons are put at top of buffer but inserts happen before them
;;

;;; Code:

(require 'ring)

(declare-function bufhist-ordinary-erase-buffer "bufhist")

;;; First a function which ought to be in ring.el

(defun bufhist-ring-update (ring index newitem)
  "Update RING at position INDEX with NEWITEM."
  (if (ring-empty-p ring)
      (error "Accessing an empty ring")
    (let* ((hd (car ring))  (ln (car (cdr ring)))  (vec (cdr (cdr ring))))
      (aset vec (ring-index index hd ln (length vec)) newitem))))

;;; Now our code

(defgroup bufhist nil
  "In-memory history of buffer contents"
  :group 'tools)

(defcustom bufhist-ring-size 30
  "*Default size of buffer history ring."
  :group 'bufhist
  :type 'integer)

(defvar bufhist-ring nil
  "Ring history of buffer.  Always non-empty.")

(defvar bufhist-ring-pos nil
  "Current position in ring history of buffer.")

(defvar bufhist-lastswitch-modified-tick nil
  "Value of (buffer-modified-tick) at last switch buffer.")

(defvar bufhist-read-only-history t
  "Whether history is editable.")

(defvar bufhist-saved-mode-line-format nil
  "Ordinary value of `mode-line-format' for this buffer.")

(defvar bufhist-normal-read-only nil
  "Ordinary value `buffer-read-only' for this buffer.")

(defvar bufhist-top-point 0
  "Poistion of top of real buffer contents, after buttons.")

(defun bufhist-mode-line-format-entry ()
  (when bufhist-ring-pos
    (let* ((histpos   (- (ring-length bufhist-ring) bufhist-ring-pos))
	   (histsize  (ring-length bufhist-ring))
	   (desc      (format "History %d of %d; mouse-1 previous; mouse-3 next"
			      histpos histsize))
	   (indicator (format "[%d/%d]" histpos histsize)))
      (propertize
       indicator
       'help-echo desc
       'keymap (eval-when-compile
		 (let ((map (make-sparse-keymap)))
		   ;; FIXME: clicking can go wrong here because the
		   ;; current buffer can be something else which has no hist!
		   (define-key map [mode-line mouse-1] 'bufhist-prev)
		   (define-key map [mode-line mouse-3] 'bufhist-next)
		   ;; (define-key map [mode-line control mouse-1] 'bufhist-first)
		   ;; (define-key map [mode-line control mouse-3] 'bufhist-last)
		   map))
       'mouse-face 'mode-line-highlight))))

;simple:
;  '(" [hist:"
;    (:eval (int-to-string (- (ring-length bufhist-)
;			     bufhist-ring-pos))) "/"
;    (:eval (int-to-string (ring-length bufhist-ring))) "]"))

;;; Minor mode

(defconst bufhist-minor-mode-map
  (let ((map (make-sparse-keymap)))
    ;; (define-key map [mouse-2] 'bufhist-popup-menu)
    (define-key map [(meta left)] 'bufhist-prev)
    (define-key map [(meta right)] 'bufhist-next)
    (define-key map [(meta up)] 'bufhist-first)
    (define-key map [(meta down)] 'bufhist-last)
    (define-key map [(meta c)] 'bufhist-clear)
    (define-key map [(meta d)] 'bufhist-delete)
    map)
  "Keymap for `bufhist-minor-mode'.")

;;;###autoload
(define-minor-mode bufhist-mode
  "Minor mode retaining an in-memory history of the buffer contents.

Commands:\\<bufhist-minor-mode-map>
\\[bufhist-prev]    bufhist-prev    go back in history
\\[bufhist-next]    bufhist-next    go forward in history
\\[bufhist-first]   bufhist-first   go to first item in history
\\[bufhist-last]    bufhist-last    go to last (current) item in history.
\\[bufhist-clear]   bufhist-clear   clear history.
\\[bufhist-delete]  bufhist-clear   delete current item from history."
  nil "" bufhist-minor-mode-map
  :group 'bufhist
  (if bufhist-mode
      (bufhist-init)
    (bufhist-exit)))

(make-variable-buffer-local 'bufhist-ring)
(make-variable-buffer-local 'bufhist-ring-pos)
(make-variable-buffer-local 'bufhist-lastswitch-modified-tick)
(make-variable-buffer-local 'bufhist-read-only-history)
(make-variable-buffer-local 'bufhist-top-point)

(defun bufhist-get-buffer-contents ()
  "Return the stored representation of the current buffer contents.
This is as a pair (POINT . CONTENTS)."
  (cons (point)
	(buffer-substring bufhist-top-point (point-max))))

(fset 'bufhist-ordinary-erase-buffer (symbol-function 'erase-buffer))
;(defalias 'bufhist-ordinary-erase-buffer 'erase-buffer)

(defun bufhist-restore-buffer-contents (buf)
  "Restore BUF as the contents of the current buffer."
  (bufhist-ordinary-erase-buffer)
  (bufhist-insert-buttons)
  (insert (cdr buf))
  ;; don't count this as a buffer update
  (setq bufhist-lastswitch-modified-tick (buffer-modified-tick))
  (goto-char (car buf)))

(defun bufhist-checkpoint ()
  "Add buffer contents to the ring history.  No action if not in bufhist mode."
  (interactive)
  (if bufhist-mode ;; safety
      (ring-insert bufhist-ring (bufhist-get-buffer-contents))))

;; Unfortunately, erase-buffer doesn't call before-change-functions.
;; We could provide advice for erase-buffer, but instead make this part of API.
(defun bufhist-erase-buffer ()
  "Erase buffer contents, maybe running bufhist-before-change-function first."
  (if (and
       bufhist-mode
       (memq 'bufhist-before-change-function before-change-functions))
      (let ((before-change-functions nil)
	    (after-change-functions nil))
	(bufhist-before-change-function)))
  (erase-buffer)
  (bufhist-insert-buttons))

(defun bufhist-checkpoint-and-erase ()
  "Add buffer contents to history then erase. Only erase if not in bufhist mode"
  (interactive)
  (bufhist-checkpoint)
  (bufhist-erase-buffer))

(defun bufhist-switch-to-index (n &optional nosave browsing)
  "Switch to position N in buffer history, maybe updating history.
If optional NOSAVE is non-nil, do not try to save current contents."
  (unless (equal n bufhist-ring-pos)
    ;; we're moving to different position
    (let ((tick (buffer-modified-tick)))
      ;; Save changes back to history for most recent contents or for
      ;; older contents if we have read-write history
      (unless (or nosave
		  (and bufhist-read-only-history (not (eq bufhist-ring-pos 0)))
		  (equal tick bufhist-lastswitch-modified-tick))
	;; If we're browsing away from position 0, checkpoint instead
	;; of updating.
	;; NB: logic here should ideally keep flag to say whether
	;; changes are "during" a browse or not.  This is going
	;; to result in too many checkpoints if we have manual
	;; editing.
	(if (and browsing (eq bufhist-ring-pos 0))
	    ;(progn
	    (bufhist-checkpoint)
	  ; (setq n (1+ n)))
	  ;; Otherwise update in-position
	  (bufhist-ring-update bufhist-ring bufhist-ring-pos
			       (bufhist-get-buffer-contents))))
      (setq bufhist-lastswitch-modified-tick tick)
      (let ((before-change-functions nil)
	    (buffer-read-only nil))
	(bufhist-restore-buffer-contents (ring-ref bufhist-ring n)))
      (if bufhist-read-only-history
	  (setq buffer-read-only
		(if (eq n 0) bufhist-normal-read-only t)))
      (setq bufhist-ring-pos n)
      (force-mode-line-update)
      (if browsing
	  (message "History position %d of %d in %s"
		   (- (ring-length bufhist-ring) n)
		   (ring-length bufhist-ring)
		   (buffer-name))))))

(defun bufhist-first ()
  "Switch to most oldest buffer contents."
  (interactive)
  (bufhist-switch-to-index (1- (ring-length bufhist-ring)) nil 'browsing))

(defun bufhist-last ()
  "Switch to last (most recent; current) buffer contents."
  (interactive)
  (bufhist-switch-to-index 0 nil 'browsing))

(defun bufhist-prev (&optional n)
  "Browse backward in the history of buffer contents."
  (interactive "p")
  (bufhist-switch-to-index
   (mod (+ bufhist-ring-pos (or n 1))
	(ring-length bufhist-ring))
   nil 'browsing))

(defun bufhist-next (&optional n)
  "Browse forward in the history of buffer contents."
  (interactive "p")
  (bufhist-prev (- (or n 1))))

(defun bufhist-delete ()
  "Delete the current item in the buffer history."
  (interactive)
  (message "History item deleted from buffer %s." (buffer-name))
  (unless (eq 0 bufhist-ring-pos)
    (ring-remove bufhist-ring bufhist-ring-pos)
    (bufhist-switch-to-index (1- bufhist-ring-pos) 'nosave)))

;; FIXME: glitch here: we get duplicated first item after clear.
;; Bit like on startup: we always get empty buffer/current contents
;; twice.  Reason is because of invariant of non-empty ring;
;; when we checkpoint we always add to ring.
(defun bufhist-clear ()
  "Clear history."
  (interactive)
  (message "Buffer history in %s cleared." (buffer-name))
  (bufhist-switch-to-index 0 'nosave)
  (setq bufhist-ring (make-ring (ring-size bufhist-ring)))
  (setq bufhist-ring-pos 0)
  (bufhist-checkpoint)
  (setq bufhist-lastswitch-modified-tick (buffer-modified-tick))
  (force-mode-line-update))


;; Setup functions

;;;###autoload
(defun bufhist-init (&optional readwrite ringsize)
  "Initialise a ring history for the current buffer.
The history will be read-only unless READWRITE is non-nil.
For read-only histories, edits to the buffer switch to the latest version.
The size defaults to `bufhist-ring-size'."
  (interactive)
  (setq bufhist-ring (make-ring (or ringsize bufhist-ring-size)))
  (setq bufhist-normal-read-only buffer-read-only)
  (setq bufhist-read-only-history (not readwrite))
  (setq bufhist-ring-pos 0)
  (setq bufhist-saved-mode-line-format mode-line-format)
  (save-excursion
    (goto-char (point-min))
    (bufhist-insert-buttons))
  (bufhist-checkpoint)
  (setq mode-line-format
	(cons '(bufhist-mode
		(:eval (bufhist-mode-line-format-entry)))
	      ;; surely it's always a list, but in case not
	      (if (listp mode-line-format)
		  mode-line-format
		(list mode-line-format))))
  (force-mode-line-update)
  (make-local-variable 'before-change-functions)
  (bufhist-set-readwrite readwrite))


;;;###autoload
(defun bufhist-exit ()
  "Stop keeping ring history for current buffer."
  (interactive)
  (bufhist-switch-to-index 0)
  (setq bufhist-ring-pos nil)
  (bufhist-set-readwrite t)
  (setq mode-line-format bufhist-saved-mode-line-format)
  (force-mode-line-update))


(defun bufhist-set-readwrite (readwrite)
  "Set `before-change-functions' for read-only history."
  (if readwrite
      ;; edit directly
      (progn
	(setq before-change-functions
	      (remq 'bufhist-before-change-function before-change-functions)))
;	    (ad-disable-advice 'erase-buffer 'before 'bufhist-last-advice)))
    ;; readonly history: switch to latest contents
    (setq before-change-functions
	  (cons 'bufhist-before-change-function before-change-functions))))
;	    (ad-enable-advice 'erase-buffer 'before 'bufhist-last-advice))))

;; Restore the latest buffer contents before changes from elsewhere.

(defun bufhist-before-change-function (&rest args)
  "Restore the most recent contents of the buffer before changes."
  (bufhist-switch-to-index 0))

;; Unfortunately, erase-buffer does not call before-change-function
;      (defadvice erase-buffer (before bufhist-last-advice activate)
;	(if (and bufhist-mode bufhist-read-only-history)
;	    (bufhist-last)))
;      (ad-activate-on 'erase-buffer)))

;;;
;;; Buttons
;;;

(define-button-type 'bufhist-next
  'follow-link t
  'help-echo "Next"
  'action #'bufhist-next)
(define-button-type 'bufhist-prev
  'follow-link t
  'help-echo "Previous"
  'action #'bufhist-prev)

;; Little bit tricky: inserts by clients start at (point-min) which
;; is going to insert above these buttons
(defun bufhist-insert-buttons ()
  (when bufhist-mode
    (let ((inhibit-read-only t))
      (save-excursion
	(goto-char (point-min))
	(insert-text-button " < " :type 'bufhist-prev)
	(insert " ")
	(insert-text-button " > " :type 'bufhist-next)
	(insert "\n\n")
	(setq bufhist-top-point (point))))))

(provide 'bufhist)