]> code.delx.au - gnu-emacs/blob - lisp/simple.el
* lisp/simple.el (undo-amalgamate-change-group): New function
[gnu-emacs] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1985-1987, 1993-2016 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl-lib))
32
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
35
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
39
40 (defcustom idle-update-delay 0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
44 :type 'number
45 :group 'display
46 :version "22.1")
47
48 (defgroup killing nil
49 "Killing and yanking commands."
50 :group 'editing)
51
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
54 :group 'matching)
55 \f
56 ;;; next-error support framework
57
58 (defgroup next-error nil
59 "`next-error' support framework."
60 :group 'compilation
61 :version "22.1")
62
63 (defface next-error
64 '((t (:inherit region)))
65 "Face used to highlight next error locus."
66 :group 'next-error
67 :version "22.1")
68
69 (defcustom next-error-highlight 0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow
77 indefinitely until some other locus replaces it."
78 :type '(choice (number :tag "Highlight for specified time")
79 (const :tag "Semipermanent highlighting" t)
80 (const :tag "No highlighting" nil)
81 (const :tag "Fringe arrow" fringe-arrow))
82 :group 'next-error
83 :version "22.1")
84
85 (defcustom next-error-highlight-no-select 0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow
91 indefinitely until some other locus replaces it."
92 :type '(choice (number :tag "Highlight for specified time")
93 (const :tag "Semipermanent highlighting" t)
94 (const :tag "No highlighting" nil)
95 (const :tag "Fringe arrow" fringe-arrow))
96 :group 'next-error
97 :version "22.1")
98
99 (defcustom next-error-recenter nil
100 "Display the line in the visited source file recentered as specified.
101 If non-nil, the value is passed directly to `recenter'."
102 :type '(choice (integer :tag "Line to recenter to")
103 (const :tag "Center of window" (4))
104 (const :tag "No recentering" nil))
105 :group 'next-error
106 :version "23.1")
107
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
110 :type 'hook
111 :group 'next-error)
112
113 (defvar next-error-highlight-timer nil)
114
115 (defvar next-error-overlay-arrow-position nil)
116 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
117 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
118
119 (defvar next-error-last-buffer nil
120 "The most recent `next-error' buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
124
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
133 to navigate in it.")
134 (make-variable-buffer-local 'next-error-function)
135
136 (defvar next-error-move-function nil
137 "Function to use to move to an error locus.
138 It takes two arguments, a buffer position in the error buffer
139 and a buffer position in the error locus buffer.
140 The buffer for the error locus should already be current.
141 nil means use goto-char using the second argument position.")
142 (make-variable-buffer-local 'next-error-move-function)
143
144 (defsubst next-error-buffer-p (buffer
145 &optional avoid-current
146 extra-test-inclusive
147 extra-test-exclusive)
148 "Return non-nil if BUFFER is a `next-error' capable buffer.
149 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
150 return nil.
151
152 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
153 BUFFER would not normally qualify. If it returns non-nil, BUFFER
154 is considered `next-error' capable, anyway, and the function
155 returns non-nil.
156
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
158 buffer would normally qualify. If it returns nil, BUFFER is
159 rejected, and the function returns nil."
160 (and (buffer-name buffer) ;First make sure it's live.
161 (not (and avoid-current (eq buffer (current-buffer))))
162 (with-current-buffer buffer
163 (if next-error-function ; This is the normal test.
164 ;; Optionally reject some buffers.
165 (if extra-test-exclusive
166 (funcall extra-test-exclusive)
167 t)
168 ;; Optionally accept some other buffers.
169 (and extra-test-inclusive
170 (funcall extra-test-inclusive))))))
171
172 (defun next-error-find-buffer (&optional avoid-current
173 extra-test-inclusive
174 extra-test-exclusive)
175 "Return a `next-error' capable buffer.
176
177 If AVOID-CURRENT is non-nil, treat the current buffer
178 as an absolute last resort only.
179
180 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 that normally would not qualify. If it returns t, the buffer
182 in question is treated as usable.
183
184 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 that would normally be considered usable. If it returns nil,
186 that buffer is rejected."
187 (or
188 ;; 1. If one window on the selected frame displays such buffer, return it.
189 (let ((window-buffers
190 (delete-dups
191 (delq nil (mapcar (lambda (w)
192 (if (next-error-buffer-p
193 (window-buffer w)
194 avoid-current
195 extra-test-inclusive extra-test-exclusive)
196 (window-buffer w)))
197 (window-list))))))
198 (if (eq (length window-buffers) 1)
199 (car window-buffers)))
200 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201 (if (and next-error-last-buffer
202 (next-error-buffer-p next-error-last-buffer avoid-current
203 extra-test-inclusive extra-test-exclusive))
204 next-error-last-buffer)
205 ;; 3. If the current buffer is acceptable, choose it.
206 (if (next-error-buffer-p (current-buffer) avoid-current
207 extra-test-inclusive extra-test-exclusive)
208 (current-buffer))
209 ;; 4. Look for any acceptable buffer.
210 (let ((buffers (buffer-list)))
211 (while (and buffers
212 (not (next-error-buffer-p
213 (car buffers) avoid-current
214 extra-test-inclusive extra-test-exclusive)))
215 (setq buffers (cdr buffers)))
216 (car buffers))
217 ;; 5. Use the current buffer as a last resort if it qualifies,
218 ;; even despite AVOID-CURRENT.
219 (and avoid-current
220 (next-error-buffer-p (current-buffer) nil
221 extra-test-inclusive extra-test-exclusive)
222 (progn
223 (message "This is the only buffer with error message locations")
224 (current-buffer)))
225 ;; 6. Give up.
226 (error "No buffers contain error message locations")))
227
228 (defun next-error (&optional arg reset)
229 "Visit next `next-error' message and corresponding source code.
230
231 If all the error messages parsed so far have been processed already,
232 the message buffer is checked for new ones.
233
234 A prefix ARG specifies how many error messages to move;
235 negative means move back to previous error messages.
236 Just \\[universal-argument] as a prefix means reparse the error message buffer
237 and start at the first error.
238
239 The RESET argument specifies that we should restart from the beginning.
240
241 \\[next-error] normally uses the most recently started
242 compilation, grep, or occur buffer. It can also operate on any
243 buffer with output from the \\[compile], \\[grep] commands, or,
244 more generally, on any buffer in Compilation mode or with
245 Compilation Minor mode enabled, or any buffer in which
246 `next-error-function' is bound to an appropriate function.
247 To specify use of a particular buffer for error messages, type
248 \\[next-error] in that buffer when it is the only one displayed
249 in the current frame.
250
251 Once \\[next-error] has chosen the buffer for error messages, it
252 runs `next-error-hook' with `run-hooks', and stays with that buffer
253 until you use it in some other buffer which uses Compilation mode
254 or Compilation Minor mode.
255
256 To control which errors are matched, customize the variable
257 `compilation-error-regexp-alist'."
258 (interactive "P")
259 (if (consp arg) (setq reset t arg nil))
260 (when (setq next-error-last-buffer (next-error-find-buffer))
261 ;; we know here that next-error-function is a valid symbol we can funcall
262 (with-current-buffer next-error-last-buffer
263 (funcall next-error-function (prefix-numeric-value arg) reset)
264 (when next-error-recenter
265 (recenter next-error-recenter))
266 (run-hooks 'next-error-hook))))
267
268 (defun next-error-internal ()
269 "Visit the source code corresponding to the `next-error' message at point."
270 (setq next-error-last-buffer (current-buffer))
271 ;; we know here that next-error-function is a valid symbol we can funcall
272 (with-current-buffer next-error-last-buffer
273 (funcall next-error-function 0 nil)
274 (when next-error-recenter
275 (recenter next-error-recenter))
276 (run-hooks 'next-error-hook)))
277
278 (defalias 'goto-next-locus 'next-error)
279 (defalias 'next-match 'next-error)
280
281 (defun previous-error (&optional n)
282 "Visit previous `next-error' message and corresponding source code.
283
284 Prefix arg N says how many error messages to move backwards (or
285 forwards, if negative).
286
287 This operates on the output from the \\[compile] and \\[grep] commands."
288 (interactive "p")
289 (next-error (- (or n 1))))
290
291 (defun first-error (&optional n)
292 "Restart at the first error.
293 Visit corresponding source code.
294 With prefix arg N, visit the source code of the Nth error.
295 This operates on the output from the \\[compile] command, for instance."
296 (interactive "p")
297 (next-error n t))
298
299 (defun next-error-no-select (&optional n)
300 "Move point to the next error in the `next-error' buffer and highlight match.
301 Prefix arg N says how many error messages to move forwards (or
302 backwards, if negative).
303 Finds and highlights the source line like \\[next-error], but does not
304 select the source buffer."
305 (interactive "p")
306 (let ((next-error-highlight next-error-highlight-no-select))
307 (next-error n))
308 (pop-to-buffer next-error-last-buffer))
309
310 (defun previous-error-no-select (&optional n)
311 "Move point to the previous error in the `next-error' buffer and highlight match.
312 Prefix arg N says how many error messages to move backwards (or
313 forwards, if negative).
314 Finds and highlights the source line like \\[previous-error], but does not
315 select the source buffer."
316 (interactive "p")
317 (next-error-no-select (- (or n 1))))
318
319 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 (defvar next-error-follow-last-line nil)
321
322 (define-minor-mode next-error-follow-minor-mode
323 "Minor mode for compilation, occur and diff modes.
324 With a prefix argument ARG, enable mode if ARG is positive, and
325 disable it otherwise. If called from Lisp, enable mode if ARG is
326 omitted or nil.
327 When turned on, cursor motion in the compilation, grep, occur or diff
328 buffer causes automatic display of the corresponding source code location."
329 :group 'next-error :init-value nil :lighter " Fol"
330 (if (not next-error-follow-minor-mode)
331 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
332 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
333 (make-local-variable 'next-error-follow-last-line)))
334
335 ;; Used as a `post-command-hook' by `next-error-follow-mode'
336 ;; for the *Compilation* *grep* and *Occur* buffers.
337 (defun next-error-follow-mode-post-command-hook ()
338 (unless (equal next-error-follow-last-line (line-number-at-pos))
339 (setq next-error-follow-last-line (line-number-at-pos))
340 (condition-case nil
341 (let ((compilation-context-lines nil))
342 (setq compilation-current-error (point))
343 (next-error-no-select 0))
344 (error t))))
345
346 \f
347 ;;;
348
349 (defun fundamental-mode ()
350 "Major mode not specialized for anything in particular.
351 Other major modes are defined by comparison with this one."
352 (interactive)
353 (kill-all-local-variables)
354 (run-mode-hooks))
355
356 ;; Special major modes to view specially formatted data rather than files.
357
358 (defvar special-mode-map
359 (let ((map (make-sparse-keymap)))
360 (suppress-keymap map)
361 (define-key map "q" 'quit-window)
362 (define-key map " " 'scroll-up-command)
363 (define-key map [?\S-\ ] 'scroll-down-command)
364 (define-key map "\C-?" 'scroll-down-command)
365 (define-key map "?" 'describe-mode)
366 (define-key map "h" 'describe-mode)
367 (define-key map ">" 'end-of-buffer)
368 (define-key map "<" 'beginning-of-buffer)
369 (define-key map "g" 'revert-buffer)
370 map))
371
372 (put 'special-mode 'mode-class 'special)
373 (define-derived-mode special-mode nil "Special"
374 "Parent major mode from which special major modes should inherit."
375 (setq buffer-read-only t))
376
377 ;; Making and deleting lines.
378
379 (defvar self-insert-uses-region-functions nil
380 "Special hook to tell if `self-insert-command' will use the region.
381 It must be called via `run-hook-with-args-until-success' with no arguments.
382 Any `post-self-insert-command' which consumes the region should
383 register a function on this hook so that things like `delete-selection-mode'
384 can refrain from consuming the region.")
385
386 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
387 "Propertized string representing a hard newline character.")
388
389 (defun newline (&optional arg interactive)
390 "Insert a newline, and move to left margin of the new line if it's blank.
391 If option `use-hard-newlines' is non-nil, the newline is marked with the
392 text-property `hard'.
393 With ARG, insert that many newlines.
394
395 If `electric-indent-mode' is enabled, this indents the final new line
396 that it adds, and reindents the preceding line. To just insert
397 a newline, use \\[electric-indent-just-newline].
398
399 Calls `auto-fill-function' if the current column number is greater
400 than the value of `fill-column' and ARG is nil.
401 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
402 (interactive "*P\np")
403 (barf-if-buffer-read-only)
404 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
405 ;; Set last-command-event to tell self-insert what to insert.
406 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
407 (beforepos (point))
408 (last-command-event ?\n)
409 ;; Don't auto-fill if we have a numeric argument.
410 (auto-fill-function (if arg nil auto-fill-function))
411 (arg (prefix-numeric-value arg))
412 (postproc
413 ;; Do the rest in post-self-insert-hook, because we want to do it
414 ;; *before* other functions on that hook.
415 (lambda ()
416 ;; We are not going to insert any newlines if arg is
417 ;; non-positive.
418 (or (and (numberp arg) (<= arg 0))
419 (cl-assert (eq ?\n (char-before))))
420 ;; Mark the newline(s) `hard'.
421 (if use-hard-newlines
422 (set-hard-newline-properties
423 (- (point) arg) (point)))
424 ;; If the newline leaves the previous line blank, and we
425 ;; have a left margin, delete that from the blank line.
426 (save-excursion
427 (goto-char beforepos)
428 (beginning-of-line)
429 (and (looking-at "[ \t]$")
430 (> (current-left-margin) 0)
431 (delete-region (point)
432 (line-end-position))))
433 ;; Indent the line after the newline, except in one case:
434 ;; when we added the newline at the beginning of a line which
435 ;; starts a page.
436 (or was-page-start
437 (move-to-left-margin nil t)))))
438 (unwind-protect
439 (if (not interactive)
440 ;; FIXME: For non-interactive uses, many calls actually
441 ;; just want (insert "\n"), so maybe we should do just
442 ;; that, so as to avoid the risk of filling or running
443 ;; abbrevs unexpectedly.
444 (let ((post-self-insert-hook (list postproc)))
445 (self-insert-command arg))
446 (unwind-protect
447 (progn
448 (add-hook 'post-self-insert-hook postproc nil t)
449 (self-insert-command arg))
450 ;; We first used let-binding to protect the hook, but that
451 ;; was naive since add-hook affects the symbol-default
452 ;; value of the variable, whereas the let-binding might
453 ;; only protect the buffer-local value.
454 (remove-hook 'post-self-insert-hook postproc t)))
455 (cl-assert (not (member postproc post-self-insert-hook)))
456 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
457 nil)
458
459 (defun set-hard-newline-properties (from to)
460 (let ((sticky (get-text-property from 'rear-nonsticky)))
461 (put-text-property from to 'hard 't)
462 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
463 (if (and (listp sticky) (not (memq 'hard sticky)))
464 (put-text-property from (point) 'rear-nonsticky
465 (cons 'hard sticky)))))
466
467 (defun open-line (n)
468 "Insert a newline and leave point before it.
469 If there is a fill prefix and/or a `left-margin', insert them on
470 the new line if the line would have been blank.
471 With arg N, insert N newlines."
472 (interactive "*p")
473 (let* ((do-fill-prefix (and fill-prefix (bolp)))
474 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
475 (loc (point-marker))
476 ;; Don't expand an abbrev before point.
477 (abbrev-mode nil))
478 (newline n)
479 (goto-char loc)
480 (while (> n 0)
481 (cond ((bolp)
482 (if do-left-margin (indent-to (current-left-margin)))
483 (if do-fill-prefix (insert-and-inherit fill-prefix))))
484 (forward-line 1)
485 (setq n (1- n)))
486 (goto-char loc)
487 ;; Necessary in case a margin or prefix was inserted.
488 (end-of-line)))
489
490 (defun split-line (&optional arg)
491 "Split current line, moving portion beyond point vertically down.
492 If the current line starts with `fill-prefix', insert it on the new
493 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
494
495 When called from Lisp code, ARG may be a prefix string to copy."
496 (interactive "*P")
497 (skip-chars-forward " \t")
498 (let* ((col (current-column))
499 (pos (point))
500 ;; What prefix should we check for (nil means don't).
501 (prefix (cond ((stringp arg) arg)
502 (arg nil)
503 (t fill-prefix)))
504 ;; Does this line start with it?
505 (have-prfx (and prefix
506 (save-excursion
507 (beginning-of-line)
508 (looking-at (regexp-quote prefix))))))
509 (newline 1)
510 (if have-prfx (insert-and-inherit prefix))
511 (indent-to col 0)
512 (goto-char pos)))
513
514 (defun delete-indentation (&optional arg)
515 "Join this line to previous and fix up whitespace at join.
516 If there is a fill prefix, delete it from the beginning of this line.
517 With argument, join this line to following line."
518 (interactive "*P")
519 (beginning-of-line)
520 (if arg (forward-line 1))
521 (if (eq (preceding-char) ?\n)
522 (progn
523 (delete-region (point) (1- (point)))
524 ;; If the second line started with the fill prefix,
525 ;; delete the prefix.
526 (if (and fill-prefix
527 (<= (+ (point) (length fill-prefix)) (point-max))
528 (string= fill-prefix
529 (buffer-substring (point)
530 (+ (point) (length fill-prefix)))))
531 (delete-region (point) (+ (point) (length fill-prefix))))
532 (fixup-whitespace))))
533
534 (defalias 'join-line #'delete-indentation) ; easier to find
535
536 (defun delete-blank-lines ()
537 "On blank line, delete all surrounding blank lines, leaving just one.
538 On isolated blank line, delete that one.
539 On nonblank line, delete any immediately following blank lines."
540 (interactive "*")
541 (let (thisblank singleblank)
542 (save-excursion
543 (beginning-of-line)
544 (setq thisblank (looking-at "[ \t]*$"))
545 ;; Set singleblank if there is just one blank line here.
546 (setq singleblank
547 (and thisblank
548 (not (looking-at "[ \t]*\n[ \t]*$"))
549 (or (bobp)
550 (progn (forward-line -1)
551 (not (looking-at "[ \t]*$")))))))
552 ;; Delete preceding blank lines, and this one too if it's the only one.
553 (if thisblank
554 (progn
555 (beginning-of-line)
556 (if singleblank (forward-line 1))
557 (delete-region (point)
558 (if (re-search-backward "[^ \t\n]" nil t)
559 (progn (forward-line 1) (point))
560 (point-min)))))
561 ;; Delete following blank lines, unless the current line is blank
562 ;; and there are no following blank lines.
563 (if (not (and thisblank singleblank))
564 (save-excursion
565 (end-of-line)
566 (forward-line 1)
567 (delete-region (point)
568 (if (re-search-forward "[^ \t\n]" nil t)
569 (progn (beginning-of-line) (point))
570 (point-max)))))
571 ;; Handle the special case where point is followed by newline and eob.
572 ;; Delete the line, leaving point at eob.
573 (if (looking-at "^[ \t]*\n\\'")
574 (delete-region (point) (point-max)))))
575
576 (defcustom delete-trailing-lines t
577 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
578 Trailing lines are deleted only if `delete-trailing-whitespace'
579 is called on the entire buffer (rather than an active region)."
580 :type 'boolean
581 :group 'editing
582 :version "24.3")
583
584 (defun delete-trailing-whitespace (&optional start end)
585 "Delete trailing whitespace between START and END.
586 If called interactively, START and END are the start/end of the
587 region if the mark is active, or of the buffer's accessible
588 portion if the mark is inactive.
589
590 This command deletes whitespace characters after the last
591 non-whitespace character in each line between START and END. It
592 does not consider formfeed characters to be whitespace.
593
594 If this command acts on the entire buffer (i.e. if called
595 interactively with the mark inactive, or called from Lisp with
596 END nil), it also deletes all trailing lines at the end of the
597 buffer if the variable `delete-trailing-lines' is non-nil."
598 (interactive (progn
599 (barf-if-buffer-read-only)
600 (if (use-region-p)
601 (list (region-beginning) (region-end))
602 (list nil nil))))
603 (save-match-data
604 (save-excursion
605 (let ((end-marker (and end (copy-marker end))))
606 (goto-char (or start (point-min)))
607 (with-syntax-table (make-syntax-table (syntax-table))
608 ;; Don't delete formfeeds, even if they are considered whitespace.
609 (modify-syntax-entry ?\f "_")
610 ;; Treating \n as non-whitespace makes things easier.
611 (modify-syntax-entry ?\n "_")
612 (while (re-search-forward "\\s-+$" end-marker t)
613 (delete-region (match-beginning 0) (match-end 0))))
614 (if end
615 (set-marker end-marker nil)
616 ;; Delete trailing empty lines.
617 (and delete-trailing-lines
618 ;; Really the end of buffer.
619 (= (goto-char (point-max)) (1+ (buffer-size)))
620 (<= (skip-chars-backward "\n") -2)
621 (delete-region (1+ (point)) (point-max)))))))
622 ;; Return nil for the benefit of `write-file-functions'.
623 nil)
624
625 (defun newline-and-indent ()
626 "Insert a newline, then indent according to major mode.
627 Indentation is done using the value of `indent-line-function'.
628 In programming language modes, this is the same as TAB.
629 In some text modes, where TAB inserts a tab, this command indents to the
630 column specified by the function `current-left-margin'."
631 (interactive "*")
632 (delete-horizontal-space t)
633 (newline nil t)
634 (indent-according-to-mode))
635
636 (defun reindent-then-newline-and-indent ()
637 "Reindent current line, insert newline, then indent the new line.
638 Indentation of both lines is done according to the current major mode,
639 which means calling the current value of `indent-line-function'.
640 In programming language modes, this is the same as TAB.
641 In some text modes, where TAB inserts a tab, this indents to the
642 column specified by the function `current-left-margin'."
643 (interactive "*")
644 (let ((pos (point)))
645 ;; Be careful to insert the newline before indenting the line.
646 ;; Otherwise, the indentation might be wrong.
647 (newline)
648 (save-excursion
649 (goto-char pos)
650 ;; We are at EOL before the call to indent-according-to-mode, and
651 ;; after it we usually are as well, but not always. We tried to
652 ;; address it with `save-excursion' but that uses a normal marker
653 ;; whereas we need `move after insertion', so we do the save/restore
654 ;; by hand.
655 (setq pos (copy-marker pos t))
656 (indent-according-to-mode)
657 (goto-char pos)
658 ;; Remove the trailing white-space after indentation because
659 ;; indentation may introduce the whitespace.
660 (delete-horizontal-space t))
661 (indent-according-to-mode)))
662
663 (defcustom read-quoted-char-radix 8
664 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
665 Legitimate radix values are 8, 10 and 16."
666 :type '(choice (const 8) (const 10) (const 16))
667 :group 'editing-basics)
668
669 (defun read-quoted-char (&optional prompt)
670 "Like `read-char', but do not allow quitting.
671 Also, if the first character read is an octal digit,
672 we read any number of octal digits and return the
673 specified character code. Any nondigit terminates the sequence.
674 If the terminator is RET, it is discarded;
675 any other terminator is used itself as input.
676
677 The optional argument PROMPT specifies a string to use to prompt the user.
678 The variable `read-quoted-char-radix' controls which radix to use
679 for numeric input."
680 (let ((message-log-max nil)
681 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
682 help-event-list)))
683 done (first t) (code 0) translated)
684 (while (not done)
685 (let ((inhibit-quit first)
686 ;; Don't let C-h or other help chars get the help
687 ;; message--only help function keys. See bug#16617.
688 (help-char nil)
689 (help-event-list help-events)
690 (help-form
691 "Type the special character you want to use,
692 or the octal character code.
693 RET terminates the character code and is discarded;
694 any other non-digit terminates the character code and is then used as input."))
695 (setq translated (read-key (and prompt (format "%s-" prompt))))
696 (if inhibit-quit (setq quit-flag nil)))
697 (if (integerp translated)
698 (setq translated (char-resolve-modifiers translated)))
699 (cond ((null translated))
700 ((not (integerp translated))
701 (setq unread-command-events
702 (nconc (listify-key-sequence (this-single-command-raw-keys))
703 unread-command-events)
704 done t))
705 ((/= (logand translated ?\M-\^@) 0)
706 ;; Turn a meta-character into a character with the 0200 bit set.
707 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
708 done t))
709 ((and (<= ?0 translated)
710 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
711 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
712 (and prompt (setq prompt (message "%s %c" prompt translated))))
713 ((and (<= ?a (downcase translated))
714 (< (downcase translated)
715 (+ ?a -10 (min 36 read-quoted-char-radix))))
716 (setq code (+ (* code read-quoted-char-radix)
717 (+ 10 (- (downcase translated) ?a))))
718 (and prompt (setq prompt (message "%s %c" prompt translated))))
719 ((and (not first) (eq translated ?\C-m))
720 (setq done t))
721 ((not first)
722 (setq unread-command-events
723 (nconc (listify-key-sequence (this-single-command-raw-keys))
724 unread-command-events)
725 done t))
726 (t (setq code translated
727 done t)))
728 (setq first nil))
729 code))
730
731 (defun quoted-insert (arg)
732 "Read next input character and insert it.
733 This is useful for inserting control characters.
734 With argument, insert ARG copies of the character.
735
736 If the first character you type after this command is an octal digit,
737 you should type a sequence of octal digits which specify a character code.
738 Any nondigit terminates the sequence. If the terminator is a RET,
739 it is discarded; any other terminator is used itself as input.
740 The variable `read-quoted-char-radix' specifies the radix for this feature;
741 set it to 10 or 16 to use decimal or hex instead of octal.
742
743 In overwrite mode, this function inserts the character anyway, and
744 does not handle octal digits specially. This means that if you use
745 overwrite as your normal editing mode, you can use this function to
746 insert characters when necessary.
747
748 In binary overwrite mode, this function does overwrite, and octal
749 digits are interpreted as a character code. This is intended to be
750 useful for editing binary files."
751 (interactive "*p")
752 (let* ((char
753 ;; Avoid "obsolete" warnings for translation-table-for-input.
754 (with-no-warnings
755 (let (translation-table-for-input input-method-function)
756 (if (or (not overwrite-mode)
757 (eq overwrite-mode 'overwrite-mode-binary))
758 (read-quoted-char)
759 (read-char))))))
760 ;; This used to assume character codes 0240 - 0377 stand for
761 ;; characters in some single-byte character set, and converted them
762 ;; to Emacs characters. But in 23.1 this feature is deprecated
763 ;; in favor of inserting the corresponding Unicode characters.
764 ;; (if (and enable-multibyte-characters
765 ;; (>= char ?\240)
766 ;; (<= char ?\377))
767 ;; (setq char (unibyte-char-to-multibyte char)))
768 (unless (characterp char)
769 (user-error "%s is not a valid character"
770 (key-description (vector char))))
771 (if (> arg 0)
772 (if (eq overwrite-mode 'overwrite-mode-binary)
773 (delete-char arg)))
774 (while (> arg 0)
775 (insert-and-inherit char)
776 (setq arg (1- arg)))))
777
778 (defun forward-to-indentation (&optional arg)
779 "Move forward ARG lines and position at first nonblank character."
780 (interactive "^p")
781 (forward-line (or arg 1))
782 (skip-chars-forward " \t"))
783
784 (defun backward-to-indentation (&optional arg)
785 "Move backward ARG lines and position at first nonblank character."
786 (interactive "^p")
787 (forward-line (- (or arg 1)))
788 (skip-chars-forward " \t"))
789
790 (defun back-to-indentation ()
791 "Move point to the first non-whitespace character on this line."
792 (interactive "^")
793 (beginning-of-line 1)
794 (skip-syntax-forward " " (line-end-position))
795 ;; Move back over chars that have whitespace syntax but have the p flag.
796 (backward-prefix-chars))
797
798 (defun fixup-whitespace ()
799 "Fixup white space between objects around point.
800 Leave one space or none, according to the context."
801 (interactive "*")
802 (save-excursion
803 (delete-horizontal-space)
804 (if (or (looking-at "^\\|\\s)")
805 (save-excursion (forward-char -1)
806 (looking-at "$\\|\\s(\\|\\s'")))
807 nil
808 (insert ?\s))))
809
810 (defun delete-horizontal-space (&optional backward-only)
811 "Delete all spaces and tabs around point.
812 If BACKWARD-ONLY is non-nil, only delete them before point."
813 (interactive "*P")
814 (let ((orig-pos (point)))
815 (delete-region
816 (if backward-only
817 orig-pos
818 (progn
819 (skip-chars-forward " \t")
820 (constrain-to-field nil orig-pos t)))
821 (progn
822 (skip-chars-backward " \t")
823 (constrain-to-field nil orig-pos)))))
824
825 (defun just-one-space (&optional n)
826 "Delete all spaces and tabs around point, leaving one space (or N spaces).
827 If N is negative, delete newlines as well, leaving -N spaces.
828 See also `cycle-spacing'."
829 (interactive "*p")
830 (cycle-spacing n nil 'single-shot))
831
832 (defvar cycle-spacing--context nil
833 "Store context used in consecutive calls to `cycle-spacing' command.
834 The first time `cycle-spacing' runs, it saves in this variable:
835 its N argument, the original point position, and the original spacing
836 around point.")
837
838 (defun cycle-spacing (&optional n preserve-nl-back mode)
839 "Manipulate whitespace around point in a smart way.
840 In interactive use, this function behaves differently in successive
841 consecutive calls.
842
843 The first call in a sequence acts like `just-one-space'.
844 It deletes all spaces and tabs around point, leaving one space
845 \(or N spaces). N is the prefix argument. If N is negative,
846 it deletes newlines as well, leaving -N spaces.
847 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
848
849 The second call in a sequence deletes all spaces.
850
851 The third call in a sequence restores the original whitespace (and point).
852
853 If MODE is `single-shot', it only performs the first step in the sequence.
854 If MODE is `fast' and the first step would not result in any change
855 \(i.e., there are exactly (abs N) spaces around point),
856 the function goes straight to the second step.
857
858 Repeatedly calling the function with different values of N starts a
859 new sequence each time."
860 (interactive "*p")
861 (let ((orig-pos (point))
862 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
863 (num (abs (or n 1))))
864 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
865 (constrain-to-field nil orig-pos)
866 (cond
867 ;; Command run for the first time, single-shot mode or different argument
868 ((or (eq 'single-shot mode)
869 (not (equal last-command this-command))
870 (not cycle-spacing--context)
871 (not (eq (car cycle-spacing--context) n)))
872 (let* ((start (point))
873 (num (- num (skip-chars-forward " " (+ num (point)))))
874 (mid (point))
875 (end (progn
876 (skip-chars-forward skip-characters)
877 (constrain-to-field nil orig-pos t))))
878 (setq cycle-spacing--context ;; Save for later.
879 ;; Special handling for case where there was no space at all.
880 (unless (= start end)
881 (cons n (cons orig-pos (buffer-substring start (point))))))
882 ;; If this run causes no change in buffer content, delete all spaces,
883 ;; otherwise delete all excess spaces.
884 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
885 start mid) end)
886 (insert (make-string num ?\s))))
887
888 ;; Command run for the second time.
889 ((not (equal orig-pos (point)))
890 (delete-region (point) orig-pos))
891
892 ;; Command run for the third time.
893 (t
894 (insert (cddr cycle-spacing--context))
895 (goto-char (cadr cycle-spacing--context))
896 (setq cycle-spacing--context nil)))))
897 \f
898 (defun beginning-of-buffer (&optional arg)
899 "Move point to the beginning of the buffer.
900 With numeric arg N, put point N/10 of the way from the beginning.
901 If the buffer is narrowed, this command uses the beginning of the
902 accessible part of the buffer.
903
904 Push mark at previous position, unless either a \\[universal-argument] prefix
905 is supplied, or Transient Mark mode is enabled and the mark is active."
906 (declare (interactive-only "use `(goto-char (point-min))' instead."))
907 (interactive "^P")
908 (or (consp arg)
909 (region-active-p)
910 (push-mark))
911 (let ((size (- (point-max) (point-min))))
912 (goto-char (if (and arg (not (consp arg)))
913 (+ (point-min)
914 (if (> size 10000)
915 ;; Avoid overflow for large buffer sizes!
916 (* (prefix-numeric-value arg)
917 (/ size 10))
918 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
919 (point-min))))
920 (if (and arg (not (consp arg))) (forward-line 1)))
921
922 (defun end-of-buffer (&optional arg)
923 "Move point to the end of the buffer.
924 With numeric arg N, put point N/10 of the way from the end.
925 If the buffer is narrowed, this command uses the end of the
926 accessible part of the buffer.
927
928 Push mark at previous position, unless either a \\[universal-argument] prefix
929 is supplied, or Transient Mark mode is enabled and the mark is active."
930 (declare (interactive-only "use `(goto-char (point-max))' instead."))
931 (interactive "^P")
932 (or (consp arg) (region-active-p) (push-mark))
933 (let ((size (- (point-max) (point-min))))
934 (goto-char (if (and arg (not (consp arg)))
935 (- (point-max)
936 (if (> size 10000)
937 ;; Avoid overflow for large buffer sizes!
938 (* (prefix-numeric-value arg)
939 (/ size 10))
940 (/ (* size (prefix-numeric-value arg)) 10)))
941 (point-max))))
942 ;; If we went to a place in the middle of the buffer,
943 ;; adjust it to the beginning of a line.
944 (cond ((and arg (not (consp arg))) (forward-line 1))
945 ((and (eq (current-buffer) (window-buffer))
946 (> (point) (window-end nil t)))
947 ;; If the end of the buffer is not already on the screen,
948 ;; then scroll specially to put it near, but not at, the bottom.
949 (overlay-recenter (point))
950 (recenter -3))))
951
952 (defcustom delete-active-region t
953 "Whether single-char deletion commands delete an active region.
954 This has an effect only if Transient Mark mode is enabled, and
955 affects `delete-forward-char' and `delete-backward-char', though
956 not `delete-char'.
957
958 If the value is the symbol `kill', the active region is killed
959 instead of deleted."
960 :type '(choice (const :tag "Delete active region" t)
961 (const :tag "Kill active region" kill)
962 (const :tag "Do ordinary deletion" nil))
963 :group 'killing
964 :version "24.1")
965
966 (defvar region-extract-function
967 (lambda (delete)
968 (when (region-beginning)
969 (cond
970 ((eq delete 'bounds)
971 (list (cons (region-beginning) (region-end))))
972 ((eq delete 'delete-only)
973 (delete-region (region-beginning) (region-end)))
974 (t
975 (filter-buffer-substring (region-beginning) (region-end) delete)))))
976 "Function to get the region's content.
977 Called with one argument DELETE.
978 If DELETE is `delete-only', then only delete the region and the return value
979 is undefined. If DELETE is nil, just return the content as a string.
980 If DELETE is `bounds', then don't delete, but just return the
981 boundaries of the region as a list of (START . END) positions.
982 If anything else, delete the region and return its content as a string,
983 after filtering it with `filter-buffer-substring'.")
984
985 (defvar region-insert-function
986 (lambda (lines)
987 (let ((first t))
988 (while lines
989 (or first
990 (insert ?\n))
991 (insert-for-yank (car lines))
992 (setq lines (cdr lines)
993 first nil))))
994 "Function to insert the region's content.
995 Called with one argument LINES.
996 Insert the region as a list of lines.")
997
998 (defun delete-backward-char (n &optional killflag)
999 "Delete the previous N characters (following if N is negative).
1000 If Transient Mark mode is enabled, the mark is active, and N is 1,
1001 delete the text in the region and deactivate the mark instead.
1002 To disable this, set option `delete-active-region' to nil.
1003
1004 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1005 kill ring) instead of delete. Interactively, N is the prefix
1006 arg, and KILLFLAG is set if N is explicitly specified.
1007
1008 When killing, the killed text is filtered by
1009 `filter-buffer-substring' before it is saved in the kill ring, so
1010 the actual saved text might be different from what was killed.
1011
1012 In Overwrite mode, single character backward deletion may replace
1013 tabs with spaces so as to back over columns, unless point is at
1014 the end of the line."
1015 (declare (interactive-only delete-char))
1016 (interactive "p\nP")
1017 (unless (integerp n)
1018 (signal 'wrong-type-argument (list 'integerp n)))
1019 (cond ((and (use-region-p)
1020 delete-active-region
1021 (= n 1))
1022 ;; If a region is active, kill or delete it.
1023 (if (eq delete-active-region 'kill)
1024 (kill-region (region-beginning) (region-end) 'region)
1025 (funcall region-extract-function 'delete-only)))
1026 ;; In Overwrite mode, maybe untabify while deleting
1027 ((null (or (null overwrite-mode)
1028 (<= n 0)
1029 (memq (char-before) '(?\t ?\n))
1030 (eobp)
1031 (eq (char-after) ?\n)))
1032 (let ((ocol (current-column)))
1033 (delete-char (- n) killflag)
1034 (save-excursion
1035 (insert-char ?\s (- ocol (current-column)) nil))))
1036 ;; Otherwise, do simple deletion.
1037 (t (delete-char (- n) killflag))))
1038
1039 (defun delete-forward-char (n &optional killflag)
1040 "Delete the following N characters (previous if N is negative).
1041 If Transient Mark mode is enabled, the mark is active, and N is 1,
1042 delete the text in the region and deactivate the mark instead.
1043 To disable this, set variable `delete-active-region' to nil.
1044
1045 Optional second arg KILLFLAG non-nil means to kill (save in kill
1046 ring) instead of delete. Interactively, N is the prefix arg, and
1047 KILLFLAG is set if N was explicitly specified.
1048
1049 When killing, the killed text is filtered by
1050 `filter-buffer-substring' before it is saved in the kill ring, so
1051 the actual saved text might be different from what was killed."
1052 (declare (interactive-only delete-char))
1053 (interactive "p\nP")
1054 (unless (integerp n)
1055 (signal 'wrong-type-argument (list 'integerp n)))
1056 (cond ((and (use-region-p)
1057 delete-active-region
1058 (= n 1))
1059 ;; If a region is active, kill or delete it.
1060 (if (eq delete-active-region 'kill)
1061 (kill-region (region-beginning) (region-end) 'region)
1062 (funcall region-extract-function 'delete-only)))
1063
1064 ;; Otherwise, do simple deletion.
1065 (t (delete-char n killflag))))
1066
1067 (defun mark-whole-buffer ()
1068 "Put point at beginning and mark at end of buffer.
1069 If narrowing is in effect, only uses the accessible part of the buffer.
1070 You probably should not use this function in Lisp programs;
1071 it is usually a mistake for a Lisp function to use any subroutine
1072 that uses or sets the mark."
1073 (declare (interactive-only t))
1074 (interactive)
1075 (push-mark (point))
1076 (push-mark (point-max) nil t)
1077 ;; This is really `point-min' in most cases, but if we're in the
1078 ;; minibuffer, this is at the end of the prompt.
1079 (goto-char (minibuffer-prompt-end)))
1080 \f
1081
1082 ;; Counting lines, one way or another.
1083
1084 (defun goto-line (line &optional buffer)
1085 "Go to LINE, counting from line 1 at beginning of buffer.
1086 If called interactively, a numeric prefix argument specifies
1087 LINE; without a numeric prefix argument, read LINE from the
1088 minibuffer.
1089
1090 If optional argument BUFFER is non-nil, switch to that buffer and
1091 move to line LINE there. If called interactively with \\[universal-argument]
1092 as argument, BUFFER is the most recently selected other buffer.
1093
1094 Prior to moving point, this function sets the mark (without
1095 activating it), unless Transient Mark mode is enabled and the
1096 mark is already active.
1097
1098 This function is usually the wrong thing to use in a Lisp program.
1099 What you probably want instead is something like:
1100 (goto-char (point-min))
1101 (forward-line (1- N))
1102 If at all possible, an even better solution is to use char counts
1103 rather than line counts."
1104 (declare (interactive-only forward-line))
1105 (interactive
1106 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1107 (list (prefix-numeric-value current-prefix-arg))
1108 ;; Look for a default, a number in the buffer at point.
1109 (let* ((default
1110 (save-excursion
1111 (skip-chars-backward "0-9")
1112 (if (looking-at "[0-9]")
1113 (string-to-number
1114 (buffer-substring-no-properties
1115 (point)
1116 (progn (skip-chars-forward "0-9")
1117 (point)))))))
1118 ;; Decide if we're switching buffers.
1119 (buffer
1120 (if (consp current-prefix-arg)
1121 (other-buffer (current-buffer) t)))
1122 (buffer-prompt
1123 (if buffer
1124 (concat " in " (buffer-name buffer))
1125 "")))
1126 ;; Read the argument, offering that number (if any) as default.
1127 (list (read-number (format "Goto line%s: " buffer-prompt)
1128 (list default (line-number-at-pos)))
1129 buffer))))
1130 ;; Switch to the desired buffer, one way or another.
1131 (if buffer
1132 (let ((window (get-buffer-window buffer)))
1133 (if window (select-window window)
1134 (switch-to-buffer-other-window buffer))))
1135 ;; Leave mark at previous position
1136 (or (region-active-p) (push-mark))
1137 ;; Move to the specified line number in that buffer.
1138 (save-restriction
1139 (widen)
1140 (goto-char (point-min))
1141 (if (eq selective-display t)
1142 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1143 (forward-line (1- line)))))
1144
1145 (defun count-words-region (start end &optional arg)
1146 "Count the number of words in the region.
1147 If called interactively, print a message reporting the number of
1148 lines, words, and characters in the region (whether or not the
1149 region is active); with prefix ARG, report for the entire buffer
1150 rather than the region.
1151
1152 If called from Lisp, return the number of words between positions
1153 START and END."
1154 (interactive (if current-prefix-arg
1155 (list nil nil current-prefix-arg)
1156 (list (region-beginning) (region-end) nil)))
1157 (cond ((not (called-interactively-p 'any))
1158 (count-words start end))
1159 (arg
1160 (count-words--buffer-message))
1161 (t
1162 (count-words--message "Region" start end))))
1163
1164 (defun count-words (start end)
1165 "Count words between START and END.
1166 If called interactively, START and END are normally the start and
1167 end of the buffer; but if the region is active, START and END are
1168 the start and end of the region. Print a message reporting the
1169 number of lines, words, and chars.
1170
1171 If called from Lisp, return the number of words between START and
1172 END, without printing any message."
1173 (interactive (list nil nil))
1174 (cond ((not (called-interactively-p 'any))
1175 (let ((words 0))
1176 (save-excursion
1177 (save-restriction
1178 (narrow-to-region start end)
1179 (goto-char (point-min))
1180 (while (forward-word-strictly 1)
1181 (setq words (1+ words)))))
1182 words))
1183 ((use-region-p)
1184 (call-interactively 'count-words-region))
1185 (t
1186 (count-words--buffer-message))))
1187
1188 (defun count-words--buffer-message ()
1189 (count-words--message
1190 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1191 (point-min) (point-max)))
1192
1193 (defun count-words--message (str start end)
1194 (let ((lines (count-lines start end))
1195 (words (count-words start end))
1196 (chars (- end start)))
1197 (message "%s has %d line%s, %d word%s, and %d character%s."
1198 str
1199 lines (if (= lines 1) "" "s")
1200 words (if (= words 1) "" "s")
1201 chars (if (= chars 1) "" "s"))))
1202
1203 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1204
1205 (defun what-line ()
1206 "Print the current buffer line number and narrowed line number of point."
1207 (interactive)
1208 (let ((start (point-min))
1209 (n (line-number-at-pos)))
1210 (if (= start 1)
1211 (message "Line %d" n)
1212 (save-excursion
1213 (save-restriction
1214 (widen)
1215 (message "line %d (narrowed line %d)"
1216 (+ n (line-number-at-pos start) -1) n))))))
1217
1218 (defun count-lines (start end)
1219 "Return number of lines between START and END.
1220 This is usually the number of newlines between them,
1221 but can be one more if START is not equal to END
1222 and the greater of them is not at the start of a line."
1223 (save-excursion
1224 (save-restriction
1225 (narrow-to-region start end)
1226 (goto-char (point-min))
1227 (if (eq selective-display t)
1228 (save-match-data
1229 (let ((done 0))
1230 (while (re-search-forward "[\n\C-m]" nil t 40)
1231 (setq done (+ 40 done)))
1232 (while (re-search-forward "[\n\C-m]" nil t 1)
1233 (setq done (+ 1 done)))
1234 (goto-char (point-max))
1235 (if (and (/= start end)
1236 (not (bolp)))
1237 (1+ done)
1238 done)))
1239 (- (buffer-size) (forward-line (buffer-size)))))))
1240
1241 (defun line-number-at-pos (&optional pos)
1242 "Return (narrowed) buffer line number at position POS.
1243 If POS is nil, use current buffer location.
1244 Counting starts at (point-min), so the value refers
1245 to the contents of the accessible portion of the buffer."
1246 (let ((opoint (or pos (point))) start)
1247 (save-excursion
1248 (goto-char (point-min))
1249 (setq start (point))
1250 (goto-char opoint)
1251 (forward-line 0)
1252 (1+ (count-lines start (point))))))
1253
1254 (defun what-cursor-position (&optional detail)
1255 "Print info on cursor position (on screen and within buffer).
1256 Also describe the character after point, and give its character code
1257 in octal, decimal and hex.
1258
1259 For a non-ASCII multibyte character, also give its encoding in the
1260 buffer's selected coding system if the coding system encodes the
1261 character safely. If the character is encoded into one byte, that
1262 code is shown in hex. If the character is encoded into more than one
1263 byte, just \"...\" is shown.
1264
1265 In addition, with prefix argument, show details about that character
1266 in *Help* buffer. See also the command `describe-char'."
1267 (interactive "P")
1268 (let* ((char (following-char))
1269 (bidi-fixer
1270 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1271 ;; start a directional embedding, which could completely
1272 ;; disrupt the rest of the line (e.g., RLO will display the
1273 ;; rest of the line right-to-left). So we put an invisible
1274 ;; PDF character after these characters, to end the
1275 ;; embedding, which eliminates any effects on the rest of
1276 ;; the line. For RLE and RLO we also append an invisible
1277 ;; LRM, to avoid reordering the following numerical
1278 ;; characters. For LRI/RLI/FSI we append a PDI.
1279 (cond ((memq char '(?\x202a ?\x202d))
1280 (propertize (string ?\x202c) 'invisible t))
1281 ((memq char '(?\x202b ?\x202e))
1282 (propertize (string ?\x202c ?\x200e) 'invisible t))
1283 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1284 (propertize (string ?\x2069) 'invisible t))
1285 ;; Strong right-to-left characters cause reordering of
1286 ;; the following numerical characters which show the
1287 ;; codepoint, so append LRM to countermand that.
1288 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1289 (propertize (string ?\x200e) 'invisible t))
1290 (t
1291 "")))
1292 (beg (point-min))
1293 (end (point-max))
1294 (pos (point))
1295 (total (buffer-size))
1296 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1297 (hscroll (if (= (window-hscroll) 0)
1298 ""
1299 (format " Hscroll=%d" (window-hscroll))))
1300 (col (current-column)))
1301 (if (= pos end)
1302 (if (or (/= beg 1) (/= end (1+ total)))
1303 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1304 pos total percent beg end col hscroll)
1305 (message "point=%d of %d (EOB) column=%d%s"
1306 pos total col hscroll))
1307 (let ((coding buffer-file-coding-system)
1308 encoded encoding-msg display-prop under-display)
1309 (if (or (not coding)
1310 (eq (coding-system-type coding) t))
1311 (setq coding (default-value 'buffer-file-coding-system)))
1312 (if (eq (char-charset char) 'eight-bit)
1313 (setq encoding-msg
1314 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1315 ;; Check if the character is displayed with some `display'
1316 ;; text property. In that case, set under-display to the
1317 ;; buffer substring covered by that property.
1318 (setq display-prop (get-char-property pos 'display))
1319 (if display-prop
1320 (let ((to (or (next-single-char-property-change pos 'display)
1321 (point-max))))
1322 (if (< to (+ pos 4))
1323 (setq under-display "")
1324 (setq under-display "..."
1325 to (+ pos 4)))
1326 (setq under-display
1327 (concat (buffer-substring-no-properties pos to)
1328 under-display)))
1329 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1330 (setq encoding-msg
1331 (if display-prop
1332 (if (not (stringp display-prop))
1333 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1334 char char char under-display)
1335 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1336 char char char under-display display-prop))
1337 (if encoded
1338 (format "(%d, #o%o, #x%x, file %s)"
1339 char char char
1340 (if (> (length encoded) 1)
1341 "..."
1342 (encoded-string-description encoded coding)))
1343 (format "(%d, #o%o, #x%x)" char char char)))))
1344 (if detail
1345 ;; We show the detailed information about CHAR.
1346 (describe-char (point)))
1347 (if (or (/= beg 1) (/= end (1+ total)))
1348 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1349 (if (< char 256)
1350 (single-key-description char)
1351 (buffer-substring-no-properties (point) (1+ (point))))
1352 bidi-fixer
1353 encoding-msg pos total percent beg end col hscroll)
1354 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1355 (if enable-multibyte-characters
1356 (if (< char 128)
1357 (single-key-description char)
1358 (buffer-substring-no-properties (point) (1+ (point))))
1359 (single-key-description char))
1360 bidi-fixer encoding-msg pos total percent col hscroll))))))
1361 \f
1362 ;; Initialize read-expression-map. It is defined at C level.
1363 (defvar read-expression-map
1364 (let ((m (make-sparse-keymap)))
1365 (define-key m "\M-\t" 'completion-at-point)
1366 ;; Might as well bind TAB to completion, since inserting a TAB char is
1367 ;; much too rarely useful.
1368 (define-key m "\t" 'completion-at-point)
1369 (set-keymap-parent m minibuffer-local-map)
1370 m))
1371
1372 (defun read-minibuffer (prompt &optional initial-contents)
1373 "Return a Lisp object read using the minibuffer, unevaluated.
1374 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1375 is a string to insert in the minibuffer before reading.
1376 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1377 Such arguments are used as in `read-from-minibuffer'.)"
1378 ;; Used for interactive spec `x'.
1379 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1380 t 'minibuffer-history))
1381
1382 (defun eval-minibuffer (prompt &optional initial-contents)
1383 "Return value of Lisp expression read using the minibuffer.
1384 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1385 is a string to insert in the minibuffer before reading.
1386 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1387 Such arguments are used as in `read-from-minibuffer'.)"
1388 ;; Used for interactive spec `X'.
1389 (eval (read--expression prompt initial-contents)))
1390
1391 (defvar minibuffer-completing-symbol nil
1392 "Non-nil means completing a Lisp symbol in the minibuffer.")
1393 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1394
1395 (defvar minibuffer-default nil
1396 "The current default value or list of default values in the minibuffer.
1397 The functions `read-from-minibuffer' and `completing-read' bind
1398 this variable locally.")
1399
1400 (defcustom eval-expression-print-level 4
1401 "Value for `print-level' while printing value in `eval-expression'.
1402 A value of nil means no limit."
1403 :group 'lisp
1404 :type '(choice (const :tag "No Limit" nil) integer)
1405 :version "21.1")
1406
1407 (defcustom eval-expression-print-length 12
1408 "Value for `print-length' while printing value in `eval-expression'.
1409 A value of nil means no limit."
1410 :group 'lisp
1411 :type '(choice (const :tag "No Limit" nil) integer)
1412 :version "21.1")
1413
1414 (defcustom eval-expression-debug-on-error t
1415 "If non-nil set `debug-on-error' to t in `eval-expression'.
1416 If nil, don't change the value of `debug-on-error'."
1417 :group 'lisp
1418 :type 'boolean
1419 :version "21.1")
1420
1421 (defun eval-expression-print-format (value)
1422 "If VALUE in an integer, return a specially formatted string.
1423 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1424 If VALUE is not an integer, nil is returned.
1425 This function is used by functions like `prin1' that display the
1426 result of expression evaluation."
1427 (if (and (integerp value)
1428 (or (eq standard-output t)
1429 (zerop (prefix-numeric-value current-prefix-arg))))
1430 (let ((char-string
1431 (if (and (characterp value)
1432 (char-displayable-p value))
1433 (prin1-char value))))
1434 (if char-string
1435 (format " (#o%o, #x%x, %s)" value value char-string)
1436 (format " (#o%o, #x%x)" value value)))))
1437
1438 (defvar eval-expression-minibuffer-setup-hook nil
1439 "Hook run by `eval-expression' when entering the minibuffer.")
1440
1441 (defun read--expression (prompt &optional initial-contents)
1442 (let ((minibuffer-completing-symbol t))
1443 (minibuffer-with-setup-hook
1444 (lambda ()
1445 ;; FIXME: call emacs-lisp-mode?
1446 (add-function :before-until (local 'eldoc-documentation-function)
1447 #'elisp-eldoc-documentation-function)
1448 (add-hook 'completion-at-point-functions
1449 #'elisp-completion-at-point nil t)
1450 (run-hooks 'eval-expression-minibuffer-setup-hook))
1451 (read-from-minibuffer prompt initial-contents
1452 read-expression-map t
1453 'read-expression-history))))
1454
1455 ;; We define this, rather than making `eval' interactive,
1456 ;; for the sake of completion of names like eval-region, eval-buffer.
1457 (defun eval-expression (exp &optional insert-value)
1458 "Evaluate EXP and print value in the echo area.
1459 When called interactively, read an Emacs Lisp expression and evaluate it.
1460 Value is also consed on to front of the variable `values'.
1461 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1462 argument) means insert the result into the current buffer instead of
1463 printing it in the echo area.
1464
1465 Normally, this function truncates long output according to the value
1466 of the variables `eval-expression-print-length' and
1467 `eval-expression-print-level'. With a prefix argument of zero,
1468 however, there is no such truncation. Such a prefix argument
1469 also causes integers to be printed in several additional formats
1470 \(octal, hexadecimal, and character).
1471
1472 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1473 minibuffer.
1474
1475 If `eval-expression-debug-on-error' is non-nil, which is the default,
1476 this command arranges for all errors to enter the debugger."
1477 (interactive
1478 (list (read--expression "Eval: ")
1479 current-prefix-arg))
1480
1481 (if (null eval-expression-debug-on-error)
1482 (push (eval exp lexical-binding) values)
1483 (let ((old-value (make-symbol "t")) new-value)
1484 ;; Bind debug-on-error to something unique so that we can
1485 ;; detect when evalled code changes it.
1486 (let ((debug-on-error old-value))
1487 (push (eval (macroexpand-all exp) lexical-binding) values)
1488 (setq new-value debug-on-error))
1489 ;; If evalled code has changed the value of debug-on-error,
1490 ;; propagate that change to the global binding.
1491 (unless (eq old-value new-value)
1492 (setq debug-on-error new-value))))
1493
1494 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1495 eval-expression-print-length))
1496 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1497 eval-expression-print-level))
1498 (deactivate-mark))
1499 (if insert-value
1500 (with-no-warnings
1501 (let ((standard-output (current-buffer)))
1502 (prog1
1503 (prin1 (car values))
1504 (when (zerop (prefix-numeric-value insert-value))
1505 (let ((str (eval-expression-print-format (car values))))
1506 (if str (princ str)))))))
1507 (prog1
1508 (prin1 (car values) t)
1509 (let ((str (eval-expression-print-format (car values))))
1510 (if str (princ str t)))))))
1511
1512 (defun edit-and-eval-command (prompt command)
1513 "Prompting with PROMPT, let user edit COMMAND and eval result.
1514 COMMAND is a Lisp expression. Let user edit that expression in
1515 the minibuffer, then read and evaluate the result."
1516 (let ((command
1517 (let ((print-level nil)
1518 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1519 (unwind-protect
1520 (read-from-minibuffer prompt
1521 (prin1-to-string command)
1522 read-expression-map t
1523 'command-history)
1524 ;; If command was added to command-history as a string,
1525 ;; get rid of that. We want only evaluable expressions there.
1526 (if (stringp (car command-history))
1527 (setq command-history (cdr command-history)))))))
1528
1529 ;; If command to be redone does not match front of history,
1530 ;; add it to the history.
1531 (or (equal command (car command-history))
1532 (setq command-history (cons command command-history)))
1533 (eval command)))
1534
1535 (defun repeat-complex-command (arg)
1536 "Edit and re-evaluate last complex command, or ARGth from last.
1537 A complex command is one which used the minibuffer.
1538 The command is placed in the minibuffer as a Lisp form for editing.
1539 The result is executed, repeating the command as changed.
1540 If the command has been changed or is not the most recent previous
1541 command it is added to the front of the command history.
1542 You can use the minibuffer history commands \
1543 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1544 to get different commands to edit and resubmit."
1545 (interactive "p")
1546 (let ((elt (nth (1- arg) command-history))
1547 newcmd)
1548 (if elt
1549 (progn
1550 (setq newcmd
1551 (let ((print-level nil)
1552 (minibuffer-history-position arg)
1553 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1554 (unwind-protect
1555 (read-from-minibuffer
1556 "Redo: " (prin1-to-string elt) read-expression-map t
1557 (cons 'command-history arg))
1558
1559 ;; If command was added to command-history as a
1560 ;; string, get rid of that. We want only
1561 ;; evaluable expressions there.
1562 (if (stringp (car command-history))
1563 (setq command-history (cdr command-history))))))
1564
1565 ;; If command to be redone does not match front of history,
1566 ;; add it to the history.
1567 (or (equal newcmd (car command-history))
1568 (setq command-history (cons newcmd command-history)))
1569 (apply #'funcall-interactively
1570 (car newcmd)
1571 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1572 (if command-history
1573 (error "Argument %d is beyond length of command history" arg)
1574 (error "There are no previous complex commands to repeat")))))
1575
1576
1577 (defvar extended-command-history nil)
1578 (defvar execute-extended-command--last-typed nil)
1579
1580 (defun read-extended-command ()
1581 "Read command name to invoke in `execute-extended-command'."
1582 (minibuffer-with-setup-hook
1583 (lambda ()
1584 (add-hook 'post-self-insert-hook
1585 (lambda ()
1586 (setq execute-extended-command--last-typed
1587 (minibuffer-contents)))
1588 nil 'local)
1589 (set (make-local-variable 'minibuffer-default-add-function)
1590 (lambda ()
1591 ;; Get a command name at point in the original buffer
1592 ;; to propose it after M-n.
1593 (with-current-buffer (window-buffer (minibuffer-selected-window))
1594 (and (commandp (function-called-at-point))
1595 (format "%S" (function-called-at-point)))))))
1596 ;; Read a string, completing from and restricting to the set of
1597 ;; all defined commands. Don't provide any initial input.
1598 ;; Save the command read on the extended-command history list.
1599 (completing-read
1600 (concat (cond
1601 ((eq current-prefix-arg '-) "- ")
1602 ((and (consp current-prefix-arg)
1603 (eq (car current-prefix-arg) 4)) "C-u ")
1604 ((and (consp current-prefix-arg)
1605 (integerp (car current-prefix-arg)))
1606 (format "%d " (car current-prefix-arg)))
1607 ((integerp current-prefix-arg)
1608 (format "%d " current-prefix-arg)))
1609 ;; This isn't strictly correct if `execute-extended-command'
1610 ;; is bound to anything else (e.g. [menu]).
1611 ;; It could use (key-description (this-single-command-keys)),
1612 ;; but actually a prompt other than "M-x" would be confusing,
1613 ;; because "M-x" is a well-known prompt to read a command
1614 ;; and it serves as a shorthand for "Extended command: ".
1615 "M-x ")
1616 (lambda (string pred action)
1617 (let ((pred
1618 (if (memq action '(nil t))
1619 ;; Exclude obsolete commands from completions.
1620 (lambda (sym)
1621 (and (funcall pred sym)
1622 (or (equal string (symbol-name sym))
1623 (not (get sym 'byte-obsolete-info)))))
1624 pred)))
1625 (complete-with-action action obarray string pred)))
1626 #'commandp t nil 'extended-command-history)))
1627
1628 (defcustom suggest-key-bindings t
1629 "Non-nil means show the equivalent key-binding when M-x command has one.
1630 The value can be a length of time to show the message for.
1631 If the value is non-nil and not a number, we wait 2 seconds."
1632 :group 'keyboard
1633 :type '(choice (const :tag "off" nil)
1634 (integer :tag "time" 2)
1635 (other :tag "on")))
1636
1637 (defcustom extended-command-suggest-shorter t
1638 "If non-nil, show a shorter M-x invocation when there is one."
1639 :group 'keyboard
1640 :type 'boolean
1641 :version "25.2")
1642
1643 (defun execute-extended-command--shorter-1 (name length)
1644 (cond
1645 ((zerop length) (list ""))
1646 ((equal name "") nil)
1647 (t
1648 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1649 (execute-extended-command--shorter-1
1650 (substring name 1) (1- length)))
1651 (when (string-match "\\`\\(-\\)?[^-]*" name)
1652 (execute-extended-command--shorter-1
1653 (substring name (match-end 0)) length))))))
1654
1655 (defun execute-extended-command--shorter (name typed)
1656 (let ((candidates '())
1657 (max (length typed))
1658 (len 1)
1659 binding)
1660 (while (and (not binding)
1661 (progn
1662 (unless candidates
1663 (setq len (1+ len))
1664 (setq candidates (execute-extended-command--shorter-1
1665 name len)))
1666 ;; Don't show the help message if the binding isn't
1667 ;; significantly shorter than the M-x command the user typed.
1668 (< len (- max 5))))
1669 (let ((candidate (pop candidates)))
1670 (when (equal name
1671 (car-safe (completion-try-completion
1672 candidate obarray 'commandp len)))
1673 (setq binding candidate))))
1674 binding))
1675
1676 (defun execute-extended-command (prefixarg &optional command-name typed)
1677 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1678 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1679 "Read a command name, then read the arguments and call the command.
1680 To pass a prefix argument to the command you are
1681 invoking, give a prefix argument to `execute-extended-command'."
1682 (declare (interactive-only command-execute))
1683 ;; FIXME: Remember the actual text typed by the user before completion,
1684 ;; so that we don't later on suggest the same shortening.
1685 (interactive
1686 (let ((execute-extended-command--last-typed nil))
1687 (list current-prefix-arg
1688 (read-extended-command)
1689 execute-extended-command--last-typed)))
1690 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1691 (unless command-name
1692 (let ((current-prefix-arg prefixarg) ; for prompt
1693 (execute-extended-command--last-typed nil))
1694 (setq command-name (read-extended-command))
1695 (setq typed execute-extended-command--last-typed)))
1696 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1697 (binding (and suggest-key-bindings
1698 (not executing-kbd-macro)
1699 (where-is-internal function overriding-local-map t))))
1700 (unless (commandp function)
1701 (error "`%s' is not a valid command name" command-name))
1702 (setq this-command function)
1703 ;; Normally `real-this-command' should never be changed, but here we really
1704 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1705 ;; binding" for <cmd>, so the command the user really wanted to run is
1706 ;; `function' and not `execute-extended-command'. The difference is
1707 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1708 (setq real-this-command function)
1709 (let ((prefix-arg prefixarg))
1710 (command-execute function 'record))
1711 ;; If enabled, show which key runs this command.
1712 ;; But first wait, and skip the message if there is input.
1713 (let* ((waited
1714 ;; If this command displayed something in the echo area;
1715 ;; wait a few seconds, then display our suggestion message.
1716 ;; FIXME: Wait *after* running post-command-hook!
1717 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1718 ;; find a better answer anyway!
1719 (when suggest-key-bindings
1720 (sit-for (cond
1721 ((zerop (length (current-message))) 0)
1722 ((numberp suggest-key-bindings) suggest-key-bindings)
1723 (t 2))))))
1724 (when (and waited (not (consp unread-command-events)))
1725 (unless (or (not extended-command-suggest-shorter)
1726 binding executing-kbd-macro (not (symbolp function))
1727 (<= (length (symbol-name function)) 2))
1728 ;; There's no binding for CMD. Let's try and find the shortest
1729 ;; string to use in M-x.
1730 ;; FIXME: Can be slow. Cache it maybe?
1731 (while-no-input
1732 (setq binding (execute-extended-command--shorter
1733 (symbol-name function) typed))))
1734 (when binding
1735 (with-temp-message
1736 (format-message "You can run the command `%s' with %s"
1737 function
1738 (if (stringp binding)
1739 (concat "M-x " binding " RET")
1740 (key-description binding)))
1741 (sit-for (if (numberp suggest-key-bindings)
1742 suggest-key-bindings
1743 2))))))))
1744
1745 (defun command-execute (cmd &optional record-flag keys special)
1746 ;; BEWARE: Called directly from the C code.
1747 "Execute CMD as an editor command.
1748 CMD must be a symbol that satisfies the `commandp' predicate.
1749 Optional second arg RECORD-FLAG non-nil
1750 means unconditionally put this command in the variable `command-history'.
1751 Otherwise, that is done only if an arg is read using the minibuffer.
1752 The argument KEYS specifies the value to use instead of (this-command-keys)
1753 when reading the arguments; if it is nil, (this-command-keys) is used.
1754 The argument SPECIAL, if non-nil, means that this command is executing
1755 a special event, so ignore the prefix argument and don't clear it."
1756 (setq debug-on-next-call nil)
1757 (let ((prefixarg (unless special
1758 ;; FIXME: This should probably be done around
1759 ;; pre-command-hook rather than here!
1760 (prog1 prefix-arg
1761 (setq current-prefix-arg prefix-arg)
1762 (setq prefix-arg nil)
1763 (when current-prefix-arg
1764 (prefix-command-update))))))
1765 (if (and (symbolp cmd)
1766 (get cmd 'disabled)
1767 disabled-command-function)
1768 ;; FIXME: Weird calling convention!
1769 (run-hooks 'disabled-command-function)
1770 (let ((final cmd))
1771 (while
1772 (progn
1773 (setq final (indirect-function final))
1774 (if (autoloadp final)
1775 (setq final (autoload-do-load final cmd)))))
1776 (cond
1777 ((arrayp final)
1778 ;; If requested, place the macro in the command history. For
1779 ;; other sorts of commands, call-interactively takes care of this.
1780 (when record-flag
1781 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1782 ;; Don't keep command history around forever.
1783 (when (and (numberp history-length) (> history-length 0))
1784 (let ((cell (nthcdr history-length command-history)))
1785 (if (consp cell) (setcdr cell nil)))))
1786 (execute-kbd-macro final prefixarg))
1787 (t
1788 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1789 (prog1 (call-interactively cmd record-flag keys)
1790 (when (and (symbolp cmd)
1791 (get cmd 'byte-obsolete-info)
1792 (not (get cmd 'command-execute-obsolete-warned)))
1793 (put cmd 'command-execute-obsolete-warned t)
1794 (message "%s" (macroexp--obsolete-warning
1795 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1796 \f
1797 (defvar minibuffer-history nil
1798 "Default minibuffer history list.
1799 This is used for all minibuffer input
1800 except when an alternate history list is specified.
1801
1802 Maximum length of the history list is determined by the value
1803 of `history-length', which see.")
1804 (defvar minibuffer-history-sexp-flag nil
1805 "Control whether history list elements are expressions or strings.
1806 If the value of this variable equals current minibuffer depth,
1807 they are expressions; otherwise they are strings.
1808 \(That convention is designed to do the right thing for
1809 recursive uses of the minibuffer.)")
1810 (setq minibuffer-history-variable 'minibuffer-history)
1811 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1812 (defvar minibuffer-history-search-history nil)
1813
1814 (defvar minibuffer-text-before-history nil
1815 "Text that was in this minibuffer before any history commands.
1816 This is nil if there have not yet been any history commands
1817 in this use of the minibuffer.")
1818
1819 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1820
1821 (defun minibuffer-history-initialize ()
1822 (setq minibuffer-text-before-history nil))
1823
1824 (defun minibuffer-avoid-prompt (_new _old)
1825 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1826 (declare (obsolete cursor-intangible-mode "25.1"))
1827 (constrain-to-field nil (point-max)))
1828
1829 (defcustom minibuffer-history-case-insensitive-variables nil
1830 "Minibuffer history variables for which matching should ignore case.
1831 If a history variable is a member of this list, then the
1832 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1833 commands ignore case when searching it, regardless of `case-fold-search'."
1834 :type '(repeat variable)
1835 :group 'minibuffer)
1836
1837 (defun previous-matching-history-element (regexp n)
1838 "Find the previous history element that matches REGEXP.
1839 \(Previous history elements refer to earlier actions.)
1840 With prefix argument N, search for Nth previous match.
1841 If N is negative, find the next or Nth next match.
1842 Normally, history elements are matched case-insensitively if
1843 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1844 makes the search case-sensitive.
1845 See also `minibuffer-history-case-insensitive-variables'."
1846 (interactive
1847 (let* ((enable-recursive-minibuffers t)
1848 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1849 nil
1850 minibuffer-local-map
1851 nil
1852 'minibuffer-history-search-history
1853 (car minibuffer-history-search-history))))
1854 ;; Use the last regexp specified, by default, if input is empty.
1855 (list (if (string= regexp "")
1856 (if minibuffer-history-search-history
1857 (car minibuffer-history-search-history)
1858 (user-error "No previous history search regexp"))
1859 regexp)
1860 (prefix-numeric-value current-prefix-arg))))
1861 (unless (zerop n)
1862 (if (and (zerop minibuffer-history-position)
1863 (null minibuffer-text-before-history))
1864 (setq minibuffer-text-before-history
1865 (minibuffer-contents-no-properties)))
1866 (let ((history (symbol-value minibuffer-history-variable))
1867 (case-fold-search
1868 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1869 ;; On some systems, ignore case for file names.
1870 (if (memq minibuffer-history-variable
1871 minibuffer-history-case-insensitive-variables)
1872 t
1873 ;; Respect the user's setting for case-fold-search:
1874 case-fold-search)
1875 nil))
1876 prevpos
1877 match-string
1878 match-offset
1879 (pos minibuffer-history-position))
1880 (while (/= n 0)
1881 (setq prevpos pos)
1882 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1883 (when (= pos prevpos)
1884 (user-error (if (= pos 1)
1885 "No later matching history item"
1886 "No earlier matching history item")))
1887 (setq match-string
1888 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1889 (let ((print-level nil))
1890 (prin1-to-string (nth (1- pos) history)))
1891 (nth (1- pos) history)))
1892 (setq match-offset
1893 (if (< n 0)
1894 (and (string-match regexp match-string)
1895 (match-end 0))
1896 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1897 (match-beginning 1))))
1898 (when match-offset
1899 (setq n (+ n (if (< n 0) 1 -1)))))
1900 (setq minibuffer-history-position pos)
1901 (goto-char (point-max))
1902 (delete-minibuffer-contents)
1903 (insert match-string)
1904 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1905 (if (memq (car (car command-history)) '(previous-matching-history-element
1906 next-matching-history-element))
1907 (setq command-history (cdr command-history))))
1908
1909 (defun next-matching-history-element (regexp n)
1910 "Find the next history element that matches REGEXP.
1911 \(The next history element refers to a more recent action.)
1912 With prefix argument N, search for Nth next match.
1913 If N is negative, find the previous or Nth previous match.
1914 Normally, history elements are matched case-insensitively if
1915 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1916 makes the search case-sensitive."
1917 (interactive
1918 (let* ((enable-recursive-minibuffers t)
1919 (regexp (read-from-minibuffer "Next element matching (regexp): "
1920 nil
1921 minibuffer-local-map
1922 nil
1923 'minibuffer-history-search-history
1924 (car minibuffer-history-search-history))))
1925 ;; Use the last regexp specified, by default, if input is empty.
1926 (list (if (string= regexp "")
1927 (if minibuffer-history-search-history
1928 (car minibuffer-history-search-history)
1929 (user-error "No previous history search regexp"))
1930 regexp)
1931 (prefix-numeric-value current-prefix-arg))))
1932 (previous-matching-history-element regexp (- n)))
1933
1934 (defvar minibuffer-temporary-goal-position nil)
1935
1936 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1937 "Function run by `goto-history-element' before consuming default values.
1938 This is useful to dynamically add more elements to the list of default values
1939 when `goto-history-element' reaches the end of this list.
1940 Before calling this function `goto-history-element' sets the variable
1941 `minibuffer-default-add-done' to t, so it will call this function only
1942 once. In special cases, when this function needs to be called more
1943 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1944 overriding the setting of this variable to t in `goto-history-element'.")
1945
1946 (defvar minibuffer-default-add-done nil
1947 "When nil, add more elements to the end of the list of default values.
1948 The value nil causes `goto-history-element' to add more elements to
1949 the list of defaults when it reaches the end of this list. It does
1950 this by calling a function defined by `minibuffer-default-add-function'.")
1951
1952 (make-variable-buffer-local 'minibuffer-default-add-done)
1953
1954 (defun minibuffer-default-add-completions ()
1955 "Return a list of all completions without the default value.
1956 This function is used to add all elements of the completion table to
1957 the end of the list of defaults just after the default value."
1958 (let ((def minibuffer-default)
1959 (all (all-completions ""
1960 minibuffer-completion-table
1961 minibuffer-completion-predicate)))
1962 (if (listp def)
1963 (append def all)
1964 (cons def (delete def all)))))
1965
1966 (defun goto-history-element (nabs)
1967 "Puts element of the minibuffer history in the minibuffer.
1968 The argument NABS specifies the absolute history position."
1969 (interactive "p")
1970 (when (and (not minibuffer-default-add-done)
1971 (functionp minibuffer-default-add-function)
1972 (< nabs (- (if (listp minibuffer-default)
1973 (length minibuffer-default)
1974 1))))
1975 (setq minibuffer-default-add-done t
1976 minibuffer-default (funcall minibuffer-default-add-function)))
1977 (let ((minimum (if minibuffer-default
1978 (- (if (listp minibuffer-default)
1979 (length minibuffer-default)
1980 1))
1981 0))
1982 elt minibuffer-returned-to-present)
1983 (if (and (zerop minibuffer-history-position)
1984 (null minibuffer-text-before-history))
1985 (setq minibuffer-text-before-history
1986 (minibuffer-contents-no-properties)))
1987 (if (< nabs minimum)
1988 (user-error (if minibuffer-default
1989 "End of defaults; no next item"
1990 "End of history; no default available")))
1991 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
1992 (length (symbol-value minibuffer-history-variable))
1993 0))
1994 (user-error "Beginning of history; no preceding item"))
1995 (unless (memq last-command '(next-history-element
1996 previous-history-element))
1997 (let ((prompt-end (minibuffer-prompt-end)))
1998 (set (make-local-variable 'minibuffer-temporary-goal-position)
1999 (cond ((<= (point) prompt-end) prompt-end)
2000 ((eobp) nil)
2001 (t (point))))))
2002 (goto-char (point-max))
2003 (delete-minibuffer-contents)
2004 (setq minibuffer-history-position nabs)
2005 (cond ((< nabs 0)
2006 (setq elt (if (listp minibuffer-default)
2007 (nth (1- (abs nabs)) minibuffer-default)
2008 minibuffer-default)))
2009 ((= nabs 0)
2010 (setq elt (or minibuffer-text-before-history ""))
2011 (setq minibuffer-returned-to-present t)
2012 (setq minibuffer-text-before-history nil))
2013 (t (setq elt (nth (1- minibuffer-history-position)
2014 (symbol-value minibuffer-history-variable)))))
2015 (insert
2016 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2017 (not minibuffer-returned-to-present))
2018 (let ((print-level nil))
2019 (prin1-to-string elt))
2020 elt))
2021 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2022
2023 (defun next-history-element (n)
2024 "Puts next element of the minibuffer history in the minibuffer.
2025 With argument N, it uses the Nth following element."
2026 (interactive "p")
2027 (or (zerop n)
2028 (goto-history-element (- minibuffer-history-position n))))
2029
2030 (defun previous-history-element (n)
2031 "Puts previous element of the minibuffer history in the minibuffer.
2032 With argument N, it uses the Nth previous element."
2033 (interactive "p")
2034 (or (zerop n)
2035 (goto-history-element (+ minibuffer-history-position n))))
2036
2037 (defun next-line-or-history-element (&optional arg)
2038 "Move cursor vertically down ARG lines, or to the next history element.
2039 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2040 next element of the minibuffer history in the minibuffer."
2041 (interactive "^p")
2042 (or arg (setq arg 1))
2043 (let* ((old-point (point))
2044 ;; Remember the original goal column of possibly multi-line input
2045 ;; excluding the length of the prompt on the first line.
2046 (prompt-end (minibuffer-prompt-end))
2047 (old-column (unless (and (eolp) (> (point) prompt-end))
2048 (if (= (line-number-at-pos) 1)
2049 (max (- (current-column) (1- prompt-end)) 0)
2050 (current-column)))))
2051 (condition-case nil
2052 (with-no-warnings
2053 (next-line arg))
2054 (end-of-buffer
2055 ;; Restore old position since `line-move-visual' moves point to
2056 ;; the end of the line when it fails to go to the next line.
2057 (goto-char old-point)
2058 (next-history-element arg)
2059 ;; Reset `temporary-goal-column' because a correct value is not
2060 ;; calculated when `next-line' above fails by bumping against
2061 ;; the bottom of the minibuffer (bug#22544).
2062 (setq temporary-goal-column 0)
2063 ;; Restore the original goal column on the last line
2064 ;; of possibly multi-line input.
2065 (goto-char (point-max))
2066 (when old-column
2067 (if (= (line-number-at-pos) 1)
2068 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2069 (move-to-column old-column)))))))
2070
2071 (defun previous-line-or-history-element (&optional arg)
2072 "Move cursor vertically up ARG lines, or to the previous history element.
2073 When point moves over the top line of multi-line minibuffer, puts ARGth
2074 previous element of the minibuffer history in the minibuffer."
2075 (interactive "^p")
2076 (or arg (setq arg 1))
2077 (let* ((old-point (point))
2078 ;; Remember the original goal column of possibly multi-line input
2079 ;; excluding the length of the prompt on the first line.
2080 (prompt-end (minibuffer-prompt-end))
2081 (old-column (unless (and (eolp) (> (point) prompt-end))
2082 (if (= (line-number-at-pos) 1)
2083 (max (- (current-column) (1- prompt-end)) 0)
2084 (current-column)))))
2085 (condition-case nil
2086 (with-no-warnings
2087 (previous-line arg))
2088 (beginning-of-buffer
2089 ;; Restore old position since `line-move-visual' moves point to
2090 ;; the beginning of the line when it fails to go to the previous line.
2091 (goto-char old-point)
2092 (previous-history-element arg)
2093 ;; Reset `temporary-goal-column' because a correct value is not
2094 ;; calculated when `previous-line' above fails by bumping against
2095 ;; the top of the minibuffer (bug#22544).
2096 (setq temporary-goal-column 0)
2097 ;; Restore the original goal column on the first line
2098 ;; of possibly multi-line input.
2099 (goto-char (minibuffer-prompt-end))
2100 (if old-column
2101 (if (= (line-number-at-pos) 1)
2102 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2103 (move-to-column old-column))
2104 ;; Put the cursor at the end of the visual line instead of the
2105 ;; logical line, so the next `previous-line-or-history-element'
2106 ;; would move to the previous history element, not to a possible upper
2107 ;; visual line from the end of logical line in `line-move-visual' mode.
2108 (end-of-visual-line)
2109 ;; Since `end-of-visual-line' puts the cursor at the beginning
2110 ;; of the next visual line, move it one char back to the end
2111 ;; of the first visual line (bug#22544).
2112 (unless (eolp) (backward-char 1)))))))
2113
2114 (defun next-complete-history-element (n)
2115 "Get next history element which completes the minibuffer before the point.
2116 The contents of the minibuffer after the point are deleted, and replaced
2117 by the new completion."
2118 (interactive "p")
2119 (let ((point-at-start (point)))
2120 (next-matching-history-element
2121 (concat
2122 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2123 n)
2124 ;; next-matching-history-element always puts us at (point-min).
2125 ;; Move to the position we were at before changing the buffer contents.
2126 ;; This is still sensible, because the text before point has not changed.
2127 (goto-char point-at-start)))
2128
2129 (defun previous-complete-history-element (n)
2130 "\
2131 Get previous history element which completes the minibuffer before the point.
2132 The contents of the minibuffer after the point are deleted, and replaced
2133 by the new completion."
2134 (interactive "p")
2135 (next-complete-history-element (- n)))
2136
2137 ;; For compatibility with the old subr of the same name.
2138 (defun minibuffer-prompt-width ()
2139 "Return the display width of the minibuffer prompt.
2140 Return 0 if current buffer is not a minibuffer."
2141 ;; Return the width of everything before the field at the end of
2142 ;; the buffer; this should be 0 for normal buffers.
2143 (1- (minibuffer-prompt-end)))
2144 \f
2145 ;; isearch minibuffer history
2146 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2147
2148 (defvar minibuffer-history-isearch-message-overlay)
2149 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2150
2151 (defun minibuffer-history-isearch-setup ()
2152 "Set up a minibuffer for using isearch to search the minibuffer history.
2153 Intended to be added to `minibuffer-setup-hook'."
2154 (set (make-local-variable 'isearch-search-fun-function)
2155 'minibuffer-history-isearch-search)
2156 (set (make-local-variable 'isearch-message-function)
2157 'minibuffer-history-isearch-message)
2158 (set (make-local-variable 'isearch-wrap-function)
2159 'minibuffer-history-isearch-wrap)
2160 (set (make-local-variable 'isearch-push-state-function)
2161 'minibuffer-history-isearch-push-state)
2162 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2163
2164 (defun minibuffer-history-isearch-end ()
2165 "Clean up the minibuffer after terminating isearch in the minibuffer."
2166 (if minibuffer-history-isearch-message-overlay
2167 (delete-overlay minibuffer-history-isearch-message-overlay)))
2168
2169 (defun minibuffer-history-isearch-search ()
2170 "Return the proper search function, for isearch in minibuffer history."
2171 (lambda (string bound noerror)
2172 (let ((search-fun
2173 ;; Use standard functions to search within minibuffer text
2174 (isearch-search-fun-default))
2175 found)
2176 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2177 ;; searching forward. Lazy-highlight calls this lambda with the
2178 ;; bound arg, so skip the minibuffer prompt.
2179 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2180 (goto-char (minibuffer-prompt-end)))
2181 (or
2182 ;; 1. First try searching in the initial minibuffer text
2183 (funcall search-fun string
2184 (if isearch-forward bound (minibuffer-prompt-end))
2185 noerror)
2186 ;; 2. If the above search fails, start putting next/prev history
2187 ;; elements in the minibuffer successively, and search the string
2188 ;; in them. Do this only when bound is nil (i.e. not while
2189 ;; lazy-highlighting search strings in the current minibuffer text).
2190 (unless bound
2191 (condition-case nil
2192 (progn
2193 (while (not found)
2194 (cond (isearch-forward
2195 (next-history-element 1)
2196 (goto-char (minibuffer-prompt-end)))
2197 (t
2198 (previous-history-element 1)
2199 (goto-char (point-max))))
2200 (setq isearch-barrier (point) isearch-opoint (point))
2201 ;; After putting the next/prev history element, search
2202 ;; the string in them again, until next-history-element
2203 ;; or previous-history-element raises an error at the
2204 ;; beginning/end of history.
2205 (setq found (funcall search-fun string
2206 (unless isearch-forward
2207 ;; For backward search, don't search
2208 ;; in the minibuffer prompt
2209 (minibuffer-prompt-end))
2210 noerror)))
2211 ;; Return point of the new search result
2212 (point))
2213 ;; Return nil when next(prev)-history-element fails
2214 (error nil)))))))
2215
2216 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2217 "Display the minibuffer history search prompt.
2218 If there are no search errors, this function displays an overlay with
2219 the isearch prompt which replaces the original minibuffer prompt.
2220 Otherwise, it displays the standard isearch message returned from
2221 the function `isearch-message'."
2222 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2223 ;; Use standard function `isearch-message' when not in the minibuffer,
2224 ;; or search fails, or has an error (like incomplete regexp).
2225 ;; This function overwrites minibuffer text with isearch message,
2226 ;; so it's possible to see what is wrong in the search string.
2227 (isearch-message c-q-hack ellipsis)
2228 ;; Otherwise, put the overlay with the standard isearch prompt over
2229 ;; the initial minibuffer prompt.
2230 (if (overlayp minibuffer-history-isearch-message-overlay)
2231 (move-overlay minibuffer-history-isearch-message-overlay
2232 (point-min) (minibuffer-prompt-end))
2233 (setq minibuffer-history-isearch-message-overlay
2234 (make-overlay (point-min) (minibuffer-prompt-end)))
2235 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2236 (overlay-put minibuffer-history-isearch-message-overlay
2237 'display (isearch-message-prefix c-q-hack ellipsis))
2238 ;; And clear any previous isearch message.
2239 (message "")))
2240
2241 (defun minibuffer-history-isearch-wrap ()
2242 "Wrap the minibuffer history search when search fails.
2243 Move point to the first history element for a forward search,
2244 or to the last history element for a backward search."
2245 ;; When `minibuffer-history-isearch-search' fails on reaching the
2246 ;; beginning/end of the history, wrap the search to the first/last
2247 ;; minibuffer history element.
2248 (if isearch-forward
2249 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2250 (goto-history-element 0))
2251 (setq isearch-success t)
2252 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2253
2254 (defun minibuffer-history-isearch-push-state ()
2255 "Save a function restoring the state of minibuffer history search.
2256 Save `minibuffer-history-position' to the additional state parameter
2257 in the search status stack."
2258 (let ((pos minibuffer-history-position))
2259 (lambda (cmd)
2260 (minibuffer-history-isearch-pop-state cmd pos))))
2261
2262 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2263 "Restore the minibuffer history search state.
2264 Go to the history element by the absolute history position HIST-POS."
2265 (goto-history-element hist-pos))
2266
2267 \f
2268 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2269 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2270
2271 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2272 "Table mapping redo records to the corresponding undo one.
2273 A redo record for undo-in-region maps to t.
2274 A redo record for ordinary undo maps to the following (earlier) undo.")
2275
2276 (defvar undo-in-region nil
2277 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2278
2279 (defvar undo-no-redo nil
2280 "If t, `undo' doesn't go through redo entries.")
2281
2282 (defvar pending-undo-list nil
2283 "Within a run of consecutive undo commands, list remaining to be undone.
2284 If t, we undid all the way to the end of it.")
2285
2286 (defun undo (&optional arg)
2287 "Undo some previous changes.
2288 Repeat this command to undo more changes.
2289 A numeric ARG serves as a repeat count.
2290
2291 In Transient Mark mode when the mark is active, only undo changes within
2292 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2293 as an argument limits undo to changes within the current region."
2294 (interactive "*P")
2295 ;; Make last-command indicate for the next command that this was an undo.
2296 ;; That way, another undo will undo more.
2297 ;; If we get to the end of the undo history and get an error,
2298 ;; another undo command will find the undo history empty
2299 ;; and will get another error. To begin undoing the undos,
2300 ;; you must type some other command.
2301 (let* ((modified (buffer-modified-p))
2302 ;; For an indirect buffer, look in the base buffer for the
2303 ;; auto-save data.
2304 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2305 (recent-save (with-current-buffer base-buffer
2306 (recent-auto-save-p)))
2307 message)
2308 ;; If we get an error in undo-start,
2309 ;; the next command should not be a "consecutive undo".
2310 ;; So set `this-command' to something other than `undo'.
2311 (setq this-command 'undo-start)
2312
2313 (unless (and (eq last-command 'undo)
2314 (or (eq pending-undo-list t)
2315 ;; If something (a timer or filter?) changed the buffer
2316 ;; since the previous command, don't continue the undo seq.
2317 (let ((list buffer-undo-list))
2318 (while (eq (car list) nil)
2319 (setq list (cdr list)))
2320 ;; If the last undo record made was made by undo
2321 ;; it shows nothing else happened in between.
2322 (gethash list undo-equiv-table))))
2323 (setq undo-in-region
2324 (or (region-active-p) (and arg (not (numberp arg)))))
2325 (if undo-in-region
2326 (undo-start (region-beginning) (region-end))
2327 (undo-start))
2328 ;; get rid of initial undo boundary
2329 (undo-more 1))
2330 ;; If we got this far, the next command should be a consecutive undo.
2331 (setq this-command 'undo)
2332 ;; Check to see whether we're hitting a redo record, and if
2333 ;; so, ask the user whether she wants to skip the redo/undo pair.
2334 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2335 (or (eq (selected-window) (minibuffer-window))
2336 (setq message (format "%s%s!"
2337 (if (or undo-no-redo (not equiv))
2338 "Undo" "Redo")
2339 (if undo-in-region " in region" ""))))
2340 (when (and (consp equiv) undo-no-redo)
2341 ;; The equiv entry might point to another redo record if we have done
2342 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2343 (while (let ((next (gethash equiv undo-equiv-table)))
2344 (if next (setq equiv next))))
2345 (setq pending-undo-list equiv)))
2346 (undo-more
2347 (if (numberp arg)
2348 (prefix-numeric-value arg)
2349 1))
2350 ;; Record the fact that the just-generated undo records come from an
2351 ;; undo operation--that is, they are redo records.
2352 ;; In the ordinary case (not within a region), map the redo
2353 ;; record to the following undos.
2354 ;; I don't know how to do that in the undo-in-region case.
2355 (let ((list buffer-undo-list))
2356 ;; Strip any leading undo boundaries there might be, like we do
2357 ;; above when checking.
2358 (while (eq (car list) nil)
2359 (setq list (cdr list)))
2360 (puthash list
2361 ;; Prevent identity mapping. This can happen if
2362 ;; consecutive nils are erroneously in undo list.
2363 (if (or undo-in-region (eq list pending-undo-list))
2364 t
2365 pending-undo-list)
2366 undo-equiv-table))
2367 ;; Don't specify a position in the undo record for the undo command.
2368 ;; Instead, undoing this should move point to where the change is.
2369 (let ((tail buffer-undo-list)
2370 (prev nil))
2371 (while (car tail)
2372 (when (integerp (car tail))
2373 (let ((pos (car tail)))
2374 (if prev
2375 (setcdr prev (cdr tail))
2376 (setq buffer-undo-list (cdr tail)))
2377 (setq tail (cdr tail))
2378 (while (car tail)
2379 (if (eq pos (car tail))
2380 (if prev
2381 (setcdr prev (cdr tail))
2382 (setq buffer-undo-list (cdr tail)))
2383 (setq prev tail))
2384 (setq tail (cdr tail)))
2385 (setq tail nil)))
2386 (setq prev tail tail (cdr tail))))
2387 ;; Record what the current undo list says,
2388 ;; so the next command can tell if the buffer was modified in between.
2389 (and modified (not (buffer-modified-p))
2390 (with-current-buffer base-buffer
2391 (delete-auto-save-file-if-necessary recent-save)))
2392 ;; Display a message announcing success.
2393 (if message
2394 (message "%s" message))))
2395
2396 (defun buffer-disable-undo (&optional buffer)
2397 "Make BUFFER stop keeping undo information.
2398 No argument or nil as argument means do this for the current buffer."
2399 (interactive)
2400 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2401 (setq buffer-undo-list t)))
2402
2403 (defun undo-only (&optional arg)
2404 "Undo some previous changes.
2405 Repeat this command to undo more changes.
2406 A numeric ARG serves as a repeat count.
2407 Contrary to `undo', this will not redo a previous undo."
2408 (interactive "*p")
2409 (let ((undo-no-redo t)) (undo arg)))
2410
2411 (defvar undo-in-progress nil
2412 "Non-nil while performing an undo.
2413 Some change-hooks test this variable to do something different.")
2414
2415 (defun undo-more (n)
2416 "Undo back N undo-boundaries beyond what was already undone recently.
2417 Call `undo-start' to get ready to undo recent changes,
2418 then call `undo-more' one or more times to undo them."
2419 (or (listp pending-undo-list)
2420 (user-error (concat "No further undo information"
2421 (and undo-in-region " for region"))))
2422 (let ((undo-in-progress t))
2423 ;; Note: The following, while pulling elements off
2424 ;; `pending-undo-list' will call primitive change functions which
2425 ;; will push more elements onto `buffer-undo-list'.
2426 (setq pending-undo-list (primitive-undo n pending-undo-list))
2427 (if (null pending-undo-list)
2428 (setq pending-undo-list t))))
2429
2430 (defun primitive-undo (n list)
2431 "Undo N records from the front of the list LIST.
2432 Return what remains of the list."
2433
2434 ;; This is a good feature, but would make undo-start
2435 ;; unable to do what is expected.
2436 ;;(when (null (car (list)))
2437 ;; ;; If the head of the list is a boundary, it is the boundary
2438 ;; ;; preceding this command. Get rid of it and don't count it.
2439 ;; (setq list (cdr list))))
2440
2441 (let ((arg n)
2442 ;; In a writable buffer, enable undoing read-only text that is
2443 ;; so because of text properties.
2444 (inhibit-read-only t)
2445 ;; Don't let `intangible' properties interfere with undo.
2446 (inhibit-point-motion-hooks t)
2447 ;; We use oldlist only to check for EQ. ++kfs
2448 (oldlist buffer-undo-list)
2449 (did-apply nil)
2450 (next nil))
2451 (while (> arg 0)
2452 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2453 ;; Handle an integer by setting point to that value.
2454 (pcase next
2455 ((pred integerp) (goto-char next))
2456 ;; Element (t . TIME) records previous modtime.
2457 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2458 ;; UNKNOWN_MODTIME_NSECS.
2459 (`(t . ,time)
2460 ;; If this records an obsolete save
2461 ;; (not matching the actual disk file)
2462 ;; then don't mark unmodified.
2463 (when (or (equal time (visited-file-modtime))
2464 (and (consp time)
2465 (equal (list (car time) (cdr time))
2466 (visited-file-modtime))))
2467 (when (fboundp 'unlock-buffer)
2468 (unlock-buffer))
2469 (set-buffer-modified-p nil)))
2470 ;; Element (nil PROP VAL BEG . END) is property change.
2471 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2472 (when (or (> (point-min) beg) (< (point-max) end))
2473 (error "Changes to be undone are outside visible portion of buffer"))
2474 (put-text-property beg end prop val))
2475 ;; Element (BEG . END) means range was inserted.
2476 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2477 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2478 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2479 (when (or (> (point-min) beg) (< (point-max) end))
2480 (error "Changes to be undone are outside visible portion of buffer"))
2481 ;; Set point first thing, so that undoing this undo
2482 ;; does not send point back to where it is now.
2483 (goto-char beg)
2484 (delete-region beg end))
2485 ;; Element (apply FUN . ARGS) means call FUN to undo.
2486 (`(apply . ,fun-args)
2487 (let ((currbuff (current-buffer)))
2488 (if (integerp (car fun-args))
2489 ;; Long format: (apply DELTA START END FUN . ARGS).
2490 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2491 (start-mark (copy-marker start nil))
2492 (end-mark (copy-marker end t)))
2493 (when (or (> (point-min) start) (< (point-max) end))
2494 (error "Changes to be undone are outside visible portion of buffer"))
2495 (apply fun args) ;; Use `save-current-buffer'?
2496 ;; Check that the function did what the entry
2497 ;; said it would do.
2498 (unless (and (= start start-mark)
2499 (= (+ delta end) end-mark))
2500 (error "Changes to be undone by function different than announced"))
2501 (set-marker start-mark nil)
2502 (set-marker end-mark nil))
2503 (apply fun-args))
2504 (unless (eq currbuff (current-buffer))
2505 (error "Undo function switched buffer"))
2506 (setq did-apply t)))
2507 ;; Element (STRING . POS) means STRING was deleted.
2508 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2509 (when (let ((apos (abs pos)))
2510 (or (< apos (point-min)) (> apos (point-max))))
2511 (error "Changes to be undone are outside visible portion of buffer"))
2512 (let (valid-marker-adjustments)
2513 ;; Check that marker adjustments which were recorded
2514 ;; with the (STRING . POS) record are still valid, ie
2515 ;; the markers haven't moved. We check their validity
2516 ;; before reinserting the string so as we don't need to
2517 ;; mind marker insertion-type.
2518 (while (and (markerp (car-safe (car list)))
2519 (integerp (cdr-safe (car list))))
2520 (let* ((marker-adj (pop list))
2521 (m (car marker-adj)))
2522 (and (eq (marker-buffer m) (current-buffer))
2523 (= pos m)
2524 (push marker-adj valid-marker-adjustments))))
2525 ;; Insert string and adjust point
2526 (if (< pos 0)
2527 (progn
2528 (goto-char (- pos))
2529 (insert string))
2530 (goto-char pos)
2531 (insert string)
2532 (goto-char pos))
2533 ;; Adjust the valid marker adjustments
2534 (dolist (adj valid-marker-adjustments)
2535 (set-marker (car adj)
2536 (- (car adj) (cdr adj))))))
2537 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2538 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2539 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2540 next)
2541 ;; Even though these elements are not expected in the undo
2542 ;; list, adjust them to be conservative for the 24.4
2543 ;; release. (Bug#16818)
2544 (when (marker-buffer marker)
2545 (set-marker marker
2546 (- marker offset)
2547 (marker-buffer marker))))
2548 (_ (error "Unrecognized entry in undo list %S" next))))
2549 (setq arg (1- arg)))
2550 ;; Make sure an apply entry produces at least one undo entry,
2551 ;; so the test in `undo' for continuing an undo series
2552 ;; will work right.
2553 (if (and did-apply
2554 (eq oldlist buffer-undo-list))
2555 (setq buffer-undo-list
2556 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2557 list)
2558
2559 ;; Deep copy of a list
2560 (defun undo-copy-list (list)
2561 "Make a copy of undo list LIST."
2562 (mapcar 'undo-copy-list-1 list))
2563
2564 (defun undo-copy-list-1 (elt)
2565 (if (consp elt)
2566 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2567 elt))
2568
2569 (defun undo-start (&optional beg end)
2570 "Set `pending-undo-list' to the front of the undo list.
2571 The next call to `undo-more' will undo the most recently made change.
2572 If BEG and END are specified, then only undo elements
2573 that apply to text between BEG and END are used; other undo elements
2574 are ignored. If BEG and END are nil, all undo elements are used."
2575 (if (eq buffer-undo-list t)
2576 (user-error "No undo information in this buffer"))
2577 (setq pending-undo-list
2578 (if (and beg end (not (= beg end)))
2579 (undo-make-selective-list (min beg end) (max beg end))
2580 buffer-undo-list)))
2581
2582 ;; The positions given in elements of the undo list are the positions
2583 ;; as of the time that element was recorded to undo history. In
2584 ;; general, subsequent buffer edits render those positions invalid in
2585 ;; the current buffer, unless adjusted according to the intervening
2586 ;; undo elements.
2587 ;;
2588 ;; Undo in region is a use case that requires adjustments to undo
2589 ;; elements. It must adjust positions of elements in the region based
2590 ;; on newer elements not in the region so as they may be correctly
2591 ;; applied in the current buffer. undo-make-selective-list
2592 ;; accomplishes this with its undo-deltas list of adjustments. An
2593 ;; example undo history from oldest to newest:
2594 ;;
2595 ;; buf pos:
2596 ;; 123456789 buffer-undo-list undo-deltas
2597 ;; --------- ---------------- -----------
2598 ;; aaa (1 . 4) (1 . -3)
2599 ;; aaba (3 . 4) N/A (in region)
2600 ;; ccaaba (1 . 3) (1 . -2)
2601 ;; ccaabaddd (7 . 10) (7 . -3)
2602 ;; ccaabdd ("ad" . 6) (6 . 2)
2603 ;; ccaabaddd (6 . 8) (6 . -2)
2604 ;; | |<-- region: "caab", from 2 to 6
2605 ;;
2606 ;; When the user starts a run of undos in region,
2607 ;; undo-make-selective-list is called to create the full list of in
2608 ;; region elements. Each element is adjusted forward chronologically
2609 ;; through undo-deltas to determine if it is in the region.
2610 ;;
2611 ;; In the above example, the insertion of "b" is (3 . 4) in the
2612 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2613 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2614 ;; . 6) is assessed as in the region and placed in the selective list.
2615 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2616 ;; due to the selected element. The "b" insertion is the only element
2617 ;; fully in the region, so in this example undo-make-selective-list
2618 ;; returns (nil (5 . 6)).
2619 ;;
2620 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2621 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2622 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2623 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2624 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2625 ;;
2626 ;; More interesting is how to adjust the "ddd" insertion due to the
2627 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2628 ;; If the reinsertion was a manual retyping of "ad", then the total
2629 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2630 ;; the reinsertion was due to undo, one might expect the first "d"
2631 ;; character would again be a part of the "ddd" text, meaning its
2632 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2633 ;;
2634 ;; undo-make-selective-list assumes in this situation that "ad" was a
2635 ;; new edit, even if it was inserted because of an undo.
2636 ;; Consequently, if the user undos in region "8 to 10" of the
2637 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2638 ;; "ccaabad", as though the first "d" became detached from the
2639 ;; original "ddd" insertion. This quirk is a FIXME.
2640
2641 (defun undo-make-selective-list (start end)
2642 "Return a list of undo elements for the region START to END.
2643 The elements come from `buffer-undo-list', but we keep only the
2644 elements inside this region, and discard those outside this
2645 region. The elements' positions are adjusted so as the returned
2646 list can be applied to the current buffer."
2647 (let ((ulist buffer-undo-list)
2648 ;; A list of position adjusted undo elements in the region.
2649 (selective-list (list nil))
2650 ;; A list of undo-deltas for out of region undo elements.
2651 undo-deltas
2652 undo-elt)
2653 (while ulist
2654 (when undo-no-redo
2655 (while (gethash ulist undo-equiv-table)
2656 (setq ulist (gethash ulist undo-equiv-table))))
2657 (setq undo-elt (car ulist))
2658 (cond
2659 ((null undo-elt)
2660 ;; Don't put two nils together in the list
2661 (when (car selective-list)
2662 (push nil selective-list)))
2663 ((and (consp undo-elt) (eq (car undo-elt) t))
2664 ;; This is a "was unmodified" element. Keep it
2665 ;; if we have kept everything thus far.
2666 (when (not undo-deltas)
2667 (push undo-elt selective-list)))
2668 ;; Skip over marker adjustments, instead relying
2669 ;; on finding them after (TEXT . POS) elements
2670 ((markerp (car-safe undo-elt))
2671 nil)
2672 (t
2673 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2674 undo-deltas)))
2675 (if (undo-elt-in-region adjusted-undo-elt start end)
2676 (progn
2677 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2678 (push adjusted-undo-elt selective-list)
2679 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2680 ;; kept. primitive-undo may discard them later.
2681 (when (and (stringp (car-safe adjusted-undo-elt))
2682 (integerp (cdr-safe adjusted-undo-elt)))
2683 (let ((list-i (cdr ulist)))
2684 (while (markerp (car-safe (car list-i)))
2685 (push (pop list-i) selective-list)))))
2686 (let ((delta (undo-delta undo-elt)))
2687 (when (/= 0 (cdr delta))
2688 (push delta undo-deltas)))))))
2689 (pop ulist))
2690 (nreverse selective-list)))
2691
2692 (defun undo-elt-in-region (undo-elt start end)
2693 "Determine whether UNDO-ELT falls inside the region START ... END.
2694 If it crosses the edge, we return nil.
2695
2696 Generally this function is not useful for determining
2697 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2698 because markers can be arbitrarily relocated. Instead, pass the
2699 marker adjustment's corresponding (TEXT . POS) element."
2700 (cond ((integerp undo-elt)
2701 (and (>= undo-elt start)
2702 (<= undo-elt end)))
2703 ((eq undo-elt nil)
2704 t)
2705 ((atom undo-elt)
2706 nil)
2707 ((stringp (car undo-elt))
2708 ;; (TEXT . POSITION)
2709 (and (>= (abs (cdr undo-elt)) start)
2710 (<= (abs (cdr undo-elt)) end)))
2711 ((and (consp undo-elt) (markerp (car undo-elt)))
2712 ;; (MARKER . ADJUSTMENT)
2713 (<= start (car undo-elt) end))
2714 ((null (car undo-elt))
2715 ;; (nil PROPERTY VALUE BEG . END)
2716 (let ((tail (nthcdr 3 undo-elt)))
2717 (and (>= (car tail) start)
2718 (<= (cdr tail) end))))
2719 ((integerp (car undo-elt))
2720 ;; (BEGIN . END)
2721 (and (>= (car undo-elt) start)
2722 (<= (cdr undo-elt) end)))))
2723
2724 (defun undo-elt-crosses-region (undo-elt start end)
2725 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2726 This assumes we have already decided that UNDO-ELT
2727 is not *inside* the region START...END."
2728 (declare (obsolete nil "25.1"))
2729 (cond ((atom undo-elt) nil)
2730 ((null (car undo-elt))
2731 ;; (nil PROPERTY VALUE BEG . END)
2732 (let ((tail (nthcdr 3 undo-elt)))
2733 (and (< (car tail) end)
2734 (> (cdr tail) start))))
2735 ((integerp (car undo-elt))
2736 ;; (BEGIN . END)
2737 (and (< (car undo-elt) end)
2738 (> (cdr undo-elt) start)))))
2739
2740 (defun undo-adjust-elt (elt deltas)
2741 "Return adjustment of undo element ELT by the undo DELTAS
2742 list."
2743 (pcase elt
2744 ;; POSITION
2745 ((pred integerp)
2746 (undo-adjust-pos elt deltas))
2747 ;; (BEG . END)
2748 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2749 (undo-adjust-beg-end beg end deltas))
2750 ;; (TEXT . POSITION)
2751 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2752 (cons text (* (if (< pos 0) -1 1)
2753 (undo-adjust-pos (abs pos) deltas))))
2754 ;; (nil PROPERTY VALUE BEG . END)
2755 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2756 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2757 ;; (apply DELTA START END FUN . ARGS)
2758 ;; FIXME
2759 ;; All others return same elt
2760 (_ elt)))
2761
2762 ;; (BEG . END) can adjust to the same positions, commonly when an
2763 ;; insertion was undone and they are out of region, for example:
2764 ;;
2765 ;; buf pos:
2766 ;; 123456789 buffer-undo-list undo-deltas
2767 ;; --------- ---------------- -----------
2768 ;; [...]
2769 ;; abbaa (2 . 4) (2 . -2)
2770 ;; aaa ("bb" . 2) (2 . 2)
2771 ;; [...]
2772 ;;
2773 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2774 ;; undo. Further adjustments to such an element should be the same as
2775 ;; for (TEXT . POSITION) elements. The options are:
2776 ;;
2777 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2778 ;; analogous to marker insertion-type t.
2779 ;;
2780 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2781 ;; marker insertion-type nil.
2782 ;;
2783 ;; There was no strong reason to prefer one or the other, except that
2784 ;; the first is more consistent with prior undo in region behavior.
2785 (defun undo-adjust-beg-end (beg end deltas)
2786 "Return cons of adjustments to BEG and END by the undo DELTAS
2787 list."
2788 (let ((adj-beg (undo-adjust-pos beg deltas)))
2789 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2790 (cons adj-beg
2791 (max adj-beg (undo-adjust-pos end deltas t)))))
2792
2793 (defun undo-adjust-pos (pos deltas &optional use-<)
2794 "Return adjustment of POS by the undo DELTAS list, comparing
2795 with < or <= based on USE-<."
2796 (dolist (d deltas pos)
2797 (when (if use-<
2798 (< (car d) pos)
2799 (<= (car d) pos))
2800 (setq pos
2801 ;; Don't allow pos to become less than the undo-delta
2802 ;; position. This edge case is described in the overview
2803 ;; comments.
2804 (max (car d) (- pos (cdr d)))))))
2805
2806 ;; Return the first affected buffer position and the delta for an undo element
2807 ;; delta is defined as the change in subsequent buffer positions if we *did*
2808 ;; the undo.
2809 (defun undo-delta (undo-elt)
2810 (if (consp undo-elt)
2811 (cond ((stringp (car undo-elt))
2812 ;; (TEXT . POSITION)
2813 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2814 ((integerp (car undo-elt))
2815 ;; (BEGIN . END)
2816 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2817 (t
2818 '(0 . 0)))
2819 '(0 . 0)))
2820
2821 ;;; Default undo-boundary addition
2822 ;;
2823 ;; This section adds a new undo-boundary at either after a command is
2824 ;; called or in some cases on a timer called after a change is made in
2825 ;; any buffer.
2826 (defvar-local undo-auto--last-boundary-cause nil
2827 "Describe the cause of the last undo-boundary.
2828
2829 If `explicit', the last boundary was caused by an explicit call to
2830 `undo-boundary', that is one not called by the code in this
2831 section.
2832
2833 If it is equal to `timer', then the last boundary was inserted
2834 by `undo-auto--boundary-timer'.
2835
2836 If it is equal to `command', then the last boundary was inserted
2837 automatically after a command, that is by the code defined in
2838 this section.
2839
2840 If it is equal to a list, then the last boundary was inserted by
2841 an amalgamating command. The car of the list is the number of
2842 times an amalgamating command has been called, and the cdr are the
2843 buffers that were changed during the last command.")
2844
2845 (defvar undo-auto-current-boundary-timer nil
2846 "Current timer which will run `undo-auto--boundary-timer' or nil.
2847
2848 If set to non-nil, this will effectively disable the timer.")
2849
2850 (defvar undo-auto--this-command-amalgamating nil
2851 "Non-nil if `this-command' should be amalgamated.
2852 This variable is set to nil by `undo-auto--boundaries' and is set
2853 by `undo-auto-amalgamate'." )
2854
2855 (defun undo-auto--needs-boundary-p ()
2856 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2857 (car-safe buffer-undo-list))
2858
2859 (defun undo-auto--last-boundary-amalgamating-number ()
2860 "Return the number of amalgamating last commands or nil.
2861 Amalgamating commands are, by default, either
2862 `self-insert-command' and `delete-char', but can be any command
2863 that calls `undo-auto-amalgamate'."
2864 (car-safe undo-auto--last-boundary-cause))
2865
2866 (defun undo-auto--ensure-boundary (cause)
2867 "Add an `undo-boundary' to the current buffer if needed.
2868 REASON describes the reason that the boundary is being added; see
2869 `undo-auto--last-boundary' for more information."
2870 (when (and
2871 (undo-auto--needs-boundary-p))
2872 (let ((last-amalgamating
2873 (undo-auto--last-boundary-amalgamating-number)))
2874 (undo-boundary)
2875 (setq undo-auto--last-boundary-cause
2876 (if (eq 'amalgamate cause)
2877 (cons
2878 (if last-amalgamating (1+ last-amalgamating) 0)
2879 undo-auto--undoably-changed-buffers)
2880 cause)))))
2881
2882 (defun undo-auto--boundaries (cause)
2883 "Check recently changed buffers and add a boundary if necessary.
2884 REASON describes the reason that the boundary is being added; see
2885 `undo-last-boundary' for more information."
2886 ;; (Bug #23785) All commands should ensure that there is an undo
2887 ;; boundary whether they have changed the current buffer or not.
2888 (when (eq cause 'command)
2889 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2890 (dolist (b undo-auto--undoably-changed-buffers)
2891 (when (buffer-live-p b)
2892 (with-current-buffer b
2893 (undo-auto--ensure-boundary cause))))
2894 (setq undo-auto--undoably-changed-buffers nil))
2895
2896 (defun undo-auto--boundary-timer ()
2897 "Timer which will run `undo--auto-boundary-timer'."
2898 (setq undo-auto-current-boundary-timer nil)
2899 (undo-auto--boundaries 'timer))
2900
2901 (defun undo-auto--boundary-ensure-timer ()
2902 "Ensure that the `undo-auto-boundary-timer' is set."
2903 (unless undo-auto-current-boundary-timer
2904 (setq undo-auto-current-boundary-timer
2905 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2906
2907 (defvar undo-auto--undoably-changed-buffers nil
2908 "List of buffers that have changed recently.
2909
2910 This list is maintained by `undo-auto--undoable-change' and
2911 `undo-auto--boundaries' and can be affected by changes to their
2912 default values.")
2913
2914 (defun undo-auto--add-boundary ()
2915 "Add an `undo-boundary' in appropriate buffers."
2916 (undo-auto--boundaries
2917 (let ((amal undo-auto--this-command-amalgamating))
2918 (setq undo-auto--this-command-amalgamating nil)
2919 (if amal
2920 'amalgamate
2921 'command))))
2922
2923 (defun undo-auto-amalgamate ()
2924 "Amalgamate undo if necessary.
2925 This function can be called before an amalgamating command. It
2926 removes the previous `undo-boundary' if a series of such calls
2927 have been made. By default `self-insert-command' and
2928 `delete-char' are the only amalgamating commands, although this
2929 function could be called by any command wishing to have this
2930 behavior."
2931 (let ((last-amalgamating-count
2932 (undo-auto--last-boundary-amalgamating-number)))
2933 (setq undo-auto--this-command-amalgamating t)
2934 (when
2935 last-amalgamating-count
2936 (if
2937 (and
2938 (< last-amalgamating-count 20)
2939 (eq this-command last-command))
2940 ;; Amalgamate all buffers that have changed.
2941 (dolist (b (cdr undo-auto--last-boundary-cause))
2942 (when (buffer-live-p b)
2943 (with-current-buffer
2944 b
2945 (when
2946 ;; The head of `buffer-undo-list' is nil.
2947 ;; `car-safe' doesn't work because
2948 ;; `buffer-undo-list' need not be a list!
2949 (and (listp buffer-undo-list)
2950 (not (car buffer-undo-list)))
2951 (setq buffer-undo-list
2952 (cdr buffer-undo-list))))))
2953 (setq undo-auto--last-boundary-cause 0)))))
2954
2955 (defun undo-auto--undoable-change ()
2956 "Called after every undoable buffer change."
2957 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2958 (undo-auto--boundary-ensure-timer))
2959 ;; End auto-boundary section
2960
2961 (defun undo-amalgamate-change-group (handle)
2962 "Amalgamate changes in change-group since HANDLE.
2963 Remove all undo boundaries between the state of HANDLE and now.
2964 HANDLE is as returned by `prepare-change-group'."
2965 (dolist (elt handle)
2966 (with-current-buffer (car elt)
2967 (setq elt (cdr elt))
2968 (when (consp buffer-undo-list)
2969 (let ((old-car (car-safe elt))
2970 (old-cdr (cdr-safe elt)))
2971 (unwind-protect
2972 (progn
2973 ;; Temporarily truncate the undo log at ELT.
2974 (when (consp elt)
2975 (setcar elt t) (setcdr elt nil))
2976 (when
2977 (or (null elt) ;The undo-log was empty.
2978 ;; `elt' is still in the log: normal case.
2979 (eq elt (last buffer-undo-list))
2980 ;; `elt' is not in the log any more, but that's because
2981 ;; the log is "all new", so we should remove all
2982 ;; boundaries from it.
2983 (not (eq (last buffer-undo-list) (last old-cdr))))
2984 (cl-callf (lambda (x) (delq nil x))
2985 (if (car buffer-undo-list)
2986 buffer-undo-list
2987 ;; Preserve the undo-boundaries at either ends of the
2988 ;; change-groups.
2989 (cdr buffer-undo-list)))))
2990 ;; Reset the modified cons cell ELT to its original content.
2991 (when (consp elt)
2992 (setcar elt old-car)
2993 (setcdr elt old-cdr))))))))
2994
2995
2996 (defcustom undo-ask-before-discard nil
2997 "If non-nil ask about discarding undo info for the current command.
2998 Normally, Emacs discards the undo info for the current command if
2999 it exceeds `undo-outer-limit'. But if you set this option
3000 non-nil, it asks in the echo area whether to discard the info.
3001 If you answer no, there is a slight risk that Emacs might crash, so
3002 only do it if you really want to undo the command.
3003
3004 This option is mainly intended for debugging. You have to be
3005 careful if you use it for other purposes. Garbage collection is
3006 inhibited while the question is asked, meaning that Emacs might
3007 leak memory. So you should make sure that you do not wait
3008 excessively long before answering the question."
3009 :type 'boolean
3010 :group 'undo
3011 :version "22.1")
3012
3013 (defvar undo-extra-outer-limit nil
3014 "If non-nil, an extra level of size that's ok in an undo item.
3015 We don't ask the user about truncating the undo list until the
3016 current item gets bigger than this amount.
3017
3018 This variable only matters if `undo-ask-before-discard' is non-nil.")
3019 (make-variable-buffer-local 'undo-extra-outer-limit)
3020
3021 ;; When the first undo batch in an undo list is longer than
3022 ;; undo-outer-limit, this function gets called to warn the user that
3023 ;; the undo info for the current command was discarded. Garbage
3024 ;; collection is inhibited around the call, so it had better not do a
3025 ;; lot of consing.
3026 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3027 (defun undo-outer-limit-truncate (size)
3028 (if undo-ask-before-discard
3029 (when (or (null undo-extra-outer-limit)
3030 (> size undo-extra-outer-limit))
3031 ;; Don't ask the question again unless it gets even bigger.
3032 ;; This applies, in particular, if the user quits from the question.
3033 ;; Such a quit quits out of GC, but something else will call GC
3034 ;; again momentarily. It will call this function again,
3035 ;; but we don't want to ask the question again.
3036 (setq undo-extra-outer-limit (+ size 50000))
3037 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3038 (yes-or-no-p (format-message
3039 "Buffer `%s' undo info is %d bytes long; discard it? "
3040 (buffer-name) size)))
3041 (progn (setq buffer-undo-list nil)
3042 (setq undo-extra-outer-limit nil)
3043 t)
3044 nil))
3045 (display-warning '(undo discard-info)
3046 (concat
3047 (format-message
3048 "Buffer `%s' undo info was %d bytes long.\n"
3049 (buffer-name) size)
3050 "The undo info was discarded because it exceeded \
3051 `undo-outer-limit'.
3052
3053 This is normal if you executed a command that made a huge change
3054 to the buffer. In that case, to prevent similar problems in the
3055 future, set `undo-outer-limit' to a value that is large enough to
3056 cover the maximum size of normal changes you expect a single
3057 command to make, but not so large that it might exceed the
3058 maximum memory allotted to Emacs.
3059
3060 If you did not execute any such command, the situation is
3061 probably due to a bug and you should report it.
3062
3063 You can disable the popping up of this buffer by adding the entry
3064 \(undo discard-info) to the user option `warning-suppress-types',
3065 which is defined in the `warnings' library.\n")
3066 :warning)
3067 (setq buffer-undo-list nil)
3068 t))
3069 \f
3070 (defcustom password-word-equivalents
3071 '("password" "passcode" "passphrase" "pass phrase"
3072 ; These are sorted according to the GNU en_US locale.
3073 "암호" ; ko
3074 "パスワード" ; ja
3075 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3076 "ពាក្យសម្ងាត់" ; km
3077 "adgangskode" ; da
3078 "contraseña" ; es
3079 "contrasenya" ; ca
3080 "geslo" ; sl
3081 "hasło" ; pl
3082 "heslo" ; cs, sk
3083 "iphasiwedi" ; zu
3084 "jelszó" ; hu
3085 "lösenord" ; sv
3086 "lozinka" ; hr, sr
3087 "mật khẩu" ; vi
3088 "mot de passe" ; fr
3089 "parola" ; tr
3090 "pasahitza" ; eu
3091 "passord" ; nb
3092 "passwort" ; de
3093 "pasvorto" ; eo
3094 "salasana" ; fi
3095 "senha" ; pt
3096 "slaptažodis" ; lt
3097 "wachtwoord" ; nl
3098 "كلمة السر" ; ar
3099 "ססמה" ; he
3100 "лозинка" ; sr
3101 "пароль" ; kk, ru, uk
3102 "गुप्तशब्द" ; mr
3103 "शब्दकूट" ; hi
3104 "પાસવર્ડ" ; gu
3105 "సంకేతపదము" ; te
3106 "ਪਾਸਵਰਡ" ; pa
3107 "ಗುಪ್ತಪದ" ; kn
3108 "கடவுச்சொல்" ; ta
3109 "അടയാളവാക്ക്" ; ml
3110 "গুপ্তশব্দ" ; as
3111 "পাসওয়ার্ড" ; bn_IN
3112 "රහස්පදය" ; si
3113 "密码" ; zh_CN
3114 "密碼" ; zh_TW
3115 )
3116 "List of words equivalent to \"password\".
3117 This is used by Shell mode and other parts of Emacs to recognize
3118 password prompts, including prompts in languages other than
3119 English. Different case choices should not be assumed to be
3120 included; callers should bind `case-fold-search' to t."
3121 :type '(repeat string)
3122 :version "24.4"
3123 :group 'processes)
3124
3125 (defvar shell-command-history nil
3126 "History list for some commands that read shell commands.
3127
3128 Maximum length of the history list is determined by the value
3129 of `history-length', which see.")
3130
3131 (defvar shell-command-switch (purecopy "-c")
3132 "Switch used to have the shell execute its command line argument.")
3133
3134 (defvar shell-command-default-error-buffer nil
3135 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3136 This buffer is used when `shell-command' or `shell-command-on-region'
3137 is run interactively. A value of nil means that output to stderr and
3138 stdout will be intermixed in the output stream.")
3139
3140 (declare-function mailcap-file-default-commands "mailcap" (files))
3141 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3142
3143 (defun minibuffer-default-add-shell-commands ()
3144 "Return a list of all commands associated with the current file.
3145 This function is used to add all related commands retrieved by `mailcap'
3146 to the end of the list of defaults just after the default value."
3147 (interactive)
3148 (let* ((filename (if (listp minibuffer-default)
3149 (car minibuffer-default)
3150 minibuffer-default))
3151 (commands (and filename (require 'mailcap nil t)
3152 (mailcap-file-default-commands (list filename)))))
3153 (setq commands (mapcar (lambda (command)
3154 (concat command " " filename))
3155 commands))
3156 (if (listp minibuffer-default)
3157 (append minibuffer-default commands)
3158 (cons minibuffer-default commands))))
3159
3160 (declare-function shell-completion-vars "shell" ())
3161
3162 (defvar minibuffer-local-shell-command-map
3163 (let ((map (make-sparse-keymap)))
3164 (set-keymap-parent map minibuffer-local-map)
3165 (define-key map "\t" 'completion-at-point)
3166 map)
3167 "Keymap used for completing shell commands in minibuffer.")
3168
3169 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3170 "Read a shell command from the minibuffer.
3171 The arguments are the same as the ones of `read-from-minibuffer',
3172 except READ and KEYMAP are missing and HIST defaults
3173 to `shell-command-history'."
3174 (require 'shell)
3175 (minibuffer-with-setup-hook
3176 (lambda ()
3177 (shell-completion-vars)
3178 (set (make-local-variable 'minibuffer-default-add-function)
3179 'minibuffer-default-add-shell-commands))
3180 (apply 'read-from-minibuffer prompt initial-contents
3181 minibuffer-local-shell-command-map
3182 nil
3183 (or hist 'shell-command-history)
3184 args)))
3185
3186 (defcustom async-shell-command-buffer 'confirm-new-buffer
3187 "What to do when the output buffer is used by another shell command.
3188 This option specifies how to resolve the conflict where a new command
3189 wants to direct its output to the buffer `*Async Shell Command*',
3190 but this buffer is already taken by another running shell command.
3191
3192 The value `confirm-kill-process' is used to ask for confirmation before
3193 killing the already running process and running a new process
3194 in the same buffer, `confirm-new-buffer' for confirmation before running
3195 the command in a new buffer with a name other than the default buffer name,
3196 `new-buffer' for doing the same without confirmation,
3197 `confirm-rename-buffer' for confirmation before renaming the existing
3198 output buffer and running a new command in the default buffer,
3199 `rename-buffer' for doing the same without confirmation."
3200 :type '(choice (const :tag "Confirm killing of running command"
3201 confirm-kill-process)
3202 (const :tag "Confirm creation of a new buffer"
3203 confirm-new-buffer)
3204 (const :tag "Create a new buffer"
3205 new-buffer)
3206 (const :tag "Confirm renaming of existing buffer"
3207 confirm-rename-buffer)
3208 (const :tag "Rename the existing buffer"
3209 rename-buffer))
3210 :group 'shell
3211 :version "24.3")
3212
3213 (defun async-shell-command (command &optional output-buffer error-buffer)
3214 "Execute string COMMAND asynchronously in background.
3215
3216 Like `shell-command', but adds `&' at the end of COMMAND
3217 to execute it asynchronously.
3218
3219 The output appears in the buffer `*Async Shell Command*'.
3220 That buffer is in shell mode.
3221
3222 You can configure `async-shell-command-buffer' to specify what to do in
3223 case when `*Async Shell Command*' buffer is already taken by another
3224 running shell command. To run COMMAND without displaying the output
3225 in a window you can configure `display-buffer-alist' to use the action
3226 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3227
3228 In Elisp, you will often be better served by calling `start-process'
3229 directly, since it offers more control and does not impose the use of a
3230 shell (with its need to quote arguments)."
3231 (interactive
3232 (list
3233 (read-shell-command "Async shell command: " nil nil
3234 (let ((filename
3235 (cond
3236 (buffer-file-name)
3237 ((eq major-mode 'dired-mode)
3238 (dired-get-filename nil t)))))
3239 (and filename (file-relative-name filename))))
3240 current-prefix-arg
3241 shell-command-default-error-buffer))
3242 (unless (string-match "&[ \t]*\\'" command)
3243 (setq command (concat command " &")))
3244 (shell-command command output-buffer error-buffer))
3245
3246 (defun shell-command (command &optional output-buffer error-buffer)
3247 "Execute string COMMAND in inferior shell; display output, if any.
3248 With prefix argument, insert the COMMAND's output at point.
3249
3250 Interactively, prompt for COMMAND in the minibuffer.
3251
3252 If COMMAND ends in `&', execute it asynchronously.
3253 The output appears in the buffer `*Async Shell Command*'.
3254 That buffer is in shell mode. You can also use
3255 `async-shell-command' that automatically adds `&'.
3256
3257 Otherwise, COMMAND is executed synchronously. The output appears in
3258 the buffer `*Shell Command Output*'. If the output is short enough to
3259 display in the echo area (which is determined by the variables
3260 `resize-mini-windows' and `max-mini-window-height'), it is shown
3261 there, but it is nonetheless available in buffer `*Shell Command
3262 Output*' even though that buffer is not automatically displayed.
3263
3264 To specify a coding system for converting non-ASCII characters
3265 in the shell command output, use \\[universal-coding-system-argument] \
3266 before this command.
3267
3268 Noninteractive callers can specify coding systems by binding
3269 `coding-system-for-read' and `coding-system-for-write'.
3270
3271 The optional second argument OUTPUT-BUFFER, if non-nil,
3272 says to put the output in some other buffer.
3273 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3274 and insert the output there.
3275 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3276 in current buffer after point leaving mark after it.
3277 This cannot be done asynchronously.
3278
3279 If the command terminates without error, but generates output,
3280 and you did not specify \"insert it in the current buffer\",
3281 the output can be displayed in the echo area or in its buffer.
3282 If the output is short enough to display in the echo area
3283 \(determined by the variable `max-mini-window-height' if
3284 `resize-mini-windows' is non-nil), it is shown there.
3285 Otherwise,the buffer containing the output is displayed.
3286
3287 If there is output and an error, and you did not specify \"insert it
3288 in the current buffer\", a message about the error goes at the end
3289 of the output.
3290
3291 If there is no output, or if output is inserted in the current buffer,
3292 then `*Shell Command Output*' is deleted.
3293
3294 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3295 or buffer name to which to direct the command's standard error output.
3296 If it is nil, error output is mingled with regular output.
3297 In an interactive call, the variable `shell-command-default-error-buffer'
3298 specifies the value of ERROR-BUFFER.
3299
3300 In Elisp, you will often be better served by calling `call-process' or
3301 `start-process' directly, since it offers more control and does not impose
3302 the use of a shell (with its need to quote arguments)."
3303
3304 (interactive
3305 (list
3306 (read-shell-command "Shell command: " nil nil
3307 (let ((filename
3308 (cond
3309 (buffer-file-name)
3310 ((eq major-mode 'dired-mode)
3311 (dired-get-filename nil t)))))
3312 (and filename (file-relative-name filename))))
3313 current-prefix-arg
3314 shell-command-default-error-buffer))
3315 ;; Look for a handler in case default-directory is a remote file name.
3316 (let ((handler
3317 (find-file-name-handler (directory-file-name default-directory)
3318 'shell-command)))
3319 (if handler
3320 (funcall handler 'shell-command command output-buffer error-buffer)
3321 (if (and output-buffer
3322 (not (or (bufferp output-buffer) (stringp output-buffer))))
3323 ;; Output goes in current buffer.
3324 (let ((error-file
3325 (if error-buffer
3326 (make-temp-file
3327 (expand-file-name "scor"
3328 (or small-temporary-file-directory
3329 temporary-file-directory)))
3330 nil)))
3331 (barf-if-buffer-read-only)
3332 (push-mark nil t)
3333 ;; We do not use -f for csh; we will not support broken use of
3334 ;; .cshrcs. Even the BSD csh manual says to use
3335 ;; "if ($?prompt) exit" before things which are not useful
3336 ;; non-interactively. Besides, if someone wants their other
3337 ;; aliases for shell commands then they can still have them.
3338 (call-process shell-file-name nil
3339 (if error-file
3340 (list t error-file)
3341 t)
3342 nil shell-command-switch command)
3343 (when (and error-file (file-exists-p error-file))
3344 (if (< 0 (nth 7 (file-attributes error-file)))
3345 (with-current-buffer (get-buffer-create error-buffer)
3346 (let ((pos-from-end (- (point-max) (point))))
3347 (or (bobp)
3348 (insert "\f\n"))
3349 ;; Do no formatting while reading error file,
3350 ;; because that can run a shell command, and we
3351 ;; don't want that to cause an infinite recursion.
3352 (format-insert-file error-file nil)
3353 ;; Put point after the inserted errors.
3354 (goto-char (- (point-max) pos-from-end)))
3355 (display-buffer (current-buffer))))
3356 (delete-file error-file))
3357 ;; This is like exchange-point-and-mark, but doesn't
3358 ;; activate the mark. It is cleaner to avoid activation,
3359 ;; even though the command loop would deactivate the mark
3360 ;; because we inserted text.
3361 (goto-char (prog1 (mark t)
3362 (set-marker (mark-marker) (point)
3363 (current-buffer)))))
3364 ;; Output goes in a separate buffer.
3365 ;; Preserve the match data in case called from a program.
3366 ;; FIXME: It'd be ridiculous for an Elisp function to call
3367 ;; shell-command and assume that it won't mess the match-data!
3368 (save-match-data
3369 (if (string-match "[ \t]*&[ \t]*\\'" command)
3370 ;; Command ending with ampersand means asynchronous.
3371 (let ((buffer (get-buffer-create
3372 (or output-buffer "*Async Shell Command*")))
3373 (directory default-directory)
3374 proc)
3375 ;; Remove the ampersand.
3376 (setq command (substring command 0 (match-beginning 0)))
3377 ;; Ask the user what to do with already running process.
3378 (setq proc (get-buffer-process buffer))
3379 (when proc
3380 (cond
3381 ((eq async-shell-command-buffer 'confirm-kill-process)
3382 ;; If will kill a process, query first.
3383 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3384 (kill-process proc)
3385 (error "Shell command in progress")))
3386 ((eq async-shell-command-buffer 'confirm-new-buffer)
3387 ;; If will create a new buffer, query first.
3388 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3389 (setq buffer (generate-new-buffer
3390 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3391 output-buffer "*Async Shell Command*")))
3392 (error "Shell command in progress")))
3393 ((eq async-shell-command-buffer 'new-buffer)
3394 ;; It will create a new buffer.
3395 (setq buffer (generate-new-buffer
3396 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3397 output-buffer "*Async Shell Command*"))))
3398 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3399 ;; If will rename the buffer, query first.
3400 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3401 (progn
3402 (with-current-buffer buffer
3403 (rename-uniquely))
3404 (setq buffer (get-buffer-create
3405 (or output-buffer "*Async Shell Command*"))))
3406 (error "Shell command in progress")))
3407 ((eq async-shell-command-buffer 'rename-buffer)
3408 ;; It will rename the buffer.
3409 (with-current-buffer buffer
3410 (rename-uniquely))
3411 (setq buffer (get-buffer-create
3412 (or output-buffer "*Async Shell Command*"))))))
3413 (with-current-buffer buffer
3414 (setq buffer-read-only nil)
3415 ;; Setting buffer-read-only to nil doesn't suffice
3416 ;; if some text has a non-nil read-only property,
3417 ;; which comint sometimes adds for prompts.
3418 (let ((inhibit-read-only t))
3419 (erase-buffer))
3420 (display-buffer buffer '(nil (allow-no-window . t)))
3421 (setq default-directory directory)
3422 (setq proc (start-process "Shell" buffer shell-file-name
3423 shell-command-switch command))
3424 (setq mode-line-process '(":%s"))
3425 (require 'shell) (shell-mode)
3426 (set-process-sentinel proc 'shell-command-sentinel)
3427 ;; Use the comint filter for proper handling of carriage motion
3428 ;; (see `comint-inhibit-carriage-motion'),.
3429 (set-process-filter proc 'comint-output-filter)
3430 ))
3431 ;; Otherwise, command is executed synchronously.
3432 (shell-command-on-region (point) (point) command
3433 output-buffer nil error-buffer)))))))
3434
3435 (defun display-message-or-buffer (message &optional buffer-name action frame)
3436 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3437 MESSAGE may be either a string or a buffer.
3438
3439 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3440 for maximum height of the echo area, as defined by `max-mini-window-height'
3441 if `resize-mini-windows' is non-nil.
3442
3443 Returns either the string shown in the echo area, or when a pop-up
3444 buffer is used, the window used to display it.
3445
3446 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3447 name of the buffer used to display it in the case where a pop-up buffer
3448 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3449 string and it is displayed in the echo area, it is not specified whether
3450 the contents are inserted into the buffer anyway.
3451
3452 Optional arguments ACTION and FRAME are as for `display-buffer',
3453 and are only used if a pop-up buffer is displayed."
3454 (cond ((and (stringp message) (not (string-match "\n" message)))
3455 ;; Trivial case where we can use the echo area
3456 (message "%s" message))
3457 ((and (stringp message)
3458 (= (string-match "\n" message) (1- (length message))))
3459 ;; Trivial case where we can just remove single trailing newline
3460 (message "%s" (substring message 0 (1- (length message)))))
3461 (t
3462 ;; General case
3463 (with-current-buffer
3464 (if (bufferp message)
3465 message
3466 (get-buffer-create (or buffer-name "*Message*")))
3467
3468 (unless (bufferp message)
3469 (erase-buffer)
3470 (insert message))
3471
3472 (let ((lines
3473 (if (= (buffer-size) 0)
3474 0
3475 (count-screen-lines nil nil nil (minibuffer-window)))))
3476 (cond ((= lines 0))
3477 ((and (or (<= lines 1)
3478 (<= lines
3479 (if resize-mini-windows
3480 (cond ((floatp max-mini-window-height)
3481 (* (frame-height)
3482 max-mini-window-height))
3483 ((integerp max-mini-window-height)
3484 max-mini-window-height)
3485 (t
3486 1))
3487 1)))
3488 ;; Don't use the echo area if the output buffer is
3489 ;; already displayed in the selected frame.
3490 (not (get-buffer-window (current-buffer))))
3491 ;; Echo area
3492 (goto-char (point-max))
3493 (when (bolp)
3494 (backward-char 1))
3495 (message "%s" (buffer-substring (point-min) (point))))
3496 (t
3497 ;; Buffer
3498 (goto-char (point-min))
3499 (display-buffer (current-buffer) action frame))))))))
3500
3501
3502 ;; We have a sentinel to prevent insertion of a termination message
3503 ;; in the buffer itself.
3504 (defun shell-command-sentinel (process signal)
3505 (if (memq (process-status process) '(exit signal))
3506 (message "%s: %s."
3507 (car (cdr (cdr (process-command process))))
3508 (substring signal 0 -1))))
3509
3510 (defun shell-command-on-region (start end command
3511 &optional output-buffer replace
3512 error-buffer display-error-buffer
3513 region-noncontiguous-p)
3514 "Execute string COMMAND in inferior shell with region as input.
3515 Normally display output (if any) in temp buffer `*Shell Command Output*';
3516 Prefix arg means replace the region with it. Return the exit code of
3517 COMMAND.
3518
3519 To specify a coding system for converting non-ASCII characters
3520 in the input and output to the shell command, use \\[universal-coding-system-argument]
3521 before this command. By default, the input (from the current buffer)
3522 is encoded using coding-system specified by `process-coding-system-alist',
3523 falling back to `default-process-coding-system' if no match for COMMAND
3524 is found in `process-coding-system-alist'.
3525
3526 Noninteractive callers can specify coding systems by binding
3527 `coding-system-for-read' and `coding-system-for-write'.
3528
3529 If the command generates output, the output may be displayed
3530 in the echo area or in a buffer.
3531 If the output is short enough to display in the echo area
3532 \(determined by the variable `max-mini-window-height' if
3533 `resize-mini-windows' is non-nil), it is shown there.
3534 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3535 The output is available in that buffer in both cases.
3536
3537 If there is output and an error, a message about the error
3538 appears at the end of the output. If there is no output, or if
3539 output is inserted in the current buffer, the buffer `*Shell
3540 Command Output*' is deleted.
3541
3542 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3543 command's output. If the value is a buffer or buffer name,
3544 erase that buffer and insert the output there.
3545 If the value is nil, use the buffer `*Shell Command Output*'.
3546 Any other non-nil value means to insert the output in the
3547 current buffer after START.
3548
3549 Optional fifth arg REPLACE, if non-nil, means to insert the
3550 output in place of text from START to END, putting point and mark
3551 around it.
3552
3553 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3554 or buffer name to which to direct the command's standard error
3555 output. If nil, error output is mingled with regular output.
3556 When called interactively, `shell-command-default-error-buffer'
3557 is used for ERROR-BUFFER.
3558
3559 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3560 display the error buffer if there were any errors. When called
3561 interactively, this is t."
3562 (interactive (let (string)
3563 (unless (mark)
3564 (user-error "The mark is not set now, so there is no region"))
3565 ;; Do this before calling region-beginning
3566 ;; and region-end, in case subprocess output
3567 ;; relocates them while we are in the minibuffer.
3568 (setq string (read-shell-command "Shell command on region: "))
3569 ;; call-interactively recognizes region-beginning and
3570 ;; region-end specially, leaving them in the history.
3571 (list (region-beginning) (region-end)
3572 string
3573 current-prefix-arg
3574 current-prefix-arg
3575 shell-command-default-error-buffer
3576 t
3577 (region-noncontiguous-p))))
3578 (let ((error-file
3579 (if error-buffer
3580 (make-temp-file
3581 (expand-file-name "scor"
3582 (or small-temporary-file-directory
3583 temporary-file-directory)))
3584 nil))
3585 exit-status)
3586 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3587 (if region-noncontiguous-p
3588 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3589 output)
3590 (with-temp-buffer
3591 (insert input)
3592 (call-process-region (point-min) (point-max)
3593 shell-file-name t t
3594 nil shell-command-switch
3595 command)
3596 (setq output (split-string (buffer-string) "\n")))
3597 (goto-char start)
3598 (funcall region-insert-function output))
3599 (if (or replace
3600 (and output-buffer
3601 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3602 ;; Replace specified region with output from command.
3603 (let ((swap (and replace (< start end))))
3604 ;; Don't muck with mark unless REPLACE says we should.
3605 (goto-char start)
3606 (and replace (push-mark (point) 'nomsg))
3607 (setq exit-status
3608 (call-process-region start end shell-file-name replace
3609 (if error-file
3610 (list t error-file)
3611 t)
3612 nil shell-command-switch command))
3613 ;; It is rude to delete a buffer which the command is not using.
3614 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3615 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3616 ;; (kill-buffer shell-buffer)))
3617 ;; Don't muck with mark unless REPLACE says we should.
3618 (and replace swap (exchange-point-and-mark)))
3619 ;; No prefix argument: put the output in a temp buffer,
3620 ;; replacing its entire contents.
3621 (let ((buffer (get-buffer-create
3622 (or output-buffer "*Shell Command Output*"))))
3623 (unwind-protect
3624 (if (eq buffer (current-buffer))
3625 ;; If the input is the same buffer as the output,
3626 ;; delete everything but the specified region,
3627 ;; then replace that region with the output.
3628 (progn (setq buffer-read-only nil)
3629 (delete-region (max start end) (point-max))
3630 (delete-region (point-min) (min start end))
3631 (setq exit-status
3632 (call-process-region (point-min) (point-max)
3633 shell-file-name t
3634 (if error-file
3635 (list t error-file)
3636 t)
3637 nil shell-command-switch
3638 command)))
3639 ;; Clear the output buffer, then run the command with
3640 ;; output there.
3641 (let ((directory default-directory))
3642 (with-current-buffer buffer
3643 (setq buffer-read-only nil)
3644 (if (not output-buffer)
3645 (setq default-directory directory))
3646 (erase-buffer)))
3647 (setq exit-status
3648 (call-process-region start end shell-file-name nil
3649 (if error-file
3650 (list buffer error-file)
3651 buffer)
3652 nil shell-command-switch command)))
3653 ;; Report the output.
3654 (with-current-buffer buffer
3655 (setq mode-line-process
3656 (cond ((null exit-status)
3657 " - Error")
3658 ((stringp exit-status)
3659 (format " - Signal [%s]" exit-status))
3660 ((not (equal 0 exit-status))
3661 (format " - Exit [%d]" exit-status)))))
3662 (if (with-current-buffer buffer (> (point-max) (point-min)))
3663 ;; There's some output, display it
3664 (display-message-or-buffer buffer)
3665 ;; No output; error?
3666 (let ((output
3667 (if (and error-file
3668 (< 0 (nth 7 (file-attributes error-file))))
3669 (format "some error output%s"
3670 (if shell-command-default-error-buffer
3671 (format " to the \"%s\" buffer"
3672 shell-command-default-error-buffer)
3673 ""))
3674 "no output")))
3675 (cond ((null exit-status)
3676 (message "(Shell command failed with error)"))
3677 ((equal 0 exit-status)
3678 (message "(Shell command succeeded with %s)"
3679 output))
3680 ((stringp exit-status)
3681 (message "(Shell command killed by signal %s)"
3682 exit-status))
3683 (t
3684 (message "(Shell command failed with code %d and %s)"
3685 exit-status output))))
3686 ;; Don't kill: there might be useful info in the undo-log.
3687 ;; (kill-buffer buffer)
3688 )))))
3689
3690 (when (and error-file (file-exists-p error-file))
3691 (if (< 0 (nth 7 (file-attributes error-file)))
3692 (with-current-buffer (get-buffer-create error-buffer)
3693 (let ((pos-from-end (- (point-max) (point))))
3694 (or (bobp)
3695 (insert "\f\n"))
3696 ;; Do no formatting while reading error file,
3697 ;; because that can run a shell command, and we
3698 ;; don't want that to cause an infinite recursion.
3699 (format-insert-file error-file nil)
3700 ;; Put point after the inserted errors.
3701 (goto-char (- (point-max) pos-from-end)))
3702 (and display-error-buffer
3703 (display-buffer (current-buffer)))))
3704 (delete-file error-file))
3705 exit-status))
3706
3707 (defun shell-command-to-string (command)
3708 "Execute shell command COMMAND and return its output as a string."
3709 (with-output-to-string
3710 (with-current-buffer
3711 standard-output
3712 (process-file shell-file-name nil t nil shell-command-switch command))))
3713
3714 (defun process-file (program &optional infile buffer display &rest args)
3715 "Process files synchronously in a separate process.
3716 Similar to `call-process', but may invoke a file handler based on
3717 `default-directory'. The current working directory of the
3718 subprocess is `default-directory'.
3719
3720 File names in INFILE and BUFFER are handled normally, but file
3721 names in ARGS should be relative to `default-directory', as they
3722 are passed to the process verbatim. (This is a difference to
3723 `call-process' which does not support file handlers for INFILE
3724 and BUFFER.)
3725
3726 Some file handlers might not support all variants, for example
3727 they might behave as if DISPLAY was nil, regardless of the actual
3728 value passed."
3729 (let ((fh (find-file-name-handler default-directory 'process-file))
3730 lc stderr-file)
3731 (unwind-protect
3732 (if fh (apply fh 'process-file program infile buffer display args)
3733 (when infile (setq lc (file-local-copy infile)))
3734 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3735 (make-temp-file "emacs")))
3736 (prog1
3737 (apply 'call-process program
3738 (or lc infile)
3739 (if stderr-file (list (car buffer) stderr-file) buffer)
3740 display args)
3741 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3742 (when stderr-file (delete-file stderr-file))
3743 (when lc (delete-file lc)))))
3744
3745 (defvar process-file-side-effects t
3746 "Whether a call of `process-file' changes remote files.
3747
3748 By default, this variable is always set to t, meaning that a
3749 call of `process-file' could potentially change any file on a
3750 remote host. When set to nil, a file handler could optimize
3751 its behavior with respect to remote file attribute caching.
3752
3753 You should only ever change this variable with a let-binding;
3754 never with `setq'.")
3755
3756 (defun start-file-process (name buffer program &rest program-args)
3757 "Start a program in a subprocess. Return the process object for it.
3758
3759 Similar to `start-process', but may invoke a file handler based on
3760 `default-directory'. See Info node `(elisp)Magic File Names'.
3761
3762 This handler ought to run PROGRAM, perhaps on the local host,
3763 perhaps on a remote host that corresponds to `default-directory'.
3764 In the latter case, the local part of `default-directory' becomes
3765 the working directory of the process.
3766
3767 PROGRAM and PROGRAM-ARGS might be file names. They are not
3768 objects of file handler invocation. File handlers might not
3769 support pty association, if PROGRAM is nil."
3770 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3771 (if fh (apply fh 'start-file-process name buffer program program-args)
3772 (apply 'start-process name buffer program program-args))))
3773 \f
3774 ;;;; Process menu
3775
3776 (defvar tabulated-list-format)
3777 (defvar tabulated-list-entries)
3778 (defvar tabulated-list-sort-key)
3779 (declare-function tabulated-list-init-header "tabulated-list" ())
3780 (declare-function tabulated-list-print "tabulated-list"
3781 (&optional remember-pos update))
3782
3783 (defvar process-menu-query-only nil)
3784
3785 (defvar process-menu-mode-map
3786 (let ((map (make-sparse-keymap)))
3787 (define-key map [?d] 'process-menu-delete-process)
3788 map))
3789
3790 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3791 "Major mode for listing the processes called by Emacs."
3792 (setq tabulated-list-format [("Process" 15 t)
3793 ("PID" 7 t)
3794 ("Status" 7 t)
3795 ("Buffer" 15 t)
3796 ("TTY" 12 t)
3797 ("Command" 0 t)])
3798 (make-local-variable 'process-menu-query-only)
3799 (setq tabulated-list-sort-key (cons "Process" nil))
3800 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3801 (tabulated-list-init-header))
3802
3803 (defun process-menu-delete-process ()
3804 "Kill process at point in a `list-processes' buffer."
3805 (interactive)
3806 (let ((pos (point)))
3807 (delete-process (tabulated-list-get-id))
3808 (revert-buffer)
3809 (goto-char (min pos (point-max)))
3810 (if (eobp)
3811 (forward-line -1)
3812 (beginning-of-line))))
3813
3814 (defun list-processes--refresh ()
3815 "Recompute the list of processes for the Process List buffer.
3816 Also, delete any process that is exited or signaled."
3817 (setq tabulated-list-entries nil)
3818 (dolist (p (process-list))
3819 (cond ((memq (process-status p) '(exit signal closed))
3820 (delete-process p))
3821 ((or (not process-menu-query-only)
3822 (process-query-on-exit-flag p))
3823 (let* ((buf (process-buffer p))
3824 (type (process-type p))
3825 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3826 (name (process-name p))
3827 (status (symbol-name (process-status p)))
3828 (buf-label (if (buffer-live-p buf)
3829 `(,(buffer-name buf)
3830 face link
3831 help-echo ,(format-message
3832 "Visit buffer `%s'"
3833 (buffer-name buf))
3834 follow-link t
3835 process-buffer ,buf
3836 action process-menu-visit-buffer)
3837 "--"))
3838 (tty (or (process-tty-name p) "--"))
3839 (cmd
3840 (if (memq type '(network serial))
3841 (let ((contact (process-contact p t)))
3842 (if (eq type 'network)
3843 (format "(%s %s)"
3844 (if (plist-get contact :type)
3845 "datagram"
3846 "network")
3847 (if (plist-get contact :server)
3848 (format "server on %s"
3849 (or
3850 (plist-get contact :host)
3851 (plist-get contact :local)))
3852 (format "connection to %s"
3853 (plist-get contact :host))))
3854 (format "(serial port %s%s)"
3855 (or (plist-get contact :port) "?")
3856 (let ((speed (plist-get contact :speed)))
3857 (if speed
3858 (format " at %s b/s" speed)
3859 "")))))
3860 (mapconcat 'identity (process-command p) " "))))
3861 (push (list p (vector name pid status buf-label tty cmd))
3862 tabulated-list-entries))))))
3863
3864 (defun process-menu-visit-buffer (button)
3865 (display-buffer (button-get button 'process-buffer)))
3866
3867 (defun list-processes (&optional query-only buffer)
3868 "Display a list of all processes that are Emacs sub-processes.
3869 If optional argument QUERY-ONLY is non-nil, only processes with
3870 the query-on-exit flag set are listed.
3871 Any process listed as exited or signaled is actually eliminated
3872 after the listing is made.
3873 Optional argument BUFFER specifies a buffer to use, instead of
3874 \"*Process List*\".
3875 The return value is always nil.
3876
3877 This function lists only processes that were launched by Emacs. To
3878 see other processes running on the system, use `list-system-processes'."
3879 (interactive)
3880 (or (fboundp 'process-list)
3881 (error "Asynchronous subprocesses are not supported on this system"))
3882 (unless (bufferp buffer)
3883 (setq buffer (get-buffer-create "*Process List*")))
3884 (with-current-buffer buffer
3885 (process-menu-mode)
3886 (setq process-menu-query-only query-only)
3887 (list-processes--refresh)
3888 (tabulated-list-print))
3889 (display-buffer buffer)
3890 nil)
3891 \f
3892 ;;;; Prefix commands
3893
3894 (setq prefix-command--needs-update nil)
3895 (setq prefix-command--last-echo nil)
3896
3897 (defun internal-echo-keystrokes-prefix ()
3898 ;; BEWARE: Called directly from C code.
3899 ;; If the return value is non-nil, it means we are in the middle of
3900 ;; a command with prefix, such as a command invoked with prefix-arg.
3901 (if (not prefix-command--needs-update)
3902 prefix-command--last-echo
3903 (setq prefix-command--last-echo
3904 (let ((strs nil))
3905 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3906 (lambda (fun) (push (funcall fun) strs)))
3907 (setq strs (delq nil strs))
3908 (when strs (mapconcat #'identity strs " "))))))
3909
3910 (defvar prefix-command-echo-keystrokes-functions nil
3911 "Abnormal hook which constructs the description of the current prefix state.
3912 Each function is called with no argument, should return a string or nil.")
3913
3914 (defun prefix-command-update ()
3915 "Update state of prefix commands.
3916 Call it whenever you change the \"prefix command state\"."
3917 (setq prefix-command--needs-update t))
3918
3919 (defvar prefix-command-preserve-state-hook nil
3920 "Normal hook run when a command needs to preserve the prefix.")
3921
3922 (defun prefix-command-preserve-state ()
3923 "Pass the current prefix command state to the next command.
3924 Should be called by all prefix commands.
3925 Runs `prefix-command-preserve-state-hook'."
3926 (run-hooks 'prefix-command-preserve-state-hook)
3927 ;; If the current command is a prefix command, we don't want the next (real)
3928 ;; command to have `last-command' set to, say, `universal-argument'.
3929 (setq this-command last-command)
3930 (setq real-this-command real-last-command)
3931 (prefix-command-update))
3932
3933 (defun reset-this-command-lengths ()
3934 (declare (obsolete prefix-command-preserve-state "25.1"))
3935 nil)
3936
3937 ;;;;; The main prefix command.
3938
3939 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3940
3941 (add-hook 'prefix-command-echo-keystrokes-functions
3942 #'universal-argument--description)
3943 (defun universal-argument--description ()
3944 (when prefix-arg
3945 (concat "C-u"
3946 (pcase prefix-arg
3947 (`(-) " -")
3948 (`(,(and (pred integerp) n))
3949 (let ((str ""))
3950 (while (and (> n 4) (= (mod n 4) 0))
3951 (setq str (concat str " C-u"))
3952 (setq n (/ n 4)))
3953 (if (= n 4) str (format " %s" prefix-arg))))
3954 (_ (format " %s" prefix-arg))))))
3955
3956 (add-hook 'prefix-command-preserve-state-hook
3957 #'universal-argument--preserve)
3958 (defun universal-argument--preserve ()
3959 (setq prefix-arg current-prefix-arg))
3960
3961 (defvar universal-argument-map
3962 (let ((map (make-sparse-keymap))
3963 (universal-argument-minus
3964 ;; For backward compatibility, minus with no modifiers is an ordinary
3965 ;; command if digits have already been entered.
3966 `(menu-item "" negative-argument
3967 :filter ,(lambda (cmd)
3968 (if (integerp prefix-arg) nil cmd)))))
3969 (define-key map [switch-frame]
3970 (lambda (e) (interactive "e")
3971 (handle-switch-frame e) (universal-argument--mode)))
3972 (define-key map [?\C-u] 'universal-argument-more)
3973 (define-key map [?-] universal-argument-minus)
3974 (define-key map [?0] 'digit-argument)
3975 (define-key map [?1] 'digit-argument)
3976 (define-key map [?2] 'digit-argument)
3977 (define-key map [?3] 'digit-argument)
3978 (define-key map [?4] 'digit-argument)
3979 (define-key map [?5] 'digit-argument)
3980 (define-key map [?6] 'digit-argument)
3981 (define-key map [?7] 'digit-argument)
3982 (define-key map [?8] 'digit-argument)
3983 (define-key map [?9] 'digit-argument)
3984 (define-key map [kp-0] 'digit-argument)
3985 (define-key map [kp-1] 'digit-argument)
3986 (define-key map [kp-2] 'digit-argument)
3987 (define-key map [kp-3] 'digit-argument)
3988 (define-key map [kp-4] 'digit-argument)
3989 (define-key map [kp-5] 'digit-argument)
3990 (define-key map [kp-6] 'digit-argument)
3991 (define-key map [kp-7] 'digit-argument)
3992 (define-key map [kp-8] 'digit-argument)
3993 (define-key map [kp-9] 'digit-argument)
3994 (define-key map [kp-subtract] universal-argument-minus)
3995 map)
3996 "Keymap used while processing \\[universal-argument].")
3997
3998 (defun universal-argument--mode ()
3999 (prefix-command-update)
4000 (set-transient-map universal-argument-map nil))
4001
4002 (defun universal-argument ()
4003 "Begin a numeric argument for the following command.
4004 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4005 \\[universal-argument] following the digits or minus sign ends the argument.
4006 \\[universal-argument] without digits or minus sign provides 4 as argument.
4007 Repeating \\[universal-argument] without digits or minus sign
4008 multiplies the argument by 4 each time.
4009 For some commands, just \\[universal-argument] by itself serves as a flag
4010 which is different in effect from any particular numeric argument.
4011 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4012 (interactive)
4013 (prefix-command-preserve-state)
4014 (setq prefix-arg (list 4))
4015 (universal-argument--mode))
4016
4017 (defun universal-argument-more (arg)
4018 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4019 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4020 (interactive "P")
4021 (prefix-command-preserve-state)
4022 (setq prefix-arg (if (consp arg)
4023 (list (* 4 (car arg)))
4024 (if (eq arg '-)
4025 (list -4)
4026 arg)))
4027 (when (consp prefix-arg) (universal-argument--mode)))
4028
4029 (defun negative-argument (arg)
4030 "Begin a negative numeric argument for the next command.
4031 \\[universal-argument] following digits or minus sign ends the argument."
4032 (interactive "P")
4033 (prefix-command-preserve-state)
4034 (setq prefix-arg (cond ((integerp arg) (- arg))
4035 ((eq arg '-) nil)
4036 (t '-)))
4037 (universal-argument--mode))
4038
4039 (defun digit-argument (arg)
4040 "Part of the numeric argument for the next command.
4041 \\[universal-argument] following digits or minus sign ends the argument."
4042 (interactive "P")
4043 (prefix-command-preserve-state)
4044 (let* ((char (if (integerp last-command-event)
4045 last-command-event
4046 (get last-command-event 'ascii-character)))
4047 (digit (- (logand char ?\177) ?0)))
4048 (setq prefix-arg (cond ((integerp arg)
4049 (+ (* arg 10)
4050 (if (< arg 0) (- digit) digit)))
4051 ((eq arg '-)
4052 ;; Treat -0 as just -, so that -01 will work.
4053 (if (zerop digit) '- (- digit)))
4054 (t
4055 digit))))
4056 (universal-argument--mode))
4057 \f
4058
4059 (defvar filter-buffer-substring-functions nil
4060 "This variable is a wrapper hook around `buffer-substring--filter'.")
4061 (make-obsolete-variable 'filter-buffer-substring-functions
4062 'filter-buffer-substring-function "24.4")
4063
4064 (defvar filter-buffer-substring-function #'buffer-substring--filter
4065 "Function to perform the filtering in `filter-buffer-substring'.
4066 The function is called with the same 3 arguments (BEG END DELETE)
4067 that `filter-buffer-substring' received. It should return the
4068 buffer substring between BEG and END, after filtering. If DELETE is
4069 non-nil, it should delete the text between BEG and END from the buffer.")
4070
4071 (defvar buffer-substring-filters nil
4072 "List of filter functions for `buffer-substring--filter'.
4073 Each function must accept a single argument, a string, and return a string.
4074 The buffer substring is passed to the first function in the list,
4075 and the return value of each function is passed to the next.
4076 As a special convention, point is set to the start of the buffer text
4077 being operated on (i.e., the first argument of `buffer-substring--filter')
4078 before these functions are called.")
4079 (make-obsolete-variable 'buffer-substring-filters
4080 'filter-buffer-substring-function "24.1")
4081
4082 (defun filter-buffer-substring (beg end &optional delete)
4083 "Return the buffer substring between BEG and END, after filtering.
4084 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4085
4086 This calls the function that `filter-buffer-substring-function' specifies
4087 \(passing the same three arguments that it received) to do the work,
4088 and returns whatever it does. The default function does no filtering,
4089 unless a hook has been set.
4090
4091 Use `filter-buffer-substring' instead of `buffer-substring',
4092 `buffer-substring-no-properties', or `delete-and-extract-region' when
4093 you want to allow filtering to take place. For example, major or minor
4094 modes can use `filter-buffer-substring-function' to extract characters
4095 that are special to a buffer, and should not be copied into other buffers."
4096 (funcall filter-buffer-substring-function beg end delete))
4097
4098 (defun buffer-substring--filter (beg end &optional delete)
4099 "Default function to use for `filter-buffer-substring-function'.
4100 Its arguments and return value are as specified for `filter-buffer-substring'.
4101 This respects the wrapper hook `filter-buffer-substring-functions',
4102 and the abnormal hook `buffer-substring-filters'.
4103 No filtering is done unless a hook says to."
4104 (subr--with-wrapper-hook-no-warnings
4105 filter-buffer-substring-functions (beg end delete)
4106 (cond
4107 ((or delete buffer-substring-filters)
4108 (save-excursion
4109 (goto-char beg)
4110 (let ((string (if delete (delete-and-extract-region beg end)
4111 (buffer-substring beg end))))
4112 (dolist (filter buffer-substring-filters)
4113 (setq string (funcall filter string)))
4114 string)))
4115 (t
4116 (buffer-substring beg end)))))
4117
4118
4119 ;;;; Window system cut and paste hooks.
4120
4121 (defvar interprogram-cut-function #'gui-select-text
4122 "Function to call to make a killed region available to other programs.
4123 Most window systems provide a facility for cutting and pasting
4124 text between different programs, such as the clipboard on X and
4125 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4126
4127 This variable holds a function that Emacs calls whenever text is
4128 put in the kill ring, to make the new kill available to other
4129 programs. The function takes one argument, TEXT, which is a
4130 string containing the text which should be made available.")
4131
4132 (defvar interprogram-paste-function #'gui-selection-value
4133 "Function to call to get text cut from other programs.
4134 Most window systems provide a facility for cutting and pasting
4135 text between different programs, such as the clipboard on X and
4136 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4137
4138 This variable holds a function that Emacs calls to obtain text
4139 that other programs have provided for pasting. The function is
4140 called with no arguments. If no other program has provided text
4141 to paste, the function should return nil (in which case the
4142 caller, usually `current-kill', should use the top of the Emacs
4143 kill ring). If another program has provided text to paste, the
4144 function should return that text as a string (in which case the
4145 caller should put this string in the kill ring as the latest
4146 kill).
4147
4148 The function may also return a list of strings if the window
4149 system supports multiple selections. The first string will be
4150 used as the pasted text, but the other will be placed in the kill
4151 ring for easy access via `yank-pop'.
4152
4153 Note that the function should return a string only if a program
4154 other than Emacs has provided a string for pasting; if Emacs
4155 provided the most recent string, the function should return nil.
4156 If it is difficult to tell whether Emacs or some other program
4157 provided the current string, it is probably good enough to return
4158 nil if the string is equal (according to `string=') to the last
4159 text Emacs provided.")
4160 \f
4161
4162
4163 ;;;; The kill ring data structure.
4164
4165 (defvar kill-ring nil
4166 "List of killed text sequences.
4167 Since the kill ring is supposed to interact nicely with cut-and-paste
4168 facilities offered by window systems, use of this variable should
4169 interact nicely with `interprogram-cut-function' and
4170 `interprogram-paste-function'. The functions `kill-new',
4171 `kill-append', and `current-kill' are supposed to implement this
4172 interaction; you may want to use them instead of manipulating the kill
4173 ring directly.")
4174
4175 (defcustom kill-ring-max 60
4176 "Maximum length of kill ring before oldest elements are thrown away."
4177 :type 'integer
4178 :group 'killing)
4179
4180 (defvar kill-ring-yank-pointer nil
4181 "The tail of the kill ring whose car is the last thing yanked.")
4182
4183 (defcustom save-interprogram-paste-before-kill nil
4184 "Save clipboard strings into kill ring before replacing them.
4185 When one selects something in another program to paste it into Emacs,
4186 but kills something in Emacs before actually pasting it,
4187 this selection is gone unless this variable is non-nil,
4188 in which case the other program's selection is saved in the `kill-ring'
4189 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4190 :type 'boolean
4191 :group 'killing
4192 :version "23.2")
4193
4194 (defcustom kill-do-not-save-duplicates nil
4195 "Do not add a new string to `kill-ring' if it duplicates the last one.
4196 The comparison is done using `equal-including-properties'."
4197 :type 'boolean
4198 :group 'killing
4199 :version "23.2")
4200
4201 (defun kill-new (string &optional replace)
4202 "Make STRING the latest kill in the kill ring.
4203 Set `kill-ring-yank-pointer' to point to it.
4204 If `interprogram-cut-function' is non-nil, apply it to STRING.
4205 Optional second argument REPLACE non-nil means that STRING will replace
4206 the front of the kill ring, rather than being added to the list.
4207
4208 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4209 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4210 STRING.
4211
4212 When the yank handler has a non-nil PARAM element, the original STRING
4213 argument is not used by `insert-for-yank'. However, since Lisp code
4214 may access and use elements from the kill ring directly, the STRING
4215 argument should still be a \"useful\" string for such uses."
4216 (unless (and kill-do-not-save-duplicates
4217 ;; Due to text properties such as 'yank-handler that
4218 ;; can alter the contents to yank, comparison using
4219 ;; `equal' is unsafe.
4220 (equal-including-properties string (car kill-ring)))
4221 (if (fboundp 'menu-bar-update-yank-menu)
4222 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4223 (when save-interprogram-paste-before-kill
4224 (let ((interprogram-paste (and interprogram-paste-function
4225 (funcall interprogram-paste-function))))
4226 (when interprogram-paste
4227 (dolist (s (if (listp interprogram-paste)
4228 (nreverse interprogram-paste)
4229 (list interprogram-paste)))
4230 (unless (and kill-do-not-save-duplicates
4231 (equal-including-properties s (car kill-ring)))
4232 (push s kill-ring))))))
4233 (unless (and kill-do-not-save-duplicates
4234 (equal-including-properties string (car kill-ring)))
4235 (if (and replace kill-ring)
4236 (setcar kill-ring string)
4237 (push string kill-ring)
4238 (if (> (length kill-ring) kill-ring-max)
4239 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4240 (setq kill-ring-yank-pointer kill-ring)
4241 (if interprogram-cut-function
4242 (funcall interprogram-cut-function string)))
4243
4244 ;; It has been argued that this should work similar to `self-insert-command'
4245 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4246 (defcustom kill-append-merge-undo nil
4247 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4248 :type 'boolean
4249 :group 'killing
4250 :version "25.1")
4251
4252 (defun kill-append (string before-p)
4253 "Append STRING to the end of the latest kill in the kill ring.
4254 If BEFORE-P is non-nil, prepend STRING to the kill.
4255 Also removes the last undo boundary in the current buffer,
4256 depending on `kill-append-merge-undo'.
4257 If `interprogram-cut-function' is set, pass the resulting kill to it."
4258 (let* ((cur (car kill-ring)))
4259 (kill-new (if before-p (concat string cur) (concat cur string))
4260 (or (= (length cur) 0)
4261 (equal nil (get-text-property 0 'yank-handler cur))))
4262 (when (and kill-append-merge-undo (not buffer-read-only))
4263 (let ((prev buffer-undo-list)
4264 (next (cdr buffer-undo-list)))
4265 ;; find the next undo boundary
4266 (while (car next)
4267 (pop next)
4268 (pop prev))
4269 ;; remove this undo boundary
4270 (when prev
4271 (setcdr prev (cdr next)))))))
4272
4273 (defcustom yank-pop-change-selection nil
4274 "Whether rotating the kill ring changes the window system selection.
4275 If non-nil, whenever the kill ring is rotated (usually via the
4276 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4277 to copy the new kill to the window system selection."
4278 :type 'boolean
4279 :group 'killing
4280 :version "23.1")
4281
4282 (defun current-kill (n &optional do-not-move)
4283 "Rotate the yanking point by N places, and then return that kill.
4284 If N is zero and `interprogram-paste-function' is set to a
4285 function that returns a string or a list of strings, and if that
4286 function doesn't return nil, then that string (or list) is added
4287 to the front of the kill ring and the string (or first string in
4288 the list) is returned as the latest kill.
4289
4290 If N is not zero, and if `yank-pop-change-selection' is
4291 non-nil, use `interprogram-cut-function' to transfer the
4292 kill at the new yank point into the window system selection.
4293
4294 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4295 move the yanking point; just return the Nth kill forward."
4296
4297 (let ((interprogram-paste (and (= n 0)
4298 interprogram-paste-function
4299 (funcall interprogram-paste-function))))
4300 (if interprogram-paste
4301 (progn
4302 ;; Disable the interprogram cut function when we add the new
4303 ;; text to the kill ring, so Emacs doesn't try to own the
4304 ;; selection, with identical text.
4305 (let ((interprogram-cut-function nil))
4306 (if (listp interprogram-paste)
4307 (mapc 'kill-new (nreverse interprogram-paste))
4308 (kill-new interprogram-paste)))
4309 (car kill-ring))
4310 (or kill-ring (error "Kill ring is empty"))
4311 (let ((ARGth-kill-element
4312 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4313 (length kill-ring))
4314 kill-ring)))
4315 (unless do-not-move
4316 (setq kill-ring-yank-pointer ARGth-kill-element)
4317 (when (and yank-pop-change-selection
4318 (> n 0)
4319 interprogram-cut-function)
4320 (funcall interprogram-cut-function (car ARGth-kill-element))))
4321 (car ARGth-kill-element)))))
4322
4323
4324
4325 ;;;; Commands for manipulating the kill ring.
4326
4327 (defcustom kill-read-only-ok nil
4328 "Non-nil means don't signal an error for killing read-only text."
4329 :type 'boolean
4330 :group 'killing)
4331
4332 (defun kill-region (beg end &optional region)
4333 "Kill (\"cut\") text between point and mark.
4334 This deletes the text from the buffer and saves it in the kill ring.
4335 The command \\[yank] can retrieve it from there.
4336 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4337
4338 If you want to append the killed region to the last killed text,
4339 use \\[append-next-kill] before \\[kill-region].
4340
4341 Any command that calls this function is a \"kill command\".
4342 If the previous command was also a kill command,
4343 the text killed this time appends to the text killed last time
4344 to make one entry in the kill ring.
4345
4346 The killed text is filtered by `filter-buffer-substring' before it is
4347 saved in the kill ring, so the actual saved text might be different
4348 from what was killed.
4349
4350 If the buffer is read-only, Emacs will beep and refrain from deleting
4351 the text, but put the text in the kill ring anyway. This means that
4352 you can use the killing commands to copy text from a read-only buffer.
4353
4354 Lisp programs should use this function for killing text.
4355 (To delete text, use `delete-region'.)
4356 Supply two arguments, character positions BEG and END indicating the
4357 stretch of text to be killed. If the optional argument REGION is
4358 non-nil, the function ignores BEG and END, and kills the current
4359 region instead."
4360 ;; Pass mark first, then point, because the order matters when
4361 ;; calling `kill-append'.
4362 (interactive (list (mark) (point) 'region))
4363 (unless (and beg end)
4364 (user-error "The mark is not set now, so there is no region"))
4365 (condition-case nil
4366 (let ((string (if region
4367 (funcall region-extract-function 'delete)
4368 (filter-buffer-substring beg end 'delete))))
4369 (when string ;STRING is nil if BEG = END
4370 ;; Add that string to the kill ring, one way or another.
4371 (if (eq last-command 'kill-region)
4372 (kill-append string (< end beg))
4373 (kill-new string)))
4374 (when (or string (eq last-command 'kill-region))
4375 (setq this-command 'kill-region))
4376 (setq deactivate-mark t)
4377 nil)
4378 ((buffer-read-only text-read-only)
4379 ;; The code above failed because the buffer, or some of the characters
4380 ;; in the region, are read-only.
4381 ;; We should beep, in case the user just isn't aware of this.
4382 ;; However, there's no harm in putting
4383 ;; the region's text in the kill ring, anyway.
4384 (copy-region-as-kill beg end region)
4385 ;; Set this-command now, so it will be set even if we get an error.
4386 (setq this-command 'kill-region)
4387 ;; This should barf, if appropriate, and give us the correct error.
4388 (if kill-read-only-ok
4389 (progn (message "Read only text copied to kill ring") nil)
4390 ;; Signal an error if the buffer is read-only.
4391 (barf-if-buffer-read-only)
4392 ;; If the buffer isn't read-only, the text is.
4393 (signal 'text-read-only (list (current-buffer)))))))
4394
4395 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4396 ;; to get two copies of the text when the user accidentally types M-w and
4397 ;; then corrects it with the intended C-w.
4398 (defun copy-region-as-kill (beg end &optional region)
4399 "Save the region as if killed, but don't kill it.
4400 In Transient Mark mode, deactivate the mark.
4401 If `interprogram-cut-function' is non-nil, also save the text for a window
4402 system cut and paste.
4403
4404 The copied text is filtered by `filter-buffer-substring' before it is
4405 saved in the kill ring, so the actual saved text might be different
4406 from what was in the buffer.
4407
4408 When called from Lisp, save in the kill ring the stretch of text
4409 between BEG and END, unless the optional argument REGION is
4410 non-nil, in which case ignore BEG and END, and save the current
4411 region instead.
4412
4413 This command's old key binding has been given to `kill-ring-save'."
4414 ;; Pass mark first, then point, because the order matters when
4415 ;; calling `kill-append'.
4416 (interactive (list (mark) (point)
4417 (prefix-numeric-value current-prefix-arg)))
4418 (let ((str (if region
4419 (funcall region-extract-function nil)
4420 (filter-buffer-substring beg end))))
4421 (if (eq last-command 'kill-region)
4422 (kill-append str (< end beg))
4423 (kill-new str)))
4424 (setq deactivate-mark t)
4425 nil)
4426
4427 (defun kill-ring-save (beg end &optional region)
4428 "Save the region as if killed, but don't kill it.
4429 In Transient Mark mode, deactivate the mark.
4430 If `interprogram-cut-function' is non-nil, also save the text for a window
4431 system cut and paste.
4432
4433 If you want to append the killed line to the last killed text,
4434 use \\[append-next-kill] before \\[kill-ring-save].
4435
4436 The copied text is filtered by `filter-buffer-substring' before it is
4437 saved in the kill ring, so the actual saved text might be different
4438 from what was in the buffer.
4439
4440 When called from Lisp, save in the kill ring the stretch of text
4441 between BEG and END, unless the optional argument REGION is
4442 non-nil, in which case ignore BEG and END, and save the current
4443 region instead.
4444
4445 This command is similar to `copy-region-as-kill', except that it gives
4446 visual feedback indicating the extent of the region being copied."
4447 ;; Pass mark first, then point, because the order matters when
4448 ;; calling `kill-append'.
4449 (interactive (list (mark) (point)
4450 (prefix-numeric-value current-prefix-arg)))
4451 (copy-region-as-kill beg end region)
4452 ;; This use of called-interactively-p is correct because the code it
4453 ;; controls just gives the user visual feedback.
4454 (if (called-interactively-p 'interactive)
4455 (indicate-copied-region)))
4456
4457 (defun indicate-copied-region (&optional message-len)
4458 "Indicate that the region text has been copied interactively.
4459 If the mark is visible in the selected window, blink the cursor
4460 between point and mark if there is currently no active region
4461 highlighting.
4462
4463 If the mark lies outside the selected window, display an
4464 informative message containing a sample of the copied text. The
4465 optional argument MESSAGE-LEN, if non-nil, specifies the length
4466 of this sample text; it defaults to 40."
4467 (let ((mark (mark t))
4468 (point (point))
4469 ;; Inhibit quitting so we can make a quit here
4470 ;; look like a C-g typed as a command.
4471 (inhibit-quit t))
4472 (if (pos-visible-in-window-p mark (selected-window))
4473 ;; Swap point-and-mark quickly so as to show the region that
4474 ;; was selected. Don't do it if the region is highlighted.
4475 (unless (and (region-active-p)
4476 (face-background 'region))
4477 ;; Swap point and mark.
4478 (set-marker (mark-marker) (point) (current-buffer))
4479 (goto-char mark)
4480 (sit-for blink-matching-delay)
4481 ;; Swap back.
4482 (set-marker (mark-marker) mark (current-buffer))
4483 (goto-char point)
4484 ;; If user quit, deactivate the mark
4485 ;; as C-g would as a command.
4486 (and quit-flag (region-active-p)
4487 (deactivate-mark)))
4488 (let ((len (min (abs (- mark point))
4489 (or message-len 40))))
4490 (if (< point mark)
4491 ;; Don't say "killed"; that is misleading.
4492 (message "Saved text until \"%s\""
4493 (buffer-substring-no-properties (- mark len) mark))
4494 (message "Saved text from \"%s\""
4495 (buffer-substring-no-properties mark (+ mark len))))))))
4496
4497 (defun append-next-kill (&optional interactive)
4498 "Cause following command, if it kills, to add to previous kill.
4499 If the next command kills forward from point, the kill is
4500 appended to the previous killed text. If the command kills
4501 backward, the kill is prepended. Kill commands that act on the
4502 region, such as `kill-region', are regarded as killing forward if
4503 point is after mark, and killing backward if point is before
4504 mark.
4505
4506 If the next command is not a kill command, `append-next-kill' has
4507 no effect.
4508
4509 The argument is used for internal purposes; do not supply one."
4510 (interactive "p")
4511 ;; We don't use (interactive-p), since that breaks kbd macros.
4512 (if interactive
4513 (progn
4514 (setq this-command 'kill-region)
4515 (message "If the next command is a kill, it will append"))
4516 (setq last-command 'kill-region)))
4517
4518 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4519 "Character set that matches bidirectional formatting control characters.")
4520
4521 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4522 "Character set that matches any character except bidirectional controls.")
4523
4524 (defun squeeze-bidi-context-1 (from to category replacement)
4525 "A subroutine of `squeeze-bidi-context'.
4526 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4527 (let ((pt (copy-marker from))
4528 (limit (copy-marker to))
4529 (old-pt 0)
4530 lim1)
4531 (setq lim1 limit)
4532 (goto-char pt)
4533 (while (< pt limit)
4534 (if (> pt old-pt)
4535 (move-marker lim1
4536 (save-excursion
4537 ;; L and R categories include embedding and
4538 ;; override controls, but we don't want to
4539 ;; replace them, because that might change
4540 ;; the visual order. Likewise with PDF and
4541 ;; isolate controls.
4542 (+ pt (skip-chars-forward
4543 bidi-directional-non-controls-chars
4544 limit)))))
4545 ;; Replace any run of non-RTL characters by a single LRM.
4546 (if (null (re-search-forward category lim1 t))
4547 ;; No more characters of CATEGORY, we are done.
4548 (setq pt limit)
4549 (replace-match replacement nil t)
4550 (move-marker pt (point)))
4551 (setq old-pt pt)
4552 ;; Skip directional controls, if any.
4553 (move-marker
4554 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4555
4556 (defun squeeze-bidi-context (from to)
4557 "Replace characters between FROM and TO while keeping bidi context.
4558
4559 This function replaces the region of text with as few characters
4560 as possible, while preserving the effect that region will have on
4561 bidirectional display before and after the region."
4562 (let ((start (set-marker (make-marker)
4563 (if (> from 0) from (+ (point-max) from))))
4564 (end (set-marker (make-marker) to))
4565 ;; This is for when they copy text with read-only text
4566 ;; properties.
4567 (inhibit-read-only t))
4568 (if (null (marker-position end))
4569 (setq end (point-max-marker)))
4570 ;; Replace each run of non-RTL characters with a single LRM.
4571 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4572 ;; Replace each run of non-LTR characters with a single RLM. Note
4573 ;; that the \cR category includes both the Arabic Letter (AL) and
4574 ;; R characters; here we ignore the distinction between them,
4575 ;; because that distinction only affects Arabic Number (AN)
4576 ;; characters, which are weak and don't affect the reordering.
4577 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4578
4579 (defun line-substring-with-bidi-context (start end &optional no-properties)
4580 "Return buffer text between START and END with its bidi context.
4581
4582 START and END are assumed to belong to the same physical line
4583 of buffer text. This function prepends and appends to the text
4584 between START and END bidi control characters that preserve the
4585 visual order of that text when it is inserted at some other place."
4586 (if (or (< start (point-min))
4587 (> end (point-max)))
4588 (signal 'args-out-of-range (list (current-buffer) start end)))
4589 (let ((buf (current-buffer))
4590 substr para-dir from to)
4591 (save-excursion
4592 (goto-char start)
4593 (setq para-dir (current-bidi-paragraph-direction))
4594 (setq from (line-beginning-position)
4595 to (line-end-position))
4596 (goto-char from)
4597 ;; If we don't have any mixed directional characters in the
4598 ;; entire line, we can just copy the substring without adding
4599 ;; any context.
4600 (if (or (looking-at-p "\\CR*$")
4601 (looking-at-p "\\CL*$"))
4602 (setq substr (if no-properties
4603 (buffer-substring-no-properties start end)
4604 (buffer-substring start end)))
4605 (setq substr
4606 (with-temp-buffer
4607 (if no-properties
4608 (insert-buffer-substring-no-properties buf from to)
4609 (insert-buffer-substring buf from to))
4610 (squeeze-bidi-context 1 (1+ (- start from)))
4611 (squeeze-bidi-context (- end to) nil)
4612 (buffer-substring 1 (point-max)))))
4613
4614 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4615 ;; (1) force the string to have the same base embedding
4616 ;; direction as the paragraph direction at the source, no matter
4617 ;; what is the paragraph direction at destination; and (2) avoid
4618 ;; affecting the visual order of the surrounding text at
4619 ;; destination if there are characters of different
4620 ;; directionality there.
4621 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4622 substr "\x2069"))))
4623
4624 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4625 "Return portion of current buffer between START and END with bidi context.
4626
4627 This function works similar to `buffer-substring', but it prepends and
4628 appends to the text bidi directional control characters necessary to
4629 preserve the visual appearance of the text if it is inserted at another
4630 place. This is useful when the buffer substring includes bidirectional
4631 text and control characters that cause non-trivial reordering on display.
4632 If copied verbatim, such text can have a very different visual appearance,
4633 and can also change the visual appearance of the surrounding text at the
4634 destination of the copy.
4635
4636 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4637 the text properties."
4638 (let (line-end substr)
4639 (if (or (< start (point-min))
4640 (> end (point-max)))
4641 (signal 'args-out-of-range (list (current-buffer) start end)))
4642 (save-excursion
4643 (goto-char start)
4644 (setq line-end (min end (line-end-position)))
4645 (while (< start end)
4646 (setq substr
4647 (concat substr
4648 (if substr "\n" "")
4649 (line-substring-with-bidi-context start line-end
4650 no-properties)))
4651 (forward-line 1)
4652 (setq start (point))
4653 (setq line-end (min end (line-end-position))))
4654 substr)))
4655 \f
4656 ;; Yanking.
4657
4658 (defcustom yank-handled-properties
4659 '((font-lock-face . yank-handle-font-lock-face-property)
4660 (category . yank-handle-category-property))
4661 "List of special text property handling conditions for yanking.
4662 Each element should have the form (PROP . FUN), where PROP is a
4663 property symbol and FUN is a function. When the `yank' command
4664 inserts text into the buffer, it scans the inserted text for
4665 stretches of text that have `eq' values of the text property
4666 PROP; for each such stretch of text, FUN is called with three
4667 arguments: the property's value in that text, and the start and
4668 end positions of the text.
4669
4670 This is done prior to removing the properties specified by
4671 `yank-excluded-properties'."
4672 :group 'killing
4673 :type '(repeat (cons (symbol :tag "property symbol")
4674 function))
4675 :version "24.3")
4676
4677 ;; This is actually used in subr.el but defcustom does not work there.
4678 (defcustom yank-excluded-properties
4679 '(category field follow-link fontified font-lock-face help-echo
4680 intangible invisible keymap local-map mouse-face read-only
4681 yank-handler)
4682 "Text properties to discard when yanking.
4683 The value should be a list of text properties to discard or t,
4684 which means to discard all text properties.
4685
4686 See also `yank-handled-properties'."
4687 :type '(choice (const :tag "All" t) (repeat symbol))
4688 :group 'killing
4689 :version "24.3")
4690
4691 (defvar yank-window-start nil)
4692 (defvar yank-undo-function nil
4693 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4694 Function is called with two parameters, START and END corresponding to
4695 the value of the mark and point; it is guaranteed that START <= END.
4696 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4697
4698 (defun yank-pop (&optional arg)
4699 "Replace just-yanked stretch of killed text with a different stretch.
4700 This command is allowed only immediately after a `yank' or a `yank-pop'.
4701 At such a time, the region contains a stretch of reinserted
4702 previously-killed text. `yank-pop' deletes that text and inserts in its
4703 place a different stretch of killed text.
4704
4705 With no argument, the previous kill is inserted.
4706 With argument N, insert the Nth previous kill.
4707 If N is negative, this is a more recent kill.
4708
4709 The sequence of kills wraps around, so that after the oldest one
4710 comes the newest one.
4711
4712 When this command inserts killed text into the buffer, it honors
4713 `yank-excluded-properties' and `yank-handler' as described in the
4714 doc string for `insert-for-yank-1', which see."
4715 (interactive "*p")
4716 (if (not (eq last-command 'yank))
4717 (user-error "Previous command was not a yank"))
4718 (setq this-command 'yank)
4719 (unless arg (setq arg 1))
4720 (let ((inhibit-read-only t)
4721 (before (< (point) (mark t))))
4722 (if before
4723 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4724 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4725 (setq yank-undo-function nil)
4726 (set-marker (mark-marker) (point) (current-buffer))
4727 (insert-for-yank (current-kill arg))
4728 ;; Set the window start back where it was in the yank command,
4729 ;; if possible.
4730 (set-window-start (selected-window) yank-window-start t)
4731 (if before
4732 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4733 ;; It is cleaner to avoid activation, even though the command
4734 ;; loop would deactivate the mark because we inserted text.
4735 (goto-char (prog1 (mark t)
4736 (set-marker (mark-marker) (point) (current-buffer))))))
4737 nil)
4738
4739 (defun yank (&optional arg)
4740 "Reinsert (\"paste\") the last stretch of killed text.
4741 More precisely, reinsert the most recent kill, which is the
4742 stretch of killed text most recently killed OR yanked. Put point
4743 at the end, and set mark at the beginning without activating it.
4744 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4745 With argument N, reinsert the Nth most recent kill.
4746
4747 When this command inserts text into the buffer, it honors the
4748 `yank-handled-properties' and `yank-excluded-properties'
4749 variables, and the `yank-handler' text property. See
4750 `insert-for-yank-1' for details.
4751
4752 See also the command `yank-pop' (\\[yank-pop])."
4753 (interactive "*P")
4754 (setq yank-window-start (window-start))
4755 ;; If we don't get all the way thru, make last-command indicate that
4756 ;; for the following command.
4757 (setq this-command t)
4758 (push-mark (point))
4759 (insert-for-yank (current-kill (cond
4760 ((listp arg) 0)
4761 ((eq arg '-) -2)
4762 (t (1- arg)))))
4763 (if (consp arg)
4764 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4765 ;; It is cleaner to avoid activation, even though the command
4766 ;; loop would deactivate the mark because we inserted text.
4767 (goto-char (prog1 (mark t)
4768 (set-marker (mark-marker) (point) (current-buffer)))))
4769 ;; If we do get all the way thru, make this-command indicate that.
4770 (if (eq this-command t)
4771 (setq this-command 'yank))
4772 nil)
4773
4774 (defun rotate-yank-pointer (arg)
4775 "Rotate the yanking point in the kill ring.
4776 With ARG, rotate that many kills forward (or backward, if negative)."
4777 (interactive "p")
4778 (current-kill arg))
4779 \f
4780 ;; Some kill commands.
4781
4782 ;; Internal subroutine of delete-char
4783 (defun kill-forward-chars (arg)
4784 (if (listp arg) (setq arg (car arg)))
4785 (if (eq arg '-) (setq arg -1))
4786 (kill-region (point) (+ (point) arg)))
4787
4788 ;; Internal subroutine of backward-delete-char
4789 (defun kill-backward-chars (arg)
4790 (if (listp arg) (setq arg (car arg)))
4791 (if (eq arg '-) (setq arg -1))
4792 (kill-region (point) (- (point) arg)))
4793
4794 (defcustom backward-delete-char-untabify-method 'untabify
4795 "The method for untabifying when deleting backward.
4796 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4797 `hungry' -- delete all whitespace, both tabs and spaces;
4798 `all' -- delete all whitespace, including tabs, spaces and newlines;
4799 nil -- just delete one character."
4800 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4801 :version "20.3"
4802 :group 'killing)
4803
4804 (defun backward-delete-char-untabify (arg &optional killp)
4805 "Delete characters backward, changing tabs into spaces.
4806 The exact behavior depends on `backward-delete-char-untabify-method'.
4807 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4808 Interactively, ARG is the prefix arg (default 1)
4809 and KILLP is t if a prefix arg was specified."
4810 (interactive "*p\nP")
4811 (when (eq backward-delete-char-untabify-method 'untabify)
4812 (let ((count arg))
4813 (save-excursion
4814 (while (and (> count 0) (not (bobp)))
4815 (if (= (preceding-char) ?\t)
4816 (let ((col (current-column)))
4817 (forward-char -1)
4818 (setq col (- col (current-column)))
4819 (insert-char ?\s col)
4820 (delete-char 1)))
4821 (forward-char -1)
4822 (setq count (1- count))))))
4823 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4824 ((eq backward-delete-char-untabify-method 'all)
4825 " \t\n\r")))
4826 (n (if skip
4827 (let* ((oldpt (point))
4828 (wh (- oldpt (save-excursion
4829 (skip-chars-backward skip)
4830 (constrain-to-field nil oldpt)))))
4831 (+ arg (if (zerop wh) 0 (1- wh))))
4832 arg)))
4833 ;; Avoid warning about delete-backward-char
4834 (with-no-warnings (delete-backward-char n killp))))
4835
4836 (defun zap-to-char (arg char)
4837 "Kill up to and including ARGth occurrence of CHAR.
4838 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4839 Goes backward if ARG is negative; error if CHAR not found."
4840 (interactive (list (prefix-numeric-value current-prefix-arg)
4841 (read-char "Zap to char: " t)))
4842 ;; Avoid "obsolete" warnings for translation-table-for-input.
4843 (with-no-warnings
4844 (if (char-table-p translation-table-for-input)
4845 (setq char (or (aref translation-table-for-input char) char))))
4846 (kill-region (point) (progn
4847 (search-forward (char-to-string char) nil nil arg)
4848 (point))))
4849
4850 ;; kill-line and its subroutines.
4851
4852 (defcustom kill-whole-line nil
4853 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4854 :type 'boolean
4855 :group 'killing)
4856
4857 (defun kill-line (&optional arg)
4858 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4859 With prefix argument ARG, kill that many lines from point.
4860 Negative arguments kill lines backward.
4861 With zero argument, kills the text before point on the current line.
4862
4863 When calling from a program, nil means \"no arg\",
4864 a number counts as a prefix arg.
4865
4866 To kill a whole line, when point is not at the beginning, type \
4867 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4868
4869 If `show-trailing-whitespace' is non-nil, this command will just
4870 kill the rest of the current line, even if there are only
4871 nonblanks there.
4872
4873 If option `kill-whole-line' is non-nil, then this command kills the whole line
4874 including its terminating newline, when used at the beginning of a line
4875 with no argument. As a consequence, you can always kill a whole line
4876 by typing \\[move-beginning-of-line] \\[kill-line].
4877
4878 If you want to append the killed line to the last killed text,
4879 use \\[append-next-kill] before \\[kill-line].
4880
4881 If the buffer is read-only, Emacs will beep and refrain from deleting
4882 the line, but put the line in the kill ring anyway. This means that
4883 you can use this command to copy text from a read-only buffer.
4884 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4885 even beep.)"
4886 (interactive "P")
4887 (kill-region (point)
4888 ;; It is better to move point to the other end of the kill
4889 ;; before killing. That way, in a read-only buffer, point
4890 ;; moves across the text that is copied to the kill ring.
4891 ;; The choice has no effect on undo now that undo records
4892 ;; the value of point from before the command was run.
4893 (progn
4894 (if arg
4895 (forward-visible-line (prefix-numeric-value arg))
4896 (if (eobp)
4897 (signal 'end-of-buffer nil))
4898 (let ((end
4899 (save-excursion
4900 (end-of-visible-line) (point))))
4901 (if (or (save-excursion
4902 ;; If trailing whitespace is visible,
4903 ;; don't treat it as nothing.
4904 (unless show-trailing-whitespace
4905 (skip-chars-forward " \t" end))
4906 (= (point) end))
4907 (and kill-whole-line (bolp)))
4908 (forward-visible-line 1)
4909 (goto-char end))))
4910 (point))))
4911
4912 (defun kill-whole-line (&optional arg)
4913 "Kill current line.
4914 With prefix ARG, kill that many lines starting from the current line.
4915 If ARG is negative, kill backward. Also kill the preceding newline.
4916 \(This is meant to make \\[repeat] work well with negative arguments.)
4917 If ARG is zero, kill current line but exclude the trailing newline."
4918 (interactive "p")
4919 (or arg (setq arg 1))
4920 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4921 (signal 'end-of-buffer nil))
4922 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4923 (signal 'beginning-of-buffer nil))
4924 (unless (eq last-command 'kill-region)
4925 (kill-new "")
4926 (setq last-command 'kill-region))
4927 (cond ((zerop arg)
4928 ;; We need to kill in two steps, because the previous command
4929 ;; could have been a kill command, in which case the text
4930 ;; before point needs to be prepended to the current kill
4931 ;; ring entry and the text after point appended. Also, we
4932 ;; need to use save-excursion to avoid copying the same text
4933 ;; twice to the kill ring in read-only buffers.
4934 (save-excursion
4935 (kill-region (point) (progn (forward-visible-line 0) (point))))
4936 (kill-region (point) (progn (end-of-visible-line) (point))))
4937 ((< arg 0)
4938 (save-excursion
4939 (kill-region (point) (progn (end-of-visible-line) (point))))
4940 (kill-region (point)
4941 (progn (forward-visible-line (1+ arg))
4942 (unless (bobp) (backward-char))
4943 (point))))
4944 (t
4945 (save-excursion
4946 (kill-region (point) (progn (forward-visible-line 0) (point))))
4947 (kill-region (point)
4948 (progn (forward-visible-line arg) (point))))))
4949
4950 (defun forward-visible-line (arg)
4951 "Move forward by ARG lines, ignoring currently invisible newlines only.
4952 If ARG is negative, move backward -ARG lines.
4953 If ARG is zero, move to the beginning of the current line."
4954 (condition-case nil
4955 (if (> arg 0)
4956 (progn
4957 (while (> arg 0)
4958 (or (zerop (forward-line 1))
4959 (signal 'end-of-buffer nil))
4960 ;; If the newline we just skipped is invisible,
4961 ;; don't count it.
4962 (let ((prop
4963 (get-char-property (1- (point)) 'invisible)))
4964 (if (if (eq buffer-invisibility-spec t)
4965 prop
4966 (or (memq prop buffer-invisibility-spec)
4967 (assq prop buffer-invisibility-spec)))
4968 (setq arg (1+ arg))))
4969 (setq arg (1- arg)))
4970 ;; If invisible text follows, and it is a number of complete lines,
4971 ;; skip it.
4972 (let ((opoint (point)))
4973 (while (and (not (eobp))
4974 (let ((prop
4975 (get-char-property (point) 'invisible)))
4976 (if (eq buffer-invisibility-spec t)
4977 prop
4978 (or (memq prop buffer-invisibility-spec)
4979 (assq prop buffer-invisibility-spec)))))
4980 (goto-char
4981 (if (get-text-property (point) 'invisible)
4982 (or (next-single-property-change (point) 'invisible)
4983 (point-max))
4984 (next-overlay-change (point)))))
4985 (unless (bolp)
4986 (goto-char opoint))))
4987 (let ((first t))
4988 (while (or first (<= arg 0))
4989 (if first
4990 (beginning-of-line)
4991 (or (zerop (forward-line -1))
4992 (signal 'beginning-of-buffer nil)))
4993 ;; If the newline we just moved to is invisible,
4994 ;; don't count it.
4995 (unless (bobp)
4996 (let ((prop
4997 (get-char-property (1- (point)) 'invisible)))
4998 (unless (if (eq buffer-invisibility-spec t)
4999 prop
5000 (or (memq prop buffer-invisibility-spec)
5001 (assq prop buffer-invisibility-spec)))
5002 (setq arg (1+ arg)))))
5003 (setq first nil))
5004 ;; If invisible text follows, and it is a number of complete lines,
5005 ;; skip it.
5006 (let ((opoint (point)))
5007 (while (and (not (bobp))
5008 (let ((prop
5009 (get-char-property (1- (point)) 'invisible)))
5010 (if (eq buffer-invisibility-spec t)
5011 prop
5012 (or (memq prop buffer-invisibility-spec)
5013 (assq prop buffer-invisibility-spec)))))
5014 (goto-char
5015 (if (get-text-property (1- (point)) 'invisible)
5016 (or (previous-single-property-change (point) 'invisible)
5017 (point-min))
5018 (previous-overlay-change (point)))))
5019 (unless (bolp)
5020 (goto-char opoint)))))
5021 ((beginning-of-buffer end-of-buffer)
5022 nil)))
5023
5024 (defun end-of-visible-line ()
5025 "Move to end of current visible line."
5026 (end-of-line)
5027 ;; If the following character is currently invisible,
5028 ;; skip all characters with that same `invisible' property value,
5029 ;; then find the next newline.
5030 (while (and (not (eobp))
5031 (save-excursion
5032 (skip-chars-forward "^\n")
5033 (let ((prop
5034 (get-char-property (point) 'invisible)))
5035 (if (eq buffer-invisibility-spec t)
5036 prop
5037 (or (memq prop buffer-invisibility-spec)
5038 (assq prop buffer-invisibility-spec))))))
5039 (skip-chars-forward "^\n")
5040 (if (get-text-property (point) 'invisible)
5041 (goto-char (or (next-single-property-change (point) 'invisible)
5042 (point-max)))
5043 (goto-char (next-overlay-change (point))))
5044 (end-of-line)))
5045 \f
5046 (defun insert-buffer (buffer)
5047 "Insert after point the contents of BUFFER.
5048 Puts mark after the inserted text.
5049 BUFFER may be a buffer or a buffer name."
5050 (declare (interactive-only insert-buffer-substring))
5051 (interactive
5052 (list
5053 (progn
5054 (barf-if-buffer-read-only)
5055 (read-buffer "Insert buffer: "
5056 (if (eq (selected-window) (next-window))
5057 (other-buffer (current-buffer))
5058 (window-buffer (next-window)))
5059 t))))
5060 (push-mark
5061 (save-excursion
5062 (insert-buffer-substring (get-buffer buffer))
5063 (point)))
5064 nil)
5065
5066 (defun append-to-buffer (buffer start end)
5067 "Append to specified buffer the text of the region.
5068 It is inserted into that buffer before its point.
5069
5070 When calling from a program, give three arguments:
5071 BUFFER (or buffer name), START and END.
5072 START and END specify the portion of the current buffer to be copied."
5073 (interactive
5074 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5075 (region-beginning) (region-end)))
5076 (let* ((oldbuf (current-buffer))
5077 (append-to (get-buffer-create buffer))
5078 (windows (get-buffer-window-list append-to t t))
5079 point)
5080 (save-excursion
5081 (with-current-buffer append-to
5082 (setq point (point))
5083 (barf-if-buffer-read-only)
5084 (insert-buffer-substring oldbuf start end)
5085 (dolist (window windows)
5086 (when (= (window-point window) point)
5087 (set-window-point window (point))))))))
5088
5089 (defun prepend-to-buffer (buffer start end)
5090 "Prepend to specified buffer the text of the region.
5091 It is inserted into that buffer after its point.
5092
5093 When calling from a program, give three arguments:
5094 BUFFER (or buffer name), START and END.
5095 START and END specify the portion of the current buffer to be copied."
5096 (interactive "BPrepend to buffer: \nr")
5097 (let ((oldbuf (current-buffer)))
5098 (with-current-buffer (get-buffer-create buffer)
5099 (barf-if-buffer-read-only)
5100 (save-excursion
5101 (insert-buffer-substring oldbuf start end)))))
5102
5103 (defun copy-to-buffer (buffer start end)
5104 "Copy to specified buffer the text of the region.
5105 It is inserted into that buffer, replacing existing text there.
5106
5107 When calling from a program, give three arguments:
5108 BUFFER (or buffer name), START and END.
5109 START and END specify the portion of the current buffer to be copied."
5110 (interactive "BCopy to buffer: \nr")
5111 (let ((oldbuf (current-buffer)))
5112 (with-current-buffer (get-buffer-create buffer)
5113 (barf-if-buffer-read-only)
5114 (erase-buffer)
5115 (save-excursion
5116 (insert-buffer-substring oldbuf start end)))))
5117 \f
5118 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5119
5120 (defvar activate-mark-hook nil
5121 "Hook run when the mark becomes active.
5122 It is also run at the end of a command, if the mark is active and
5123 it is possible that the region may have changed.")
5124
5125 (defvar deactivate-mark-hook nil
5126 "Hook run when the mark becomes inactive.")
5127
5128 (defun mark (&optional force)
5129 "Return this buffer's mark value as integer, or nil if never set.
5130
5131 In Transient Mark mode, this function signals an error if
5132 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5133 or the argument FORCE is non-nil, it disregards whether the mark
5134 is active, and returns an integer or nil in the usual way.
5135
5136 If you are using this in an editing command, you are most likely making
5137 a mistake; see the documentation of `set-mark'."
5138 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5139 (marker-position (mark-marker))
5140 (signal 'mark-inactive nil)))
5141
5142 ;; Behind display-selections-p.
5143
5144 (defun deactivate-mark (&optional force)
5145 "Deactivate the mark.
5146 If Transient Mark mode is disabled, this function normally does
5147 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5148
5149 Deactivating the mark sets `mark-active' to nil, updates the
5150 primary selection according to `select-active-regions', and runs
5151 `deactivate-mark-hook'.
5152
5153 If Transient Mark mode was temporarily enabled, reset the value
5154 of the variable `transient-mark-mode'; if this causes Transient
5155 Mark mode to be disabled, don't change `mark-active' to nil or
5156 run `deactivate-mark-hook'."
5157 (when (or (region-active-p) force)
5158 (when (and (if (eq select-active-regions 'only)
5159 (eq (car-safe transient-mark-mode) 'only)
5160 select-active-regions)
5161 (region-active-p)
5162 (display-selections-p))
5163 ;; The var `saved-region-selection', if non-nil, is the text in
5164 ;; the region prior to the last command modifying the buffer.
5165 ;; Set the selection to that, or to the current region.
5166 (cond (saved-region-selection
5167 (if (gui-backend-selection-owner-p 'PRIMARY)
5168 (gui-set-selection 'PRIMARY saved-region-selection))
5169 (setq saved-region-selection nil))
5170 ;; If another program has acquired the selection, region
5171 ;; deactivation should not clobber it (Bug#11772).
5172 ((and (/= (region-beginning) (region-end))
5173 (or (gui-backend-selection-owner-p 'PRIMARY)
5174 (null (gui-backend-selection-exists-p 'PRIMARY))))
5175 (gui-set-selection 'PRIMARY
5176 (funcall region-extract-function nil)))))
5177 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5178 (cond
5179 ((eq (car-safe transient-mark-mode) 'only)
5180 (setq transient-mark-mode (cdr transient-mark-mode))
5181 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5182 (kill-local-variable 'transient-mark-mode)))
5183 ((eq transient-mark-mode 'lambda)
5184 (kill-local-variable 'transient-mark-mode)))
5185 (setq mark-active nil)
5186 (run-hooks 'deactivate-mark-hook)
5187 (redisplay--update-region-highlight (selected-window))))
5188
5189 (defun activate-mark (&optional no-tmm)
5190 "Activate the mark.
5191 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5192 (when (mark t)
5193 (unless (region-active-p)
5194 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5195 (setq mark-active t)
5196 (unless (or transient-mark-mode no-tmm)
5197 (setq-local transient-mark-mode 'lambda))
5198 (run-hooks 'activate-mark-hook))))
5199
5200 (defun set-mark (pos)
5201 "Set this buffer's mark to POS. Don't use this function!
5202 That is to say, don't use this function unless you want
5203 the user to see that the mark has moved, and you want the previous
5204 mark position to be lost.
5205
5206 Normally, when a new mark is set, the old one should go on the stack.
5207 This is why most applications should use `push-mark', not `set-mark'.
5208
5209 Novice Emacs Lisp programmers often try to use the mark for the wrong
5210 purposes. The mark saves a location for the user's convenience.
5211 Most editing commands should not alter the mark.
5212 To remember a location for internal use in the Lisp program,
5213 store it in a Lisp variable. Example:
5214
5215 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5216 (if pos
5217 (progn
5218 (set-marker (mark-marker) pos (current-buffer))
5219 (activate-mark 'no-tmm))
5220 ;; Normally we never clear mark-active except in Transient Mark mode.
5221 ;; But when we actually clear out the mark value too, we must
5222 ;; clear mark-active in any mode.
5223 (deactivate-mark t)
5224 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5225 ;; it should never be nil if the mark is nil.
5226 (setq mark-active nil)
5227 (set-marker (mark-marker) nil)))
5228
5229 (defun save-mark-and-excursion--save ()
5230 (cons
5231 (let ((mark (mark-marker)))
5232 (and (marker-position mark) (copy-marker mark)))
5233 mark-active))
5234
5235 (defun save-mark-and-excursion--restore (saved-mark-info)
5236 (let ((saved-mark (car saved-mark-info))
5237 (omark (marker-position (mark-marker)))
5238 (nmark nil)
5239 (saved-mark-active (cdr saved-mark-info)))
5240 ;; Mark marker
5241 (if (null saved-mark)
5242 (set-marker (mark-marker) nil)
5243 (setf nmark (marker-position saved-mark))
5244 (set-marker (mark-marker) nmark)
5245 (set-marker saved-mark nil))
5246 ;; Mark active
5247 (let ((cur-mark-active mark-active))
5248 (setq mark-active saved-mark-active)
5249 ;; If mark is active now, and either was not active or was at a
5250 ;; different place, run the activate hook.
5251 (if saved-mark-active
5252 (when (or (not cur-mark-active)
5253 (not (eq omark nmark)))
5254 (run-hooks 'activate-mark-hook))
5255 ;; If mark has ceased to be active, run deactivate hook.
5256 (when cur-mark-active
5257 (run-hooks 'deactivate-mark-hook))))))
5258
5259 (defmacro save-mark-and-excursion (&rest body)
5260 "Like `save-excursion', but also save and restore the mark state.
5261 This macro does what `save-excursion' did before Emacs 25.1."
5262 (declare (indent 0) (debug t))
5263 (let ((saved-marker-sym (make-symbol "saved-marker")))
5264 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5265 (unwind-protect
5266 (save-excursion ,@body)
5267 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5268
5269 (defcustom use-empty-active-region nil
5270 "Whether \"region-aware\" commands should act on empty regions.
5271 If nil, region-aware commands treat the empty region as inactive.
5272 If non-nil, region-aware commands treat the region as active as
5273 long as the mark is active, even if the region is empty.
5274
5275 Region-aware commands are those that act on the region if it is
5276 active and Transient Mark mode is enabled, and on the text near
5277 point otherwise."
5278 :type 'boolean
5279 :version "23.1"
5280 :group 'editing-basics)
5281
5282 (defun use-region-p ()
5283 "Return t if the region is active and it is appropriate to act on it.
5284 This is used by commands that act specially on the region under
5285 Transient Mark mode.
5286
5287 The return value is t if Transient Mark mode is enabled and the
5288 mark is active; furthermore, if `use-empty-active-region' is nil,
5289 the region must not be empty. Otherwise, the return value is nil.
5290
5291 For some commands, it may be appropriate to ignore the value of
5292 `use-empty-active-region'; in that case, use `region-active-p'."
5293 (and (region-active-p)
5294 (or use-empty-active-region (> (region-end) (region-beginning)))))
5295
5296 (defun region-active-p ()
5297 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5298
5299 Some commands act specially on the region when Transient Mark
5300 mode is enabled. Usually, such commands should use
5301 `use-region-p' instead of this function, because `use-region-p'
5302 also checks the value of `use-empty-active-region'."
5303 (and transient-mark-mode mark-active
5304 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5305 ;; without the mark being set (e.g. bug#17324). We really should fix
5306 ;; that problem, but in the mean time, let's make sure we don't say the
5307 ;; region is active when there's no mark.
5308 (progn (cl-assert (mark)) t)))
5309
5310 (defun region-noncontiguous-p ()
5311 "Return non-nil if the region contains several pieces.
5312 An example is a rectangular region handled as a list of
5313 separate contiguous regions for each line."
5314 (> (length (funcall region-extract-function 'bounds)) 1))
5315
5316 (defvar redisplay-unhighlight-region-function
5317 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5318
5319 (defvar redisplay-highlight-region-function
5320 (lambda (start end window rol)
5321 (if (not (overlayp rol))
5322 (let ((nrol (make-overlay start end)))
5323 (funcall redisplay-unhighlight-region-function rol)
5324 (overlay-put nrol 'window window)
5325 (overlay-put nrol 'face 'region)
5326 ;; Normal priority so that a large region doesn't hide all the
5327 ;; overlays within it, but high secondary priority so that if it
5328 ;; ends/starts in the middle of a small overlay, that small overlay
5329 ;; won't hide the region's boundaries.
5330 (overlay-put nrol 'priority '(nil . 100))
5331 nrol)
5332 (unless (and (eq (overlay-buffer rol) (current-buffer))
5333 (eq (overlay-start rol) start)
5334 (eq (overlay-end rol) end))
5335 (move-overlay rol start end (current-buffer)))
5336 rol)))
5337
5338 (defun redisplay--update-region-highlight (window)
5339 (let ((rol (window-parameter window 'internal-region-overlay)))
5340 (if (not (and (region-active-p)
5341 (or highlight-nonselected-windows
5342 (eq window (selected-window))
5343 (and (window-minibuffer-p)
5344 (eq window (minibuffer-selected-window))))))
5345 (funcall redisplay-unhighlight-region-function rol)
5346 (let* ((pt (window-point window))
5347 (mark (mark))
5348 (start (min pt mark))
5349 (end (max pt mark))
5350 (new
5351 (funcall redisplay-highlight-region-function
5352 start end window rol)))
5353 (unless (equal new rol)
5354 (set-window-parameter window 'internal-region-overlay
5355 new))))))
5356
5357 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5358 "Hook run just before redisplay.
5359 It is called in each window that is to be redisplayed. It takes one argument,
5360 which is the window that will be redisplayed. When run, the `current-buffer'
5361 is set to the buffer displayed in that window.")
5362
5363 (defun redisplay--pre-redisplay-functions (windows)
5364 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5365 (if (null windows)
5366 (with-current-buffer (window-buffer (selected-window))
5367 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5368 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5369 (with-current-buffer (window-buffer win)
5370 (run-hook-with-args 'pre-redisplay-functions win))))))
5371
5372 (add-function :before pre-redisplay-function
5373 #'redisplay--pre-redisplay-functions)
5374
5375
5376 (defvar-local mark-ring nil
5377 "The list of former marks of the current buffer, most recent first.")
5378 (put 'mark-ring 'permanent-local t)
5379
5380 (defcustom mark-ring-max 16
5381 "Maximum size of mark ring. Start discarding off end if gets this big."
5382 :type 'integer
5383 :group 'editing-basics)
5384
5385 (defvar global-mark-ring nil
5386 "The list of saved global marks, most recent first.")
5387
5388 (defcustom global-mark-ring-max 16
5389 "Maximum size of global mark ring. \
5390 Start discarding off end if gets this big."
5391 :type 'integer
5392 :group 'editing-basics)
5393
5394 (defun pop-to-mark-command ()
5395 "Jump to mark, and pop a new position for mark off the ring.
5396 \(Does not affect global mark ring)."
5397 (interactive)
5398 (if (null (mark t))
5399 (user-error "No mark set in this buffer")
5400 (if (= (point) (mark t))
5401 (message "Mark popped"))
5402 (goto-char (mark t))
5403 (pop-mark)))
5404
5405 (defun push-mark-command (arg &optional nomsg)
5406 "Set mark at where point is.
5407 If no prefix ARG and mark is already set there, just activate it.
5408 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5409 (interactive "P")
5410 (let ((mark (mark t)))
5411 (if (or arg (null mark) (/= mark (point)))
5412 (push-mark nil nomsg t)
5413 (activate-mark 'no-tmm)
5414 (unless nomsg
5415 (message "Mark activated")))))
5416
5417 (defcustom set-mark-command-repeat-pop nil
5418 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5419 That means that C-u \\[set-mark-command] \\[set-mark-command]
5420 will pop the mark twice, and
5421 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5422 will pop the mark three times.
5423
5424 A value of nil means \\[set-mark-command]'s behavior does not change
5425 after C-u \\[set-mark-command]."
5426 :type 'boolean
5427 :group 'editing-basics)
5428
5429 (defun set-mark-command (arg)
5430 "Set the mark where point is, or jump to the mark.
5431 Setting the mark also alters the region, which is the text
5432 between point and mark; this is the closest equivalent in
5433 Emacs to what some editors call the \"selection\".
5434
5435 With no prefix argument, set the mark at point, and push the
5436 old mark position on local mark ring. Also push the old mark on
5437 global mark ring, if the previous mark was set in another buffer.
5438
5439 When Transient Mark Mode is off, immediately repeating this
5440 command activates `transient-mark-mode' temporarily.
5441
5442 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5443 jump to the mark, and set the mark from
5444 position popped off the local mark ring (this does not affect the global
5445 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5446 mark ring (see `pop-global-mark').
5447
5448 If `set-mark-command-repeat-pop' is non-nil, repeating
5449 the \\[set-mark-command] command with no prefix argument pops the next position
5450 off the local (or global) mark ring and jumps there.
5451
5452 With \\[universal-argument] \\[universal-argument] as prefix
5453 argument, unconditionally set mark where point is, even if
5454 `set-mark-command-repeat-pop' is non-nil.
5455
5456 Novice Emacs Lisp programmers often try to use the mark for the wrong
5457 purposes. See the documentation of `set-mark' for more information."
5458 (interactive "P")
5459 (cond ((eq transient-mark-mode 'lambda)
5460 (kill-local-variable 'transient-mark-mode))
5461 ((eq (car-safe transient-mark-mode) 'only)
5462 (deactivate-mark)))
5463 (cond
5464 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5465 (push-mark-command nil))
5466 ((not (eq this-command 'set-mark-command))
5467 (if arg
5468 (pop-to-mark-command)
5469 (push-mark-command t)))
5470 ((and set-mark-command-repeat-pop
5471 (eq last-command 'pop-global-mark)
5472 (not arg))
5473 (setq this-command 'pop-global-mark)
5474 (pop-global-mark))
5475 ((or (and set-mark-command-repeat-pop
5476 (eq last-command 'pop-to-mark-command))
5477 arg)
5478 (setq this-command 'pop-to-mark-command)
5479 (pop-to-mark-command))
5480 ((eq last-command 'set-mark-command)
5481 (if (region-active-p)
5482 (progn
5483 (deactivate-mark)
5484 (message "Mark deactivated"))
5485 (activate-mark)
5486 (message "Mark activated")))
5487 (t
5488 (push-mark-command nil))))
5489
5490 (defun push-mark (&optional location nomsg activate)
5491 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5492 If the last global mark pushed was not in the current buffer,
5493 also push LOCATION on the global mark ring.
5494 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5495
5496 Novice Emacs Lisp programmers often try to use the mark for the wrong
5497 purposes. See the documentation of `set-mark' for more information.
5498
5499 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5500 (unless (null (mark t))
5501 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5502 (when (> (length mark-ring) mark-ring-max)
5503 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5504 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5505 (set-marker (mark-marker) (or location (point)) (current-buffer))
5506 ;; Now push the mark on the global mark ring.
5507 (if (and global-mark-ring
5508 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5509 ;; The last global mark pushed was in this same buffer.
5510 ;; Don't push another one.
5511 nil
5512 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5513 (when (> (length global-mark-ring) global-mark-ring-max)
5514 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5515 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5516 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5517 (message "Mark set"))
5518 (if (or activate (not transient-mark-mode))
5519 (set-mark (mark t)))
5520 nil)
5521
5522 (defun pop-mark ()
5523 "Pop off mark ring into the buffer's actual mark.
5524 Does not set point. Does nothing if mark ring is empty."
5525 (when mark-ring
5526 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5527 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5528 (move-marker (car mark-ring) nil)
5529 (if (null (mark t)) (ding))
5530 (setq mark-ring (cdr mark-ring)))
5531 (deactivate-mark))
5532
5533 (define-obsolete-function-alias
5534 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5535 (defun exchange-point-and-mark (&optional arg)
5536 "Put the mark where point is now, and point where the mark is now.
5537 This command works even when the mark is not active,
5538 and it reactivates the mark.
5539
5540 If Transient Mark mode is on, a prefix ARG deactivates the mark
5541 if it is active, and otherwise avoids reactivating it. If
5542 Transient Mark mode is off, a prefix ARG enables Transient Mark
5543 mode temporarily."
5544 (interactive "P")
5545 (let ((omark (mark t))
5546 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5547 (if (null omark)
5548 (user-error "No mark set in this buffer"))
5549 (set-mark (point))
5550 (goto-char omark)
5551 (cond (temp-highlight
5552 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5553 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5554 (not (or arg (region-active-p))))
5555 (deactivate-mark))
5556 (t (activate-mark)))
5557 nil))
5558
5559 (defcustom shift-select-mode t
5560 "When non-nil, shifted motion keys activate the mark momentarily.
5561
5562 While the mark is activated in this way, any shift-translated point
5563 motion key extends the region, and if Transient Mark mode was off, it
5564 is temporarily turned on. Furthermore, the mark will be deactivated
5565 by any subsequent point motion key that was not shift-translated, or
5566 by any action that normally deactivates the mark in Transient Mark mode.
5567
5568 See `this-command-keys-shift-translated' for the meaning of
5569 shift-translation."
5570 :type 'boolean
5571 :group 'editing-basics)
5572
5573 (defun handle-shift-selection ()
5574 "Activate/deactivate mark depending on invocation thru shift translation.
5575 This function is called by `call-interactively' when a command
5576 with a `^' character in its `interactive' spec is invoked, before
5577 running the command itself.
5578
5579 If `shift-select-mode' is enabled and the command was invoked
5580 through shift translation, set the mark and activate the region
5581 temporarily, unless it was already set in this way. See
5582 `this-command-keys-shift-translated' for the meaning of shift
5583 translation.
5584
5585 Otherwise, if the region has been activated temporarily,
5586 deactivate it, and restore the variable `transient-mark-mode' to
5587 its earlier value."
5588 (cond ((and shift-select-mode this-command-keys-shift-translated)
5589 (unless (and mark-active
5590 (eq (car-safe transient-mark-mode) 'only))
5591 (setq-local transient-mark-mode
5592 (cons 'only
5593 (unless (eq transient-mark-mode 'lambda)
5594 transient-mark-mode)))
5595 (push-mark nil nil t)))
5596 ((eq (car-safe transient-mark-mode) 'only)
5597 (setq transient-mark-mode (cdr transient-mark-mode))
5598 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5599 (kill-local-variable 'transient-mark-mode))
5600 (deactivate-mark))))
5601
5602 (define-minor-mode transient-mark-mode
5603 "Toggle Transient Mark mode.
5604 With a prefix argument ARG, enable Transient Mark mode if ARG is
5605 positive, and disable it otherwise. If called from Lisp, enable
5606 Transient Mark mode if ARG is omitted or nil.
5607
5608 Transient Mark mode is a global minor mode. When enabled, the
5609 region is highlighted with the `region' face whenever the mark
5610 is active. The mark is \"deactivated\" by changing the buffer,
5611 and after certain other operations that set the mark but whose
5612 main purpose is something else--for example, incremental search,
5613 \\[beginning-of-buffer], and \\[end-of-buffer].
5614
5615 You can also deactivate the mark by typing \\[keyboard-quit] or
5616 \\[keyboard-escape-quit].
5617
5618 Many commands change their behavior when Transient Mark mode is
5619 in effect and the mark is active, by acting on the region instead
5620 of their usual default part of the buffer's text. Examples of
5621 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5622 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5623 To see the documentation of commands which are sensitive to the
5624 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5625 or \"mark.*active\" at the prompt."
5626 :global t
5627 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5628 :variable (default-value 'transient-mark-mode))
5629
5630 (defvar widen-automatically t
5631 "Non-nil means it is ok for commands to call `widen' when they want to.
5632 Some commands will do this in order to go to positions outside
5633 the current accessible part of the buffer.
5634
5635 If `widen-automatically' is nil, these commands will do something else
5636 as a fallback, and won't change the buffer bounds.")
5637
5638 (defvar non-essential nil
5639 "Whether the currently executing code is performing an essential task.
5640 This variable should be non-nil only when running code which should not
5641 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5642 user for a password when we are simply scanning a set of files in the
5643 background or displaying possible completions before the user even asked
5644 for it.")
5645
5646 (defun pop-global-mark ()
5647 "Pop off global mark ring and jump to the top location."
5648 (interactive)
5649 ;; Pop entries which refer to non-existent buffers.
5650 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5651 (setq global-mark-ring (cdr global-mark-ring)))
5652 (or global-mark-ring
5653 (error "No global mark set"))
5654 (let* ((marker (car global-mark-ring))
5655 (buffer (marker-buffer marker))
5656 (position (marker-position marker)))
5657 (setq global-mark-ring (nconc (cdr global-mark-ring)
5658 (list (car global-mark-ring))))
5659 (set-buffer buffer)
5660 (or (and (>= position (point-min))
5661 (<= position (point-max)))
5662 (if widen-automatically
5663 (widen)
5664 (error "Global mark position is outside accessible part of buffer")))
5665 (goto-char position)
5666 (switch-to-buffer buffer)))
5667 \f
5668 (defcustom next-line-add-newlines nil
5669 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5670 :type 'boolean
5671 :version "21.1"
5672 :group 'editing-basics)
5673
5674 (defun next-line (&optional arg try-vscroll)
5675 "Move cursor vertically down ARG lines.
5676 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5677 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5678 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5679 function will not vscroll.
5680
5681 ARG defaults to 1.
5682
5683 If there is no character in the target line exactly under the current column,
5684 the cursor is positioned after the character in that line which spans this
5685 column, or at the end of the line if it is not long enough.
5686 If there is no line in the buffer after this one, behavior depends on the
5687 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5688 to create a line, and moves the cursor to that line. Otherwise it moves the
5689 cursor to the end of the buffer.
5690
5691 If the variable `line-move-visual' is non-nil, this command moves
5692 by display lines. Otherwise, it moves by buffer lines, without
5693 taking variable-width characters or continued lines into account.
5694
5695 The command \\[set-goal-column] can be used to create
5696 a semipermanent goal column for this command.
5697 Then instead of trying to move exactly vertically (or as close as possible),
5698 this command moves to the specified goal column (or as close as possible).
5699 The goal column is stored in the variable `goal-column', which is nil
5700 when there is no goal column. Note that setting `goal-column'
5701 overrides `line-move-visual' and causes this command to move by buffer
5702 lines rather than by display lines."
5703 (declare (interactive-only forward-line))
5704 (interactive "^p\np")
5705 (or arg (setq arg 1))
5706 (if (and next-line-add-newlines (= arg 1))
5707 (if (save-excursion (end-of-line) (eobp))
5708 ;; When adding a newline, don't expand an abbrev.
5709 (let ((abbrev-mode nil))
5710 (end-of-line)
5711 (insert (if use-hard-newlines hard-newline "\n")))
5712 (line-move arg nil nil try-vscroll))
5713 (if (called-interactively-p 'interactive)
5714 (condition-case err
5715 (line-move arg nil nil try-vscroll)
5716 ((beginning-of-buffer end-of-buffer)
5717 (signal (car err) (cdr err))))
5718 (line-move arg nil nil try-vscroll)))
5719 nil)
5720
5721 (defun previous-line (&optional arg try-vscroll)
5722 "Move cursor vertically up ARG lines.
5723 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5724 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5725 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5726 function will not vscroll.
5727
5728 ARG defaults to 1.
5729
5730 If there is no character in the target line exactly over the current column,
5731 the cursor is positioned after the character in that line which spans this
5732 column, or at the end of the line if it is not long enough.
5733
5734 If the variable `line-move-visual' is non-nil, this command moves
5735 by display lines. Otherwise, it moves by buffer lines, without
5736 taking variable-width characters or continued lines into account.
5737
5738 The command \\[set-goal-column] can be used to create
5739 a semipermanent goal column for this command.
5740 Then instead of trying to move exactly vertically (or as close as possible),
5741 this command moves to the specified goal column (or as close as possible).
5742 The goal column is stored in the variable `goal-column', which is nil
5743 when there is no goal column. Note that setting `goal-column'
5744 overrides `line-move-visual' and causes this command to move by buffer
5745 lines rather than by display lines."
5746 (declare (interactive-only
5747 "use `forward-line' with negative argument instead."))
5748 (interactive "^p\np")
5749 (or arg (setq arg 1))
5750 (if (called-interactively-p 'interactive)
5751 (condition-case err
5752 (line-move (- arg) nil nil try-vscroll)
5753 ((beginning-of-buffer end-of-buffer)
5754 (signal (car err) (cdr err))))
5755 (line-move (- arg) nil nil try-vscroll))
5756 nil)
5757
5758 (defcustom track-eol nil
5759 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5760 This means moving to the end of each line moved onto.
5761 The beginning of a blank line does not count as the end of a line.
5762 This has no effect when the variable `line-move-visual' is non-nil."
5763 :type 'boolean
5764 :group 'editing-basics)
5765
5766 (defcustom goal-column nil
5767 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5768 A non-nil setting overrides the variable `line-move-visual', which see."
5769 :type '(choice integer
5770 (const :tag "None" nil))
5771 :group 'editing-basics)
5772 (make-variable-buffer-local 'goal-column)
5773
5774 (defvar temporary-goal-column 0
5775 "Current goal column for vertical motion.
5776 It is the column where point was at the start of the current run
5777 of vertical motion commands.
5778
5779 When moving by visual lines via the function `line-move-visual', it is a cons
5780 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5781 divided by the default column width, and HSCROLL is the number of
5782 columns by which window is scrolled from left margin.
5783
5784 When the `track-eol' feature is doing its job, the value is
5785 `most-positive-fixnum'.")
5786
5787 (defcustom line-move-ignore-invisible t
5788 "Non-nil means commands that move by lines ignore invisible newlines.
5789 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5790 as if newlines that are invisible didn't exist, and count
5791 only visible newlines. Thus, moving across across 2 newlines
5792 one of which is invisible will be counted as a one-line move.
5793 Also, a non-nil value causes invisible text to be ignored when
5794 counting columns for the purposes of keeping point in the same
5795 column by \\[next-line] and \\[previous-line].
5796
5797 Outline mode sets this."
5798 :type 'boolean
5799 :group 'editing-basics)
5800
5801 (defcustom line-move-visual t
5802 "When non-nil, `line-move' moves point by visual lines.
5803 This movement is based on where the cursor is displayed on the
5804 screen, instead of relying on buffer contents alone. It takes
5805 into account variable-width characters and line continuation.
5806 If nil, `line-move' moves point by logical lines.
5807 A non-nil setting of `goal-column' overrides the value of this variable
5808 and forces movement by logical lines.
5809 A window that is horizontally scrolled also forces movement by logical
5810 lines."
5811 :type 'boolean
5812 :group 'editing-basics
5813 :version "23.1")
5814
5815 ;; Only used if display-graphic-p.
5816 (declare-function font-info "font.c" (name &optional frame))
5817
5818 (defun default-font-height ()
5819 "Return the height in pixels of the current buffer's default face font.
5820
5821 If the default font is remapped (see `face-remapping-alist'), the
5822 function returns the height of the remapped face."
5823 (let ((default-font (face-font 'default)))
5824 (cond
5825 ((and (display-multi-font-p)
5826 ;; Avoid calling font-info if the frame's default font was
5827 ;; not changed since the frame was created. That's because
5828 ;; font-info is expensive for some fonts, see bug #14838.
5829 (not (string= (frame-parameter nil 'font) default-font)))
5830 (aref (font-info default-font) 3))
5831 (t (frame-char-height)))))
5832
5833 (defun default-font-width ()
5834 "Return the width in pixels of the current buffer's default face font.
5835
5836 If the default font is remapped (see `face-remapping-alist'), the
5837 function returns the width of the remapped face."
5838 (let ((default-font (face-font 'default)))
5839 (cond
5840 ((and (display-multi-font-p)
5841 ;; Avoid calling font-info if the frame's default font was
5842 ;; not changed since the frame was created. That's because
5843 ;; font-info is expensive for some fonts, see bug #14838.
5844 (not (string= (frame-parameter nil 'font) default-font)))
5845 (let* ((info (font-info (face-font 'default)))
5846 (width (aref info 11)))
5847 (if (> width 0)
5848 width
5849 (aref info 10))))
5850 (t (frame-char-width)))))
5851
5852 (defun default-line-height ()
5853 "Return the pixel height of current buffer's default-face text line.
5854
5855 The value includes `line-spacing', if any, defined for the buffer
5856 or the frame."
5857 (let ((dfh (default-font-height))
5858 (lsp (if (display-graphic-p)
5859 (or line-spacing
5860 (default-value 'line-spacing)
5861 (frame-parameter nil 'line-spacing)
5862 0)
5863 0)))
5864 (if (floatp lsp)
5865 (setq lsp (truncate (* (frame-char-height) lsp))))
5866 (+ dfh lsp)))
5867
5868 (defun window-screen-lines ()
5869 "Return the number of screen lines in the text area of the selected window.
5870
5871 This is different from `window-text-height' in that this function counts
5872 lines in units of the height of the font used by the default face displayed
5873 in the window, not in units of the frame's default font, and also accounts
5874 for `line-spacing', if any, defined for the window's buffer or frame.
5875
5876 The value is a floating-point number."
5877 (let ((edges (window-inside-pixel-edges))
5878 (dlh (default-line-height)))
5879 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5880
5881 ;; Returns non-nil if partial move was done.
5882 (defun line-move-partial (arg noerror &optional _to-end)
5883 (if (< arg 0)
5884 ;; Move backward (up).
5885 ;; If already vscrolled, reduce vscroll
5886 (let ((vs (window-vscroll nil t))
5887 (dlh (default-line-height)))
5888 (when (> vs dlh)
5889 (set-window-vscroll nil (- vs dlh) t)))
5890
5891 ;; Move forward (down).
5892 (let* ((lh (window-line-height -1))
5893 (rowh (car lh))
5894 (vpos (nth 1 lh))
5895 (ypos (nth 2 lh))
5896 (rbot (nth 3 lh))
5897 (this-lh (window-line-height))
5898 (this-height (car this-lh))
5899 (this-ypos (nth 2 this-lh))
5900 (dlh (default-line-height))
5901 (wslines (window-screen-lines))
5902 (edges (window-inside-pixel-edges))
5903 (winh (- (nth 3 edges) (nth 1 edges) 1))
5904 py vs last-line)
5905 (if (> (mod wslines 1.0) 0.0)
5906 (setq wslines (round (+ wslines 0.5))))
5907 (when (or (null lh)
5908 (>= rbot dlh)
5909 (<= ypos (- dlh))
5910 (null this-lh)
5911 (<= this-ypos (- dlh)))
5912 (unless lh
5913 (let ((wend (pos-visible-in-window-p t nil t)))
5914 (setq rbot (nth 3 wend)
5915 rowh (nth 4 wend)
5916 vpos (nth 5 wend))))
5917 (unless this-lh
5918 (let ((wstart (pos-visible-in-window-p nil nil t)))
5919 (setq this-ypos (nth 2 wstart)
5920 this-height (nth 4 wstart))))
5921 (setq py
5922 (or (nth 1 this-lh)
5923 (let ((ppos (posn-at-point))
5924 col-row)
5925 (setq col-row (posn-actual-col-row ppos))
5926 (if col-row
5927 (- (cdr col-row) (window-vscroll))
5928 (cdr (posn-col-row ppos))))))
5929 ;; VPOS > 0 means the last line is only partially visible.
5930 ;; But if the part that is visible is at least as tall as the
5931 ;; default font, that means the line is actually fully
5932 ;; readable, and something like line-spacing is hidden. So in
5933 ;; that case we accept the last line in the window as still
5934 ;; visible, and consider the margin as starting one line
5935 ;; later.
5936 (if (and vpos (> vpos 0))
5937 (if (and rowh
5938 (>= rowh (default-font-height))
5939 (< rowh dlh))
5940 (setq last-line (min (- wslines scroll-margin) vpos))
5941 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5942 (cond
5943 ;; If last line of window is fully visible, and vscrolling
5944 ;; more would make this line invisible, move forward.
5945 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5946 (null this-height)
5947 (<= this-height dlh))
5948 (or (null rbot) (= rbot 0)))
5949 nil)
5950 ;; If cursor is not in the bottom scroll margin, and the
5951 ;; current line is is not too tall, move forward.
5952 ((and (or (null this-height) (<= this-height winh))
5953 vpos
5954 (> vpos 0)
5955 (< py last-line))
5956 nil)
5957 ;; When already vscrolled, we vscroll some more if we can,
5958 ;; or clear vscroll and move forward at end of tall image.
5959 ((> vs 0)
5960 (when (or (and rbot (> rbot 0))
5961 (and this-height (> this-height dlh)))
5962 (set-window-vscroll nil (+ vs dlh) t)))
5963 ;; If cursor just entered the bottom scroll margin, move forward,
5964 ;; but also optionally vscroll one line so redisplay won't recenter.
5965 ((and vpos
5966 (> vpos 0)
5967 (= py last-line))
5968 ;; Don't vscroll if the partially-visible line at window
5969 ;; bottom is not too tall (a.k.a. "just one more text
5970 ;; line"): in that case, we do want redisplay to behave
5971 ;; normally, i.e. recenter or whatever.
5972 ;;
5973 ;; Note: ROWH + RBOT from the value returned by
5974 ;; pos-visible-in-window-p give the total height of the
5975 ;; partially-visible glyph row at the end of the window. As
5976 ;; we are dealing with floats, we disregard sub-pixel
5977 ;; discrepancies between that and DLH.
5978 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5979 (set-window-vscroll nil dlh t))
5980 (line-move-1 arg noerror)
5981 t)
5982 ;; If there are lines above the last line, scroll-up one line.
5983 ((and vpos (> vpos 0))
5984 (scroll-up 1)
5985 t)
5986 ;; Finally, start vscroll.
5987 (t
5988 (set-window-vscroll nil dlh t)))))))
5989
5990
5991 ;; This is like line-move-1 except that it also performs
5992 ;; vertical scrolling of tall images if appropriate.
5993 ;; That is not really a clean thing to do, since it mixes
5994 ;; scrolling with cursor motion. But so far we don't have
5995 ;; a cleaner solution to the problem of making C-n do something
5996 ;; useful given a tall image.
5997 (defun line-move (arg &optional noerror _to-end try-vscroll)
5998 "Move forward ARG lines.
5999 If NOERROR, don't signal an error if we can't move ARG lines.
6000 TO-END is unused.
6001 TRY-VSCROLL controls whether to vscroll tall lines: if either
6002 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6003 not vscroll."
6004 (if noninteractive
6005 (line-move-1 arg noerror)
6006 (unless (and auto-window-vscroll try-vscroll
6007 ;; Only vscroll for single line moves
6008 (= (abs arg) 1)
6009 ;; Under scroll-conservatively, the display engine
6010 ;; does this better.
6011 (zerop scroll-conservatively)
6012 ;; But don't vscroll in a keyboard macro.
6013 (not defining-kbd-macro)
6014 (not executing-kbd-macro)
6015 (line-move-partial arg noerror))
6016 (set-window-vscroll nil 0 t)
6017 (if (and line-move-visual
6018 ;; Display-based column are incompatible with goal-column.
6019 (not goal-column)
6020 ;; When the text in the window is scrolled to the left,
6021 ;; display-based motion doesn't make sense (because each
6022 ;; logical line occupies exactly one screen line).
6023 (not (> (window-hscroll) 0))
6024 ;; Likewise when the text _was_ scrolled to the left
6025 ;; when the current run of vertical motion commands
6026 ;; started.
6027 (not (and (memq last-command
6028 `(next-line previous-line ,this-command))
6029 auto-hscroll-mode
6030 (numberp temporary-goal-column)
6031 (>= temporary-goal-column
6032 (- (window-width) hscroll-margin)))))
6033 (prog1 (line-move-visual arg noerror)
6034 ;; If we moved into a tall line, set vscroll to make
6035 ;; scrolling through tall images more smooth.
6036 (let ((lh (line-pixel-height))
6037 (edges (window-inside-pixel-edges))
6038 (dlh (default-line-height))
6039 winh)
6040 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6041 (if (and (< arg 0)
6042 (< (point) (window-start))
6043 (> lh winh))
6044 (set-window-vscroll
6045 nil
6046 (- lh dlh) t))))
6047 (line-move-1 arg noerror)))))
6048
6049 ;; Display-based alternative to line-move-1.
6050 ;; Arg says how many lines to move. The value is t if we can move the
6051 ;; specified number of lines.
6052 (defun line-move-visual (arg &optional noerror)
6053 "Move ARG lines forward.
6054 If NOERROR, don't signal an error if we can't move that many lines."
6055 (let ((opoint (point))
6056 (hscroll (window-hscroll))
6057 target-hscroll)
6058 ;; Check if the previous command was a line-motion command, or if
6059 ;; we were called from some other command.
6060 (if (and (consp temporary-goal-column)
6061 (memq last-command `(next-line previous-line ,this-command)))
6062 ;; If so, there's no need to reset `temporary-goal-column',
6063 ;; but we may need to hscroll.
6064 (if (or (/= (cdr temporary-goal-column) hscroll)
6065 (> (cdr temporary-goal-column) 0))
6066 (setq target-hscroll (cdr temporary-goal-column)))
6067 ;; Otherwise, we should reset `temporary-goal-column'.
6068 (let ((posn (posn-at-point))
6069 x-pos)
6070 (cond
6071 ;; Handle the `overflow-newline-into-fringe' case:
6072 ((eq (nth 1 posn) 'right-fringe)
6073 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6074 ((car (posn-x-y posn))
6075 (setq x-pos (car (posn-x-y posn)))
6076 ;; In R2L lines, the X pixel coordinate is measured from the
6077 ;; left edge of the window, but columns are still counted
6078 ;; from the logical-order beginning of the line, i.e. from
6079 ;; the right edge in this case. We need to adjust for that.
6080 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6081 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6082 (setq temporary-goal-column
6083 (cons (/ (float x-pos)
6084 (frame-char-width))
6085 hscroll)))
6086 (executing-kbd-macro
6087 ;; When we move beyond the first/last character visible in
6088 ;; the window, posn-at-point will return nil, so we need to
6089 ;; approximate the goal column as below.
6090 (setq temporary-goal-column
6091 (mod (current-column) (window-text-width)))))))
6092 (if target-hscroll
6093 (set-window-hscroll (selected-window) target-hscroll))
6094 ;; vertical-motion can move more than it was asked to if it moves
6095 ;; across display strings with newlines. We don't want to ring
6096 ;; the bell and announce beginning/end of buffer in that case.
6097 (or (and (or (and (>= arg 0)
6098 (>= (vertical-motion
6099 (cons (or goal-column
6100 (if (consp temporary-goal-column)
6101 (car temporary-goal-column)
6102 temporary-goal-column))
6103 arg))
6104 arg))
6105 (and (< arg 0)
6106 (<= (vertical-motion
6107 (cons (or goal-column
6108 (if (consp temporary-goal-column)
6109 (car temporary-goal-column)
6110 temporary-goal-column))
6111 arg))
6112 arg)))
6113 (or (>= arg 0)
6114 (/= (point) opoint)
6115 ;; If the goal column lies on a display string,
6116 ;; `vertical-motion' advances the cursor to the end
6117 ;; of the string. For arg < 0, this can cause the
6118 ;; cursor to get stuck. (Bug#3020).
6119 (= (vertical-motion arg) arg)))
6120 (unless noerror
6121 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6122 nil)))))
6123
6124 ;; This is the guts of next-line and previous-line.
6125 ;; Arg says how many lines to move.
6126 ;; The value is t if we can move the specified number of lines.
6127 (defun line-move-1 (arg &optional noerror _to-end)
6128 ;; Don't run any point-motion hooks, and disregard intangibility,
6129 ;; for intermediate positions.
6130 (let ((inhibit-point-motion-hooks t)
6131 (opoint (point))
6132 (orig-arg arg))
6133 (if (consp temporary-goal-column)
6134 (setq temporary-goal-column (+ (car temporary-goal-column)
6135 (cdr temporary-goal-column))))
6136 (unwind-protect
6137 (progn
6138 (if (not (memq last-command '(next-line previous-line)))
6139 (setq temporary-goal-column
6140 (if (and track-eol (eolp)
6141 ;; Don't count beg of empty line as end of line
6142 ;; unless we just did explicit end-of-line.
6143 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6144 most-positive-fixnum
6145 (current-column))))
6146
6147 (if (not (or (integerp selective-display)
6148 line-move-ignore-invisible))
6149 ;; Use just newline characters.
6150 ;; Set ARG to 0 if we move as many lines as requested.
6151 (or (if (> arg 0)
6152 (progn (if (> arg 1) (forward-line (1- arg)))
6153 ;; This way of moving forward ARG lines
6154 ;; verifies that we have a newline after the last one.
6155 ;; It doesn't get confused by intangible text.
6156 (end-of-line)
6157 (if (zerop (forward-line 1))
6158 (setq arg 0)))
6159 (and (zerop (forward-line arg))
6160 (bolp)
6161 (setq arg 0)))
6162 (unless noerror
6163 (signal (if (< arg 0)
6164 'beginning-of-buffer
6165 'end-of-buffer)
6166 nil)))
6167 ;; Move by arg lines, but ignore invisible ones.
6168 (let (done)
6169 (while (and (> arg 0) (not done))
6170 ;; If the following character is currently invisible,
6171 ;; skip all characters with that same `invisible' property value.
6172 (while (and (not (eobp)) (invisible-p (point)))
6173 (goto-char (next-char-property-change (point))))
6174 ;; Move a line.
6175 ;; We don't use `end-of-line', since we want to escape
6176 ;; from field boundaries occurring exactly at point.
6177 (goto-char (constrain-to-field
6178 (let ((inhibit-field-text-motion t))
6179 (line-end-position))
6180 (point) t t
6181 'inhibit-line-move-field-capture))
6182 ;; If there's no invisibility here, move over the newline.
6183 (cond
6184 ((eobp)
6185 (if (not noerror)
6186 (signal 'end-of-buffer nil)
6187 (setq done t)))
6188 ((and (> arg 1) ;; Use vertical-motion for last move
6189 (not (integerp selective-display))
6190 (not (invisible-p (point))))
6191 ;; We avoid vertical-motion when possible
6192 ;; because that has to fontify.
6193 (forward-line 1))
6194 ;; Otherwise move a more sophisticated way.
6195 ((zerop (vertical-motion 1))
6196 (if (not noerror)
6197 (signal 'end-of-buffer nil)
6198 (setq done t))))
6199 (unless done
6200 (setq arg (1- arg))))
6201 ;; The logic of this is the same as the loop above,
6202 ;; it just goes in the other direction.
6203 (while (and (< arg 0) (not done))
6204 ;; For completely consistency with the forward-motion
6205 ;; case, we should call beginning-of-line here.
6206 ;; However, if point is inside a field and on a
6207 ;; continued line, the call to (vertical-motion -1)
6208 ;; below won't move us back far enough; then we return
6209 ;; to the same column in line-move-finish, and point
6210 ;; gets stuck -- cyd
6211 (forward-line 0)
6212 (cond
6213 ((bobp)
6214 (if (not noerror)
6215 (signal 'beginning-of-buffer nil)
6216 (setq done t)))
6217 ((and (< arg -1) ;; Use vertical-motion for last move
6218 (not (integerp selective-display))
6219 (not (invisible-p (1- (point)))))
6220 (forward-line -1))
6221 ((zerop (vertical-motion -1))
6222 (if (not noerror)
6223 (signal 'beginning-of-buffer nil)
6224 (setq done t))))
6225 (unless done
6226 (setq arg (1+ arg))
6227 (while (and ;; Don't move over previous invis lines
6228 ;; if our target is the middle of this line.
6229 (or (zerop (or goal-column temporary-goal-column))
6230 (< arg 0))
6231 (not (bobp)) (invisible-p (1- (point))))
6232 (goto-char (previous-char-property-change (point))))))))
6233 ;; This is the value the function returns.
6234 (= arg 0))
6235
6236 (cond ((> arg 0)
6237 ;; If we did not move down as far as desired, at least go
6238 ;; to end of line. Be sure to call point-entered and
6239 ;; point-left-hooks.
6240 (let* ((npoint (prog1 (line-end-position)
6241 (goto-char opoint)))
6242 (inhibit-point-motion-hooks nil))
6243 (goto-char npoint)))
6244 ((< arg 0)
6245 ;; If we did not move up as far as desired,
6246 ;; at least go to beginning of line.
6247 (let* ((npoint (prog1 (line-beginning-position)
6248 (goto-char opoint)))
6249 (inhibit-point-motion-hooks nil))
6250 (goto-char npoint)))
6251 (t
6252 (line-move-finish (or goal-column temporary-goal-column)
6253 opoint (> orig-arg 0)))))))
6254
6255 (defun line-move-finish (column opoint forward)
6256 (let ((repeat t))
6257 (while repeat
6258 ;; Set REPEAT to t to repeat the whole thing.
6259 (setq repeat nil)
6260
6261 (let (new
6262 (old (point))
6263 (line-beg (line-beginning-position))
6264 (line-end
6265 ;; Compute the end of the line
6266 ;; ignoring effectively invisible newlines.
6267 (save-excursion
6268 ;; Like end-of-line but ignores fields.
6269 (skip-chars-forward "^\n")
6270 (while (and (not (eobp)) (invisible-p (point)))
6271 (goto-char (next-char-property-change (point)))
6272 (skip-chars-forward "^\n"))
6273 (point))))
6274
6275 ;; Move to the desired column.
6276 (line-move-to-column (truncate column))
6277
6278 ;; Corner case: suppose we start out in a field boundary in
6279 ;; the middle of a continued line. When we get to
6280 ;; line-move-finish, point is at the start of a new *screen*
6281 ;; line but the same text line; then line-move-to-column would
6282 ;; move us backwards. Test using C-n with point on the "x" in
6283 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6284 (and forward
6285 (< (point) old)
6286 (goto-char old))
6287
6288 (setq new (point))
6289
6290 ;; Process intangibility within a line.
6291 ;; With inhibit-point-motion-hooks bound to nil, a call to
6292 ;; goto-char moves point past intangible text.
6293
6294 ;; However, inhibit-point-motion-hooks controls both the
6295 ;; intangibility and the point-entered/point-left hooks. The
6296 ;; following hack avoids calling the point-* hooks
6297 ;; unnecessarily. Note that we move *forward* past intangible
6298 ;; text when the initial and final points are the same.
6299 (goto-char new)
6300 (let ((inhibit-point-motion-hooks nil))
6301 (goto-char new)
6302
6303 ;; If intangibility moves us to a different (later) place
6304 ;; in the same line, use that as the destination.
6305 (if (<= (point) line-end)
6306 (setq new (point))
6307 ;; If that position is "too late",
6308 ;; try the previous allowable position.
6309 ;; See if it is ok.
6310 (backward-char)
6311 (if (if forward
6312 ;; If going forward, don't accept the previous
6313 ;; allowable position if it is before the target line.
6314 (< line-beg (point))
6315 ;; If going backward, don't accept the previous
6316 ;; allowable position if it is still after the target line.
6317 (<= (point) line-end))
6318 (setq new (point))
6319 ;; As a last resort, use the end of the line.
6320 (setq new line-end))))
6321
6322 ;; Now move to the updated destination, processing fields
6323 ;; as well as intangibility.
6324 (goto-char opoint)
6325 (let ((inhibit-point-motion-hooks nil))
6326 (goto-char
6327 ;; Ignore field boundaries if the initial and final
6328 ;; positions have the same `field' property, even if the
6329 ;; fields are non-contiguous. This seems to be "nicer"
6330 ;; behavior in many situations.
6331 (if (eq (get-char-property new 'field)
6332 (get-char-property opoint 'field))
6333 new
6334 (constrain-to-field new opoint t t
6335 'inhibit-line-move-field-capture))))
6336
6337 ;; If all this moved us to a different line,
6338 ;; retry everything within that new line.
6339 (when (or (< (point) line-beg) (> (point) line-end))
6340 ;; Repeat the intangibility and field processing.
6341 (setq repeat t))))))
6342
6343 (defun line-move-to-column (col)
6344 "Try to find column COL, considering invisibility.
6345 This function works only in certain cases,
6346 because what we really need is for `move-to-column'
6347 and `current-column' to be able to ignore invisible text."
6348 (if (zerop col)
6349 (beginning-of-line)
6350 (move-to-column col))
6351
6352 (when (and line-move-ignore-invisible
6353 (not (bolp)) (invisible-p (1- (point))))
6354 (let ((normal-location (point))
6355 (normal-column (current-column)))
6356 ;; If the following character is currently invisible,
6357 ;; skip all characters with that same `invisible' property value.
6358 (while (and (not (eobp))
6359 (invisible-p (point)))
6360 (goto-char (next-char-property-change (point))))
6361 ;; Have we advanced to a larger column position?
6362 (if (> (current-column) normal-column)
6363 ;; We have made some progress towards the desired column.
6364 ;; See if we can make any further progress.
6365 (line-move-to-column (+ (current-column) (- col normal-column)))
6366 ;; Otherwise, go to the place we originally found
6367 ;; and move back over invisible text.
6368 ;; that will get us to the same place on the screen
6369 ;; but with a more reasonable buffer position.
6370 (goto-char normal-location)
6371 (let ((line-beg
6372 ;; We want the real line beginning, so it's consistent
6373 ;; with bolp below, otherwise we might infloop.
6374 (let ((inhibit-field-text-motion t))
6375 (line-beginning-position))))
6376 (while (and (not (bolp)) (invisible-p (1- (point))))
6377 (goto-char (previous-char-property-change (point) line-beg))))))))
6378
6379 (defun move-end-of-line (arg)
6380 "Move point to end of current line as displayed.
6381 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6382 If point reaches the beginning or end of buffer, it stops there.
6383
6384 To ignore the effects of the `intangible' text or overlay
6385 property, bind `inhibit-point-motion-hooks' to t.
6386 If there is an image in the current line, this function
6387 disregards newlines that are part of the text on which the image
6388 rests."
6389 (interactive "^p")
6390 (or arg (setq arg 1))
6391 (let (done)
6392 (while (not done)
6393 (let ((newpos
6394 (save-excursion
6395 (let ((goal-column 0)
6396 (line-move-visual nil))
6397 (and (line-move arg t)
6398 ;; With bidi reordering, we may not be at bol,
6399 ;; so make sure we are.
6400 (skip-chars-backward "^\n")
6401 (not (bobp))
6402 (progn
6403 (while (and (not (bobp)) (invisible-p (1- (point))))
6404 (goto-char (previous-single-char-property-change
6405 (point) 'invisible)))
6406 (backward-char 1)))
6407 (point)))))
6408 (goto-char newpos)
6409 (if (and (> (point) newpos)
6410 (eq (preceding-char) ?\n))
6411 (backward-char 1)
6412 (if (and (> (point) newpos) (not (eobp))
6413 (not (eq (following-char) ?\n)))
6414 ;; If we skipped something intangible and now we're not
6415 ;; really at eol, keep going.
6416 (setq arg 1)
6417 (setq done t)))))))
6418
6419 (defun move-beginning-of-line (arg)
6420 "Move point to beginning of current line as displayed.
6421 \(If there's an image in the line, this disregards newlines
6422 which are part of the text that the image rests on.)
6423
6424 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6425 If point reaches the beginning or end of buffer, it stops there.
6426 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6427 (interactive "^p")
6428 (or arg (setq arg 1))
6429
6430 (let ((orig (point))
6431 first-vis first-vis-field-value)
6432
6433 ;; Move by lines, if ARG is not 1 (the default).
6434 (if (/= arg 1)
6435 (let ((line-move-visual nil))
6436 (line-move (1- arg) t)))
6437
6438 ;; Move to beginning-of-line, ignoring fields and invisible text.
6439 (skip-chars-backward "^\n")
6440 (while (and (not (bobp)) (invisible-p (1- (point))))
6441 (goto-char (previous-char-property-change (point)))
6442 (skip-chars-backward "^\n"))
6443
6444 ;; Now find first visible char in the line.
6445 (while (and (< (point) orig) (invisible-p (point)))
6446 (goto-char (next-char-property-change (point) orig)))
6447 (setq first-vis (point))
6448
6449 ;; See if fields would stop us from reaching FIRST-VIS.
6450 (setq first-vis-field-value
6451 (constrain-to-field first-vis orig (/= arg 1) t nil))
6452
6453 (goto-char (if (/= first-vis-field-value first-vis)
6454 ;; If yes, obey them.
6455 first-vis-field-value
6456 ;; Otherwise, move to START with attention to fields.
6457 ;; (It is possible that fields never matter in this case.)
6458 (constrain-to-field (point) orig
6459 (/= arg 1) t nil)))))
6460
6461
6462 ;; Many people have said they rarely use this feature, and often type
6463 ;; it by accident. Maybe it shouldn't even be on a key.
6464 (put 'set-goal-column 'disabled t)
6465
6466 (defun set-goal-column (arg)
6467 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6468 Those commands will move to this position in the line moved to
6469 rather than trying to keep the same horizontal position.
6470 With a non-nil argument ARG, clears out the goal column
6471 so that \\[next-line] and \\[previous-line] resume vertical motion.
6472 The goal column is stored in the variable `goal-column'.
6473 This is a buffer-local setting."
6474 (interactive "P")
6475 (if arg
6476 (progn
6477 (setq goal-column nil)
6478 (message "No goal column"))
6479 (setq goal-column (current-column))
6480 ;; The older method below can be erroneous if `set-goal-column' is bound
6481 ;; to a sequence containing %
6482 ;;(message (substitute-command-keys
6483 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6484 ;;goal-column)
6485 (message "%s"
6486 (concat
6487 (format "Goal column %d " goal-column)
6488 (substitute-command-keys
6489 "(use \\[set-goal-column] with an arg to unset it)")))
6490
6491 )
6492 nil)
6493 \f
6494 ;;; Editing based on visual lines, as opposed to logical lines.
6495
6496 (defun end-of-visual-line (&optional n)
6497 "Move point to end of current visual line.
6498 With argument N not nil or 1, move forward N - 1 visual lines first.
6499 If point reaches the beginning or end of buffer, it stops there.
6500 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6501 (interactive "^p")
6502 (or n (setq n 1))
6503 (if (/= n 1)
6504 (let ((line-move-visual t))
6505 (line-move (1- n) t)))
6506 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6507 ;; constrain to field boundaries, so we don't either.
6508 (vertical-motion (cons (window-width) 0)))
6509
6510 (defun beginning-of-visual-line (&optional n)
6511 "Move point to beginning of current visual line.
6512 With argument N not nil or 1, move forward N - 1 visual lines first.
6513 If point reaches the beginning or end of buffer, it stops there.
6514 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6515 (interactive "^p")
6516 (or n (setq n 1))
6517 (let ((opoint (point)))
6518 (if (/= n 1)
6519 (let ((line-move-visual t))
6520 (line-move (1- n) t)))
6521 (vertical-motion 0)
6522 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6523 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6524
6525 (defun kill-visual-line (&optional arg)
6526 "Kill the rest of the visual line.
6527 With prefix argument ARG, kill that many visual lines from point.
6528 If ARG is negative, kill visual lines backward.
6529 If ARG is zero, kill the text before point on the current visual
6530 line.
6531
6532 If you want to append the killed line to the last killed text,
6533 use \\[append-next-kill] before \\[kill-line].
6534
6535 If the buffer is read-only, Emacs will beep and refrain from deleting
6536 the line, but put the line in the kill ring anyway. This means that
6537 you can use this command to copy text from a read-only buffer.
6538 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6539 even beep.)"
6540 (interactive "P")
6541 ;; Like in `kill-line', it's better to move point to the other end
6542 ;; of the kill before killing.
6543 (let ((opoint (point))
6544 (kill-whole-line (and kill-whole-line (bolp))))
6545 (if arg
6546 (vertical-motion (prefix-numeric-value arg))
6547 (end-of-visual-line 1)
6548 (if (= (point) opoint)
6549 (vertical-motion 1)
6550 ;; Skip any trailing whitespace at the end of the visual line.
6551 ;; We used to do this only if `show-trailing-whitespace' is
6552 ;; nil, but that's wrong; the correct thing would be to check
6553 ;; whether the trailing whitespace is highlighted. But, it's
6554 ;; OK to just do this unconditionally.
6555 (skip-chars-forward " \t")))
6556 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6557 (1+ (point))
6558 (point)))))
6559
6560 (defun next-logical-line (&optional arg try-vscroll)
6561 "Move cursor vertically down ARG lines.
6562 This is identical to `next-line', except that it always moves
6563 by logical lines instead of visual lines, ignoring the value of
6564 the variable `line-move-visual'."
6565 (interactive "^p\np")
6566 (let ((line-move-visual nil))
6567 (with-no-warnings
6568 (next-line arg try-vscroll))))
6569
6570 (defun previous-logical-line (&optional arg try-vscroll)
6571 "Move cursor vertically up ARG lines.
6572 This is identical to `previous-line', except that it always moves
6573 by logical lines instead of visual lines, ignoring the value of
6574 the variable `line-move-visual'."
6575 (interactive "^p\np")
6576 (let ((line-move-visual nil))
6577 (with-no-warnings
6578 (previous-line arg try-vscroll))))
6579
6580 (defgroup visual-line nil
6581 "Editing based on visual lines."
6582 :group 'convenience
6583 :version "23.1")
6584
6585 (defvar visual-line-mode-map
6586 (let ((map (make-sparse-keymap)))
6587 (define-key map [remap kill-line] 'kill-visual-line)
6588 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6589 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6590 ;; These keybindings interfere with xterm function keys. Are
6591 ;; there any other suitable bindings?
6592 ;; (define-key map "\M-[" 'previous-logical-line)
6593 ;; (define-key map "\M-]" 'next-logical-line)
6594 map))
6595
6596 (defcustom visual-line-fringe-indicators '(nil nil)
6597 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6598 The value should be a list of the form (LEFT RIGHT), where LEFT
6599 and RIGHT are symbols representing the bitmaps to display, to
6600 indicate wrapped lines, in the left and right fringes respectively.
6601 See also `fringe-indicator-alist'.
6602 The default is not to display fringe indicators for wrapped lines.
6603 This variable does not affect fringe indicators displayed for
6604 other purposes."
6605 :type '(list (choice (const :tag "Hide left indicator" nil)
6606 (const :tag "Left curly arrow" left-curly-arrow)
6607 (symbol :tag "Other bitmap"))
6608 (choice (const :tag "Hide right indicator" nil)
6609 (const :tag "Right curly arrow" right-curly-arrow)
6610 (symbol :tag "Other bitmap")))
6611 :set (lambda (symbol value)
6612 (dolist (buf (buffer-list))
6613 (with-current-buffer buf
6614 (when (and (boundp 'visual-line-mode)
6615 (symbol-value 'visual-line-mode))
6616 (setq fringe-indicator-alist
6617 (cons (cons 'continuation value)
6618 (assq-delete-all
6619 'continuation
6620 (copy-tree fringe-indicator-alist)))))))
6621 (set-default symbol value)))
6622
6623 (defvar visual-line--saved-state nil)
6624
6625 (define-minor-mode visual-line-mode
6626 "Toggle visual line based editing (Visual Line mode).
6627 With a prefix argument ARG, enable Visual Line mode if ARG is
6628 positive, and disable it otherwise. If called from Lisp, enable
6629 the mode if ARG is omitted or nil.
6630
6631 When Visual Line mode is enabled, `word-wrap' is turned on in
6632 this buffer, and simple editing commands are redefined to act on
6633 visual lines, not logical lines. See Info node `Visual Line
6634 Mode' for details."
6635 :keymap visual-line-mode-map
6636 :group 'visual-line
6637 :lighter " Wrap"
6638 (if visual-line-mode
6639 (progn
6640 (set (make-local-variable 'visual-line--saved-state) nil)
6641 ;; Save the local values of some variables, to be restored if
6642 ;; visual-line-mode is turned off.
6643 (dolist (var '(line-move-visual truncate-lines
6644 truncate-partial-width-windows
6645 word-wrap fringe-indicator-alist))
6646 (if (local-variable-p var)
6647 (push (cons var (symbol-value var))
6648 visual-line--saved-state)))
6649 (set (make-local-variable 'line-move-visual) t)
6650 (set (make-local-variable 'truncate-partial-width-windows) nil)
6651 (setq truncate-lines nil
6652 word-wrap t
6653 fringe-indicator-alist
6654 (cons (cons 'continuation visual-line-fringe-indicators)
6655 fringe-indicator-alist)))
6656 (kill-local-variable 'line-move-visual)
6657 (kill-local-variable 'word-wrap)
6658 (kill-local-variable 'truncate-lines)
6659 (kill-local-variable 'truncate-partial-width-windows)
6660 (kill-local-variable 'fringe-indicator-alist)
6661 (dolist (saved visual-line--saved-state)
6662 (set (make-local-variable (car saved)) (cdr saved)))
6663 (kill-local-variable 'visual-line--saved-state)))
6664
6665 (defun turn-on-visual-line-mode ()
6666 (visual-line-mode 1))
6667
6668 (define-globalized-minor-mode global-visual-line-mode
6669 visual-line-mode turn-on-visual-line-mode)
6670
6671 \f
6672 (defun transpose-chars (arg)
6673 "Interchange characters around point, moving forward one character.
6674 With prefix arg ARG, effect is to take character before point
6675 and drag it forward past ARG other characters (backward if ARG negative).
6676 If no argument and at end of line, the previous two chars are exchanged."
6677 (interactive "*P")
6678 (when (and (null arg) (eolp) (not (bobp))
6679 (not (get-text-property (1- (point)) 'read-only)))
6680 (forward-char -1))
6681 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6682
6683 (defun transpose-words (arg)
6684 "Interchange words around point, leaving point at end of them.
6685 With prefix arg ARG, effect is to take word before or around point
6686 and drag it forward past ARG other words (backward if ARG negative).
6687 If ARG is zero, the words around or after point and around or after mark
6688 are interchanged."
6689 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6690 (interactive "*p")
6691 (transpose-subr 'forward-word arg))
6692
6693 (defun transpose-sexps (arg)
6694 "Like \\[transpose-words] but applies to sexps.
6695 Does not work on a sexp that point is in the middle of
6696 if it is a list or string."
6697 (interactive "*p")
6698 (transpose-subr
6699 (lambda (arg)
6700 ;; Here we should try to simulate the behavior of
6701 ;; (cons (progn (forward-sexp x) (point))
6702 ;; (progn (forward-sexp (- x)) (point)))
6703 ;; Except that we don't want to rely on the second forward-sexp
6704 ;; putting us back to where we want to be, since forward-sexp-function
6705 ;; might do funny things like infix-precedence.
6706 (if (if (> arg 0)
6707 (looking-at "\\sw\\|\\s_")
6708 (and (not (bobp))
6709 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6710 ;; Jumping over a symbol. We might be inside it, mind you.
6711 (progn (funcall (if (> arg 0)
6712 'skip-syntax-backward 'skip-syntax-forward)
6713 "w_")
6714 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6715 ;; Otherwise, we're between sexps. Take a step back before jumping
6716 ;; to make sure we'll obey the same precedence no matter which direction
6717 ;; we're going.
6718 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6719 (cons (save-excursion (forward-sexp arg) (point))
6720 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6721 (not (zerop (funcall (if (> arg 0)
6722 'skip-syntax-forward
6723 'skip-syntax-backward)
6724 ".")))))
6725 (point)))))
6726 arg 'special))
6727
6728 (defun transpose-lines (arg)
6729 "Exchange current line and previous line, leaving point after both.
6730 With argument ARG, takes previous line and moves it past ARG lines.
6731 With argument 0, interchanges line point is in with line mark is in."
6732 (interactive "*p")
6733 (transpose-subr (function
6734 (lambda (arg)
6735 (if (> arg 0)
6736 (progn
6737 ;; Move forward over ARG lines,
6738 ;; but create newlines if necessary.
6739 (setq arg (forward-line arg))
6740 (if (/= (preceding-char) ?\n)
6741 (setq arg (1+ arg)))
6742 (if (> arg 0)
6743 (newline arg)))
6744 (forward-line arg))))
6745 arg))
6746
6747 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6748 ;; which seems inconsistent with the ARG /= 0 case.
6749 ;; FIXME document SPECIAL.
6750 (defun transpose-subr (mover arg &optional special)
6751 "Subroutine to do the work of transposing objects.
6752 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6753 moves forward by units of the given object (e.g. forward-sentence,
6754 forward-paragraph). If ARG is zero, exchanges the current object
6755 with the one containing mark. If ARG is an integer, moves the
6756 current object past ARG following (if ARG is positive) or
6757 preceding (if ARG is negative) objects, leaving point after the
6758 current object."
6759 (let ((aux (if special mover
6760 (lambda (x)
6761 (cons (progn (funcall mover x) (point))
6762 (progn (funcall mover (- x)) (point))))))
6763 pos1 pos2)
6764 (cond
6765 ((= arg 0)
6766 (save-excursion
6767 (setq pos1 (funcall aux 1))
6768 (goto-char (or (mark) (error "No mark set in this buffer")))
6769 (setq pos2 (funcall aux 1))
6770 (transpose-subr-1 pos1 pos2))
6771 (exchange-point-and-mark))
6772 ((> arg 0)
6773 (setq pos1 (funcall aux -1))
6774 (setq pos2 (funcall aux arg))
6775 (transpose-subr-1 pos1 pos2)
6776 (goto-char (car pos2)))
6777 (t
6778 (setq pos1 (funcall aux -1))
6779 (goto-char (car pos1))
6780 (setq pos2 (funcall aux arg))
6781 (transpose-subr-1 pos1 pos2)
6782 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6783
6784 (defun transpose-subr-1 (pos1 pos2)
6785 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6786 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6787 (when (> (car pos1) (car pos2))
6788 (let ((swap pos1))
6789 (setq pos1 pos2 pos2 swap)))
6790 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6791 (atomic-change-group
6792 ;; This sequence of insertions attempts to preserve marker
6793 ;; positions at the start and end of the transposed objects.
6794 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6795 (len1 (- (cdr pos1) (car pos1)))
6796 (len2 (length word))
6797 (boundary (make-marker)))
6798 (set-marker boundary (car pos2))
6799 (goto-char (cdr pos1))
6800 (insert-before-markers word)
6801 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6802 (goto-char boundary)
6803 (insert word)
6804 (goto-char (+ boundary len1))
6805 (delete-region (point) (+ (point) len2))
6806 (set-marker boundary nil))))
6807 \f
6808 (defun backward-word (&optional arg)
6809 "Move backward until encountering the beginning of a word.
6810 With argument ARG, do this that many times.
6811 If ARG is omitted or nil, move point backward one word.
6812
6813 The word boundaries are normally determined by the buffer's syntax
6814 table, but `find-word-boundary-function-table', such as set up
6815 by `subword-mode', can change that. If a Lisp program needs to
6816 move by words determined strictly by the syntax table, it should
6817 use `backward-word-strictly' instead."
6818 (interactive "^p")
6819 (forward-word (- (or arg 1))))
6820
6821 (defun mark-word (&optional arg allow-extend)
6822 "Set mark ARG words away from point.
6823 The place mark goes is the same place \\[forward-word] would
6824 move to with the same argument.
6825 Interactively, if this command is repeated
6826 or (in Transient Mark mode) if the mark is active,
6827 it marks the next ARG words after the ones already marked."
6828 (interactive "P\np")
6829 (cond ((and allow-extend
6830 (or (and (eq last-command this-command) (mark t))
6831 (region-active-p)))
6832 (setq arg (if arg (prefix-numeric-value arg)
6833 (if (< (mark) (point)) -1 1)))
6834 (set-mark
6835 (save-excursion
6836 (goto-char (mark))
6837 (forward-word arg)
6838 (point))))
6839 (t
6840 (push-mark
6841 (save-excursion
6842 (forward-word (prefix-numeric-value arg))
6843 (point))
6844 nil t))))
6845
6846 (defun kill-word (arg)
6847 "Kill characters forward until encountering the end of a word.
6848 With argument ARG, do this that many times."
6849 (interactive "p")
6850 (kill-region (point) (progn (forward-word arg) (point))))
6851
6852 (defun backward-kill-word (arg)
6853 "Kill characters backward until encountering the beginning of a word.
6854 With argument ARG, do this that many times."
6855 (interactive "p")
6856 (kill-word (- arg)))
6857
6858 (defun current-word (&optional strict really-word)
6859 "Return the symbol or word that point is on (or a nearby one) as a string.
6860 The return value includes no text properties.
6861 If optional arg STRICT is non-nil, return nil unless point is within
6862 or adjacent to a symbol or word. In all cases the value can be nil
6863 if there is no word nearby.
6864 The function, belying its name, normally finds a symbol.
6865 If optional arg REALLY-WORD is non-nil, it finds just a word."
6866 (save-excursion
6867 (let* ((oldpoint (point)) (start (point)) (end (point))
6868 (syntaxes (if really-word "w" "w_"))
6869 (not-syntaxes (concat "^" syntaxes)))
6870 (skip-syntax-backward syntaxes) (setq start (point))
6871 (goto-char oldpoint)
6872 (skip-syntax-forward syntaxes) (setq end (point))
6873 (when (and (eq start oldpoint) (eq end oldpoint)
6874 ;; Point is neither within nor adjacent to a word.
6875 (not strict))
6876 ;; Look for preceding word in same line.
6877 (skip-syntax-backward not-syntaxes (line-beginning-position))
6878 (if (bolp)
6879 ;; No preceding word in same line.
6880 ;; Look for following word in same line.
6881 (progn
6882 (skip-syntax-forward not-syntaxes (line-end-position))
6883 (setq start (point))
6884 (skip-syntax-forward syntaxes)
6885 (setq end (point)))
6886 (setq end (point))
6887 (skip-syntax-backward syntaxes)
6888 (setq start (point))))
6889 ;; If we found something nonempty, return it as a string.
6890 (unless (= start end)
6891 (buffer-substring-no-properties start end)))))
6892 \f
6893 (defcustom fill-prefix nil
6894 "String for filling to insert at front of new line, or nil for none."
6895 :type '(choice (const :tag "None" nil)
6896 string)
6897 :group 'fill)
6898 (make-variable-buffer-local 'fill-prefix)
6899 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6900
6901 (defcustom auto-fill-inhibit-regexp nil
6902 "Regexp to match lines which should not be auto-filled."
6903 :type '(choice (const :tag "None" nil)
6904 regexp)
6905 :group 'fill)
6906
6907 (defun do-auto-fill ()
6908 "The default value for `normal-auto-fill-function'.
6909 This is the default auto-fill function, some major modes use a different one.
6910 Returns t if it really did any work."
6911 (let (fc justify give-up
6912 (fill-prefix fill-prefix))
6913 (if (or (not (setq justify (current-justification)))
6914 (null (setq fc (current-fill-column)))
6915 (and (eq justify 'left)
6916 (<= (current-column) fc))
6917 (and auto-fill-inhibit-regexp
6918 (save-excursion (beginning-of-line)
6919 (looking-at auto-fill-inhibit-regexp))))
6920 nil ;; Auto-filling not required
6921 (if (memq justify '(full center right))
6922 (save-excursion (unjustify-current-line)))
6923
6924 ;; Choose a fill-prefix automatically.
6925 (when (and adaptive-fill-mode
6926 (or (null fill-prefix) (string= fill-prefix "")))
6927 (let ((prefix
6928 (fill-context-prefix
6929 (save-excursion (fill-forward-paragraph -1) (point))
6930 (save-excursion (fill-forward-paragraph 1) (point)))))
6931 (and prefix (not (equal prefix ""))
6932 ;; Use auto-indentation rather than a guessed empty prefix.
6933 (not (and fill-indent-according-to-mode
6934 (string-match "\\`[ \t]*\\'" prefix)))
6935 (setq fill-prefix prefix))))
6936
6937 (while (and (not give-up) (> (current-column) fc))
6938 ;; Determine where to split the line.
6939 (let* (after-prefix
6940 (fill-point
6941 (save-excursion
6942 (beginning-of-line)
6943 (setq after-prefix (point))
6944 (and fill-prefix
6945 (looking-at (regexp-quote fill-prefix))
6946 (setq after-prefix (match-end 0)))
6947 (move-to-column (1+ fc))
6948 (fill-move-to-break-point after-prefix)
6949 (point))))
6950
6951 ;; See whether the place we found is any good.
6952 (if (save-excursion
6953 (goto-char fill-point)
6954 (or (bolp)
6955 ;; There is no use breaking at end of line.
6956 (save-excursion (skip-chars-forward " ") (eolp))
6957 ;; It is futile to split at the end of the prefix
6958 ;; since we would just insert the prefix again.
6959 (and after-prefix (<= (point) after-prefix))
6960 ;; Don't split right after a comment starter
6961 ;; since we would just make another comment starter.
6962 (and comment-start-skip
6963 (let ((limit (point)))
6964 (beginning-of-line)
6965 (and (re-search-forward comment-start-skip
6966 limit t)
6967 (eq (point) limit))))))
6968 ;; No good place to break => stop trying.
6969 (setq give-up t)
6970 ;; Ok, we have a useful place to break the line. Do it.
6971 (let ((prev-column (current-column)))
6972 ;; If point is at the fill-point, do not `save-excursion'.
6973 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6974 ;; point will end up before it rather than after it.
6975 (if (save-excursion
6976 (skip-chars-backward " \t")
6977 (= (point) fill-point))
6978 (default-indent-new-line t)
6979 (save-excursion
6980 (goto-char fill-point)
6981 (default-indent-new-line t)))
6982 ;; Now do justification, if required
6983 (if (not (eq justify 'left))
6984 (save-excursion
6985 (end-of-line 0)
6986 (justify-current-line justify nil t)))
6987 ;; If making the new line didn't reduce the hpos of
6988 ;; the end of the line, then give up now;
6989 ;; trying again will not help.
6990 (if (>= (current-column) prev-column)
6991 (setq give-up t))))))
6992 ;; Justify last line.
6993 (justify-current-line justify t t)
6994 t)))
6995
6996 (defvar comment-line-break-function 'comment-indent-new-line
6997 "Mode-specific function which line breaks and continues a comment.
6998 This function is called during auto-filling when a comment syntax
6999 is defined.
7000 The function should take a single optional argument, which is a flag
7001 indicating whether it should use soft newlines.")
7002
7003 (defun default-indent-new-line (&optional soft)
7004 "Break line at point and indent.
7005 If a comment syntax is defined, call `comment-indent-new-line'.
7006
7007 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7008 unless optional argument SOFT is non-nil."
7009 (interactive)
7010 (if comment-start
7011 (funcall comment-line-break-function soft)
7012 ;; Insert the newline before removing empty space so that markers
7013 ;; get preserved better.
7014 (if soft (insert-and-inherit ?\n) (newline 1))
7015 (save-excursion (forward-char -1) (delete-horizontal-space))
7016 (delete-horizontal-space)
7017
7018 (if (and fill-prefix (not adaptive-fill-mode))
7019 ;; Blindly trust a non-adaptive fill-prefix.
7020 (progn
7021 (indent-to-left-margin)
7022 (insert-before-markers-and-inherit fill-prefix))
7023
7024 (cond
7025 ;; If there's an adaptive prefix, use it unless we're inside
7026 ;; a comment and the prefix is not a comment starter.
7027 (fill-prefix
7028 (indent-to-left-margin)
7029 (insert-and-inherit fill-prefix))
7030 ;; If we're not inside a comment, just try to indent.
7031 (t (indent-according-to-mode))))))
7032
7033 (defvar normal-auto-fill-function 'do-auto-fill
7034 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7035 Some major modes set this.")
7036
7037 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7038 ;; `functions' and `hooks' are usually unsafe to set, but setting
7039 ;; auto-fill-function to nil in a file-local setting is safe and
7040 ;; can be useful to prevent auto-filling.
7041 (put 'auto-fill-function 'safe-local-variable 'null)
7042
7043 (define-minor-mode auto-fill-mode
7044 "Toggle automatic line breaking (Auto Fill mode).
7045 With a prefix argument ARG, enable Auto Fill mode if ARG is
7046 positive, and disable it otherwise. If called from Lisp, enable
7047 the mode if ARG is omitted or nil.
7048
7049 When Auto Fill mode is enabled, inserting a space at a column
7050 beyond `current-fill-column' automatically breaks the line at a
7051 previous space.
7052
7053 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7054 non-nil.
7055
7056 The value of `normal-auto-fill-function' specifies the function to use
7057 for `auto-fill-function' when turning Auto Fill mode on."
7058 :variable (auto-fill-function
7059 . (lambda (v) (setq auto-fill-function
7060 (if v normal-auto-fill-function)))))
7061
7062 ;; This holds a document string used to document auto-fill-mode.
7063 (defun auto-fill-function ()
7064 "Automatically break line at a previous space, in insertion of text."
7065 nil)
7066
7067 (defun turn-on-auto-fill ()
7068 "Unconditionally turn on Auto Fill mode."
7069 (auto-fill-mode 1))
7070
7071 (defun turn-off-auto-fill ()
7072 "Unconditionally turn off Auto Fill mode."
7073 (auto-fill-mode -1))
7074
7075 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7076
7077 (defun set-fill-column (arg)
7078 "Set `fill-column' to specified argument.
7079 Use \\[universal-argument] followed by a number to specify a column.
7080 Just \\[universal-argument] as argument means to use the current column."
7081 (interactive
7082 (list (or current-prefix-arg
7083 ;; We used to use current-column silently, but C-x f is too easily
7084 ;; typed as a typo for C-x C-f, so we turned it into an error and
7085 ;; now an interactive prompt.
7086 (read-number "Set fill-column to: " (current-column)))))
7087 (if (consp arg)
7088 (setq arg (current-column)))
7089 (if (not (integerp arg))
7090 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7091 (error "set-fill-column requires an explicit argument")
7092 (message "Fill column set to %d (was %d)" arg fill-column)
7093 (setq fill-column arg)))
7094 \f
7095 (defun set-selective-display (arg)
7096 "Set `selective-display' to ARG; clear it if no arg.
7097 When the value of `selective-display' is a number > 0,
7098 lines whose indentation is >= that value are not displayed.
7099 The variable `selective-display' has a separate value for each buffer."
7100 (interactive "P")
7101 (if (eq selective-display t)
7102 (error "selective-display already in use for marked lines"))
7103 (let ((current-vpos
7104 (save-restriction
7105 (narrow-to-region (point-min) (point))
7106 (goto-char (window-start))
7107 (vertical-motion (window-height)))))
7108 (setq selective-display
7109 (and arg (prefix-numeric-value arg)))
7110 (recenter current-vpos))
7111 (set-window-start (selected-window) (window-start))
7112 (princ "selective-display set to " t)
7113 (prin1 selective-display t)
7114 (princ "." t))
7115
7116 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7117
7118 (defun toggle-truncate-lines (&optional arg)
7119 "Toggle truncating of long lines for the current buffer.
7120 When truncating is off, long lines are folded.
7121 With prefix argument ARG, truncate long lines if ARG is positive,
7122 otherwise fold them. Note that in side-by-side windows, this
7123 command has no effect if `truncate-partial-width-windows' is
7124 non-nil."
7125 (interactive "P")
7126 (setq truncate-lines
7127 (if (null arg)
7128 (not truncate-lines)
7129 (> (prefix-numeric-value arg) 0)))
7130 (force-mode-line-update)
7131 (unless truncate-lines
7132 (let ((buffer (current-buffer)))
7133 (walk-windows (lambda (window)
7134 (if (eq buffer (window-buffer window))
7135 (set-window-hscroll window 0)))
7136 nil t)))
7137 (message "Truncate long lines %s"
7138 (if truncate-lines "enabled" "disabled")))
7139
7140 (defun toggle-word-wrap (&optional arg)
7141 "Toggle whether to use word-wrapping for continuation lines.
7142 With prefix argument ARG, wrap continuation lines at word boundaries
7143 if ARG is positive, otherwise wrap them at the right screen edge.
7144 This command toggles the value of `word-wrap'. It has no effect
7145 if long lines are truncated."
7146 (interactive "P")
7147 (setq word-wrap
7148 (if (null arg)
7149 (not word-wrap)
7150 (> (prefix-numeric-value arg) 0)))
7151 (force-mode-line-update)
7152 (message "Word wrapping %s"
7153 (if word-wrap "enabled" "disabled")))
7154
7155 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7156 "The string displayed in the mode line when in overwrite mode.")
7157 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7158 "The string displayed in the mode line when in binary overwrite mode.")
7159
7160 (define-minor-mode overwrite-mode
7161 "Toggle Overwrite mode.
7162 With a prefix argument ARG, enable Overwrite mode if ARG is
7163 positive, and disable it otherwise. If called from Lisp, enable
7164 the mode if ARG is omitted or nil.
7165
7166 When Overwrite mode is enabled, printing characters typed in
7167 replace existing text on a one-for-one basis, rather than pushing
7168 it to the right. At the end of a line, such characters extend
7169 the line. Before a tab, such characters insert until the tab is
7170 filled in. \\[quoted-insert] still inserts characters in
7171 overwrite mode; this is supposed to make it easier to insert
7172 characters when necessary."
7173 :variable (overwrite-mode
7174 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7175
7176 (define-minor-mode binary-overwrite-mode
7177 "Toggle Binary Overwrite mode.
7178 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7179 is positive, and disable it otherwise. If called from Lisp,
7180 enable the mode if ARG is omitted or nil.
7181
7182 When Binary Overwrite mode is enabled, printing characters typed
7183 in replace existing text. Newlines are not treated specially, so
7184 typing at the end of a line joins the line to the next, with the
7185 typed character between them. Typing before a tab character
7186 simply replaces the tab with the character typed.
7187 \\[quoted-insert] replaces the text at the cursor, just as
7188 ordinary typing characters do.
7189
7190 Note that Binary Overwrite mode is not its own minor mode; it is
7191 a specialization of overwrite mode, entered by setting the
7192 `overwrite-mode' variable to `overwrite-mode-binary'."
7193 :variable (overwrite-mode
7194 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7195
7196 (define-minor-mode line-number-mode
7197 "Toggle line number display in the mode line (Line Number mode).
7198 With a prefix argument ARG, enable Line Number mode if ARG is
7199 positive, and disable it otherwise. If called from Lisp, enable
7200 the mode if ARG is omitted or nil.
7201
7202 Line numbers do not appear for very large buffers and buffers
7203 with very long lines; see variables `line-number-display-limit'
7204 and `line-number-display-limit-width'."
7205 :init-value t :global t :group 'mode-line)
7206
7207 (define-minor-mode column-number-mode
7208 "Toggle column number display in the mode line (Column Number mode).
7209 With a prefix argument ARG, enable Column Number mode if ARG is
7210 positive, and disable it otherwise.
7211
7212 If called from Lisp, enable the mode if ARG is omitted or nil."
7213 :global t :group 'mode-line)
7214
7215 (define-minor-mode size-indication-mode
7216 "Toggle buffer size display in the mode line (Size Indication mode).
7217 With a prefix argument ARG, enable Size Indication mode if ARG is
7218 positive, and disable it otherwise.
7219
7220 If called from Lisp, enable the mode if ARG is omitted or nil."
7221 :global t :group 'mode-line)
7222
7223 (define-minor-mode auto-save-mode
7224 "Toggle auto-saving in the current buffer (Auto Save mode).
7225 With a prefix argument ARG, enable Auto Save mode if ARG is
7226 positive, and disable it otherwise.
7227
7228 If called from Lisp, enable the mode if ARG is omitted or nil."
7229 :variable ((and buffer-auto-save-file-name
7230 ;; If auto-save is off because buffer has shrunk,
7231 ;; then toggling should turn it on.
7232 (>= buffer-saved-size 0))
7233 . (lambda (val)
7234 (setq buffer-auto-save-file-name
7235 (cond
7236 ((null val) nil)
7237 ((and buffer-file-name auto-save-visited-file-name
7238 (not buffer-read-only))
7239 buffer-file-name)
7240 (t (make-auto-save-file-name))))))
7241 ;; If -1 was stored here, to temporarily turn off saving,
7242 ;; turn it back on.
7243 (and (< buffer-saved-size 0)
7244 (setq buffer-saved-size 0)))
7245 \f
7246 (defgroup paren-blinking nil
7247 "Blinking matching of parens and expressions."
7248 :prefix "blink-matching-"
7249 :group 'paren-matching)
7250
7251 (defcustom blink-matching-paren t
7252 "Non-nil means show matching open-paren when close-paren is inserted.
7253 If t, highlight the paren. If `jump', briefly move cursor to its
7254 position. If `jump-offscreen', move cursor there even if the
7255 position is off screen. With any other non-nil value, the
7256 off-screen position of the opening paren will be shown in the
7257 echo area."
7258 :type '(choice
7259 (const :tag "Disable" nil)
7260 (const :tag "Highlight" t)
7261 (const :tag "Move cursor" jump)
7262 (const :tag "Move cursor, even if off screen" jump-offscreen))
7263 :group 'paren-blinking)
7264
7265 (defcustom blink-matching-paren-on-screen t
7266 "Non-nil means show matching open-paren when it is on screen.
7267 If nil, don't show it (but the open-paren can still be shown
7268 in the echo area when it is off screen).
7269
7270 This variable has no effect if `blink-matching-paren' is nil.
7271 \(In that case, the open-paren is never shown.)
7272 It is also ignored if `show-paren-mode' is enabled."
7273 :type 'boolean
7274 :group 'paren-blinking)
7275
7276 (defcustom blink-matching-paren-distance (* 100 1024)
7277 "If non-nil, maximum distance to search backwards for matching open-paren.
7278 If nil, search stops at the beginning of the accessible portion of the buffer."
7279 :version "23.2" ; 25->100k
7280 :type '(choice (const nil) integer)
7281 :group 'paren-blinking)
7282
7283 (defcustom blink-matching-delay 1
7284 "Time in seconds to delay after showing a matching paren."
7285 :type 'number
7286 :group 'paren-blinking)
7287
7288 (defcustom blink-matching-paren-dont-ignore-comments nil
7289 "If nil, `blink-matching-paren' ignores comments.
7290 More precisely, when looking for the matching parenthesis,
7291 it skips the contents of comments that end before point."
7292 :type 'boolean
7293 :group 'paren-blinking)
7294
7295 (defun blink-matching-check-mismatch (start end)
7296 "Return whether or not START...END are matching parens.
7297 END is the current point and START is the blink position.
7298 START might be nil if no matching starter was found.
7299 Returns non-nil if we find there is a mismatch."
7300 (let* ((end-syntax (syntax-after (1- end)))
7301 (matching-paren (and (consp end-syntax)
7302 (eq (syntax-class end-syntax) 5)
7303 (cdr end-syntax))))
7304 ;; For self-matched chars like " and $, we can't know when they're
7305 ;; mismatched or unmatched, so we can only do it for parens.
7306 (when matching-paren
7307 (not (and start
7308 (or
7309 (eq (char-after start) matching-paren)
7310 ;; The cdr might hold a new paren-class info rather than
7311 ;; a matching-char info, in which case the two CDRs
7312 ;; should match.
7313 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7314
7315 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7316 "Function to check parentheses mismatches.
7317 The function takes two arguments (START and END) where START is the
7318 position just before the opening token and END is the position right after.
7319 START can be nil, if it was not found.
7320 The function should return non-nil if the two tokens do not match.")
7321
7322 (defvar blink-matching--overlay
7323 (let ((ol (make-overlay (point) (point) nil t)))
7324 (overlay-put ol 'face 'show-paren-match)
7325 (delete-overlay ol)
7326 ol)
7327 "Overlay used to highlight the matching paren.")
7328
7329 (defun blink-matching-open ()
7330 "Momentarily highlight the beginning of the sexp before point."
7331 (interactive)
7332 (when (and (not (bobp))
7333 blink-matching-paren)
7334 (let* ((oldpos (point))
7335 (message-log-max nil) ; Don't log messages about paren matching.
7336 (blinkpos
7337 (save-excursion
7338 (save-restriction
7339 (if blink-matching-paren-distance
7340 (narrow-to-region
7341 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7342 (- (point) blink-matching-paren-distance))
7343 oldpos))
7344 (let ((parse-sexp-ignore-comments
7345 (and parse-sexp-ignore-comments
7346 (not blink-matching-paren-dont-ignore-comments))))
7347 (condition-case ()
7348 (progn
7349 (syntax-propertize (point))
7350 (forward-sexp -1)
7351 ;; backward-sexp skips backward over prefix chars,
7352 ;; so move back to the matching paren.
7353 (while (and (< (point) (1- oldpos))
7354 (let ((code (syntax-after (point))))
7355 (or (eq (syntax-class code) 6)
7356 (eq (logand 1048576 (car code))
7357 1048576))))
7358 (forward-char 1))
7359 (point))
7360 (error nil))))))
7361 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7362 (cond
7363 (mismatch
7364 (if blinkpos
7365 (if (minibufferp)
7366 (minibuffer-message "Mismatched parentheses")
7367 (message "Mismatched parentheses"))
7368 (if (minibufferp)
7369 (minibuffer-message "No matching parenthesis found")
7370 (message "No matching parenthesis found"))))
7371 ((not blinkpos) nil)
7372 ((or
7373 (eq blink-matching-paren 'jump-offscreen)
7374 (pos-visible-in-window-p blinkpos))
7375 ;; Matching open within window, temporarily move to or highlight
7376 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7377 ;; is non-nil.
7378 (and blink-matching-paren-on-screen
7379 (not show-paren-mode)
7380 (if (memq blink-matching-paren '(jump jump-offscreen))
7381 (save-excursion
7382 (goto-char blinkpos)
7383 (sit-for blink-matching-delay))
7384 (unwind-protect
7385 (progn
7386 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7387 (current-buffer))
7388 (sit-for blink-matching-delay))
7389 (delete-overlay blink-matching--overlay)))))
7390 (t
7391 (let ((open-paren-line-string
7392 (save-excursion
7393 (goto-char blinkpos)
7394 ;; Show what precedes the open in its line, if anything.
7395 (cond
7396 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7397 (buffer-substring (line-beginning-position)
7398 (1+ blinkpos)))
7399 ;; Show what follows the open in its line, if anything.
7400 ((save-excursion
7401 (forward-char 1)
7402 (skip-chars-forward " \t")
7403 (not (eolp)))
7404 (buffer-substring blinkpos
7405 (line-end-position)))
7406 ;; Otherwise show the previous nonblank line,
7407 ;; if there is one.
7408 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7409 (concat
7410 (buffer-substring (progn
7411 (skip-chars-backward "\n \t")
7412 (line-beginning-position))
7413 (progn (end-of-line)
7414 (skip-chars-backward " \t")
7415 (point)))
7416 ;; Replace the newline and other whitespace with `...'.
7417 "..."
7418 (buffer-substring blinkpos (1+ blinkpos))))
7419 ;; There is nothing to show except the char itself.
7420 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7421 (minibuffer-message
7422 "Matches %s"
7423 (substring-no-properties open-paren-line-string))))))))
7424
7425 (defvar blink-paren-function 'blink-matching-open
7426 "Function called, if non-nil, whenever a close parenthesis is inserted.
7427 More precisely, a char with closeparen syntax is self-inserted.")
7428
7429 (defun blink-paren-post-self-insert-function ()
7430 (when (and (eq (char-before) last-command-event) ; Sanity check.
7431 (memq (char-syntax last-command-event) '(?\) ?\$))
7432 blink-paren-function
7433 (not executing-kbd-macro)
7434 (not noninteractive)
7435 ;; Verify an even number of quoting characters precede the close.
7436 ;; FIXME: Also check if this parenthesis closes a comment as
7437 ;; can happen in Pascal and SML.
7438 (= 1 (logand 1 (- (point)
7439 (save-excursion
7440 (forward-char -1)
7441 (skip-syntax-backward "/\\")
7442 (point))))))
7443 (funcall blink-paren-function)))
7444
7445 (put 'blink-paren-post-self-insert-function 'priority 100)
7446
7447 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7448 ;; Most likely, this hook is nil, so this arg doesn't matter,
7449 ;; but I use it as a reminder that this function usually
7450 ;; likes to be run after others since it does
7451 ;; `sit-for'. That's also the reason it get a `priority' prop
7452 ;; of 100.
7453 'append)
7454 \f
7455 ;; This executes C-g typed while Emacs is waiting for a command.
7456 ;; Quitting out of a program does not go through here;
7457 ;; that happens in the QUIT macro at the C code level.
7458 (defun keyboard-quit ()
7459 "Signal a `quit' condition.
7460 During execution of Lisp code, this character causes a quit directly.
7461 At top-level, as an editor command, this simply beeps."
7462 (interactive)
7463 ;; Avoid adding the region to the window selection.
7464 (setq saved-region-selection nil)
7465 (let (select-active-regions)
7466 (deactivate-mark))
7467 (if (fboundp 'kmacro-keyboard-quit)
7468 (kmacro-keyboard-quit))
7469 (when completion-in-region-mode
7470 (completion-in-region-mode -1))
7471 ;; Force the next redisplay cycle to remove the "Def" indicator from
7472 ;; all the mode lines.
7473 (if defining-kbd-macro
7474 (force-mode-line-update t))
7475 (setq defining-kbd-macro nil)
7476 (let ((debug-on-quit nil))
7477 (signal 'quit nil)))
7478
7479 (defvar buffer-quit-function nil
7480 "Function to call to \"quit\" the current buffer, or nil if none.
7481 \\[keyboard-escape-quit] calls this function when its more local actions
7482 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7483
7484 (defun keyboard-escape-quit ()
7485 "Exit the current \"mode\" (in a generalized sense of the word).
7486 This command can exit an interactive command such as `query-replace',
7487 can clear out a prefix argument or a region,
7488 can get out of the minibuffer or other recursive edit,
7489 cancel the use of the current buffer (for special-purpose buffers),
7490 or go back to just one window (by deleting all but the selected window)."
7491 (interactive)
7492 (cond ((eq last-command 'mode-exited) nil)
7493 ((region-active-p)
7494 (deactivate-mark))
7495 ((> (minibuffer-depth) 0)
7496 (abort-recursive-edit))
7497 (current-prefix-arg
7498 nil)
7499 ((> (recursion-depth) 0)
7500 (exit-recursive-edit))
7501 (buffer-quit-function
7502 (funcall buffer-quit-function))
7503 ((not (one-window-p t))
7504 (delete-other-windows))
7505 ((string-match "^ \\*" (buffer-name (current-buffer)))
7506 (bury-buffer))))
7507
7508 (defun play-sound-file (file &optional volume device)
7509 "Play sound stored in FILE.
7510 VOLUME and DEVICE correspond to the keywords of the sound
7511 specification for `play-sound'."
7512 (interactive "fPlay sound file: ")
7513 (let ((sound (list :file file)))
7514 (if volume
7515 (plist-put sound :volume volume))
7516 (if device
7517 (plist-put sound :device device))
7518 (push 'sound sound)
7519 (play-sound sound)))
7520
7521 \f
7522 (defcustom read-mail-command 'rmail
7523 "Your preference for a mail reading package.
7524 This is used by some keybindings which support reading mail.
7525 See also `mail-user-agent' concerning sending mail."
7526 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7527 (function-item :tag "Gnus" :format "%t\n" gnus)
7528 (function-item :tag "Emacs interface to MH"
7529 :format "%t\n" mh-rmail)
7530 (function :tag "Other"))
7531 :version "21.1"
7532 :group 'mail)
7533
7534 (defcustom mail-user-agent 'message-user-agent
7535 "Your preference for a mail composition package.
7536 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7537 outgoing email message. This variable lets you specify which
7538 mail-sending package you prefer.
7539
7540 Valid values include:
7541
7542 `message-user-agent' -- use the Message package.
7543 See Info node `(message)'.
7544 `sendmail-user-agent' -- use the Mail package.
7545 See Info node `(emacs)Sending Mail'.
7546 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7547 See Info node `(mh-e)'.
7548 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7549 paraphernalia if Gnus is running, particularly
7550 the Gcc: header for archiving.
7551
7552 Additional valid symbols may be available; check with the author of
7553 your package for details. The function should return non-nil if it
7554 succeeds.
7555
7556 See also `read-mail-command' concerning reading mail."
7557 :type '(radio (function-item :tag "Message package"
7558 :format "%t\n"
7559 message-user-agent)
7560 (function-item :tag "Mail package"
7561 :format "%t\n"
7562 sendmail-user-agent)
7563 (function-item :tag "Emacs interface to MH"
7564 :format "%t\n"
7565 mh-e-user-agent)
7566 (function-item :tag "Message with full Gnus features"
7567 :format "%t\n"
7568 gnus-user-agent)
7569 (function :tag "Other"))
7570 :version "23.2" ; sendmail->message
7571 :group 'mail)
7572
7573 (defcustom compose-mail-user-agent-warnings t
7574 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7575 If the value of `mail-user-agent' is the default, and the user
7576 appears to have customizations applying to the old default,
7577 `compose-mail' issues a warning."
7578 :type 'boolean
7579 :version "23.2"
7580 :group 'mail)
7581
7582 (defun rfc822-goto-eoh ()
7583 "If the buffer starts with a mail header, move point to the header's end.
7584 Otherwise, moves to `point-min'.
7585 The end of the header is the start of the next line, if there is one,
7586 else the end of the last line. This function obeys RFC822."
7587 (goto-char (point-min))
7588 (when (re-search-forward
7589 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7590 (goto-char (match-beginning 0))))
7591
7592 ;; Used by Rmail (e.g., rmail-forward).
7593 (defvar mail-encode-mml nil
7594 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7595 the outgoing message before sending it.")
7596
7597 (defun compose-mail (&optional to subject other-headers continue
7598 switch-function yank-action send-actions
7599 return-action)
7600 "Start composing a mail message to send.
7601 This uses the user's chosen mail composition package
7602 as selected with the variable `mail-user-agent'.
7603 The optional arguments TO and SUBJECT specify recipients
7604 and the initial Subject field, respectively.
7605
7606 OTHER-HEADERS is an alist specifying additional
7607 header fields. Elements look like (HEADER . VALUE) where both
7608 HEADER and VALUE are strings.
7609
7610 CONTINUE, if non-nil, says to continue editing a message already
7611 being composed. Interactively, CONTINUE is the prefix argument.
7612
7613 SWITCH-FUNCTION, if non-nil, is a function to use to
7614 switch to and display the buffer used for mail composition.
7615
7616 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7617 to insert the raw text of the message being replied to.
7618 It has the form (FUNCTION . ARGS). The user agent will apply
7619 FUNCTION to ARGS, to insert the raw text of the original message.
7620 \(The user agent will also run `mail-citation-hook', *after* the
7621 original text has been inserted in this way.)
7622
7623 SEND-ACTIONS is a list of actions to call when the message is sent.
7624 Each action has the form (FUNCTION . ARGS).
7625
7626 RETURN-ACTION, if non-nil, is an action for returning to the
7627 caller. It has the form (FUNCTION . ARGS). The function is
7628 called after the mail has been sent or put aside, and the mail
7629 buffer buried."
7630 (interactive
7631 (list nil nil nil current-prefix-arg))
7632
7633 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7634 ;; from sendmail-user-agent to message-user-agent. Some users may
7635 ;; encounter incompatibilities. This hack tries to detect problems
7636 ;; and warn about them.
7637 (and compose-mail-user-agent-warnings
7638 (eq mail-user-agent 'message-user-agent)
7639 (let (warn-vars)
7640 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7641 mail-yank-hooks mail-archive-file-name
7642 mail-default-reply-to mail-mailing-lists
7643 mail-self-blind))
7644 (and (boundp var)
7645 (symbol-value var)
7646 (push var warn-vars)))
7647 (when warn-vars
7648 (display-warning 'mail
7649 (format-message "\
7650 The default mail mode is now Message mode.
7651 You have the following Mail mode variable%s customized:
7652 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7653 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7654 (if (> (length warn-vars) 1) "s" "")
7655 (mapconcat 'symbol-name
7656 warn-vars " "))))))
7657
7658 (let ((function (get mail-user-agent 'composefunc)))
7659 (funcall function to subject other-headers continue switch-function
7660 yank-action send-actions return-action)))
7661
7662 (defun compose-mail-other-window (&optional to subject other-headers continue
7663 yank-action send-actions
7664 return-action)
7665 "Like \\[compose-mail], but edit the outgoing message in another window."
7666 (interactive (list nil nil nil current-prefix-arg))
7667 (compose-mail to subject other-headers continue
7668 'switch-to-buffer-other-window yank-action send-actions
7669 return-action))
7670
7671 (defun compose-mail-other-frame (&optional to subject other-headers continue
7672 yank-action send-actions
7673 return-action)
7674 "Like \\[compose-mail], but edit the outgoing message in another frame."
7675 (interactive (list nil nil nil current-prefix-arg))
7676 (compose-mail to subject other-headers continue
7677 'switch-to-buffer-other-frame yank-action send-actions
7678 return-action))
7679
7680 \f
7681 (defvar set-variable-value-history nil
7682 "History of values entered with `set-variable'.
7683
7684 Maximum length of the history list is determined by the value
7685 of `history-length', which see.")
7686
7687 (defun set-variable (variable value &optional make-local)
7688 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7689 VARIABLE should be a user option variable name, a Lisp variable
7690 meant to be customized by users. You should enter VALUE in Lisp syntax,
7691 so if you want VALUE to be a string, you must surround it with doublequotes.
7692 VALUE is used literally, not evaluated.
7693
7694 If VARIABLE has a `variable-interactive' property, that is used as if
7695 it were the arg to `interactive' (which see) to interactively read VALUE.
7696
7697 If VARIABLE has been defined with `defcustom', then the type information
7698 in the definition is used to check that VALUE is valid.
7699
7700 Note that this function is at heart equivalent to the basic `set' function.
7701 For a variable defined with `defcustom', it does not pay attention to
7702 any :set property that the variable might have (if you want that, use
7703 \\[customize-set-variable] instead).
7704
7705 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7706 (interactive
7707 (let* ((default-var (variable-at-point))
7708 (var (if (custom-variable-p default-var)
7709 (read-variable (format "Set variable (default %s): " default-var)
7710 default-var)
7711 (read-variable "Set variable: ")))
7712 (minibuffer-help-form '(describe-variable var))
7713 (prop (get var 'variable-interactive))
7714 (obsolete (car (get var 'byte-obsolete-variable)))
7715 (prompt (format "Set %s %s to value: " var
7716 (cond ((local-variable-p var)
7717 "(buffer-local)")
7718 ((or current-prefix-arg
7719 (local-variable-if-set-p var))
7720 "buffer-locally")
7721 (t "globally"))))
7722 (val (progn
7723 (when obsolete
7724 (message (concat "`%S' is obsolete; "
7725 (if (symbolp obsolete) "use `%S' instead" "%s"))
7726 var obsolete)
7727 (sit-for 3))
7728 (if prop
7729 ;; Use VAR's `variable-interactive' property
7730 ;; as an interactive spec for prompting.
7731 (call-interactively `(lambda (arg)
7732 (interactive ,prop)
7733 arg))
7734 (read-from-minibuffer prompt nil
7735 read-expression-map t
7736 'set-variable-value-history
7737 (format "%S" (symbol-value var)))))))
7738 (list var val current-prefix-arg)))
7739
7740 (and (custom-variable-p variable)
7741 (not (get variable 'custom-type))
7742 (custom-load-symbol variable))
7743 (let ((type (get variable 'custom-type)))
7744 (when type
7745 ;; Match with custom type.
7746 (require 'cus-edit)
7747 (setq type (widget-convert type))
7748 (unless (widget-apply type :match value)
7749 (user-error "Value `%S' does not match type %S of %S"
7750 value (car type) variable))))
7751
7752 (if make-local
7753 (make-local-variable variable))
7754
7755 (set variable value)
7756
7757 ;; Force a thorough redisplay for the case that the variable
7758 ;; has an effect on the display, like `tab-width' has.
7759 (force-mode-line-update))
7760 \f
7761 ;; Define the major mode for lists of completions.
7762
7763 (defvar completion-list-mode-map
7764 (let ((map (make-sparse-keymap)))
7765 (define-key map [mouse-2] 'choose-completion)
7766 (define-key map [follow-link] 'mouse-face)
7767 (define-key map [down-mouse-2] nil)
7768 (define-key map "\C-m" 'choose-completion)
7769 (define-key map "\e\e\e" 'delete-completion-window)
7770 (define-key map [left] 'previous-completion)
7771 (define-key map [right] 'next-completion)
7772 (define-key map [?\t] 'next-completion)
7773 (define-key map [backtab] 'previous-completion)
7774 (define-key map "q" 'quit-window)
7775 (define-key map "z" 'kill-this-buffer)
7776 map)
7777 "Local map for completion list buffers.")
7778
7779 ;; Completion mode is suitable only for specially formatted data.
7780 (put 'completion-list-mode 'mode-class 'special)
7781
7782 (defvar completion-reference-buffer nil
7783 "Record the buffer that was current when the completion list was requested.
7784 This is a local variable in the completion list buffer.
7785 Initial value is nil to avoid some compiler warnings.")
7786
7787 (defvar completion-no-auto-exit nil
7788 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7789 This also applies to other functions such as `choose-completion'.")
7790
7791 (defvar completion-base-position nil
7792 "Position of the base of the text corresponding to the shown completions.
7793 This variable is used in the *Completions* buffers.
7794 Its value is a list of the form (START END) where START is the place
7795 where the completion should be inserted and END (if non-nil) is the end
7796 of the text to replace. If END is nil, point is used instead.")
7797
7798 (defvar completion-list-insert-choice-function #'completion--replace
7799 "Function to use to insert the text chosen in *Completions*.
7800 Called with three arguments (BEG END TEXT), it should replace the text
7801 between BEG and END with TEXT. Expected to be set buffer-locally
7802 in the *Completions* buffer.")
7803
7804 (defvar completion-base-size nil
7805 "Number of chars before point not involved in completion.
7806 This is a local variable in the completion list buffer.
7807 It refers to the chars in the minibuffer if completing in the
7808 minibuffer, or in `completion-reference-buffer' otherwise.
7809 Only characters in the field at point are included.
7810
7811 If nil, Emacs determines which part of the tail end of the
7812 buffer's text is involved in completion by comparing the text
7813 directly.")
7814 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7815
7816 (defun delete-completion-window ()
7817 "Delete the completion list window.
7818 Go to the window from which completion was requested."
7819 (interactive)
7820 (let ((buf completion-reference-buffer))
7821 (if (one-window-p t)
7822 (if (window-dedicated-p) (delete-frame))
7823 (delete-window (selected-window))
7824 (if (get-buffer-window buf)
7825 (select-window (get-buffer-window buf))))))
7826
7827 (defun previous-completion (n)
7828 "Move to the previous item in the completion list."
7829 (interactive "p")
7830 (next-completion (- n)))
7831
7832 (defun next-completion (n)
7833 "Move to the next item in the completion list.
7834 With prefix argument N, move N items (negative N means move backward)."
7835 (interactive "p")
7836 (let ((beg (point-min)) (end (point-max)))
7837 (while (and (> n 0) (not (eobp)))
7838 ;; If in a completion, move to the end of it.
7839 (when (get-text-property (point) 'mouse-face)
7840 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7841 ;; Move to start of next one.
7842 (unless (get-text-property (point) 'mouse-face)
7843 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7844 (setq n (1- n)))
7845 (while (and (< n 0) (not (bobp)))
7846 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7847 ;; If in a completion, move to the start of it.
7848 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7849 (goto-char (previous-single-property-change
7850 (point) 'mouse-face nil beg)))
7851 ;; Move to end of the previous completion.
7852 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7853 (goto-char (previous-single-property-change
7854 (point) 'mouse-face nil beg)))
7855 ;; Move to the start of that one.
7856 (goto-char (previous-single-property-change
7857 (point) 'mouse-face nil beg))
7858 (setq n (1+ n))))))
7859
7860 (defun choose-completion (&optional event)
7861 "Choose the completion at point.
7862 If EVENT, use EVENT's position to determine the starting position."
7863 (interactive (list last-nonmenu-event))
7864 ;; In case this is run via the mouse, give temporary modes such as
7865 ;; isearch a chance to turn off.
7866 (run-hooks 'mouse-leave-buffer-hook)
7867 (with-current-buffer (window-buffer (posn-window (event-start event)))
7868 (let ((buffer completion-reference-buffer)
7869 (base-size completion-base-size)
7870 (base-position completion-base-position)
7871 (insert-function completion-list-insert-choice-function)
7872 (choice
7873 (save-excursion
7874 (goto-char (posn-point (event-start event)))
7875 (let (beg end)
7876 (cond
7877 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7878 (setq end (point) beg (1+ (point))))
7879 ((and (not (bobp))
7880 (get-text-property (1- (point)) 'mouse-face))
7881 (setq end (1- (point)) beg (point)))
7882 (t (error "No completion here")))
7883 (setq beg (previous-single-property-change beg 'mouse-face))
7884 (setq end (or (next-single-property-change end 'mouse-face)
7885 (point-max)))
7886 (buffer-substring-no-properties beg end)))))
7887
7888 (unless (buffer-live-p buffer)
7889 (error "Destination buffer is dead"))
7890 (quit-window nil (posn-window (event-start event)))
7891
7892 (with-current-buffer buffer
7893 (choose-completion-string
7894 choice buffer
7895 (or base-position
7896 (when base-size
7897 ;; Someone's using old completion code that doesn't know
7898 ;; about base-position yet.
7899 (list (+ base-size (field-beginning))))
7900 ;; If all else fails, just guess.
7901 (list (choose-completion-guess-base-position choice)))
7902 insert-function)))))
7903
7904 ;; Delete the longest partial match for STRING
7905 ;; that can be found before POINT.
7906 (defun choose-completion-guess-base-position (string)
7907 (save-excursion
7908 (let ((opoint (point))
7909 len)
7910 ;; Try moving back by the length of the string.
7911 (goto-char (max (- (point) (length string))
7912 (minibuffer-prompt-end)))
7913 ;; See how far back we were actually able to move. That is the
7914 ;; upper bound on how much we can match and delete.
7915 (setq len (- opoint (point)))
7916 (if completion-ignore-case
7917 (setq string (downcase string)))
7918 (while (and (> len 0)
7919 (let ((tail (buffer-substring (point) opoint)))
7920 (if completion-ignore-case
7921 (setq tail (downcase tail)))
7922 (not (string= tail (substring string 0 len)))))
7923 (setq len (1- len))
7924 (forward-char 1))
7925 (point))))
7926
7927 (defun choose-completion-delete-max-match (string)
7928 (declare (obsolete choose-completion-guess-base-position "23.2"))
7929 (delete-region (choose-completion-guess-base-position string) (point)))
7930
7931 (defvar choose-completion-string-functions nil
7932 "Functions that may override the normal insertion of a completion choice.
7933 These functions are called in order with three arguments:
7934 CHOICE - the string to insert in the buffer,
7935 BUFFER - the buffer in which the choice should be inserted,
7936 BASE-POSITION - where to insert the completion.
7937
7938 If a function in the list returns non-nil, that function is supposed
7939 to have inserted the CHOICE in the BUFFER, and possibly exited
7940 the minibuffer; no further functions will be called.
7941
7942 If all functions in the list return nil, that means to use
7943 the default method of inserting the completion in BUFFER.")
7944
7945 (defun choose-completion-string (choice &optional
7946 buffer base-position insert-function)
7947 "Switch to BUFFER and insert the completion choice CHOICE.
7948 BASE-POSITION says where to insert the completion.
7949 INSERT-FUNCTION says how to insert the completion and falls
7950 back on `completion-list-insert-choice-function' when nil."
7951
7952 ;; If BUFFER is the minibuffer, exit the minibuffer
7953 ;; unless it is reading a file name and CHOICE is a directory,
7954 ;; or completion-no-auto-exit is non-nil.
7955
7956 ;; Some older code may call us passing `base-size' instead of
7957 ;; `base-position'. It's difficult to make any use of `base-size',
7958 ;; so we just ignore it.
7959 (unless (consp base-position)
7960 (message "Obsolete `base-size' passed to choose-completion-string")
7961 (setq base-position nil))
7962
7963 (let* ((buffer (or buffer completion-reference-buffer))
7964 (mini-p (minibufferp buffer)))
7965 ;; If BUFFER is a minibuffer, barf unless it's the currently
7966 ;; active minibuffer.
7967 (if (and mini-p
7968 (not (and (active-minibuffer-window)
7969 (equal buffer
7970 (window-buffer (active-minibuffer-window))))))
7971 (error "Minibuffer is not active for completion")
7972 ;; Set buffer so buffer-local choose-completion-string-functions works.
7973 (set-buffer buffer)
7974 (unless (run-hook-with-args-until-success
7975 'choose-completion-string-functions
7976 ;; The fourth arg used to be `mini-p' but was useless
7977 ;; (since minibufferp can be used on the `buffer' arg)
7978 ;; and indeed unused. The last used to be `base-size', so we
7979 ;; keep it to try and avoid breaking old code.
7980 choice buffer base-position nil)
7981 ;; This remove-text-properties should be unnecessary since `choice'
7982 ;; comes from buffer-substring-no-properties.
7983 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7984 ;; Insert the completion into the buffer where it was requested.
7985 (funcall (or insert-function completion-list-insert-choice-function)
7986 (or (car base-position) (point))
7987 (or (cadr base-position) (point))
7988 choice)
7989 ;; Update point in the window that BUFFER is showing in.
7990 (let ((window (get-buffer-window buffer t)))
7991 (set-window-point window (point)))
7992 ;; If completing for the minibuffer, exit it with this choice.
7993 (and (not completion-no-auto-exit)
7994 (minibufferp buffer)
7995 minibuffer-completion-table
7996 ;; If this is reading a file name, and the file name chosen
7997 ;; is a directory, don't exit the minibuffer.
7998 (let* ((result (buffer-substring (field-beginning) (point)))
7999 (bounds
8000 (completion-boundaries result minibuffer-completion-table
8001 minibuffer-completion-predicate
8002 "")))
8003 (if (eq (car bounds) (length result))
8004 ;; The completion chosen leads to a new set of completions
8005 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8006 (let ((mini (active-minibuffer-window)))
8007 (select-window mini)
8008 (when minibuffer-auto-raise
8009 (raise-frame (window-frame mini))))
8010 (exit-minibuffer))))))))
8011
8012 (define-derived-mode completion-list-mode nil "Completion List"
8013 "Major mode for buffers showing lists of possible completions.
8014 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8015 to select the completion near point.
8016 Or click to select one with the mouse.
8017
8018 \\{completion-list-mode-map}"
8019 (set (make-local-variable 'completion-base-size) nil))
8020
8021 (defun completion-list-mode-finish ()
8022 "Finish setup of the completions buffer.
8023 Called from `temp-buffer-show-hook'."
8024 (when (eq major-mode 'completion-list-mode)
8025 (setq buffer-read-only t)))
8026
8027 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8028
8029
8030 ;; Variables and faces used in `completion-setup-function'.
8031
8032 (defcustom completion-show-help t
8033 "Non-nil means show help message in *Completions* buffer."
8034 :type 'boolean
8035 :version "22.1"
8036 :group 'completion)
8037
8038 ;; This function goes in completion-setup-hook, so that it is called
8039 ;; after the text of the completion list buffer is written.
8040 (defun completion-setup-function ()
8041 (let* ((mainbuf (current-buffer))
8042 (base-dir
8043 ;; FIXME: This is a bad hack. We try to set the default-directory
8044 ;; in the *Completions* buffer so that the relative file names
8045 ;; displayed there can be treated as valid file names, independently
8046 ;; from the completion context. But this suffers from many problems:
8047 ;; - It's not clear when the completions are file names. With some
8048 ;; completion tables (e.g. bzr revision specs), the listed
8049 ;; completions can mix file names and other things.
8050 ;; - It doesn't pay attention to possible quoting.
8051 ;; - With fancy completion styles, the code below will not always
8052 ;; find the right base directory.
8053 (if minibuffer-completing-file-name
8054 (file-name-as-directory
8055 (expand-file-name
8056 (buffer-substring (minibuffer-prompt-end)
8057 (- (point) (or completion-base-size 0))))))))
8058 (with-current-buffer standard-output
8059 (let ((base-size completion-base-size) ;Read before killing localvars.
8060 (base-position completion-base-position)
8061 (insert-fun completion-list-insert-choice-function))
8062 (completion-list-mode)
8063 (set (make-local-variable 'completion-base-size) base-size)
8064 (set (make-local-variable 'completion-base-position) base-position)
8065 (set (make-local-variable 'completion-list-insert-choice-function)
8066 insert-fun))
8067 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8068 (if base-dir (setq default-directory base-dir))
8069 ;; Maybe insert help string.
8070 (when completion-show-help
8071 (goto-char (point-min))
8072 (if (display-mouse-p)
8073 (insert "Click on a completion to select it.\n"))
8074 (insert (substitute-command-keys
8075 "In this buffer, type \\[choose-completion] to \
8076 select the completion near point.\n\n"))))))
8077
8078 (add-hook 'completion-setup-hook 'completion-setup-function)
8079
8080 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8081 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8082
8083 (defun switch-to-completions ()
8084 "Select the completion list window."
8085 (interactive)
8086 (let ((window (or (get-buffer-window "*Completions*" 0)
8087 ;; Make sure we have a completions window.
8088 (progn (minibuffer-completion-help)
8089 (get-buffer-window "*Completions*" 0)))))
8090 (when window
8091 (select-window window)
8092 ;; In the new buffer, go to the first completion.
8093 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8094 (when (bobp)
8095 (next-completion 1)))))
8096 \f
8097 ;;; Support keyboard commands to turn on various modifiers.
8098
8099 ;; These functions -- which are not commands -- each add one modifier
8100 ;; to the following event.
8101
8102 (defun event-apply-alt-modifier (_ignore-prompt)
8103 "\\<function-key-map>Add the Alt modifier to the following event.
8104 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8105 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8106 (defun event-apply-super-modifier (_ignore-prompt)
8107 "\\<function-key-map>Add the Super modifier to the following event.
8108 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8109 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8110 (defun event-apply-hyper-modifier (_ignore-prompt)
8111 "\\<function-key-map>Add the Hyper modifier to the following event.
8112 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8113 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8114 (defun event-apply-shift-modifier (_ignore-prompt)
8115 "\\<function-key-map>Add the Shift modifier to the following event.
8116 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8117 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8118 (defun event-apply-control-modifier (_ignore-prompt)
8119 "\\<function-key-map>Add the Ctrl modifier to the following event.
8120 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8121 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8122 (defun event-apply-meta-modifier (_ignore-prompt)
8123 "\\<function-key-map>Add the Meta modifier to the following event.
8124 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8125 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8126
8127 (defun event-apply-modifier (event symbol lshiftby prefix)
8128 "Apply a modifier flag to event EVENT.
8129 SYMBOL is the name of this modifier, as a symbol.
8130 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8131 PREFIX is the string that represents this modifier in an event type symbol."
8132 (if (numberp event)
8133 (cond ((eq symbol 'control)
8134 (if (and (<= (downcase event) ?z)
8135 (>= (downcase event) ?a))
8136 (- (downcase event) ?a -1)
8137 (if (and (<= (downcase event) ?Z)
8138 (>= (downcase event) ?A))
8139 (- (downcase event) ?A -1)
8140 (logior (lsh 1 lshiftby) event))))
8141 ((eq symbol 'shift)
8142 (if (and (<= (downcase event) ?z)
8143 (>= (downcase event) ?a))
8144 (upcase event)
8145 (logior (lsh 1 lshiftby) event)))
8146 (t
8147 (logior (lsh 1 lshiftby) event)))
8148 (if (memq symbol (event-modifiers event))
8149 event
8150 (let ((event-type (if (symbolp event) event (car event))))
8151 (setq event-type (intern (concat prefix (symbol-name event-type))))
8152 (if (symbolp event)
8153 event-type
8154 (cons event-type (cdr event)))))))
8155
8156 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8157 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8158 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8159 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8160 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8161 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8162 \f
8163 ;;;; Keypad support.
8164
8165 ;; Make the keypad keys act like ordinary typing keys. If people add
8166 ;; bindings for the function key symbols, then those bindings will
8167 ;; override these, so this shouldn't interfere with any existing
8168 ;; bindings.
8169
8170 ;; Also tell read-char how to handle these keys.
8171 (mapc
8172 (lambda (keypad-normal)
8173 (let ((keypad (nth 0 keypad-normal))
8174 (normal (nth 1 keypad-normal)))
8175 (put keypad 'ascii-character normal)
8176 (define-key function-key-map (vector keypad) (vector normal))))
8177 ;; See also kp-keys bound in bindings.el.
8178 '((kp-space ?\s)
8179 (kp-tab ?\t)
8180 (kp-enter ?\r)
8181 (kp-separator ?,)
8182 (kp-equal ?=)
8183 ;; Do the same for various keys that are represented as symbols under
8184 ;; GUIs but naturally correspond to characters.
8185 (backspace 127)
8186 (delete 127)
8187 (tab ?\t)
8188 (linefeed ?\n)
8189 (clear ?\C-l)
8190 (return ?\C-m)
8191 (escape ?\e)
8192 ))
8193 \f
8194 ;;;;
8195 ;;;; forking a twin copy of a buffer.
8196 ;;;;
8197
8198 (defvar clone-buffer-hook nil
8199 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8200
8201 (defvar clone-indirect-buffer-hook nil
8202 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8203
8204 (defun clone-process (process &optional newname)
8205 "Create a twin copy of PROCESS.
8206 If NEWNAME is nil, it defaults to PROCESS' name;
8207 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8208 If PROCESS is associated with a buffer, the new process will be associated
8209 with the current buffer instead.
8210 Returns nil if PROCESS has already terminated."
8211 (setq newname (or newname (process-name process)))
8212 (if (string-match "<[0-9]+>\\'" newname)
8213 (setq newname (substring newname 0 (match-beginning 0))))
8214 (when (memq (process-status process) '(run stop open))
8215 (let* ((process-connection-type (process-tty-name process))
8216 (new-process
8217 (if (memq (process-status process) '(open))
8218 (let ((args (process-contact process t)))
8219 (setq args (plist-put args :name newname))
8220 (setq args (plist-put args :buffer
8221 (if (process-buffer process)
8222 (current-buffer))))
8223 (apply 'make-network-process args))
8224 (apply 'start-process newname
8225 (if (process-buffer process) (current-buffer))
8226 (process-command process)))))
8227 (set-process-query-on-exit-flag
8228 new-process (process-query-on-exit-flag process))
8229 (set-process-inherit-coding-system-flag
8230 new-process (process-inherit-coding-system-flag process))
8231 (set-process-filter new-process (process-filter process))
8232 (set-process-sentinel new-process (process-sentinel process))
8233 (set-process-plist new-process (copy-sequence (process-plist process)))
8234 new-process)))
8235
8236 ;; things to maybe add (currently partly covered by `funcall mode'):
8237 ;; - syntax-table
8238 ;; - overlays
8239 (defun clone-buffer (&optional newname display-flag)
8240 "Create and return a twin copy of the current buffer.
8241 Unlike an indirect buffer, the new buffer can be edited
8242 independently of the old one (if it is not read-only).
8243 NEWNAME is the name of the new buffer. It may be modified by
8244 adding or incrementing <N> at the end as necessary to create a
8245 unique buffer name. If nil, it defaults to the name of the
8246 current buffer, with the proper suffix. If DISPLAY-FLAG is
8247 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8248 clone a file-visiting buffer, or a buffer whose major mode symbol
8249 has a non-nil `no-clone' property, results in an error.
8250
8251 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8252 current buffer with appropriate suffix. However, if a prefix
8253 argument is given, then the command prompts for NEWNAME in the
8254 minibuffer.
8255
8256 This runs the normal hook `clone-buffer-hook' in the new buffer
8257 after it has been set up properly in other respects."
8258 (interactive
8259 (progn
8260 (if buffer-file-name
8261 (error "Cannot clone a file-visiting buffer"))
8262 (if (get major-mode 'no-clone)
8263 (error "Cannot clone a buffer in %s mode" mode-name))
8264 (list (if current-prefix-arg
8265 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8266 t)))
8267 (if buffer-file-name
8268 (error "Cannot clone a file-visiting buffer"))
8269 (if (get major-mode 'no-clone)
8270 (error "Cannot clone a buffer in %s mode" mode-name))
8271 (setq newname (or newname (buffer-name)))
8272 (if (string-match "<[0-9]+>\\'" newname)
8273 (setq newname (substring newname 0 (match-beginning 0))))
8274 (let ((buf (current-buffer))
8275 (ptmin (point-min))
8276 (ptmax (point-max))
8277 (pt (point))
8278 (mk (if mark-active (mark t)))
8279 (modified (buffer-modified-p))
8280 (mode major-mode)
8281 (lvars (buffer-local-variables))
8282 (process (get-buffer-process (current-buffer)))
8283 (new (generate-new-buffer (or newname (buffer-name)))))
8284 (save-restriction
8285 (widen)
8286 (with-current-buffer new
8287 (insert-buffer-substring buf)))
8288 (with-current-buffer new
8289 (narrow-to-region ptmin ptmax)
8290 (goto-char pt)
8291 (if mk (set-mark mk))
8292 (set-buffer-modified-p modified)
8293
8294 ;; Clone the old buffer's process, if any.
8295 (when process (clone-process process))
8296
8297 ;; Now set up the major mode.
8298 (funcall mode)
8299
8300 ;; Set up other local variables.
8301 (mapc (lambda (v)
8302 (condition-case () ;in case var is read-only
8303 (if (symbolp v)
8304 (makunbound v)
8305 (set (make-local-variable (car v)) (cdr v)))
8306 (error nil)))
8307 lvars)
8308
8309 ;; Run any hooks (typically set up by the major mode
8310 ;; for cloning to work properly).
8311 (run-hooks 'clone-buffer-hook))
8312 (if display-flag
8313 ;; Presumably the current buffer is shown in the selected frame, so
8314 ;; we want to display the clone elsewhere.
8315 (let ((same-window-regexps nil)
8316 (same-window-buffer-names))
8317 (pop-to-buffer new)))
8318 new))
8319
8320
8321 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8322 "Create an indirect buffer that is a twin copy of the current buffer.
8323
8324 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8325 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8326 or if not called with a prefix arg, NEWNAME defaults to the current
8327 buffer's name. The name is modified by adding a `<N>' suffix to it
8328 or by incrementing the N in an existing suffix. Trying to clone a
8329 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8330 property results in an error.
8331
8332 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8333 This is always done when called interactively.
8334
8335 Optional third arg NORECORD non-nil means do not put this buffer at the
8336 front of the list of recently selected ones.
8337
8338 Returns the newly created indirect buffer."
8339 (interactive
8340 (progn
8341 (if (get major-mode 'no-clone-indirect)
8342 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8343 (list (if current-prefix-arg
8344 (read-buffer "Name of indirect buffer: " (current-buffer)))
8345 t)))
8346 (if (get major-mode 'no-clone-indirect)
8347 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8348 (setq newname (or newname (buffer-name)))
8349 (if (string-match "<[0-9]+>\\'" newname)
8350 (setq newname (substring newname 0 (match-beginning 0))))
8351 (let* ((name (generate-new-buffer-name newname))
8352 (buffer (make-indirect-buffer (current-buffer) name t)))
8353 (with-current-buffer buffer
8354 (run-hooks 'clone-indirect-buffer-hook))
8355 (when display-flag
8356 (pop-to-buffer buffer norecord))
8357 buffer))
8358
8359
8360 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8361 "Like `clone-indirect-buffer' but display in another window."
8362 (interactive
8363 (progn
8364 (if (get major-mode 'no-clone-indirect)
8365 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8366 (list (if current-prefix-arg
8367 (read-buffer "Name of indirect buffer: " (current-buffer)))
8368 t)))
8369 (let ((pop-up-windows t))
8370 (clone-indirect-buffer newname display-flag norecord)))
8371
8372 \f
8373 ;;; Handling of Backspace and Delete keys.
8374
8375 (defcustom normal-erase-is-backspace 'maybe
8376 "Set the default behavior of the Delete and Backspace keys.
8377
8378 If set to t, Delete key deletes forward and Backspace key deletes
8379 backward.
8380
8381 If set to nil, both Delete and Backspace keys delete backward.
8382
8383 If set to `maybe' (which is the default), Emacs automatically
8384 selects a behavior. On window systems, the behavior depends on
8385 the keyboard used. If the keyboard has both a Backspace key and
8386 a Delete key, and both are mapped to their usual meanings, the
8387 option's default value is set to t, so that Backspace can be used
8388 to delete backward, and Delete can be used to delete forward.
8389
8390 If not running under a window system, customizing this option
8391 accomplishes a similar effect by mapping C-h, which is usually
8392 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8393 via `keyboard-translate'. The former functionality of C-h is
8394 available on the F1 key. You should probably not use this
8395 setting if you don't have both Backspace, Delete and F1 keys.
8396
8397 Setting this variable with setq doesn't take effect. Programmatically,
8398 call `normal-erase-is-backspace-mode' (which see) instead."
8399 :type '(choice (const :tag "Off" nil)
8400 (const :tag "Maybe" maybe)
8401 (other :tag "On" t))
8402 :group 'editing-basics
8403 :version "21.1"
8404 :set (lambda (symbol value)
8405 ;; The fboundp is because of a problem with :set when
8406 ;; dumping Emacs. It doesn't really matter.
8407 (if (fboundp 'normal-erase-is-backspace-mode)
8408 (normal-erase-is-backspace-mode (or value 0))
8409 (set-default symbol value))))
8410
8411 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8412 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8413 (unless frame (setq frame (selected-frame)))
8414 (with-selected-frame frame
8415 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8416 (normal-erase-is-backspace-mode
8417 (if (if (eq normal-erase-is-backspace 'maybe)
8418 (and (not noninteractive)
8419 (or (memq system-type '(ms-dos windows-nt))
8420 (memq window-system '(w32 ns))
8421 (and (memq window-system '(x))
8422 (fboundp 'x-backspace-delete-keys-p)
8423 (x-backspace-delete-keys-p))
8424 ;; If the terminal Emacs is running on has erase char
8425 ;; set to ^H, use the Backspace key for deleting
8426 ;; backward, and the Delete key for deleting forward.
8427 (and (null window-system)
8428 (eq tty-erase-char ?\^H))))
8429 normal-erase-is-backspace)
8430 1 0)))))
8431
8432 (define-minor-mode normal-erase-is-backspace-mode
8433 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8434 With a prefix argument ARG, enable this feature if ARG is
8435 positive, and disable it otherwise. If called from Lisp, enable
8436 the mode if ARG is omitted or nil.
8437
8438 On window systems, when this mode is on, Delete is mapped to C-d
8439 and Backspace is mapped to DEL; when this mode is off, both
8440 Delete and Backspace are mapped to DEL. (The remapping goes via
8441 `local-function-key-map', so binding Delete or Backspace in the
8442 global or local keymap will override that.)
8443
8444 In addition, on window systems, the bindings of C-Delete, M-Delete,
8445 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8446 the global keymap in accordance with the functionality of Delete and
8447 Backspace. For example, if Delete is remapped to C-d, which deletes
8448 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8449 to DEL, which deletes backward, C-Delete is bound to
8450 `backward-kill-word'.
8451
8452 If not running on a window system, a similar effect is accomplished by
8453 remapping C-h (normally produced by the Backspace key) and DEL via
8454 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8455 to C-d; if it's off, the keys are not remapped.
8456
8457 When not running on a window system, and this mode is turned on, the
8458 former functionality of C-h is available on the F1 key. You should
8459 probably not turn on this mode on a text-only terminal if you don't
8460 have both Backspace, Delete and F1 keys.
8461
8462 See also `normal-erase-is-backspace'."
8463 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8464 . (lambda (v)
8465 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8466 (if v 1 0))))
8467 (let ((enabled (eq 1 (terminal-parameter
8468 nil 'normal-erase-is-backspace))))
8469
8470 (cond ((or (memq window-system '(x w32 ns pc))
8471 (memq system-type '(ms-dos windows-nt)))
8472 (let ((bindings
8473 `(([M-delete] [M-backspace])
8474 ([C-M-delete] [C-M-backspace])
8475 ([?\e C-delete] [?\e C-backspace]))))
8476
8477 (if enabled
8478 (progn
8479 (define-key local-function-key-map [delete] [deletechar])
8480 (define-key local-function-key-map [kp-delete] [deletechar])
8481 (define-key local-function-key-map [backspace] [?\C-?])
8482 (dolist (b bindings)
8483 ;; Not sure if input-decode-map is really right, but
8484 ;; keyboard-translate-table (used below) only works
8485 ;; for integer events, and key-translation-table is
8486 ;; global (like the global-map, used earlier).
8487 (define-key input-decode-map (car b) nil)
8488 (define-key input-decode-map (cadr b) nil)))
8489 (define-key local-function-key-map [delete] [?\C-?])
8490 (define-key local-function-key-map [kp-delete] [?\C-?])
8491 (define-key local-function-key-map [backspace] [?\C-?])
8492 (dolist (b bindings)
8493 (define-key input-decode-map (car b) (cadr b))
8494 (define-key input-decode-map (cadr b) (car b))))))
8495 (t
8496 (if enabled
8497 (progn
8498 (keyboard-translate ?\C-h ?\C-?)
8499 (keyboard-translate ?\C-? ?\C-d))
8500 (keyboard-translate ?\C-h ?\C-h)
8501 (keyboard-translate ?\C-? ?\C-?))))
8502
8503 (if (called-interactively-p 'interactive)
8504 (message "Delete key deletes %s"
8505 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8506 "forward" "backward")))))
8507 \f
8508 (defvar vis-mode-saved-buffer-invisibility-spec nil
8509 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8510
8511 (define-minor-mode read-only-mode
8512 "Change whether the current buffer is read-only.
8513 With prefix argument ARG, make the buffer read-only if ARG is
8514 positive, otherwise make it writable. If buffer is read-only
8515 and `view-read-only' is non-nil, enter view mode.
8516
8517 Do not call this from a Lisp program unless you really intend to
8518 do the same thing as the \\[read-only-mode] command, including
8519 possibly enabling or disabling View mode. Also, note that this
8520 command works by setting the variable `buffer-read-only', which
8521 does not affect read-only regions caused by text properties. To
8522 ignore read-only status in a Lisp program (whether due to text
8523 properties or buffer state), bind `inhibit-read-only' temporarily
8524 to a non-nil value."
8525 :variable buffer-read-only
8526 (cond
8527 ((and (not buffer-read-only) view-mode)
8528 (View-exit-and-edit)
8529 (make-local-variable 'view-read-only)
8530 (setq view-read-only t)) ; Must leave view mode.
8531 ((and buffer-read-only view-read-only
8532 ;; If view-mode is already active, `view-mode-enter' is a nop.
8533 (not view-mode)
8534 (not (eq (get major-mode 'mode-class) 'special)))
8535 (view-mode-enter))))
8536
8537 (define-minor-mode visible-mode
8538 "Toggle making all invisible text temporarily visible (Visible mode).
8539 With a prefix argument ARG, enable Visible mode if ARG is
8540 positive, and disable it otherwise. If called from Lisp, enable
8541 the mode if ARG is omitted or nil.
8542
8543 This mode works by saving the value of `buffer-invisibility-spec'
8544 and setting it to nil."
8545 :lighter " Vis"
8546 :group 'editing-basics
8547 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8548 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8549 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8550 (when visible-mode
8551 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8552 buffer-invisibility-spec)
8553 (setq buffer-invisibility-spec nil)))
8554 \f
8555 (defvar messages-buffer-mode-map
8556 (let ((map (make-sparse-keymap)))
8557 (set-keymap-parent map special-mode-map)
8558 (define-key map "g" nil) ; nothing to revert
8559 map))
8560
8561 (define-derived-mode messages-buffer-mode special-mode "Messages"
8562 "Major mode used in the \"*Messages*\" buffer.")
8563
8564 (defun messages-buffer ()
8565 "Return the \"*Messages*\" buffer.
8566 If it does not exist, create and it switch it to `messages-buffer-mode'."
8567 (or (get-buffer "*Messages*")
8568 (with-current-buffer (get-buffer-create "*Messages*")
8569 (messages-buffer-mode)
8570 (current-buffer))))
8571
8572 \f
8573 ;; Minibuffer prompt stuff.
8574
8575 ;;(defun minibuffer-prompt-modification (start end)
8576 ;; (error "You cannot modify the prompt"))
8577 ;;
8578 ;;
8579 ;;(defun minibuffer-prompt-insertion (start end)
8580 ;; (let ((inhibit-modification-hooks t))
8581 ;; (delete-region start end)
8582 ;; ;; Discard undo information for the text insertion itself
8583 ;; ;; and for the text deletion.above.
8584 ;; (when (consp buffer-undo-list)
8585 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8586 ;; (message "You cannot modify the prompt")))
8587 ;;
8588 ;;
8589 ;;(setq minibuffer-prompt-properties
8590 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8591 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8592
8593 \f
8594 ;;;; Problematic external packages.
8595
8596 ;; rms says this should be done by specifying symbols that define
8597 ;; versions together with bad values. This is therefore not as
8598 ;; flexible as it could be. See the thread:
8599 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8600 (defconst bad-packages-alist
8601 ;; Not sure exactly which semantic versions have problems.
8602 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8603 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8604 "The version of `semantic' loaded does not work in Emacs 22.
8605 It can cause constant high CPU load.
8606 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8607 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8608 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8609 ;; provided the `CUA-mode' feature. Since this is no longer true,
8610 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8611 (CUA-mode t nil
8612 "CUA-mode is now part of the standard GNU Emacs distribution,
8613 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8614
8615 You have loaded an older version of CUA-mode which does not work
8616 correctly with this version of Emacs. You should remove the old
8617 version and use the one distributed with Emacs."))
8618 "Alist of packages known to cause problems in this version of Emacs.
8619 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8620 PACKAGE is either a regular expression to match file names, or a
8621 symbol (a feature name), like for `with-eval-after-load'.
8622 SYMBOL is either the name of a string variable, or t. Upon
8623 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8624 warning using STRING as the message.")
8625
8626 (defun bad-package-check (package)
8627 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8628 (condition-case nil
8629 (let* ((list (assoc package bad-packages-alist))
8630 (symbol (nth 1 list)))
8631 (and list
8632 (boundp symbol)
8633 (or (eq symbol t)
8634 (and (stringp (setq symbol (eval symbol)))
8635 (string-match-p (nth 2 list) symbol)))
8636 (display-warning package (nth 3 list) :warning)))
8637 (error nil)))
8638
8639 (dolist (elem bad-packages-alist)
8640 (let ((pkg (car elem)))
8641 (with-eval-after-load pkg
8642 (bad-package-check pkg))))
8643
8644 \f
8645 ;;; Generic dispatcher commands
8646
8647 ;; Macro `define-alternatives' is used to create generic commands.
8648 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8649 ;; that can have different alternative implementations where choosing
8650 ;; among them is exclusively a matter of user preference.
8651
8652 ;; (define-alternatives COMMAND) creates a new interactive command
8653 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8654 ;; Typically, the user will not need to customize this variable; packages
8655 ;; wanting to add alternative implementations should use
8656 ;;
8657 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8658
8659 (defmacro define-alternatives (command &rest customizations)
8660 "Define the new command `COMMAND'.
8661
8662 The argument `COMMAND' should be a symbol.
8663
8664 Running `M-x COMMAND RET' for the first time prompts for which
8665 alternative to use and records the selected command as a custom
8666 variable.
8667
8668 Running `C-u M-x COMMAND RET' prompts again for an alternative
8669 and overwrites the previous choice.
8670
8671 The variable `COMMAND-alternatives' contains an alist with
8672 alternative implementations of COMMAND. `define-alternatives'
8673 does not have any effect until this variable is set.
8674
8675 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8676 `defcustom' keywords and values to add to the declaration of
8677 `COMMAND-alternatives' (typically :group and :version)."
8678 (let* ((command-name (symbol-name command))
8679 (varalt-name (concat command-name "-alternatives"))
8680 (varalt-sym (intern varalt-name))
8681 (varimp-sym (intern (concat command-name "--implementation"))))
8682 `(progn
8683
8684 (defcustom ,varalt-sym nil
8685 ,(format "Alist of alternative implementations for the `%s' command.
8686
8687 Each entry must be a pair (ALTNAME . ALTFUN), where:
8688 ALTNAME - The name shown at user to describe the alternative implementation.
8689 ALTFUN - The function called to implement this alternative."
8690 command-name)
8691 :type '(alist :key-type string :value-type function)
8692 ,@customizations)
8693
8694 (put ',varalt-sym 'definition-name ',command)
8695 (defvar ,varimp-sym nil "Internal use only.")
8696
8697 (defun ,command (&optional arg)
8698 ,(format "Run generic command `%s'.
8699 If used for the first time, or with interactive ARG, ask the user which
8700 implementation to use for `%s'. The variable `%s'
8701 contains the list of implementations currently supported for this command."
8702 command-name command-name varalt-name)
8703 (interactive "P")
8704 (when (or arg (null ,varimp-sym))
8705 (let ((val (completing-read
8706 ,(format-message
8707 "Select implementation for command `%s': "
8708 command-name)
8709 ,varalt-sym nil t)))
8710 (unless (string-equal val "")
8711 (when (null ,varimp-sym)
8712 (message
8713 "Use C-u M-x %s RET`to select another implementation"
8714 ,command-name)
8715 (sit-for 3))
8716 (customize-save-variable ',varimp-sym
8717 (cdr (assoc-string val ,varalt-sym))))))
8718 (if ,varimp-sym
8719 (call-interactively ,varimp-sym)
8720 (message "%s" ,(format-message
8721 "No implementation selected for command `%s'"
8722 command-name)))))))
8723
8724 \f
8725 ;;; Functions for changing capitalization that Do What I Mean
8726 (defun upcase-dwim (arg)
8727 "Upcase words in the region, if active; if not, upcase word at point.
8728 If the region is active, this function calls `upcase-region'.
8729 Otherwise, it calls `upcase-word', with prefix argument passed to it
8730 to upcase ARG words."
8731 (interactive "*p")
8732 (if (use-region-p)
8733 (upcase-region (region-beginning) (region-end))
8734 (upcase-word arg)))
8735
8736 (defun downcase-dwim (arg)
8737 "Downcase words in the region, if active; if not, downcase word at point.
8738 If the region is active, this function calls `downcase-region'.
8739 Otherwise, it calls `downcase-word', with prefix argument passed to it
8740 to downcase ARG words."
8741 (interactive "*p")
8742 (if (use-region-p)
8743 (downcase-region (region-beginning) (region-end))
8744 (downcase-word arg)))
8745
8746 (defun capitalize-dwim (arg)
8747 "Capitalize words in the region, if active; if not, capitalize word at point.
8748 If the region is active, this function calls `capitalize-region'.
8749 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8750 to capitalize ARG words."
8751 (interactive "*p")
8752 (if (use-region-p)
8753 (capitalize-region (region-beginning) (region-end))
8754 (capitalize-word arg)))
8755
8756 \f
8757
8758 (provide 'simple)
8759
8760 ;;; simple.el ends here