Fix event race
[bpt/emacs.git] / lisp / register.el
1 ;;; register.el --- register commands for Emacs -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 1985, 1993-1994, 2001-2014 Free Software Foundation,
4 ;; Inc.
5
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: internal
8 ;; Package: emacs
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 ;; This package of functions emulates and somewhat extends the venerable
28 ;; TECO's `register' feature, which permits you to save various useful
29 ;; pieces of buffer state to named variables. The entry points are
30 ;; documented in the Emacs user's manual.
31
32 (eval-when-compile (require 'cl-lib))
33
34 ;;; Code:
35
36 (cl-defstruct
37 (registerv (:constructor nil)
38 (:constructor registerv--make (&optional data print-func
39 jump-func insert-func))
40 (:copier nil)
41 (:type vector)
42 :named)
43 (data nil :read-only t)
44 (print-func nil :read-only t)
45 (jump-func nil :read-only t)
46 (insert-func nil :read-only t))
47
48 (cl-defun registerv-make (data &key print-func jump-func insert-func)
49 "Create a register value object.
50
51 DATA can be any value.
52 PRINT-FUNC if provided controls how `list-registers' and
53 `view-register' print the register. It should be a function
54 receiving one argument DATA and print text that completes
55 this sentence:
56 Register X contains [TEXT PRINTED BY PRINT-FUNC]
57 JUMP-FUNC if provided, controls how `jump-to-register' jumps to the register.
58 INSERT-FUNC if provided, controls how `insert-register' insert the register.
59 They both receive DATA as argument."
60 (registerv--make data print-func jump-func insert-func))
61
62 (defvar register-alist nil
63 "Alist of elements (NAME . CONTENTS), one for each Emacs register.
64 NAME is a character (a number). CONTENTS is a string, number, marker, list
65 or a struct returned by `registerv-make'.
66 A list of strings represents a rectangle.
67 A list of the form (file . FILE-NAME) represents the file named FILE-NAME.
68 A list of the form (file-query FILE-NAME POSITION) represents
69 position POSITION in the file named FILE-NAME, but query before
70 visiting it.
71 A list of the form (WINDOW-CONFIGURATION POSITION)
72 represents a saved window configuration plus a saved value of point.
73 A list of the form (FRAME-CONFIGURATION POSITION)
74 represents a saved frame configuration plus a saved value of point.")
75
76 (defgroup register nil
77 "Register commands."
78 :group 'convenience
79 :version "24.3")
80
81 (defcustom register-separator nil
82 "Register containing the text to put between collected texts, or nil if none.
83
84 When collecting text with
85 `append-to-register' (resp. `prepend-to-register') contents of
86 this register is added to the beginning (resp. end) of the marked
87 text."
88 :group 'register
89 :type '(choice (const :tag "None" nil)
90 (character :tag "Use register" :value ?+)))
91
92 (defcustom register-preview-delay 1
93 "If non-nil, time to wait in seconds before popping up a preview window.
94 If nil, do not show register previews, unless `help-char' (or a member of
95 `help-event-list') is pressed."
96 :version "24.4"
97 :type '(choice number (const :tag "No preview unless requested" nil))
98 :group 'register)
99
100 (defun get-register (register)
101 "Return contents of Emacs register named REGISTER, or nil if none."
102 (cdr (assq register register-alist)))
103
104 (defun set-register (register value)
105 "Set contents of Emacs register named REGISTER to VALUE. Returns VALUE.
106 See the documentation of the variable `register-alist' for possible VALUEs."
107 (let ((aelt (assq register register-alist)))
108 (if aelt
109 (setcdr aelt value)
110 (push (cons register value) register-alist))
111 value))
112
113 (defun register-describe-oneline (c)
114 "One-line description of register C."
115 (let ((d (replace-regexp-in-string
116 "\n[ \t]*" " "
117 (with-output-to-string (describe-register-1 c)))))
118 (if (string-match "Register.+? contains \\(?:an? \\|the \\)?" d)
119 (substring d (match-end 0))
120 d)))
121
122 (defun register-preview-default (r)
123 "Default function for the variable `register-preview-function'."
124 (format "%s %s\n"
125 (concat (single-key-description (car r)) ":")
126 (register-describe-oneline (car r))))
127
128 (defvar register-preview-function #'register-preview-default
129 "Function to format a register for previewing.
130 Takes one argument, a cons (NAME . CONTENTS) as found in `register-alist'.
131 Returns a string.")
132
133 (defun register-preview (buffer &optional show-empty)
134 "Pop up a window to show register preview in BUFFER.
135 If SHOW-EMPTY is non-nil show the window even if no registers.
136 Format of each entry is controlled by the variable `register-preview-function'."
137 (when (or show-empty (consp register-alist))
138 (with-temp-buffer-window
139 buffer
140 (cons 'display-buffer-below-selected
141 '((window-height . fit-window-to-buffer)))
142 nil
143 (with-current-buffer standard-output
144 (setq cursor-in-non-selected-windows nil)
145 (insert (mapconcat register-preview-function register-alist ""))))))
146
147 (defun register-read-with-preview (prompt)
148 "Read and return a register name, possibly showing existing registers.
149 Prompt with the string PROMPT. If `register-alist' and
150 `register-preview-delay' are both non-nil, display a window
151 listing existing registers after `register-preview-delay' seconds.
152 If `help-char' (or a member of `help-event-list') is pressed,
153 display such a window regardless."
154 (let* ((buffer "*Register Preview*")
155 (timer (when (numberp register-preview-delay)
156 (run-with-timer register-preview-delay nil
157 (lambda ()
158 (unless (get-buffer-window buffer)
159 (register-preview buffer))))))
160 (help-chars (cl-loop for c in (cons help-char help-event-list)
161 when (not (get-register c))
162 collect c)))
163 (unwind-protect
164 (progn
165 (while (memq (read-event (propertize prompt 'face 'minibuffer-prompt))
166 help-chars)
167 (unless (get-buffer-window buffer)
168 (register-preview buffer 'show-empty)))
169 (if (characterp last-input-event) last-input-event
170 (error "Non-character input-event")))
171 (and (timerp timer) (cancel-timer timer))
172 (let ((w (get-buffer-window buffer)))
173 (and (window-live-p w) (delete-window w)))
174 (and (get-buffer buffer) (kill-buffer buffer)))))
175
176 (defun point-to-register (register &optional arg)
177 "Store current location of point in register REGISTER.
178 With prefix argument, store current frame configuration.
179 Use \\[jump-to-register] to go to that location or restore that configuration.
180 Argument is a character, naming the register.
181
182 Interactively, reads the register using `register-read-with-preview'."
183 (interactive (list (register-read-with-preview "Point to register: ")
184 current-prefix-arg))
185 ;; Turn the marker into a file-ref if the buffer is killed.
186 (add-hook 'kill-buffer-hook 'register-swap-out nil t)
187 (set-register register
188 (if arg (list (current-frame-configuration) (point-marker))
189 (point-marker))))
190
191 (defun window-configuration-to-register (register &optional _arg)
192 "Store the window configuration of the selected frame in register REGISTER.
193 Use \\[jump-to-register] to restore the configuration.
194 Argument is a character, naming the register.
195
196 Interactively, reads the register using `register-read-with-preview'."
197 (interactive (list (register-read-with-preview
198 "Window configuration to register: ")
199 current-prefix-arg))
200 ;; current-window-configuration does not include the value
201 ;; of point in the current buffer, so record that separately.
202 (set-register register (list (current-window-configuration) (point-marker))))
203
204 ;; It has had the optional arg for ages, but never used it.
205 (set-advertised-calling-convention 'window-configuration-to-register
206 '(register) "24.4")
207
208 (defun frame-configuration-to-register (register &optional _arg)
209 "Store the window configuration of all frames in register REGISTER.
210 Use \\[jump-to-register] to restore the configuration.
211 Argument is a character, naming the register.
212
213 Interactively, reads the register using `register-read-with-preview'."
214 (interactive (list (register-read-with-preview
215 "Frame configuration to register: ")
216 current-prefix-arg))
217 ;; current-frame-configuration does not include the value
218 ;; of point in the current buffer, so record that separately.
219 (set-register register (list (current-frame-configuration) (point-marker))))
220
221 ;; It has had the optional arg for ages, but never used it.
222 (set-advertised-calling-convention 'frame-configuration-to-register
223 '(register) "24.4")
224
225 (make-obsolete 'frame-configuration-to-register 'frameset-to-register' "24.4")
226
227 (defalias 'register-to-point 'jump-to-register)
228 (defun jump-to-register (register &optional delete)
229 "Move point to location stored in a register.
230 If the register contains a file name, find that file.
231 \(To put a file name in a register, you must use `set-register'.)
232 If the register contains a window configuration (one frame) or a frameset
233 \(all frames), restore that frame or all frames accordingly.
234 First argument is a character, naming the register.
235 Optional second arg non-nil (interactively, prefix argument) says to
236 delete any existing frames that the frameset doesn't mention.
237 \(Otherwise, these frames are iconified.)
238
239 Interactively, reads the register using `register-read-with-preview'."
240 (interactive (list (register-read-with-preview "Jump to register: ")
241 current-prefix-arg))
242 (let ((val (get-register register)))
243 (cond
244 ((registerv-p val)
245 (cl-assert (registerv-jump-func val) nil
246 "Don't know how to jump to register %s"
247 (single-key-description register))
248 (funcall (registerv-jump-func val) (registerv-data val)))
249 ((and (consp val) (frame-configuration-p (car val)))
250 (set-frame-configuration (car val) (not delete))
251 (goto-char (cadr val)))
252 ((and (consp val) (window-configuration-p (car val)))
253 (set-window-configuration (car val))
254 (goto-char (cadr val)))
255 ((markerp val)
256 (or (marker-buffer val)
257 (error "That register's buffer no longer exists"))
258 (switch-to-buffer (marker-buffer val))
259 (goto-char val))
260 ((and (consp val) (eq (car val) 'file))
261 (find-file (cdr val)))
262 ((and (consp val) (eq (car val) 'file-query))
263 (or (find-buffer-visiting (nth 1 val))
264 (y-or-n-p (format "Visit file %s again? " (nth 1 val)))
265 (error "Register access aborted"))
266 (find-file (nth 1 val))
267 (goto-char (nth 2 val)))
268 (t
269 (error "Register doesn't contain a buffer position or configuration")))))
270
271 (defun register-swap-out ()
272 "Turn markers into file-query references when a buffer is killed."
273 (and buffer-file-name
274 (dolist (elem register-alist)
275 (and (markerp (cdr elem))
276 (eq (marker-buffer (cdr elem)) (current-buffer))
277 (setcdr elem
278 (list 'file-query
279 buffer-file-name
280 (marker-position (cdr elem))))))))
281
282 (defun number-to-register (number register)
283 "Store a number in a register.
284 Two args, NUMBER and REGISTER (a character, naming the register).
285 If NUMBER is nil, a decimal number is read from the buffer starting
286 at point, and point moves to the end of that number.
287 Interactively, NUMBER is the prefix arg (none means nil).
288
289 Interactively, reads the register using `register-read-with-preview'."
290 (interactive (list current-prefix-arg
291 (register-read-with-preview "Number to register: ")))
292 (set-register register
293 (if number
294 (prefix-numeric-value number)
295 (if (looking-at "\\s-*-?[0-9]+")
296 (progn
297 (goto-char (match-end 0))
298 (string-to-number (match-string 0)))
299 0))))
300
301 (defun increment-register (prefix register)
302 "Augment contents of REGISTER.
303 Interactively, PREFIX is in raw form.
304
305 If REGISTER contains a number, add `prefix-numeric-value' of
306 PREFIX to it.
307
308 If REGISTER is empty or if it contains text, call
309 `append-to-register' with `delete-flag' set to PREFIX.
310
311 Interactively, reads the register using `register-read-with-preview'."
312 (interactive (list current-prefix-arg
313 (register-read-with-preview "Increment register: ")))
314 (let ((register-val (get-register register)))
315 (cond
316 ((numberp register-val)
317 (let ((number (prefix-numeric-value prefix)))
318 (set-register register (+ number register-val))))
319 ((or (not register-val) (stringp register-val))
320 (append-to-register register (region-beginning) (region-end) prefix))
321 (t (error "Register does not contain a number or text")))))
322
323 (defun view-register (register)
324 "Display what is contained in register named REGISTER.
325 The Lisp value REGISTER is a character.
326
327 Interactively, reads the register using `register-read-with-preview'."
328 (interactive (list (register-read-with-preview "View register: ")))
329 (let ((val (get-register register)))
330 (if (null val)
331 (message "Register %s is empty" (single-key-description register))
332 (with-output-to-temp-buffer "*Output*"
333 (describe-register-1 register t)))))
334
335 (defun list-registers ()
336 "Display a list of nonempty registers saying briefly what they contain."
337 (interactive)
338 (let ((list (copy-sequence register-alist)))
339 (setq list (sort list (lambda (a b) (< (car a) (car b)))))
340 (with-output-to-temp-buffer "*Output*"
341 (dolist (elt list)
342 (when (get-register (car elt))
343 (describe-register-1 (car elt))
344 (terpri))))))
345
346 (defun describe-register-1 (register &optional verbose)
347 (princ "Register ")
348 (princ (single-key-description register))
349 (princ " contains ")
350 (let ((val (get-register register)))
351 (cond
352 ((registerv-p val)
353 (if (registerv-print-func val)
354 (funcall (registerv-print-func val) (registerv-data val))
355 (princ "[UNPRINTABLE CONTENTS].")))
356
357 ((numberp val)
358 (princ val))
359
360 ((markerp val)
361 (let ((buf (marker-buffer val)))
362 (if (null buf)
363 (princ "a marker in no buffer")
364 (princ "a buffer position:\n buffer ")
365 (princ (buffer-name buf))
366 (princ ", position ")
367 (princ (marker-position val)))))
368
369 ((and (consp val) (window-configuration-p (car val)))
370 (princ "a window configuration."))
371
372 ((and (consp val) (frame-configuration-p (car val)))
373 (princ "a frame configuration."))
374
375 ((and (consp val) (eq (car val) 'file))
376 (princ "the file ")
377 (prin1 (cdr val))
378 (princ "."))
379
380 ((and (consp val) (eq (car val) 'file-query))
381 (princ "a file-query reference:\n file ")
382 (prin1 (car (cdr val)))
383 (princ ",\n position ")
384 (princ (car (cdr (cdr val))))
385 (princ "."))
386
387 ((consp val)
388 (if verbose
389 (progn
390 (princ "the rectangle:\n")
391 (while val
392 (princ " ")
393 (princ (car val))
394 (terpri)
395 (setq val (cdr val))))
396 (princ "a rectangle starting with ")
397 (princ (car val))))
398
399 ((stringp val)
400 (setq val (copy-sequence val))
401 (if (eq yank-excluded-properties t)
402 (set-text-properties 0 (length val) nil val)
403 (remove-list-of-text-properties 0 (length val)
404 yank-excluded-properties val))
405 (if verbose
406 (progn
407 (princ "the text:\n")
408 (princ val))
409 (cond
410 ;; Extract first N characters starting with first non-whitespace.
411 ((string-match (format "[^ \t\n].\\{,%d\\}"
412 ;; Deduct 6 for the spaces inserted below.
413 (min 20 (max 0 (- (window-width) 6))))
414 val)
415 (princ "text starting with\n ")
416 (princ (match-string 0 val)))
417 ((string-match "^[ \t\n]+$" val)
418 (princ "whitespace"))
419 (t
420 (princ "the empty string")))))
421 (t
422 (princ "Garbage:\n")
423 (if verbose (prin1 val))))))
424
425 (defun insert-register (register &optional arg)
426 "Insert contents of register REGISTER. (REGISTER is a character.)
427 Normally puts point before and mark after the inserted text.
428 If optional second arg is non-nil, puts mark before and point after.
429 Interactively, second arg is non-nil if prefix arg is supplied.
430
431 Interactively, reads the register using `register-read-with-preview'."
432 (interactive (progn
433 (barf-if-buffer-read-only)
434 (list (register-read-with-preview "Insert register: ")
435 current-prefix-arg)))
436 (push-mark)
437 (let ((val (get-register register)))
438 (cond
439 ((registerv-p val)
440 (cl-assert (registerv-insert-func val) nil
441 "Don't know how to insert register %s"
442 (single-key-description register))
443 (funcall (registerv-insert-func val) (registerv-data val)))
444 ((consp val)
445 (insert-rectangle val))
446 ((stringp val)
447 (insert-for-yank val))
448 ((numberp val)
449 (princ val (current-buffer)))
450 ((and (markerp val) (marker-position val))
451 (princ (marker-position val) (current-buffer)))
452 (t
453 (error "Register does not contain text"))))
454 (if (not arg) (exchange-point-and-mark)))
455
456 (defun copy-to-register (register start end &optional delete-flag region)
457 "Copy region into register REGISTER.
458 With prefix arg, delete as well.
459 Called from program, takes four args: REGISTER, START, END and DELETE-FLAG.
460 START and END are buffer positions indicating what to copy.
461 The optional argument REGION if non-nil, indicates that we're not just copying
462 some text between START and END, but we're copying the region.
463
464 Interactively, reads the register using `register-read-with-preview'."
465 (interactive (list (register-read-with-preview "Copy to register: ")
466 (region-beginning)
467 (region-end)
468 current-prefix-arg
469 t))
470 (set-register register (if region
471 (funcall region-extract-function delete-flag)
472 (prog1 (filter-buffer-substring start end)
473 (if delete-flag (delete-region start end)))))
474 (setq deactivate-mark t)
475 (cond (delete-flag)
476 ((called-interactively-p 'interactive)
477 (indicate-copied-region))))
478
479 (defun append-to-register (register start end &optional delete-flag)
480 "Append region to text in register REGISTER.
481 With prefix arg, delete as well.
482 Called from program, takes four args: REGISTER, START, END and DELETE-FLAG.
483 START and END are buffer positions indicating what to append.
484
485 Interactively, reads the register using `register-read-with-preview'."
486 (interactive (list (register-read-with-preview "Append to register: ")
487 (region-beginning)
488 (region-end)
489 current-prefix-arg))
490 (let ((reg (get-register register))
491 (text (filter-buffer-substring start end))
492 (separator (and register-separator (get-register register-separator))))
493 (set-register
494 register (cond ((not reg) text)
495 ((stringp reg) (concat reg separator text))
496 (t (error "Register does not contain text")))))
497 (setq deactivate-mark t)
498 (cond (delete-flag
499 (delete-region start end))
500 ((called-interactively-p 'interactive)
501 (indicate-copied-region))))
502
503 (defun prepend-to-register (register start end &optional delete-flag)
504 "Prepend region to text in register REGISTER.
505 With prefix arg, delete as well.
506 Called from program, takes four args: REGISTER, START, END and DELETE-FLAG.
507 START and END are buffer positions indicating what to prepend.
508
509 Interactively, reads the register using `register-read-with-preview'."
510 (interactive (list (register-read-with-preview "Prepend to register: ")
511 (region-beginning)
512 (region-end)
513 current-prefix-arg))
514 (let ((reg (get-register register))
515 (text (filter-buffer-substring start end))
516 (separator (and register-separator (get-register register-separator))))
517 (set-register
518 register (cond ((not reg) text)
519 ((stringp reg) (concat text separator reg))
520 (t (error "Register does not contain text")))))
521 (setq deactivate-mark t)
522 (cond (delete-flag
523 (delete-region start end))
524 ((called-interactively-p 'interactive)
525 (indicate-copied-region))))
526
527 (defun copy-rectangle-to-register (register start end &optional delete-flag)
528 "Copy rectangular region into register REGISTER.
529 With prefix arg, delete as well.
530 To insert this register in the buffer, use \\[insert-register].
531
532 Called from a program, takes four args: REGISTER, START, END and DELETE-FLAG.
533 START and END are buffer positions giving two corners of rectangle.
534
535 Interactively, reads the register using `register-read-with-preview'."
536 (interactive (list (register-read-with-preview
537 "Copy rectangle to register: ")
538 (region-beginning)
539 (region-end)
540 current-prefix-arg))
541 (let ((rectangle (if delete-flag
542 (delete-extract-rectangle start end)
543 (extract-rectangle start end))))
544 (set-register register rectangle)
545 (when (and (null delete-flag)
546 (called-interactively-p 'interactive))
547 (setq deactivate-mark t)
548 (indicate-copied-region (length (car rectangle))))))
549
550 (provide 'register)
551 ;;; register.el ends here