Fix URL cookie expiration bug
[emacs.git] / lisp / simple.el
blob4db81071b589ec160d80bb47f94826b21ad951d3
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2017 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
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.
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
40 (defcustom shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value sets the point in the output buffer
43 once the command completes.
44 The value `beg-last-out' sets point at the beginning of the output,
45 `end-last-out' sets point at the end of the buffer, `save-point'
46 restores the buffer position before the command."
47 :type '(choice
48 (const :tag "Erase buffer" nil)
49 (const :tag "Set point to beginning of last output" beg-last-out)
50 (const :tag "Set point to end of last output" end-last-out)
51 (const :tag "Save point" save-point))
52 :group 'shell
53 :version "26.1")
55 (defvar shell-command-saved-pos nil
56 "Record of point positions in output buffers after command completion.
57 The value is an alist whose elements are of the form (BUFFER . POS),
58 where BUFFER is the output buffer, and POS is the point position
59 in BUFFER once the command finishes.
60 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
62 (defcustom idle-update-delay 0.5
63 "Idle time delay before updating various things on the screen.
64 Various Emacs features that update auxiliary information when point moves
65 wait this many seconds after Emacs becomes idle before doing an update."
66 :type 'number
67 :group 'display
68 :version "22.1")
70 (defgroup killing nil
71 "Killing and yanking commands."
72 :group 'editing)
74 (defgroup paren-matching nil
75 "Highlight (un)matching of parens and expressions."
76 :group 'matching)
78 ;;; next-error support framework
80 (defgroup next-error nil
81 "`next-error' support framework."
82 :group 'compilation
83 :version "22.1")
85 (defface next-error
86 '((t (:inherit region)))
87 "Face used to highlight next error locus."
88 :group 'next-error
89 :version "22.1")
91 (defcustom next-error-highlight 0.5
92 "Highlighting of locations in selected source buffers.
93 If a number, highlight the locus in `next-error' face for the given time
94 in seconds, or until the next command is executed.
95 If t, highlight the locus until the next command is executed, or until
96 some other locus replaces it.
97 If nil, don't highlight the locus in the source buffer.
98 If `fringe-arrow', indicate the locus by the fringe arrow
99 indefinitely until some other locus replaces it."
100 :type '(choice (number :tag "Highlight for specified time")
101 (const :tag "Semipermanent highlighting" t)
102 (const :tag "No highlighting" nil)
103 (const :tag "Fringe arrow" fringe-arrow))
104 :group 'next-error
105 :version "22.1")
107 (defcustom next-error-highlight-no-select 0.5
108 "Highlighting of locations in `next-error-no-select'.
109 If number, highlight the locus in `next-error' face for given time in seconds.
110 If t, highlight the locus indefinitely until some other locus replaces it.
111 If nil, don't highlight the locus in the source buffer.
112 If `fringe-arrow', indicate the locus by the fringe arrow
113 indefinitely until some other locus replaces it."
114 :type '(choice (number :tag "Highlight for specified time")
115 (const :tag "Semipermanent highlighting" t)
116 (const :tag "No highlighting" nil)
117 (const :tag "Fringe arrow" fringe-arrow))
118 :group 'next-error
119 :version "22.1")
121 (defcustom next-error-recenter nil
122 "Display the line in the visited source file recentered as specified.
123 If non-nil, the value is passed directly to `recenter'."
124 :type '(choice (integer :tag "Line to recenter to")
125 (const :tag "Center of window" (4))
126 (const :tag "No recentering" nil))
127 :group 'next-error
128 :version "23.1")
130 (defcustom next-error-hook nil
131 "List of hook functions run by `next-error' after visiting source file."
132 :type 'hook
133 :group 'next-error)
135 (defvar next-error-highlight-timer nil)
137 (defvar next-error-overlay-arrow-position nil)
138 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
139 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
141 (defvar next-error-last-buffer nil
142 "The most recent `next-error' buffer.
143 A buffer becomes most recent when its compilation, grep, or
144 similar mode is started, or when it is used with \\[next-error]
145 or \\[compile-goto-error].")
147 (defvar next-error-function nil
148 "Function to use to find the next error in the current buffer.
149 The function is called with 2 parameters:
150 ARG is an integer specifying by how many errors to move.
151 RESET is a boolean which, if non-nil, says to go back to the beginning
152 of the errors before moving.
153 Major modes providing compile-like functionality should set this variable
154 to indicate to `next-error' that this is a candidate buffer and how
155 to navigate in it.")
156 (make-variable-buffer-local 'next-error-function)
158 (defvar next-error-move-function nil
159 "Function to use to move to an error locus.
160 It takes two arguments, a buffer position in the error buffer
161 and a buffer position in the error locus buffer.
162 The buffer for the error locus should already be current.
163 nil means use goto-char using the second argument position.")
164 (make-variable-buffer-local 'next-error-move-function)
166 (defsubst next-error-buffer-p (buffer
167 &optional avoid-current
168 extra-test-inclusive
169 extra-test-exclusive)
170 "Return non-nil if BUFFER is a `next-error' capable buffer.
171 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
172 return nil.
174 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
175 BUFFER would not normally qualify. If it returns non-nil, BUFFER
176 is considered `next-error' capable, anyway, and the function
177 returns non-nil.
179 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
180 buffer would normally qualify. If it returns nil, BUFFER is
181 rejected, and the function returns nil."
182 (and (buffer-name buffer) ;First make sure it's live.
183 (not (and avoid-current (eq buffer (current-buffer))))
184 (with-current-buffer buffer
185 (if next-error-function ; This is the normal test.
186 ;; Optionally reject some buffers.
187 (if extra-test-exclusive
188 (funcall extra-test-exclusive)
190 ;; Optionally accept some other buffers.
191 (and extra-test-inclusive
192 (funcall extra-test-inclusive))))))
194 (defun next-error-find-buffer (&optional avoid-current
195 extra-test-inclusive
196 extra-test-exclusive)
197 "Return a `next-error' capable buffer.
199 If AVOID-CURRENT is non-nil, treat the current buffer
200 as an absolute last resort only.
202 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
203 that normally would not qualify. If it returns t, the buffer
204 in question is treated as usable.
206 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
207 that would normally be considered usable. If it returns nil,
208 that buffer is rejected."
210 ;; 1. If one window on the selected frame displays such buffer, return it.
211 (let ((window-buffers
212 (delete-dups
213 (delq nil (mapcar (lambda (w)
214 (if (next-error-buffer-p
215 (window-buffer w)
216 avoid-current
217 extra-test-inclusive extra-test-exclusive)
218 (window-buffer w)))
219 (window-list))))))
220 (if (eq (length window-buffers) 1)
221 (car window-buffers)))
222 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
223 (if (and next-error-last-buffer
224 (next-error-buffer-p next-error-last-buffer avoid-current
225 extra-test-inclusive extra-test-exclusive))
226 next-error-last-buffer)
227 ;; 3. If the current buffer is acceptable, choose it.
228 (if (next-error-buffer-p (current-buffer) avoid-current
229 extra-test-inclusive extra-test-exclusive)
230 (current-buffer))
231 ;; 4. Look for any acceptable buffer.
232 (let ((buffers (buffer-list)))
233 (while (and buffers
234 (not (next-error-buffer-p
235 (car buffers) avoid-current
236 extra-test-inclusive extra-test-exclusive)))
237 (setq buffers (cdr buffers)))
238 (car buffers))
239 ;; 5. Use the current buffer as a last resort if it qualifies,
240 ;; even despite AVOID-CURRENT.
241 (and avoid-current
242 (next-error-buffer-p (current-buffer) nil
243 extra-test-inclusive extra-test-exclusive)
244 (progn
245 (message "This is the only buffer with error message locations")
246 (current-buffer)))
247 ;; 6. Give up.
248 (error "No buffers contain error message locations")))
250 (defun next-error (&optional arg reset)
251 "Visit next `next-error' message and corresponding source code.
253 If all the error messages parsed so far have been processed already,
254 the message buffer is checked for new ones.
256 A prefix ARG specifies how many error messages to move;
257 negative means move back to previous error messages.
258 Just \\[universal-argument] as a prefix means reparse the error message buffer
259 and start at the first error.
261 The RESET argument specifies that we should restart from the beginning.
263 \\[next-error] normally uses the most recently started
264 compilation, grep, or occur buffer. It can also operate on any
265 buffer with output from the \\[compile], \\[grep] commands, or,
266 more generally, on any buffer in Compilation mode or with
267 Compilation Minor mode enabled, or any buffer in which
268 `next-error-function' is bound to an appropriate function.
269 To specify use of a particular buffer for error messages, type
270 \\[next-error] in that buffer when it is the only one displayed
271 in the current frame.
273 Once \\[next-error] has chosen the buffer for error messages, it
274 runs `next-error-hook' with `run-hooks', and stays with that buffer
275 until you use it in some other buffer which uses Compilation mode
276 or Compilation Minor mode.
278 To control which errors are matched, customize the variable
279 `compilation-error-regexp-alist'."
280 (interactive "P")
281 (if (consp arg) (setq reset t arg nil))
282 (when (setq next-error-last-buffer (next-error-find-buffer))
283 ;; we know here that next-error-function is a valid symbol we can funcall
284 (with-current-buffer next-error-last-buffer
285 (funcall next-error-function (prefix-numeric-value arg) reset)
286 (when next-error-recenter
287 (recenter next-error-recenter))
288 (run-hooks 'next-error-hook))))
290 (defun next-error-internal ()
291 "Visit the source code corresponding to the `next-error' message at point."
292 (setq next-error-last-buffer (current-buffer))
293 ;; we know here that next-error-function is a valid symbol we can funcall
294 (with-current-buffer next-error-last-buffer
295 (funcall next-error-function 0 nil)
296 (when next-error-recenter
297 (recenter next-error-recenter))
298 (run-hooks 'next-error-hook)))
300 (defalias 'goto-next-locus 'next-error)
301 (defalias 'next-match 'next-error)
303 (defun previous-error (&optional n)
304 "Visit previous `next-error' message and corresponding source code.
306 Prefix arg N says how many error messages to move backwards (or
307 forwards, if negative).
309 This operates on the output from the \\[compile] and \\[grep] commands."
310 (interactive "p")
311 (next-error (- (or n 1))))
313 (defun first-error (&optional n)
314 "Restart at the first error.
315 Visit corresponding source code.
316 With prefix arg N, visit the source code of the Nth error.
317 This operates on the output from the \\[compile] command, for instance."
318 (interactive "p")
319 (next-error n t))
321 (defun next-error-no-select (&optional n)
322 "Move point to the next error in the `next-error' buffer and highlight match.
323 Prefix arg N says how many error messages to move forwards (or
324 backwards, if negative).
325 Finds and highlights the source line like \\[next-error], but does not
326 select the source buffer."
327 (interactive "p")
328 (let ((next-error-highlight next-error-highlight-no-select))
329 (next-error n))
330 (pop-to-buffer next-error-last-buffer))
332 (defun previous-error-no-select (&optional n)
333 "Move point to the previous error in the `next-error' buffer and highlight match.
334 Prefix arg N says how many error messages to move backwards (or
335 forwards, if negative).
336 Finds and highlights the source line like \\[previous-error], but does not
337 select the source buffer."
338 (interactive "p")
339 (next-error-no-select (- (or n 1))))
341 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
342 (defvar next-error-follow-last-line nil)
344 (define-minor-mode next-error-follow-minor-mode
345 "Minor mode for compilation, occur and diff modes.
346 With a prefix argument ARG, enable mode if ARG is positive, and
347 disable it otherwise. If called from Lisp, enable mode if ARG is
348 omitted or nil.
349 When turned on, cursor motion in the compilation, grep, occur or diff
350 buffer causes automatic display of the corresponding source code location."
351 :group 'next-error :init-value nil :lighter " Fol"
352 (if (not next-error-follow-minor-mode)
353 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
354 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
355 (make-local-variable 'next-error-follow-last-line)))
357 ;; Used as a `post-command-hook' by `next-error-follow-mode'
358 ;; for the *Compilation* *grep* and *Occur* buffers.
359 (defun next-error-follow-mode-post-command-hook ()
360 (unless (equal next-error-follow-last-line (line-number-at-pos))
361 (setq next-error-follow-last-line (line-number-at-pos))
362 (condition-case nil
363 (let ((compilation-context-lines nil))
364 (setq compilation-current-error (point))
365 (next-error-no-select 0))
366 (error t))))
371 (defun fundamental-mode ()
372 "Major mode not specialized for anything in particular.
373 Other major modes are defined by comparison with this one."
374 (interactive)
375 (kill-all-local-variables)
376 (run-mode-hooks))
378 ;; Special major modes to view specially formatted data rather than files.
380 (defvar special-mode-map
381 (let ((map (make-sparse-keymap)))
382 (suppress-keymap map)
383 (define-key map "q" 'quit-window)
384 (define-key map " " 'scroll-up-command)
385 (define-key map [?\S-\ ] 'scroll-down-command)
386 (define-key map "\C-?" 'scroll-down-command)
387 (define-key map "?" 'describe-mode)
388 (define-key map "h" 'describe-mode)
389 (define-key map ">" 'end-of-buffer)
390 (define-key map "<" 'beginning-of-buffer)
391 (define-key map "g" 'revert-buffer)
392 map))
394 (put 'special-mode 'mode-class 'special)
395 (define-derived-mode special-mode nil "Special"
396 "Parent major mode from which special major modes should inherit."
397 (setq buffer-read-only t))
399 ;; Making and deleting lines.
401 (defvar self-insert-uses-region-functions nil
402 "Special hook to tell if `self-insert-command' will use the region.
403 It must be called via `run-hook-with-args-until-success' with no arguments.
404 Any `post-self-insert-command' which consumes the region should
405 register a function on this hook so that things like `delete-selection-mode'
406 can refrain from consuming the region.")
408 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
409 "Propertized string representing a hard newline character.")
411 (defun newline (&optional arg interactive)
412 "Insert a newline, and move to left margin of the new line if it's blank.
413 If option `use-hard-newlines' is non-nil, the newline is marked with the
414 text-property `hard'.
415 With ARG, insert that many newlines.
417 If `electric-indent-mode' is enabled, this indents the final new line
418 that it adds, and reindents the preceding line. To just insert
419 a newline, use \\[electric-indent-just-newline].
421 Calls `auto-fill-function' if the current column number is greater
422 than the value of `fill-column' and ARG is nil.
423 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
424 (interactive "*P\np")
425 (barf-if-buffer-read-only)
426 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
427 ;; Set last-command-event to tell self-insert what to insert.
428 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
429 (beforepos (point))
430 (last-command-event ?\n)
431 ;; Don't auto-fill if we have a numeric argument.
432 (auto-fill-function (if arg nil auto-fill-function))
433 (arg (prefix-numeric-value arg))
434 (postproc
435 ;; Do the rest in post-self-insert-hook, because we want to do it
436 ;; *before* other functions on that hook.
437 (lambda ()
438 ;; Mark the newline(s) `hard'.
439 (if use-hard-newlines
440 (set-hard-newline-properties
441 (- (point) arg) (point)))
442 ;; If the newline leaves the previous line blank, and we
443 ;; have a left margin, delete that from the blank line.
444 (save-excursion
445 (goto-char beforepos)
446 (beginning-of-line)
447 (and (looking-at "[ \t]$")
448 (> (current-left-margin) 0)
449 (delete-region (point)
450 (line-end-position))))
451 ;; Indent the line after the newline, except in one case:
452 ;; when we added the newline at the beginning of a line which
453 ;; starts a page.
454 (or was-page-start
455 (move-to-left-margin nil t)))))
456 (if (not interactive)
457 ;; FIXME: For non-interactive uses, many calls actually
458 ;; just want (insert "\n"), so maybe we should do just
459 ;; that, so as to avoid the risk of filling or running
460 ;; abbrevs unexpectedly.
461 (let ((post-self-insert-hook (list postproc)))
462 (self-insert-command arg))
463 (unwind-protect
464 (progn
465 (add-hook 'post-self-insert-hook postproc nil t)
466 (self-insert-command arg))
467 ;; We first used let-binding to protect the hook, but that
468 ;; was naive since add-hook affects the symbol-default
469 ;; value of the variable, whereas the let-binding might
470 ;; only protect the buffer-local value.
471 (remove-hook 'post-self-insert-hook postproc t))))
472 nil)
474 (defun set-hard-newline-properties (from to)
475 (let ((sticky (get-text-property from 'rear-nonsticky)))
476 (put-text-property from to 'hard 't)
477 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
478 (if (and (listp sticky) (not (memq 'hard sticky)))
479 (put-text-property from (point) 'rear-nonsticky
480 (cons 'hard sticky)))))
482 (defun open-line (n)
483 "Insert a newline and leave point before it.
484 If there is a fill prefix and/or a `left-margin', insert them on
485 the new line if the line would have been blank.
486 With arg N, insert N newlines."
487 (interactive "*p")
488 (let* ((do-fill-prefix (and fill-prefix (bolp)))
489 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
490 (loc (point-marker))
491 ;; Don't expand an abbrev before point.
492 (abbrev-mode nil))
493 (newline n)
494 (goto-char loc)
495 (while (> n 0)
496 (cond ((bolp)
497 (if do-left-margin (indent-to (current-left-margin)))
498 (if do-fill-prefix (insert-and-inherit fill-prefix))))
499 (forward-line 1)
500 (setq n (1- n)))
501 (goto-char loc)
502 ;; Necessary in case a margin or prefix was inserted.
503 (end-of-line)))
505 (defun split-line (&optional arg)
506 "Split current line, moving portion beyond point vertically down.
507 If the current line starts with `fill-prefix', insert it on the new
508 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
510 When called from Lisp code, ARG may be a prefix string to copy."
511 (interactive "*P")
512 (skip-chars-forward " \t")
513 (let* ((col (current-column))
514 (pos (point))
515 ;; What prefix should we check for (nil means don't).
516 (prefix (cond ((stringp arg) arg)
517 (arg nil)
518 (t fill-prefix)))
519 ;; Does this line start with it?
520 (have-prfx (and prefix
521 (save-excursion
522 (beginning-of-line)
523 (looking-at (regexp-quote prefix))))))
524 (newline 1)
525 (if have-prfx (insert-and-inherit prefix))
526 (indent-to col 0)
527 (goto-char pos)))
529 (defun delete-indentation (&optional arg)
530 "Join this line to previous and fix up whitespace at join.
531 If there is a fill prefix, delete it from the beginning of this line.
532 With argument, join this line to following line."
533 (interactive "*P")
534 (beginning-of-line)
535 (if arg (forward-line 1))
536 (if (eq (preceding-char) ?\n)
537 (progn
538 (delete-region (point) (1- (point)))
539 ;; If the second line started with the fill prefix,
540 ;; delete the prefix.
541 (if (and fill-prefix
542 (<= (+ (point) (length fill-prefix)) (point-max))
543 (string= fill-prefix
544 (buffer-substring (point)
545 (+ (point) (length fill-prefix)))))
546 (delete-region (point) (+ (point) (length fill-prefix))))
547 (fixup-whitespace))))
549 (defalias 'join-line #'delete-indentation) ; easier to find
551 (defun delete-blank-lines ()
552 "On blank line, delete all surrounding blank lines, leaving just one.
553 On isolated blank line, delete that one.
554 On nonblank line, delete any immediately following blank lines."
555 (interactive "*")
556 (let (thisblank singleblank)
557 (save-excursion
558 (beginning-of-line)
559 (setq thisblank (looking-at "[ \t]*$"))
560 ;; Set singleblank if there is just one blank line here.
561 (setq singleblank
562 (and thisblank
563 (not (looking-at "[ \t]*\n[ \t]*$"))
564 (or (bobp)
565 (progn (forward-line -1)
566 (not (looking-at "[ \t]*$")))))))
567 ;; Delete preceding blank lines, and this one too if it's the only one.
568 (if thisblank
569 (progn
570 (beginning-of-line)
571 (if singleblank (forward-line 1))
572 (delete-region (point)
573 (if (re-search-backward "[^ \t\n]" nil t)
574 (progn (forward-line 1) (point))
575 (point-min)))))
576 ;; Delete following blank lines, unless the current line is blank
577 ;; and there are no following blank lines.
578 (if (not (and thisblank singleblank))
579 (save-excursion
580 (end-of-line)
581 (forward-line 1)
582 (delete-region (point)
583 (if (re-search-forward "[^ \t\n]" nil t)
584 (progn (beginning-of-line) (point))
585 (point-max)))))
586 ;; Handle the special case where point is followed by newline and eob.
587 ;; Delete the line, leaving point at eob.
588 (if (looking-at "^[ \t]*\n\\'")
589 (delete-region (point) (point-max)))))
591 (defcustom delete-trailing-lines t
592 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
593 Trailing lines are deleted only if `delete-trailing-whitespace'
594 is called on the entire buffer (rather than an active region)."
595 :type 'boolean
596 :group 'editing
597 :version "24.3")
599 (defun region-modifiable-p (start end)
600 "Return non-nil if the region contains no read-only text."
601 (and (not (get-text-property start 'read-only))
602 (eq end (next-single-property-change start 'read-only nil end))))
604 (defun delete-trailing-whitespace (&optional start end)
605 "Delete trailing whitespace between START and END.
606 If called interactively, START and END are the start/end of the
607 region if the mark is active, or of the buffer's accessible
608 portion if the mark is inactive.
610 This command deletes whitespace characters after the last
611 non-whitespace character in each line between START and END. It
612 does not consider formfeed characters to be whitespace.
614 If this command acts on the entire buffer (i.e. if called
615 interactively with the mark inactive, or called from Lisp with
616 END nil), it also deletes all trailing lines at the end of the
617 buffer if the variable `delete-trailing-lines' is non-nil."
618 (interactive (progn
619 (barf-if-buffer-read-only)
620 (if (use-region-p)
621 (list (region-beginning) (region-end))
622 (list nil nil))))
623 (save-match-data
624 (save-excursion
625 (let ((end-marker (and end (copy-marker end))))
626 (goto-char (or start (point-min)))
627 (with-syntax-table (make-syntax-table (syntax-table))
628 ;; Don't delete formfeeds, even if they are considered whitespace.
629 (modify-syntax-entry ?\f "_")
630 (while (re-search-forward "\\s-$" end-marker t)
631 (skip-syntax-backward "-" (line-beginning-position))
632 (let ((b (point)) (e (match-end 0)))
633 (when (region-modifiable-p b e)
634 (delete-region b e)))))
635 (if end
636 (set-marker end-marker nil)
637 ;; Delete trailing empty lines.
638 (and delete-trailing-lines
639 ;; Really the end of buffer.
640 (= (goto-char (point-max)) (1+ (buffer-size)))
641 (<= (skip-chars-backward "\n") -2)
642 (region-modifiable-p (1+ (point)) (point-max))
643 (delete-region (1+ (point)) (point-max)))))))
644 ;; Return nil for the benefit of `write-file-functions'.
645 nil)
647 (defun newline-and-indent ()
648 "Insert a newline, then indent according to major mode.
649 Indentation is done using the value of `indent-line-function'.
650 In programming language modes, this is the same as TAB.
651 In some text modes, where TAB inserts a tab, this command indents to the
652 column specified by the function `current-left-margin'."
653 (interactive "*")
654 (delete-horizontal-space t)
655 (newline nil t)
656 (indent-according-to-mode))
658 (defun reindent-then-newline-and-indent ()
659 "Reindent current line, insert newline, then indent the new line.
660 Indentation of both lines is done according to the current major mode,
661 which means calling the current value of `indent-line-function'.
662 In programming language modes, this is the same as TAB.
663 In some text modes, where TAB inserts a tab, this indents to the
664 column specified by the function `current-left-margin'."
665 (interactive "*")
666 (let ((pos (point)))
667 ;; Be careful to insert the newline before indenting the line.
668 ;; Otherwise, the indentation might be wrong.
669 (newline)
670 (save-excursion
671 (goto-char pos)
672 ;; We are at EOL before the call to indent-according-to-mode, and
673 ;; after it we usually are as well, but not always. We tried to
674 ;; address it with `save-excursion' but that uses a normal marker
675 ;; whereas we need `move after insertion', so we do the save/restore
676 ;; by hand.
677 (setq pos (copy-marker pos t))
678 (indent-according-to-mode)
679 (goto-char pos)
680 ;; Remove the trailing white-space after indentation because
681 ;; indentation may introduce the whitespace.
682 (delete-horizontal-space t))
683 (indent-according-to-mode)))
685 (defcustom read-quoted-char-radix 8
686 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
687 Legitimate radix values are 8, 10 and 16."
688 :type '(choice (const 8) (const 10) (const 16))
689 :group 'editing-basics)
691 (defun read-quoted-char (&optional prompt)
692 "Like `read-char', but do not allow quitting.
693 Also, if the first character read is an octal digit,
694 we read any number of octal digits and return the
695 specified character code. Any nondigit terminates the sequence.
696 If the terminator is RET, it is discarded;
697 any other terminator is used itself as input.
699 The optional argument PROMPT specifies a string to use to prompt the user.
700 The variable `read-quoted-char-radix' controls which radix to use
701 for numeric input."
702 (let ((message-log-max nil)
703 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
704 help-event-list)))
705 done (first t) (code 0) char translated)
706 (while (not done)
707 (let ((inhibit-quit first)
708 ;; Don't let C-h or other help chars get the help
709 ;; message--only help function keys. See bug#16617.
710 (help-char nil)
711 (help-event-list help-events)
712 (help-form
713 "Type the special character you want to use,
714 or the octal character code.
715 RET terminates the character code and is discarded;
716 any other non-digit terminates the character code and is then used as input."))
717 (setq char (read-event (and prompt (format "%s-" prompt)) t))
718 (if inhibit-quit (setq quit-flag nil)))
719 ;; Translate TAB key into control-I ASCII character, and so on.
720 ;; Note: `read-char' does it using the `ascii-character' property.
721 ;; We tried using read-key instead, but that disables the keystroke
722 ;; echo produced by 'C-q', see bug#24635.
723 (let ((translation (lookup-key local-function-key-map (vector char))))
724 (setq translated (if (arrayp translation)
725 (aref translation 0)
726 char)))
727 (if (integerp translated)
728 (setq translated (char-resolve-modifiers translated)))
729 (cond ((null translated))
730 ((not (integerp translated))
731 (setq unread-command-events (list char)
732 done t))
733 ((/= (logand translated ?\M-\^@) 0)
734 ;; Turn a meta-character into a character with the 0200 bit set.
735 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
736 done t))
737 ((and (<= ?0 translated)
738 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
739 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
740 (and prompt (setq prompt (message "%s %c" prompt translated))))
741 ((and (<= ?a (downcase translated))
742 (< (downcase translated)
743 (+ ?a -10 (min 36 read-quoted-char-radix))))
744 (setq code (+ (* code read-quoted-char-radix)
745 (+ 10 (- (downcase translated) ?a))))
746 (and prompt (setq prompt (message "%s %c" prompt translated))))
747 ((and (not first) (eq translated ?\C-m))
748 (setq done t))
749 ((not first)
750 (setq unread-command-events (list char)
751 done t))
752 (t (setq code translated
753 done t)))
754 (setq first nil))
755 code))
757 (defun quoted-insert (arg)
758 "Read next input character and insert it.
759 This is useful for inserting control characters.
760 With argument, insert ARG copies of the character.
762 If the first character you type after this command is an octal digit,
763 you should type a sequence of octal digits which specify a character code.
764 Any nondigit terminates the sequence. If the terminator is a RET,
765 it is discarded; any other terminator is used itself as input.
766 The variable `read-quoted-char-radix' specifies the radix for this feature;
767 set it to 10 or 16 to use decimal or hex instead of octal.
769 In overwrite mode, this function inserts the character anyway, and
770 does not handle octal digits specially. This means that if you use
771 overwrite as your normal editing mode, you can use this function to
772 insert characters when necessary.
774 In binary overwrite mode, this function does overwrite, and octal
775 digits are interpreted as a character code. This is intended to be
776 useful for editing binary files."
777 (interactive "*p")
778 (let* ((char
779 ;; Avoid "obsolete" warnings for translation-table-for-input.
780 (with-no-warnings
781 (let (translation-table-for-input input-method-function)
782 (if (or (not overwrite-mode)
783 (eq overwrite-mode 'overwrite-mode-binary))
784 (read-quoted-char)
785 (read-char))))))
786 ;; This used to assume character codes 0240 - 0377 stand for
787 ;; characters in some single-byte character set, and converted them
788 ;; to Emacs characters. But in 23.1 this feature is deprecated
789 ;; in favor of inserting the corresponding Unicode characters.
790 ;; (if (and enable-multibyte-characters
791 ;; (>= char ?\240)
792 ;; (<= char ?\377))
793 ;; (setq char (unibyte-char-to-multibyte char)))
794 (unless (characterp char)
795 (user-error "%s is not a valid character"
796 (key-description (vector char))))
797 (if (> arg 0)
798 (if (eq overwrite-mode 'overwrite-mode-binary)
799 (delete-char arg)))
800 (while (> arg 0)
801 (insert-and-inherit char)
802 (setq arg (1- arg)))))
804 (defun forward-to-indentation (&optional arg)
805 "Move forward ARG lines and position at first nonblank character."
806 (interactive "^p")
807 (forward-line (or arg 1))
808 (skip-chars-forward " \t"))
810 (defun backward-to-indentation (&optional arg)
811 "Move backward ARG lines and position at first nonblank character."
812 (interactive "^p")
813 (forward-line (- (or arg 1)))
814 (skip-chars-forward " \t"))
816 (defun back-to-indentation ()
817 "Move point to the first non-whitespace character on this line."
818 (interactive "^")
819 (beginning-of-line 1)
820 (skip-syntax-forward " " (line-end-position))
821 ;; Move back over chars that have whitespace syntax but have the p flag.
822 (backward-prefix-chars))
824 (defun fixup-whitespace ()
825 "Fixup white space between objects around point.
826 Leave one space or none, according to the context."
827 (interactive "*")
828 (save-excursion
829 (delete-horizontal-space)
830 (if (or (looking-at "^\\|$\\|\\s)")
831 (save-excursion (forward-char -1)
832 (looking-at "$\\|\\s(\\|\\s'")))
834 (insert ?\s))))
836 (defun delete-horizontal-space (&optional backward-only)
837 "Delete all spaces and tabs around point.
838 If BACKWARD-ONLY is non-nil, only delete them before point."
839 (interactive "*P")
840 (let ((orig-pos (point)))
841 (delete-region
842 (if backward-only
843 orig-pos
844 (progn
845 (skip-chars-forward " \t")
846 (constrain-to-field nil orig-pos t)))
847 (progn
848 (skip-chars-backward " \t")
849 (constrain-to-field nil orig-pos)))))
851 (defun just-one-space (&optional n)
852 "Delete all spaces and tabs around point, leaving one space (or N spaces).
853 If N is negative, delete newlines as well, leaving -N spaces.
854 See also `cycle-spacing'."
855 (interactive "*p")
856 (cycle-spacing n nil 'single-shot))
858 (defvar cycle-spacing--context nil
859 "Store context used in consecutive calls to `cycle-spacing' command.
860 The first time `cycle-spacing' runs, it saves in this variable:
861 its N argument, the original point position, and the original spacing
862 around point.")
864 (defun cycle-spacing (&optional n preserve-nl-back mode)
865 "Manipulate whitespace around point in a smart way.
866 In interactive use, this function behaves differently in successive
867 consecutive calls.
869 The first call in a sequence acts like `just-one-space'.
870 It deletes all spaces and tabs around point, leaving one space
871 \(or N spaces). N is the prefix argument. If N is negative,
872 it deletes newlines as well, leaving -N spaces.
873 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
875 The second call in a sequence deletes all spaces.
877 The third call in a sequence restores the original whitespace (and point).
879 If MODE is `single-shot', it only performs the first step in the sequence.
880 If MODE is `fast' and the first step would not result in any change
881 \(i.e., there are exactly (abs N) spaces around point),
882 the function goes straight to the second step.
884 Repeatedly calling the function with different values of N starts a
885 new sequence each time."
886 (interactive "*p")
887 (let ((orig-pos (point))
888 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
889 (num (abs (or n 1))))
890 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
891 (constrain-to-field nil orig-pos)
892 (cond
893 ;; Command run for the first time, single-shot mode or different argument
894 ((or (eq 'single-shot mode)
895 (not (equal last-command this-command))
896 (not cycle-spacing--context)
897 (not (eq (car cycle-spacing--context) n)))
898 (let* ((start (point))
899 (num (- num (skip-chars-forward " " (+ num (point)))))
900 (mid (point))
901 (end (progn
902 (skip-chars-forward skip-characters)
903 (constrain-to-field nil orig-pos t))))
904 (setq cycle-spacing--context ;; Save for later.
905 ;; Special handling for case where there was no space at all.
906 (unless (= start end)
907 (cons n (cons orig-pos (buffer-substring start (point))))))
908 ;; If this run causes no change in buffer content, delete all spaces,
909 ;; otherwise delete all excess spaces.
910 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
911 start mid) end)
912 (insert (make-string num ?\s))))
914 ;; Command run for the second time.
915 ((not (equal orig-pos (point)))
916 (delete-region (point) orig-pos))
918 ;; Command run for the third time.
920 (insert (cddr cycle-spacing--context))
921 (goto-char (cadr cycle-spacing--context))
922 (setq cycle-spacing--context nil)))))
924 (defun beginning-of-buffer (&optional arg)
925 "Move point to the beginning of the buffer.
926 With numeric arg N, put point N/10 of the way from the beginning.
927 If the buffer is narrowed, this command uses the beginning of the
928 accessible part of the buffer.
930 Push mark at previous position, unless either a \\[universal-argument] prefix
931 is supplied, or Transient Mark mode is enabled and the mark is active."
932 (declare (interactive-only "use `(goto-char (point-min))' instead."))
933 (interactive "^P")
934 (or (consp arg)
935 (region-active-p)
936 (push-mark))
937 (let ((size (- (point-max) (point-min))))
938 (goto-char (if (and arg (not (consp arg)))
939 (+ (point-min)
940 (if (> size 10000)
941 ;; Avoid overflow for large buffer sizes!
942 (* (prefix-numeric-value arg)
943 (/ size 10))
944 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
945 (point-min))))
946 (if (and arg (not (consp arg))) (forward-line 1)))
948 (defun end-of-buffer (&optional arg)
949 "Move point to the end of the buffer.
950 With numeric arg N, put point N/10 of the way from the end.
951 If the buffer is narrowed, this command uses the end of the
952 accessible part of the buffer.
954 Push mark at previous position, unless either a \\[universal-argument] prefix
955 is supplied, or Transient Mark mode is enabled and the mark is active."
956 (declare (interactive-only "use `(goto-char (point-max))' instead."))
957 (interactive "^P")
958 (or (consp arg) (region-active-p) (push-mark))
959 (let ((size (- (point-max) (point-min))))
960 (goto-char (if (and arg (not (consp arg)))
961 (- (point-max)
962 (if (> size 10000)
963 ;; Avoid overflow for large buffer sizes!
964 (* (prefix-numeric-value arg)
965 (/ size 10))
966 (/ (* size (prefix-numeric-value arg)) 10)))
967 (point-max))))
968 ;; If we went to a place in the middle of the buffer,
969 ;; adjust it to the beginning of a line.
970 (cond ((and arg (not (consp arg))) (forward-line 1))
971 ((and (eq (current-buffer) (window-buffer))
972 (> (point) (window-end nil t)))
973 ;; If the end of the buffer is not already on the screen,
974 ;; then scroll specially to put it near, but not at, the bottom.
975 (overlay-recenter (point))
976 (recenter -3))))
978 (defcustom delete-active-region t
979 "Whether single-char deletion commands delete an active region.
980 This has an effect only if Transient Mark mode is enabled, and
981 affects `delete-forward-char' and `delete-backward-char', though
982 not `delete-char'.
984 If the value is the symbol `kill', the active region is killed
985 instead of deleted."
986 :type '(choice (const :tag "Delete active region" t)
987 (const :tag "Kill active region" kill)
988 (const :tag "Do ordinary deletion" nil))
989 :group 'killing
990 :version "24.1")
992 (defvar region-extract-function
993 (lambda (method)
994 (when (region-beginning)
995 (cond
996 ((eq method 'bounds)
997 (list (cons (region-beginning) (region-end))))
998 ((eq method 'delete-only)
999 (delete-region (region-beginning) (region-end)))
1001 (filter-buffer-substring (region-beginning) (region-end) method)))))
1002 "Function to get the region's content.
1003 Called with one argument METHOD.
1004 If METHOD is `delete-only', then delete the region; the return value
1005 is undefined. If METHOD is nil, then return the content as a string.
1006 If METHOD is `bounds', then return the boundaries of the region
1007 as a list of cons cells of the form (START . END).
1008 If METHOD is anything else, delete the region and return its content
1009 as a string, after filtering it with `filter-buffer-substring', which
1010 is called with METHOD as its 3rd argument.")
1012 (defvar region-insert-function
1013 (lambda (lines)
1014 (let ((first t))
1015 (while lines
1016 (or first
1017 (insert ?\n))
1018 (insert-for-yank (car lines))
1019 (setq lines (cdr lines)
1020 first nil))))
1021 "Function to insert the region's content.
1022 Called with one argument LINES.
1023 Insert the region as a list of lines.")
1025 (defun delete-backward-char (n &optional killflag)
1026 "Delete the previous N characters (following if N is negative).
1027 If Transient Mark mode is enabled, the mark is active, and N is 1,
1028 delete the text in the region and deactivate the mark instead.
1029 To disable this, set option `delete-active-region' to nil.
1031 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1032 kill ring) instead of delete. Interactively, N is the prefix
1033 arg, and KILLFLAG is set if N is explicitly specified.
1035 When killing, the killed text is filtered by
1036 `filter-buffer-substring' before it is saved in the kill ring, so
1037 the actual saved text might be different from what was killed.
1039 In Overwrite mode, single character backward deletion may replace
1040 tabs with spaces so as to back over columns, unless point is at
1041 the end of the line."
1042 (declare (interactive-only delete-char))
1043 (interactive "p\nP")
1044 (unless (integerp n)
1045 (signal 'wrong-type-argument (list 'integerp n)))
1046 (cond ((and (use-region-p)
1047 delete-active-region
1048 (= n 1))
1049 ;; If a region is active, kill or delete it.
1050 (if (eq delete-active-region 'kill)
1051 (kill-region (region-beginning) (region-end) 'region)
1052 (funcall region-extract-function 'delete-only)))
1053 ;; In Overwrite mode, maybe untabify while deleting
1054 ((null (or (null overwrite-mode)
1055 (<= n 0)
1056 (memq (char-before) '(?\t ?\n))
1057 (eobp)
1058 (eq (char-after) ?\n)))
1059 (let ((ocol (current-column)))
1060 (delete-char (- n) killflag)
1061 (save-excursion
1062 (insert-char ?\s (- ocol (current-column)) nil))))
1063 ;; Otherwise, do simple deletion.
1064 (t (delete-char (- n) killflag))))
1066 (defun delete-forward-char (n &optional killflag)
1067 "Delete the following N characters (previous if N is negative).
1068 If Transient Mark mode is enabled, the mark is active, and N is 1,
1069 delete the text in the region and deactivate the mark instead.
1070 To disable this, set variable `delete-active-region' to nil.
1072 Optional second arg KILLFLAG non-nil means to kill (save in kill
1073 ring) instead of delete. Interactively, N is the prefix arg, and
1074 KILLFLAG is set if N was explicitly specified.
1076 When killing, the killed text is filtered by
1077 `filter-buffer-substring' before it is saved in the kill ring, so
1078 the actual saved text might be different from what was killed."
1079 (declare (interactive-only delete-char))
1080 (interactive "p\nP")
1081 (unless (integerp n)
1082 (signal 'wrong-type-argument (list 'integerp n)))
1083 (cond ((and (use-region-p)
1084 delete-active-region
1085 (= n 1))
1086 ;; If a region is active, kill or delete it.
1087 (if (eq delete-active-region 'kill)
1088 (kill-region (region-beginning) (region-end) 'region)
1089 (funcall region-extract-function 'delete-only)))
1091 ;; Otherwise, do simple deletion.
1092 (t (delete-char n killflag))))
1094 (defun mark-whole-buffer ()
1095 "Put point at beginning and mark at end of buffer.
1096 If narrowing is in effect, only uses the accessible part of the buffer.
1097 You probably should not use this function in Lisp programs;
1098 it is usually a mistake for a Lisp function to use any subroutine
1099 that uses or sets the mark."
1100 (declare (interactive-only t))
1101 (interactive)
1102 (push-mark)
1103 (push-mark (point-max) nil t)
1104 ;; This is really `point-min' in most cases, but if we're in the
1105 ;; minibuffer, this is at the end of the prompt.
1106 (goto-char (minibuffer-prompt-end)))
1109 ;; Counting lines, one way or another.
1111 (defun goto-line (line &optional buffer)
1112 "Go to LINE, counting from line 1 at beginning of buffer.
1113 If called interactively, a numeric prefix argument specifies
1114 LINE; without a numeric prefix argument, read LINE from the
1115 minibuffer.
1117 If optional argument BUFFER is non-nil, switch to that buffer and
1118 move to line LINE there. If called interactively with \\[universal-argument]
1119 as argument, BUFFER is the most recently selected other buffer.
1121 Prior to moving point, this function sets the mark (without
1122 activating it), unless Transient Mark mode is enabled and the
1123 mark is already active.
1125 This function is usually the wrong thing to use in a Lisp program.
1126 What you probably want instead is something like:
1127 (goto-char (point-min))
1128 (forward-line (1- N))
1129 If at all possible, an even better solution is to use char counts
1130 rather than line counts."
1131 (declare (interactive-only forward-line))
1132 (interactive
1133 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1134 (list (prefix-numeric-value current-prefix-arg))
1135 ;; Look for a default, a number in the buffer at point.
1136 (let* ((default
1137 (save-excursion
1138 (skip-chars-backward "0-9")
1139 (if (looking-at "[0-9]")
1140 (string-to-number
1141 (buffer-substring-no-properties
1142 (point)
1143 (progn (skip-chars-forward "0-9")
1144 (point)))))))
1145 ;; Decide if we're switching buffers.
1146 (buffer
1147 (if (consp current-prefix-arg)
1148 (other-buffer (current-buffer) t)))
1149 (buffer-prompt
1150 (if buffer
1151 (concat " in " (buffer-name buffer))
1152 "")))
1153 ;; Read the argument, offering that number (if any) as default.
1154 (list (read-number (format "Goto line%s: " buffer-prompt)
1155 (list default (line-number-at-pos)))
1156 buffer))))
1157 ;; Switch to the desired buffer, one way or another.
1158 (if buffer
1159 (let ((window (get-buffer-window buffer)))
1160 (if window (select-window window)
1161 (switch-to-buffer-other-window buffer))))
1162 ;; Leave mark at previous position
1163 (or (region-active-p) (push-mark))
1164 ;; Move to the specified line number in that buffer.
1165 (save-restriction
1166 (widen)
1167 (goto-char (point-min))
1168 (if (eq selective-display t)
1169 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1170 (forward-line (1- line)))))
1172 (defun count-words-region (start end &optional arg)
1173 "Count the number of words in the region.
1174 If called interactively, print a message reporting the number of
1175 lines, words, and characters in the region (whether or not the
1176 region is active); with prefix ARG, report for the entire buffer
1177 rather than the region.
1179 If called from Lisp, return the number of words between positions
1180 START and END."
1181 (interactive (if current-prefix-arg
1182 (list nil nil current-prefix-arg)
1183 (list (region-beginning) (region-end) nil)))
1184 (cond ((not (called-interactively-p 'any))
1185 (count-words start end))
1186 (arg
1187 (count-words--buffer-message))
1189 (count-words--message "Region" start end))))
1191 (defun count-words (start end)
1192 "Count words between START and END.
1193 If called interactively, START and END are normally the start and
1194 end of the buffer; but if the region is active, START and END are
1195 the start and end of the region. Print a message reporting the
1196 number of lines, words, and chars.
1198 If called from Lisp, return the number of words between START and
1199 END, without printing any message."
1200 (interactive (list nil nil))
1201 (cond ((not (called-interactively-p 'any))
1202 (let ((words 0))
1203 (save-excursion
1204 (save-restriction
1205 (narrow-to-region start end)
1206 (goto-char (point-min))
1207 (while (forward-word-strictly 1)
1208 (setq words (1+ words)))))
1209 words))
1210 ((use-region-p)
1211 (call-interactively 'count-words-region))
1213 (count-words--buffer-message))))
1215 (defun count-words--buffer-message ()
1216 (count-words--message
1217 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1218 (point-min) (point-max)))
1220 (defun count-words--message (str start end)
1221 (let ((lines (count-lines start end))
1222 (words (count-words start end))
1223 (chars (- end start)))
1224 (message "%s has %d line%s, %d word%s, and %d character%s."
1226 lines (if (= lines 1) "" "s")
1227 words (if (= words 1) "" "s")
1228 chars (if (= chars 1) "" "s"))))
1230 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1232 (defun what-line ()
1233 "Print the current buffer line number and narrowed line number of point."
1234 (interactive)
1235 (let ((start (point-min))
1236 (n (line-number-at-pos)))
1237 (if (= start 1)
1238 (message "Line %d" n)
1239 (save-excursion
1240 (save-restriction
1241 (widen)
1242 (message "line %d (narrowed line %d)"
1243 (+ n (line-number-at-pos start) -1) n))))))
1245 (defun count-lines (start end)
1246 "Return number of lines between START and END.
1247 This is usually the number of newlines between them,
1248 but can be one more if START is not equal to END
1249 and the greater of them is not at the start of a line."
1250 (save-excursion
1251 (save-restriction
1252 (narrow-to-region start end)
1253 (goto-char (point-min))
1254 (if (eq selective-display t)
1255 (save-match-data
1256 (let ((done 0))
1257 (while (re-search-forward "[\n\C-m]" nil t 40)
1258 (setq done (+ 40 done)))
1259 (while (re-search-forward "[\n\C-m]" nil t 1)
1260 (setq done (+ 1 done)))
1261 (goto-char (point-max))
1262 (if (and (/= start end)
1263 (not (bolp)))
1264 (1+ done)
1265 done)))
1266 (- (buffer-size) (forward-line (buffer-size)))))))
1268 (defun line-number-at-pos (&optional pos absolute)
1269 "Return buffer line number at position POS.
1270 If POS is nil, use current buffer location.
1272 If ABSOLUTE is nil, the default, counting starts
1273 at (point-min), so the value refers to the contents of the
1274 accessible portion of the (potentially narrowed) buffer. If
1275 ABSOLUTE is non-nil, ignore any narrowing and return the
1276 absolute line number."
1277 (save-restriction
1278 (when absolute
1279 (widen))
1280 (let ((opoint (or pos (point))) start)
1281 (save-excursion
1282 (goto-char (point-min))
1283 (setq start (point))
1284 (goto-char opoint)
1285 (forward-line 0)
1286 (1+ (count-lines start (point)))))))
1288 (defun what-cursor-position (&optional detail)
1289 "Print info on cursor position (on screen and within buffer).
1290 Also describe the character after point, and give its character code
1291 in octal, decimal and hex.
1293 For a non-ASCII multibyte character, also give its encoding in the
1294 buffer's selected coding system if the coding system encodes the
1295 character safely. If the character is encoded into one byte, that
1296 code is shown in hex. If the character is encoded into more than one
1297 byte, just \"...\" is shown.
1299 In addition, with prefix argument, show details about that character
1300 in *Help* buffer. See also the command `describe-char'."
1301 (interactive "P")
1302 (let* ((char (following-char))
1303 (bidi-fixer
1304 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1305 ;; start a directional embedding, which could completely
1306 ;; disrupt the rest of the line (e.g., RLO will display the
1307 ;; rest of the line right-to-left). So we put an invisible
1308 ;; PDF character after these characters, to end the
1309 ;; embedding, which eliminates any effects on the rest of
1310 ;; the line. For RLE and RLO we also append an invisible
1311 ;; LRM, to avoid reordering the following numerical
1312 ;; characters. For LRI/RLI/FSI we append a PDI.
1313 (cond ((memq char '(?\x202a ?\x202d))
1314 (propertize (string ?\x202c) 'invisible t))
1315 ((memq char '(?\x202b ?\x202e))
1316 (propertize (string ?\x202c ?\x200e) 'invisible t))
1317 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1318 (propertize (string ?\x2069) 'invisible t))
1319 ;; Strong right-to-left characters cause reordering of
1320 ;; the following numerical characters which show the
1321 ;; codepoint, so append LRM to countermand that.
1322 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1323 (propertize (string ?\x200e) 'invisible t))
1325 "")))
1326 (beg (point-min))
1327 (end (point-max))
1328 (pos (point))
1329 (total (buffer-size))
1330 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1331 (hscroll (if (= (window-hscroll) 0)
1333 (format " Hscroll=%d" (window-hscroll))))
1334 (col (current-column)))
1335 (if (= pos end)
1336 (if (or (/= beg 1) (/= end (1+ total)))
1337 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1338 pos total percent beg end col hscroll)
1339 (message "point=%d of %d (EOB) column=%d%s"
1340 pos total col hscroll))
1341 (let ((coding buffer-file-coding-system)
1342 encoded encoding-msg display-prop under-display)
1343 (if (or (not coding)
1344 (eq (coding-system-type coding) t))
1345 (setq coding (default-value 'buffer-file-coding-system)))
1346 (if (eq (char-charset char) 'eight-bit)
1347 (setq encoding-msg
1348 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1349 ;; Check if the character is displayed with some `display'
1350 ;; text property. In that case, set under-display to the
1351 ;; buffer substring covered by that property.
1352 (setq display-prop (get-char-property pos 'display))
1353 (if display-prop
1354 (let ((to (or (next-single-char-property-change pos 'display)
1355 (point-max))))
1356 (if (< to (+ pos 4))
1357 (setq under-display "")
1358 (setq under-display "..."
1359 to (+ pos 4)))
1360 (setq under-display
1361 (concat (buffer-substring-no-properties pos to)
1362 under-display)))
1363 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1364 (setq encoding-msg
1365 (if display-prop
1366 (if (not (stringp display-prop))
1367 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1368 char char char under-display)
1369 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1370 char char char under-display display-prop))
1371 (if encoded
1372 (format "(%d, #o%o, #x%x, file %s)"
1373 char char char
1374 (if (> (length encoded) 1)
1375 "..."
1376 (encoded-string-description encoded coding)))
1377 (format "(%d, #o%o, #x%x)" char char char)))))
1378 (if detail
1379 ;; We show the detailed information about CHAR.
1380 (describe-char (point)))
1381 (if (or (/= beg 1) (/= end (1+ total)))
1382 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1383 (if (< char 256)
1384 (single-key-description char)
1385 (buffer-substring-no-properties (point) (1+ (point))))
1386 bidi-fixer
1387 encoding-msg pos total percent beg end col hscroll)
1388 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1389 (if enable-multibyte-characters
1390 (if (< char 128)
1391 (single-key-description char)
1392 (buffer-substring-no-properties (point) (1+ (point))))
1393 (single-key-description char))
1394 bidi-fixer encoding-msg pos total percent col hscroll))))))
1396 ;; Initialize read-expression-map. It is defined at C level.
1397 (defvar read-expression-map
1398 (let ((m (make-sparse-keymap)))
1399 (define-key m "\M-\t" 'completion-at-point)
1400 ;; Might as well bind TAB to completion, since inserting a TAB char is
1401 ;; much too rarely useful.
1402 (define-key m "\t" 'completion-at-point)
1403 (set-keymap-parent m minibuffer-local-map)
1406 (defun read-minibuffer (prompt &optional initial-contents)
1407 "Return a Lisp object read using the minibuffer, unevaluated.
1408 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1409 is a string to insert in the minibuffer before reading.
1410 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1411 Such arguments are used as in `read-from-minibuffer'.)"
1412 ;; Used for interactive spec `x'.
1413 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1414 t 'minibuffer-history))
1416 (defun eval-minibuffer (prompt &optional initial-contents)
1417 "Return value of Lisp expression read using the minibuffer.
1418 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1419 is a string to insert in the minibuffer before reading.
1420 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1421 Such arguments are used as in `read-from-minibuffer'.)"
1422 ;; Used for interactive spec `X'.
1423 (eval (read--expression prompt initial-contents)))
1425 (defvar minibuffer-completing-symbol nil
1426 "Non-nil means completing a Lisp symbol in the minibuffer.")
1427 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1429 (defvar minibuffer-default nil
1430 "The current default value or list of default values in the minibuffer.
1431 The functions `read-from-minibuffer' and `completing-read' bind
1432 this variable locally.")
1434 (defcustom eval-expression-print-level 4
1435 "Value for `print-level' while printing value in `eval-expression'.
1436 A value of nil means no limit."
1437 :group 'lisp
1438 :type '(choice (const :tag "No Limit" nil) integer)
1439 :version "21.1")
1441 (defcustom eval-expression-print-length 12
1442 "Value for `print-length' while printing value in `eval-expression'.
1443 A value of nil means no limit."
1444 :group 'lisp
1445 :type '(choice (const :tag "No Limit" nil) integer)
1446 :version "21.1")
1448 (defcustom eval-expression-debug-on-error t
1449 "If non-nil set `debug-on-error' to t in `eval-expression'.
1450 If nil, don't change the value of `debug-on-error'."
1451 :group 'lisp
1452 :type 'boolean
1453 :version "21.1")
1455 (defcustom eval-expression-print-maximum-character 127
1456 "The largest integer that will be displayed as a character.
1457 This affects printing by `eval-expression' (via
1458 `eval-expression-print-format')."
1459 :group 'lisp
1460 :type 'integer
1461 :version "26.1")
1463 (defun eval-expression-print-format (value)
1464 "If VALUE in an integer, return a specially formatted string.
1465 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1466 If VALUE is not an integer, nil is returned.
1467 This function is used by commands like `eval-expression' that
1468 display the result of expression evaluation."
1469 (when (integerp value)
1470 (let ((char-string
1471 (and (characterp value)
1472 (<= value eval-expression-print-maximum-character)
1473 (char-displayable-p value)
1474 (prin1-char value))))
1475 (if char-string
1476 (format " (#o%o, #x%x, %s)" value value char-string)
1477 (format " (#o%o, #x%x)" value value)))))
1479 (defvar eval-expression-minibuffer-setup-hook nil
1480 "Hook run by `eval-expression' when entering the minibuffer.")
1482 (defun read--expression (prompt &optional initial-contents)
1483 (let ((minibuffer-completing-symbol t))
1484 (minibuffer-with-setup-hook
1485 (lambda ()
1486 ;; FIXME: call emacs-lisp-mode?
1487 (add-function :before-until (local 'eldoc-documentation-function)
1488 #'elisp-eldoc-documentation-function)
1489 (eldoc-mode 1)
1490 (add-hook 'completion-at-point-functions
1491 #'elisp-completion-at-point nil t)
1492 (run-hooks 'eval-expression-minibuffer-setup-hook))
1493 (read-from-minibuffer prompt initial-contents
1494 read-expression-map t
1495 'read-expression-history))))
1497 (defun eval-expression-get-print-arguments (prefix-argument)
1498 "Get arguments for commands that print an expression result.
1499 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1500 based on PREFIX-ARG. This function determines the interpretation
1501 of the prefix argument for `eval-expression' and
1502 `eval-last-sexp'."
1503 (let ((num (prefix-numeric-value prefix-argument)))
1504 (list (not (memq prefix-argument '(- nil)))
1505 (= num 0)
1506 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1507 ((= num -1) most-positive-fixnum)
1508 (t eval-expression-print-maximum-character)))))
1510 ;; We define this, rather than making `eval' interactive,
1511 ;; for the sake of completion of names like eval-region, eval-buffer.
1512 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1513 "Evaluate EXP and print value in the echo area.
1514 When called interactively, read an Emacs Lisp expression and
1515 evaluate it. Value is also consed on to front of the variable
1516 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1517 with a non `-' prefix argument) means insert the result into the
1518 current buffer instead of printing it in the echo area.
1520 Normally, this function truncates long output according to the
1521 value of the variables `eval-expression-print-length' and
1522 `eval-expression-print-level'. When NO-TRUNCATE is
1523 non-nil (interactively, with a prefix argument of zero), however,
1524 there is no such truncation.
1526 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1527 non-nil (interactively, unless given a positive prefix argument)
1528 it will be printed in several additional formats (octal,
1529 hexadecimal, and character). The character format is only used
1530 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1531 prefix argument is -1 or the value is below
1532 `eval-expression-print-maximum-character').
1534 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1535 minibuffer.
1537 If `eval-expression-debug-on-error' is non-nil, which is the default,
1538 this command arranges for all errors to enter the debugger."
1539 (interactive
1540 (cons (read--expression "Eval: ")
1541 (eval-expression-get-print-arguments current-prefix-arg)))
1543 (if (null eval-expression-debug-on-error)
1544 (push (eval exp lexical-binding) values)
1545 (let ((old-value (make-symbol "t")) new-value)
1546 ;; Bind debug-on-error to something unique so that we can
1547 ;; detect when evalled code changes it.
1548 (let ((debug-on-error old-value))
1549 (push (eval (macroexpand-all exp) lexical-binding) values)
1550 (setq new-value debug-on-error))
1551 ;; If evalled code has changed the value of debug-on-error,
1552 ;; propagate that change to the global binding.
1553 (unless (eq old-value new-value)
1554 (setq debug-on-error new-value))))
1556 (let ((print-length (unless no-truncate eval-expression-print-length))
1557 (print-level (unless no-truncate eval-expression-print-level))
1558 (eval-expression-print-maximum-character char-print-limit)
1559 (deactivate-mark))
1560 (let ((out (if insert-value (current-buffer) t)))
1561 (prog1
1562 (prin1 (car values) out)
1563 (let ((str (and char-print-limit
1564 (eval-expression-print-format (car values)))))
1565 (when str (princ str out)))))))
1567 (defun edit-and-eval-command (prompt command)
1568 "Prompting with PROMPT, let user edit COMMAND and eval result.
1569 COMMAND is a Lisp expression. Let user edit that expression in
1570 the minibuffer, then read and evaluate the result."
1571 (let ((command
1572 (let ((print-level nil)
1573 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1574 (unwind-protect
1575 (read-from-minibuffer prompt
1576 (prin1-to-string command)
1577 read-expression-map t
1578 'command-history)
1579 ;; If command was added to command-history as a string,
1580 ;; get rid of that. We want only evaluable expressions there.
1581 (if (stringp (car command-history))
1582 (setq command-history (cdr command-history)))))))
1584 ;; If command to be redone does not match front of history,
1585 ;; add it to the history.
1586 (or (equal command (car command-history))
1587 (setq command-history (cons command command-history)))
1588 (eval command)))
1590 (defun repeat-complex-command (arg)
1591 "Edit and re-evaluate last complex command, or ARGth from last.
1592 A complex command is one which used the minibuffer.
1593 The command is placed in the minibuffer as a Lisp form for editing.
1594 The result is executed, repeating the command as changed.
1595 If the command has been changed or is not the most recent previous
1596 command it is added to the front of the command history.
1597 You can use the minibuffer history commands \
1598 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1599 to get different commands to edit and resubmit."
1600 (interactive "p")
1601 (let ((elt (nth (1- arg) command-history))
1602 newcmd)
1603 (if elt
1604 (progn
1605 (setq newcmd
1606 (let ((print-level nil)
1607 (minibuffer-history-position arg)
1608 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1609 (unwind-protect
1610 (read-from-minibuffer
1611 "Redo: " (prin1-to-string elt) read-expression-map t
1612 (cons 'command-history arg))
1614 ;; If command was added to command-history as a
1615 ;; string, get rid of that. We want only
1616 ;; evaluable expressions there.
1617 (if (stringp (car command-history))
1618 (setq command-history (cdr command-history))))))
1620 ;; If command to be redone does not match front of history,
1621 ;; add it to the history.
1622 (or (equal newcmd (car command-history))
1623 (setq command-history (cons newcmd command-history)))
1624 (apply #'funcall-interactively
1625 (car newcmd)
1626 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1627 (if command-history
1628 (error "Argument %d is beyond length of command history" arg)
1629 (error "There are no previous complex commands to repeat")))))
1632 (defvar extended-command-history nil)
1633 (defvar execute-extended-command--last-typed nil)
1635 (defun read-extended-command ()
1636 "Read command name to invoke in `execute-extended-command'."
1637 (minibuffer-with-setup-hook
1638 (lambda ()
1639 (add-hook 'post-self-insert-hook
1640 (lambda ()
1641 (setq execute-extended-command--last-typed
1642 (minibuffer-contents)))
1643 nil 'local)
1644 (set (make-local-variable 'minibuffer-default-add-function)
1645 (lambda ()
1646 ;; Get a command name at point in the original buffer
1647 ;; to propose it after M-n.
1648 (with-current-buffer (window-buffer (minibuffer-selected-window))
1649 (and (commandp (function-called-at-point))
1650 (format "%S" (function-called-at-point)))))))
1651 ;; Read a string, completing from and restricting to the set of
1652 ;; all defined commands. Don't provide any initial input.
1653 ;; Save the command read on the extended-command history list.
1654 (completing-read
1655 (concat (cond
1656 ((eq current-prefix-arg '-) "- ")
1657 ((and (consp current-prefix-arg)
1658 (eq (car current-prefix-arg) 4)) "C-u ")
1659 ((and (consp current-prefix-arg)
1660 (integerp (car current-prefix-arg)))
1661 (format "%d " (car current-prefix-arg)))
1662 ((integerp current-prefix-arg)
1663 (format "%d " current-prefix-arg)))
1664 ;; This isn't strictly correct if `execute-extended-command'
1665 ;; is bound to anything else (e.g. [menu]).
1666 ;; It could use (key-description (this-single-command-keys)),
1667 ;; but actually a prompt other than "M-x" would be confusing,
1668 ;; because "M-x" is a well-known prompt to read a command
1669 ;; and it serves as a shorthand for "Extended command: ".
1670 "M-x ")
1671 (lambda (string pred action)
1672 (let ((pred
1673 (if (memq action '(nil t))
1674 ;; Exclude obsolete commands from completions.
1675 (lambda (sym)
1676 (and (funcall pred sym)
1677 (or (equal string (symbol-name sym))
1678 (not (get sym 'byte-obsolete-info)))))
1679 pred)))
1680 (complete-with-action action obarray string pred)))
1681 #'commandp t nil 'extended-command-history)))
1683 (defcustom suggest-key-bindings t
1684 "Non-nil means show the equivalent key-binding when M-x command has one.
1685 The value can be a length of time to show the message for.
1686 If the value is non-nil and not a number, we wait 2 seconds."
1687 :group 'keyboard
1688 :type '(choice (const :tag "off" nil)
1689 (integer :tag "time" 2)
1690 (other :tag "on")))
1692 (defcustom extended-command-suggest-shorter t
1693 "If non-nil, show a shorter M-x invocation when there is one."
1694 :group 'keyboard
1695 :type 'boolean
1696 :version "26.1")
1698 (defun execute-extended-command--shorter-1 (name length)
1699 (cond
1700 ((zerop length) (list ""))
1701 ((equal name "") nil)
1703 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1704 (execute-extended-command--shorter-1
1705 (substring name 1) (1- length)))
1706 (when (string-match "\\`\\(-\\)?[^-]*" name)
1707 (execute-extended-command--shorter-1
1708 (substring name (match-end 0)) length))))))
1710 (defun execute-extended-command--shorter (name typed)
1711 (let ((candidates '())
1712 (max (length typed))
1713 (len 1)
1714 binding)
1715 (while (and (not binding)
1716 (progn
1717 (unless candidates
1718 (setq len (1+ len))
1719 (setq candidates (execute-extended-command--shorter-1
1720 name len)))
1721 ;; Don't show the help message if the binding isn't
1722 ;; significantly shorter than the M-x command the user typed.
1723 (< len (- max 5))))
1724 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1725 (let ((candidate (pop candidates)))
1726 (when (equal name
1727 (car-safe (completion-try-completion
1728 candidate obarray 'commandp len)))
1729 (setq binding candidate))))
1730 binding))
1732 (defun execute-extended-command (prefixarg &optional command-name typed)
1733 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1734 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1735 "Read a command name, then read the arguments and call the command.
1736 To pass a prefix argument to the command you are
1737 invoking, give a prefix argument to `execute-extended-command'."
1738 (declare (interactive-only command-execute))
1739 ;; FIXME: Remember the actual text typed by the user before completion,
1740 ;; so that we don't later on suggest the same shortening.
1741 (interactive
1742 (let ((execute-extended-command--last-typed nil))
1743 (list current-prefix-arg
1744 (read-extended-command)
1745 execute-extended-command--last-typed)))
1746 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1747 (unless command-name
1748 (let ((current-prefix-arg prefixarg) ; for prompt
1749 (execute-extended-command--last-typed nil))
1750 (setq command-name (read-extended-command))
1751 (setq typed execute-extended-command--last-typed)))
1752 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1753 (binding (and suggest-key-bindings
1754 (not executing-kbd-macro)
1755 (where-is-internal function overriding-local-map t))))
1756 (unless (commandp function)
1757 (error "`%s' is not a valid command name" command-name))
1758 ;; Some features, such as novice.el, rely on this-command-keys
1759 ;; including M-x COMMAND-NAME RET.
1760 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1761 (setq this-command function)
1762 ;; Normally `real-this-command' should never be changed, but here we really
1763 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1764 ;; binding" for <cmd>, so the command the user really wanted to run is
1765 ;; `function' and not `execute-extended-command'. The difference is
1766 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1767 (setq real-this-command function)
1768 (let ((prefix-arg prefixarg))
1769 (command-execute function 'record))
1770 ;; If enabled, show which key runs this command.
1771 ;; But first wait, and skip the message if there is input.
1772 (let* ((waited
1773 ;; If this command displayed something in the echo area;
1774 ;; wait a few seconds, then display our suggestion message.
1775 ;; FIXME: Wait *after* running post-command-hook!
1776 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1777 ;; find a better answer anyway!
1778 (when suggest-key-bindings
1779 (sit-for (cond
1780 ((zerop (length (current-message))) 0)
1781 ((numberp suggest-key-bindings) suggest-key-bindings)
1782 (t 2))))))
1783 (when (and waited (not (consp unread-command-events)))
1784 (unless (or (not extended-command-suggest-shorter)
1785 binding executing-kbd-macro (not (symbolp function))
1786 (<= (length (symbol-name function)) 2))
1787 ;; There's no binding for CMD. Let's try and find the shortest
1788 ;; string to use in M-x.
1789 ;; FIXME: Can be slow. Cache it maybe?
1790 (while-no-input
1791 (setq binding (execute-extended-command--shorter
1792 (symbol-name function) typed))))
1793 (when binding
1794 (with-temp-message
1795 (format-message "You can run the command `%s' with %s"
1796 function
1797 (if (stringp binding)
1798 (concat "M-x " binding " RET")
1799 (key-description binding)))
1800 (sit-for (if (numberp suggest-key-bindings)
1801 suggest-key-bindings
1802 2))))))))
1804 (defun command-execute (cmd &optional record-flag keys special)
1805 ;; BEWARE: Called directly from the C code.
1806 "Execute CMD as an editor command.
1807 CMD must be a symbol that satisfies the `commandp' predicate.
1808 Optional second arg RECORD-FLAG non-nil
1809 means unconditionally put this command in the variable `command-history'.
1810 Otherwise, that is done only if an arg is read using the minibuffer.
1811 The argument KEYS specifies the value to use instead of (this-command-keys)
1812 when reading the arguments; if it is nil, (this-command-keys) is used.
1813 The argument SPECIAL, if non-nil, means that this command is executing
1814 a special event, so ignore the prefix argument and don't clear it."
1815 (setq debug-on-next-call nil)
1816 (let ((prefixarg (unless special
1817 ;; FIXME: This should probably be done around
1818 ;; pre-command-hook rather than here!
1819 (prog1 prefix-arg
1820 (setq current-prefix-arg prefix-arg)
1821 (setq prefix-arg nil)
1822 (when current-prefix-arg
1823 (prefix-command-update))))))
1824 (if (and (symbolp cmd)
1825 (get cmd 'disabled)
1826 disabled-command-function)
1827 ;; FIXME: Weird calling convention!
1828 (run-hooks 'disabled-command-function)
1829 (let ((final cmd))
1830 (while
1831 (progn
1832 (setq final (indirect-function final))
1833 (if (autoloadp final)
1834 (setq final (autoload-do-load final cmd)))))
1835 (cond
1836 ((arrayp final)
1837 ;; If requested, place the macro in the command history. For
1838 ;; other sorts of commands, call-interactively takes care of this.
1839 (when record-flag
1840 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1841 ;; Don't keep command history around forever.
1842 (when (and (numberp history-length) (> history-length 0))
1843 (let ((cell (nthcdr history-length command-history)))
1844 (if (consp cell) (setcdr cell nil)))))
1845 (execute-kbd-macro final prefixarg))
1847 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1848 (prog1 (call-interactively cmd record-flag keys)
1849 (when (and (symbolp cmd)
1850 (get cmd 'byte-obsolete-info)
1851 (not (get cmd 'command-execute-obsolete-warned)))
1852 (put cmd 'command-execute-obsolete-warned t)
1853 (message "%s" (macroexp--obsolete-warning
1854 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1856 (defvar minibuffer-history nil
1857 "Default minibuffer history list.
1858 This is used for all minibuffer input
1859 except when an alternate history list is specified.
1861 Maximum length of the history list is determined by the value
1862 of `history-length', which see.")
1863 (defvar minibuffer-history-sexp-flag nil
1864 "Control whether history list elements are expressions or strings.
1865 If the value of this variable equals current minibuffer depth,
1866 they are expressions; otherwise they are strings.
1867 \(That convention is designed to do the right thing for
1868 recursive uses of the minibuffer.)")
1869 (setq minibuffer-history-variable 'minibuffer-history)
1870 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1871 (defvar minibuffer-history-search-history nil)
1873 (defvar minibuffer-text-before-history nil
1874 "Text that was in this minibuffer before any history commands.
1875 This is nil if there have not yet been any history commands
1876 in this use of the minibuffer.")
1878 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1880 (defun minibuffer-history-initialize ()
1881 (setq minibuffer-text-before-history nil))
1883 (defun minibuffer-avoid-prompt (_new _old)
1884 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1885 (declare (obsolete cursor-intangible-mode "25.1"))
1886 (constrain-to-field nil (point-max)))
1888 (defcustom minibuffer-history-case-insensitive-variables nil
1889 "Minibuffer history variables for which matching should ignore case.
1890 If a history variable is a member of this list, then the
1891 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1892 commands ignore case when searching it, regardless of `case-fold-search'."
1893 :type '(repeat variable)
1894 :group 'minibuffer)
1896 (defun previous-matching-history-element (regexp n)
1897 "Find the previous history element that matches REGEXP.
1898 \(Previous history elements refer to earlier actions.)
1899 With prefix argument N, search for Nth previous match.
1900 If N is negative, find the next or Nth next match.
1901 Normally, history elements are matched case-insensitively if
1902 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1903 makes the search case-sensitive.
1904 See also `minibuffer-history-case-insensitive-variables'."
1905 (interactive
1906 (let* ((enable-recursive-minibuffers t)
1907 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1909 minibuffer-local-map
1911 'minibuffer-history-search-history
1912 (car minibuffer-history-search-history))))
1913 ;; Use the last regexp specified, by default, if input is empty.
1914 (list (if (string= regexp "")
1915 (if minibuffer-history-search-history
1916 (car minibuffer-history-search-history)
1917 (user-error "No previous history search regexp"))
1918 regexp)
1919 (prefix-numeric-value current-prefix-arg))))
1920 (unless (zerop n)
1921 (if (and (zerop minibuffer-history-position)
1922 (null minibuffer-text-before-history))
1923 (setq minibuffer-text-before-history
1924 (minibuffer-contents-no-properties)))
1925 (let ((history (symbol-value minibuffer-history-variable))
1926 (case-fold-search
1927 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1928 ;; On some systems, ignore case for file names.
1929 (if (memq minibuffer-history-variable
1930 minibuffer-history-case-insensitive-variables)
1932 ;; Respect the user's setting for case-fold-search:
1933 case-fold-search)
1934 nil))
1935 prevpos
1936 match-string
1937 match-offset
1938 (pos minibuffer-history-position))
1939 (while (/= n 0)
1940 (setq prevpos pos)
1941 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1942 (when (= pos prevpos)
1943 (user-error (if (= pos 1)
1944 "No later matching history item"
1945 "No earlier matching history item")))
1946 (setq match-string
1947 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1948 (let ((print-level nil))
1949 (prin1-to-string (nth (1- pos) history)))
1950 (nth (1- pos) history)))
1951 (setq match-offset
1952 (if (< n 0)
1953 (and (string-match regexp match-string)
1954 (match-end 0))
1955 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1956 (match-beginning 1))))
1957 (when match-offset
1958 (setq n (+ n (if (< n 0) 1 -1)))))
1959 (setq minibuffer-history-position pos)
1960 (goto-char (point-max))
1961 (delete-minibuffer-contents)
1962 (insert match-string)
1963 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1964 (if (memq (car (car command-history)) '(previous-matching-history-element
1965 next-matching-history-element))
1966 (setq command-history (cdr command-history))))
1968 (defun next-matching-history-element (regexp n)
1969 "Find the next history element that matches REGEXP.
1970 \(The next history element refers to a more recent action.)
1971 With prefix argument N, search for Nth next match.
1972 If N is negative, find the previous or Nth previous match.
1973 Normally, history elements are matched case-insensitively if
1974 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1975 makes the search case-sensitive."
1976 (interactive
1977 (let* ((enable-recursive-minibuffers t)
1978 (regexp (read-from-minibuffer "Next element matching (regexp): "
1980 minibuffer-local-map
1982 'minibuffer-history-search-history
1983 (car minibuffer-history-search-history))))
1984 ;; Use the last regexp specified, by default, if input is empty.
1985 (list (if (string= regexp "")
1986 (if minibuffer-history-search-history
1987 (car minibuffer-history-search-history)
1988 (user-error "No previous history search regexp"))
1989 regexp)
1990 (prefix-numeric-value current-prefix-arg))))
1991 (previous-matching-history-element regexp (- n)))
1993 (defvar minibuffer-temporary-goal-position nil)
1995 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1996 "Function run by `goto-history-element' before consuming default values.
1997 This is useful to dynamically add more elements to the list of default values
1998 when `goto-history-element' reaches the end of this list.
1999 Before calling this function `goto-history-element' sets the variable
2000 `minibuffer-default-add-done' to t, so it will call this function only
2001 once. In special cases, when this function needs to be called more
2002 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2003 overriding the setting of this variable to t in `goto-history-element'.")
2005 (defvar minibuffer-default-add-done nil
2006 "When nil, add more elements to the end of the list of default values.
2007 The value nil causes `goto-history-element' to add more elements to
2008 the list of defaults when it reaches the end of this list. It does
2009 this by calling a function defined by `minibuffer-default-add-function'.")
2011 (make-variable-buffer-local 'minibuffer-default-add-done)
2013 (defun minibuffer-default-add-completions ()
2014 "Return a list of all completions without the default value.
2015 This function is used to add all elements of the completion table to
2016 the end of the list of defaults just after the default value."
2017 (let ((def minibuffer-default)
2018 (all (all-completions ""
2019 minibuffer-completion-table
2020 minibuffer-completion-predicate)))
2021 (if (listp def)
2022 (append def all)
2023 (cons def (delete def all)))))
2025 (defun goto-history-element (nabs)
2026 "Puts element of the minibuffer history in the minibuffer.
2027 The argument NABS specifies the absolute history position."
2028 (interactive "p")
2029 (when (and (not minibuffer-default-add-done)
2030 (functionp minibuffer-default-add-function)
2031 (< nabs (- (if (listp minibuffer-default)
2032 (length minibuffer-default)
2033 1))))
2034 (setq minibuffer-default-add-done t
2035 minibuffer-default (funcall minibuffer-default-add-function)))
2036 (let ((minimum (if minibuffer-default
2037 (- (if (listp minibuffer-default)
2038 (length minibuffer-default)
2041 elt minibuffer-returned-to-present)
2042 (if (and (zerop minibuffer-history-position)
2043 (null minibuffer-text-before-history))
2044 (setq minibuffer-text-before-history
2045 (minibuffer-contents-no-properties)))
2046 (if (< nabs minimum)
2047 (user-error (if minibuffer-default
2048 "End of defaults; no next item"
2049 "End of history; no default available")))
2050 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2051 (length (symbol-value minibuffer-history-variable))
2053 (user-error "Beginning of history; no preceding item"))
2054 (unless (memq last-command '(next-history-element
2055 previous-history-element))
2056 (let ((prompt-end (minibuffer-prompt-end)))
2057 (set (make-local-variable 'minibuffer-temporary-goal-position)
2058 (cond ((<= (point) prompt-end) prompt-end)
2059 ((eobp) nil)
2060 (t (point))))))
2061 (goto-char (point-max))
2062 (delete-minibuffer-contents)
2063 (setq minibuffer-history-position nabs)
2064 (cond ((< nabs 0)
2065 (setq elt (if (listp minibuffer-default)
2066 (nth (1- (abs nabs)) minibuffer-default)
2067 minibuffer-default)))
2068 ((= nabs 0)
2069 (setq elt (or minibuffer-text-before-history ""))
2070 (setq minibuffer-returned-to-present t)
2071 (setq minibuffer-text-before-history nil))
2072 (t (setq elt (nth (1- minibuffer-history-position)
2073 (symbol-value minibuffer-history-variable)))))
2074 (insert
2075 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2076 (not minibuffer-returned-to-present))
2077 (let ((print-level nil))
2078 (prin1-to-string elt))
2079 elt))
2080 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2082 (defun next-history-element (n)
2083 "Puts next element of the minibuffer history in the minibuffer.
2084 With argument N, it uses the Nth following element."
2085 (interactive "p")
2086 (or (zerop n)
2087 (goto-history-element (- minibuffer-history-position n))))
2089 (defun previous-history-element (n)
2090 "Puts previous element of the minibuffer history in the minibuffer.
2091 With argument N, it uses the Nth previous element."
2092 (interactive "p")
2093 (or (zerop n)
2094 (goto-history-element (+ minibuffer-history-position n))))
2096 (defun next-line-or-history-element (&optional arg)
2097 "Move cursor vertically down ARG lines, or to the next history element.
2098 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2099 next element of the minibuffer history in the minibuffer."
2100 (interactive "^p")
2101 (or arg (setq arg 1))
2102 (let* ((old-point (point))
2103 ;; Remember the original goal column of possibly multi-line input
2104 ;; excluding the length of the prompt on the first line.
2105 (prompt-end (minibuffer-prompt-end))
2106 (old-column (unless (and (eolp) (> (point) prompt-end))
2107 (if (= (line-number-at-pos) 1)
2108 (max (- (current-column) (1- prompt-end)) 0)
2109 (current-column)))))
2110 (condition-case nil
2111 (with-no-warnings
2112 (next-line arg))
2113 (end-of-buffer
2114 ;; Restore old position since `line-move-visual' moves point to
2115 ;; the end of the line when it fails to go to the next line.
2116 (goto-char old-point)
2117 (next-history-element arg)
2118 ;; Reset `temporary-goal-column' because a correct value is not
2119 ;; calculated when `next-line' above fails by bumping against
2120 ;; the bottom of the minibuffer (bug#22544).
2121 (setq temporary-goal-column 0)
2122 ;; Restore the original goal column on the last line
2123 ;; of possibly multi-line input.
2124 (goto-char (point-max))
2125 (when old-column
2126 (if (= (line-number-at-pos) 1)
2127 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2128 (move-to-column old-column)))))))
2130 (defun previous-line-or-history-element (&optional arg)
2131 "Move cursor vertically up ARG lines, or to the previous history element.
2132 When point moves over the top line of multi-line minibuffer, puts ARGth
2133 previous element of the minibuffer history in the minibuffer."
2134 (interactive "^p")
2135 (or arg (setq arg 1))
2136 (let* ((old-point (point))
2137 ;; Remember the original goal column of possibly multi-line input
2138 ;; excluding the length of the prompt on the first line.
2139 (prompt-end (minibuffer-prompt-end))
2140 (old-column (unless (and (eolp) (> (point) prompt-end))
2141 (if (= (line-number-at-pos) 1)
2142 (max (- (current-column) (1- prompt-end)) 0)
2143 (current-column)))))
2144 (condition-case nil
2145 (with-no-warnings
2146 (previous-line arg))
2147 (beginning-of-buffer
2148 ;; Restore old position since `line-move-visual' moves point to
2149 ;; the beginning of the line when it fails to go to the previous line.
2150 (goto-char old-point)
2151 (previous-history-element arg)
2152 ;; Reset `temporary-goal-column' because a correct value is not
2153 ;; calculated when `previous-line' above fails by bumping against
2154 ;; the top of the minibuffer (bug#22544).
2155 (setq temporary-goal-column 0)
2156 ;; Restore the original goal column on the first line
2157 ;; of possibly multi-line input.
2158 (goto-char (minibuffer-prompt-end))
2159 (if old-column
2160 (if (= (line-number-at-pos) 1)
2161 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2162 (move-to-column old-column))
2163 ;; Put the cursor at the end of the visual line instead of the
2164 ;; logical line, so the next `previous-line-or-history-element'
2165 ;; would move to the previous history element, not to a possible upper
2166 ;; visual line from the end of logical line in `line-move-visual' mode.
2167 (end-of-visual-line)
2168 ;; Since `end-of-visual-line' puts the cursor at the beginning
2169 ;; of the next visual line, move it one char back to the end
2170 ;; of the first visual line (bug#22544).
2171 (unless (eolp) (backward-char 1)))))))
2173 (defun next-complete-history-element (n)
2174 "Get next history element which completes the minibuffer before the point.
2175 The contents of the minibuffer after the point are deleted, and replaced
2176 by the new completion."
2177 (interactive "p")
2178 (let ((point-at-start (point)))
2179 (next-matching-history-element
2180 (concat
2181 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2183 ;; next-matching-history-element always puts us at (point-min).
2184 ;; Move to the position we were at before changing the buffer contents.
2185 ;; This is still sensible, because the text before point has not changed.
2186 (goto-char point-at-start)))
2188 (defun previous-complete-history-element (n)
2190 Get previous history element which completes the minibuffer before the point.
2191 The contents of the minibuffer after the point are deleted, and replaced
2192 by the new completion."
2193 (interactive "p")
2194 (next-complete-history-element (- n)))
2196 ;; For compatibility with the old subr of the same name.
2197 (defun minibuffer-prompt-width ()
2198 "Return the display width of the minibuffer prompt.
2199 Return 0 if current buffer is not a minibuffer."
2200 ;; Return the width of everything before the field at the end of
2201 ;; the buffer; this should be 0 for normal buffers.
2202 (1- (minibuffer-prompt-end)))
2204 ;; isearch minibuffer history
2205 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2207 (defvar minibuffer-history-isearch-message-overlay)
2208 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2210 (defun minibuffer-history-isearch-setup ()
2211 "Set up a minibuffer for using isearch to search the minibuffer history.
2212 Intended to be added to `minibuffer-setup-hook'."
2213 (set (make-local-variable 'isearch-search-fun-function)
2214 'minibuffer-history-isearch-search)
2215 (set (make-local-variable 'isearch-message-function)
2216 'minibuffer-history-isearch-message)
2217 (set (make-local-variable 'isearch-wrap-function)
2218 'minibuffer-history-isearch-wrap)
2219 (set (make-local-variable 'isearch-push-state-function)
2220 'minibuffer-history-isearch-push-state)
2221 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2223 (defun minibuffer-history-isearch-end ()
2224 "Clean up the minibuffer after terminating isearch in the minibuffer."
2225 (if minibuffer-history-isearch-message-overlay
2226 (delete-overlay minibuffer-history-isearch-message-overlay)))
2228 (defun minibuffer-history-isearch-search ()
2229 "Return the proper search function, for isearch in minibuffer history."
2230 (lambda (string bound noerror)
2231 (let ((search-fun
2232 ;; Use standard functions to search within minibuffer text
2233 (isearch-search-fun-default))
2234 found)
2235 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2236 ;; searching forward. Lazy-highlight calls this lambda with the
2237 ;; bound arg, so skip the minibuffer prompt.
2238 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2239 (goto-char (minibuffer-prompt-end)))
2241 ;; 1. First try searching in the initial minibuffer text
2242 (funcall search-fun string
2243 (if isearch-forward bound (minibuffer-prompt-end))
2244 noerror)
2245 ;; 2. If the above search fails, start putting next/prev history
2246 ;; elements in the minibuffer successively, and search the string
2247 ;; in them. Do this only when bound is nil (i.e. not while
2248 ;; lazy-highlighting search strings in the current minibuffer text).
2249 (unless bound
2250 (condition-case nil
2251 (progn
2252 (while (not found)
2253 (cond (isearch-forward
2254 (next-history-element 1)
2255 (goto-char (minibuffer-prompt-end)))
2257 (previous-history-element 1)
2258 (goto-char (point-max))))
2259 (setq isearch-barrier (point) isearch-opoint (point))
2260 ;; After putting the next/prev history element, search
2261 ;; the string in them again, until next-history-element
2262 ;; or previous-history-element raises an error at the
2263 ;; beginning/end of history.
2264 (setq found (funcall search-fun string
2265 (unless isearch-forward
2266 ;; For backward search, don't search
2267 ;; in the minibuffer prompt
2268 (minibuffer-prompt-end))
2269 noerror)))
2270 ;; Return point of the new search result
2271 (point))
2272 ;; Return nil when next(prev)-history-element fails
2273 (error nil)))))))
2275 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2276 "Display the minibuffer history search prompt.
2277 If there are no search errors, this function displays an overlay with
2278 the isearch prompt which replaces the original minibuffer prompt.
2279 Otherwise, it displays the standard isearch message returned from
2280 the function `isearch-message'."
2281 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2282 ;; Use standard function `isearch-message' when not in the minibuffer,
2283 ;; or search fails, or has an error (like incomplete regexp).
2284 ;; This function overwrites minibuffer text with isearch message,
2285 ;; so it's possible to see what is wrong in the search string.
2286 (isearch-message c-q-hack ellipsis)
2287 ;; Otherwise, put the overlay with the standard isearch prompt over
2288 ;; the initial minibuffer prompt.
2289 (if (overlayp minibuffer-history-isearch-message-overlay)
2290 (move-overlay minibuffer-history-isearch-message-overlay
2291 (point-min) (minibuffer-prompt-end))
2292 (setq minibuffer-history-isearch-message-overlay
2293 (make-overlay (point-min) (minibuffer-prompt-end)))
2294 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2295 (overlay-put minibuffer-history-isearch-message-overlay
2296 'display (isearch-message-prefix c-q-hack ellipsis))
2297 ;; And clear any previous isearch message.
2298 (message "")))
2300 (defun minibuffer-history-isearch-wrap ()
2301 "Wrap the minibuffer history search when search fails.
2302 Move point to the first history element for a forward search,
2303 or to the last history element for a backward search."
2304 ;; When `minibuffer-history-isearch-search' fails on reaching the
2305 ;; beginning/end of the history, wrap the search to the first/last
2306 ;; minibuffer history element.
2307 (if isearch-forward
2308 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2309 (goto-history-element 0))
2310 (setq isearch-success t)
2311 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2313 (defun minibuffer-history-isearch-push-state ()
2314 "Save a function restoring the state of minibuffer history search.
2315 Save `minibuffer-history-position' to the additional state parameter
2316 in the search status stack."
2317 (let ((pos minibuffer-history-position))
2318 (lambda (cmd)
2319 (minibuffer-history-isearch-pop-state cmd pos))))
2321 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2322 "Restore the minibuffer history search state.
2323 Go to the history element by the absolute history position HIST-POS."
2324 (goto-history-element hist-pos))
2327 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2328 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2330 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2331 "Table mapping redo records to the corresponding undo one.
2332 A redo record for undo-in-region maps to t.
2333 A redo record for ordinary undo maps to the following (earlier) undo.")
2335 (defvar undo-in-region nil
2336 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2338 (defvar undo-no-redo nil
2339 "If t, `undo' doesn't go through redo entries.")
2341 (defvar pending-undo-list nil
2342 "Within a run of consecutive undo commands, list remaining to be undone.
2343 If t, we undid all the way to the end of it.")
2345 (defun undo (&optional arg)
2346 "Undo some previous changes.
2347 Repeat this command to undo more changes.
2348 A numeric ARG serves as a repeat count.
2350 In Transient Mark mode when the mark is active, only undo changes within
2351 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2352 as an argument limits undo to changes within the current region."
2353 (interactive "*P")
2354 ;; Make last-command indicate for the next command that this was an undo.
2355 ;; That way, another undo will undo more.
2356 ;; If we get to the end of the undo history and get an error,
2357 ;; another undo command will find the undo history empty
2358 ;; and will get another error. To begin undoing the undos,
2359 ;; you must type some other command.
2360 (let* ((modified (buffer-modified-p))
2361 ;; For an indirect buffer, look in the base buffer for the
2362 ;; auto-save data.
2363 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2364 (recent-save (with-current-buffer base-buffer
2365 (recent-auto-save-p)))
2366 message)
2367 ;; If we get an error in undo-start,
2368 ;; the next command should not be a "consecutive undo".
2369 ;; So set `this-command' to something other than `undo'.
2370 (setq this-command 'undo-start)
2372 (unless (and (eq last-command 'undo)
2373 (or (eq pending-undo-list t)
2374 ;; If something (a timer or filter?) changed the buffer
2375 ;; since the previous command, don't continue the undo seq.
2376 (let ((list buffer-undo-list))
2377 (while (eq (car list) nil)
2378 (setq list (cdr list)))
2379 ;; If the last undo record made was made by undo
2380 ;; it shows nothing else happened in between.
2381 (gethash list undo-equiv-table))))
2382 (setq undo-in-region
2383 (or (region-active-p) (and arg (not (numberp arg)))))
2384 (if undo-in-region
2385 (undo-start (region-beginning) (region-end))
2386 (undo-start))
2387 ;; get rid of initial undo boundary
2388 (undo-more 1))
2389 ;; If we got this far, the next command should be a consecutive undo.
2390 (setq this-command 'undo)
2391 ;; Check to see whether we're hitting a redo record, and if
2392 ;; so, ask the user whether she wants to skip the redo/undo pair.
2393 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2394 (or (eq (selected-window) (minibuffer-window))
2395 (setq message (format "%s%s!"
2396 (if (or undo-no-redo (not equiv))
2397 "Undo" "Redo")
2398 (if undo-in-region " in region" ""))))
2399 (when (and (consp equiv) undo-no-redo)
2400 ;; The equiv entry might point to another redo record if we have done
2401 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2402 (while (let ((next (gethash equiv undo-equiv-table)))
2403 (if next (setq equiv next))))
2404 (setq pending-undo-list equiv)))
2405 (undo-more
2406 (if (numberp arg)
2407 (prefix-numeric-value arg)
2409 ;; Record the fact that the just-generated undo records come from an
2410 ;; undo operation--that is, they are redo records.
2411 ;; In the ordinary case (not within a region), map the redo
2412 ;; record to the following undos.
2413 ;; I don't know how to do that in the undo-in-region case.
2414 (let ((list buffer-undo-list))
2415 ;; Strip any leading undo boundaries there might be, like we do
2416 ;; above when checking.
2417 (while (eq (car list) nil)
2418 (setq list (cdr list)))
2419 (puthash list
2420 ;; Prevent identity mapping. This can happen if
2421 ;; consecutive nils are erroneously in undo list.
2422 (if (or undo-in-region (eq list pending-undo-list))
2424 pending-undo-list)
2425 undo-equiv-table))
2426 ;; Don't specify a position in the undo record for the undo command.
2427 ;; Instead, undoing this should move point to where the change is.
2428 (let ((tail buffer-undo-list)
2429 (prev nil))
2430 (while (car tail)
2431 (when (integerp (car tail))
2432 (let ((pos (car tail)))
2433 (if prev
2434 (setcdr prev (cdr tail))
2435 (setq buffer-undo-list (cdr tail)))
2436 (setq tail (cdr tail))
2437 (while (car tail)
2438 (if (eq pos (car tail))
2439 (if prev
2440 (setcdr prev (cdr tail))
2441 (setq buffer-undo-list (cdr tail)))
2442 (setq prev tail))
2443 (setq tail (cdr tail)))
2444 (setq tail nil)))
2445 (setq prev tail tail (cdr tail))))
2446 ;; Record what the current undo list says,
2447 ;; so the next command can tell if the buffer was modified in between.
2448 (and modified (not (buffer-modified-p))
2449 (with-current-buffer base-buffer
2450 (delete-auto-save-file-if-necessary recent-save)))
2451 ;; Display a message announcing success.
2452 (if message
2453 (message "%s" message))))
2455 (defun buffer-disable-undo (&optional buffer)
2456 "Make BUFFER stop keeping undo information.
2457 No argument or nil as argument means do this for the current buffer."
2458 (interactive)
2459 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2460 (setq buffer-undo-list t)))
2462 (defun undo-only (&optional arg)
2463 "Undo some previous changes.
2464 Repeat this command to undo more changes.
2465 A numeric ARG serves as a repeat count.
2466 Contrary to `undo', this will not redo a previous undo."
2467 (interactive "*p")
2468 (let ((undo-no-redo t)) (undo arg)))
2470 (defvar undo-in-progress nil
2471 "Non-nil while performing an undo.
2472 Some change-hooks test this variable to do something different.")
2474 (defun undo-more (n)
2475 "Undo back N undo-boundaries beyond what was already undone recently.
2476 Call `undo-start' to get ready to undo recent changes,
2477 then call `undo-more' one or more times to undo them."
2478 (or (listp pending-undo-list)
2479 (user-error (concat "No further undo information"
2480 (and undo-in-region " for region"))))
2481 (let ((undo-in-progress t))
2482 ;; Note: The following, while pulling elements off
2483 ;; `pending-undo-list' will call primitive change functions which
2484 ;; will push more elements onto `buffer-undo-list'.
2485 (setq pending-undo-list (primitive-undo n pending-undo-list))
2486 (if (null pending-undo-list)
2487 (setq pending-undo-list t))))
2489 (defun primitive-undo (n list)
2490 "Undo N records from the front of the list LIST.
2491 Return what remains of the list."
2493 ;; This is a good feature, but would make undo-start
2494 ;; unable to do what is expected.
2495 ;;(when (null (car (list)))
2496 ;; ;; If the head of the list is a boundary, it is the boundary
2497 ;; ;; preceding this command. Get rid of it and don't count it.
2498 ;; (setq list (cdr list))))
2500 (let ((arg n)
2501 ;; In a writable buffer, enable undoing read-only text that is
2502 ;; so because of text properties.
2503 (inhibit-read-only t)
2504 ;; Don't let `intangible' properties interfere with undo.
2505 (inhibit-point-motion-hooks t)
2506 ;; We use oldlist only to check for EQ. ++kfs
2507 (oldlist buffer-undo-list)
2508 (did-apply nil)
2509 (next nil))
2510 (while (> arg 0)
2511 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2512 ;; Handle an integer by setting point to that value.
2513 (pcase next
2514 ((pred integerp) (goto-char next))
2515 ;; Element (t . TIME) records previous modtime.
2516 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2517 ;; UNKNOWN_MODTIME_NSECS.
2518 (`(t . ,time)
2519 ;; If this records an obsolete save
2520 ;; (not matching the actual disk file)
2521 ;; then don't mark unmodified.
2522 (when (or (equal time (visited-file-modtime))
2523 (and (consp time)
2524 (equal (list (car time) (cdr time))
2525 (visited-file-modtime))))
2526 (when (fboundp 'unlock-buffer)
2527 (unlock-buffer))
2528 (set-buffer-modified-p nil)))
2529 ;; Element (nil PROP VAL BEG . END) is property change.
2530 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2531 (when (or (> (point-min) beg) (< (point-max) end))
2532 (error "Changes to be undone are outside visible portion of buffer"))
2533 (put-text-property beg end prop val))
2534 ;; Element (BEG . END) means range was inserted.
2535 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2536 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2537 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2538 (when (or (> (point-min) beg) (< (point-max) end))
2539 (error "Changes to be undone are outside visible portion of buffer"))
2540 ;; Set point first thing, so that undoing this undo
2541 ;; does not send point back to where it is now.
2542 (goto-char beg)
2543 (delete-region beg end))
2544 ;; Element (apply FUN . ARGS) means call FUN to undo.
2545 (`(apply . ,fun-args)
2546 (let ((currbuff (current-buffer)))
2547 (if (integerp (car fun-args))
2548 ;; Long format: (apply DELTA START END FUN . ARGS).
2549 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2550 (start-mark (copy-marker start nil))
2551 (end-mark (copy-marker end t)))
2552 (when (or (> (point-min) start) (< (point-max) end))
2553 (error "Changes to be undone are outside visible portion of buffer"))
2554 (apply fun args) ;; Use `save-current-buffer'?
2555 ;; Check that the function did what the entry
2556 ;; said it would do.
2557 (unless (and (= start start-mark)
2558 (= (+ delta end) end-mark))
2559 (error "Changes to be undone by function different than announced"))
2560 (set-marker start-mark nil)
2561 (set-marker end-mark nil))
2562 (apply fun-args))
2563 (unless (eq currbuff (current-buffer))
2564 (error "Undo function switched buffer"))
2565 (setq did-apply t)))
2566 ;; Element (STRING . POS) means STRING was deleted.
2567 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2568 (when (let ((apos (abs pos)))
2569 (or (< apos (point-min)) (> apos (point-max))))
2570 (error "Changes to be undone are outside visible portion of buffer"))
2571 (let (valid-marker-adjustments)
2572 ;; Check that marker adjustments which were recorded
2573 ;; with the (STRING . POS) record are still valid, ie
2574 ;; the markers haven't moved. We check their validity
2575 ;; before reinserting the string so as we don't need to
2576 ;; mind marker insertion-type.
2577 (while (and (markerp (car-safe (car list)))
2578 (integerp (cdr-safe (car list))))
2579 (let* ((marker-adj (pop list))
2580 (m (car marker-adj)))
2581 (and (eq (marker-buffer m) (current-buffer))
2582 (= pos m)
2583 (push marker-adj valid-marker-adjustments))))
2584 ;; Insert string and adjust point
2585 (if (< pos 0)
2586 (progn
2587 (goto-char (- pos))
2588 (insert string))
2589 (goto-char pos)
2590 (insert string)
2591 (goto-char pos))
2592 ;; Adjust the valid marker adjustments
2593 (dolist (adj valid-marker-adjustments)
2594 ;; Insert might have invalidated some of the markers
2595 ;; via modification hooks. Update only the currently
2596 ;; valid ones (bug#25599).
2597 (if (marker-buffer (car adj))
2598 (set-marker (car adj)
2599 (- (car adj) (cdr adj)))))))
2600 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2601 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2602 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2603 next)
2604 ;; Even though these elements are not expected in the undo
2605 ;; list, adjust them to be conservative for the 24.4
2606 ;; release. (Bug#16818)
2607 (when (marker-buffer marker)
2608 (set-marker marker
2609 (- marker offset)
2610 (marker-buffer marker))))
2611 (_ (error "Unrecognized entry in undo list %S" next))))
2612 (setq arg (1- arg)))
2613 ;; Make sure an apply entry produces at least one undo entry,
2614 ;; so the test in `undo' for continuing an undo series
2615 ;; will work right.
2616 (if (and did-apply
2617 (eq oldlist buffer-undo-list))
2618 (setq buffer-undo-list
2619 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2620 list)
2622 ;; Deep copy of a list
2623 (defun undo-copy-list (list)
2624 "Make a copy of undo list LIST."
2625 (mapcar 'undo-copy-list-1 list))
2627 (defun undo-copy-list-1 (elt)
2628 (if (consp elt)
2629 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2630 elt))
2632 (defun undo-start (&optional beg end)
2633 "Set `pending-undo-list' to the front of the undo list.
2634 The next call to `undo-more' will undo the most recently made change.
2635 If BEG and END are specified, then only undo elements
2636 that apply to text between BEG and END are used; other undo elements
2637 are ignored. If BEG and END are nil, all undo elements are used."
2638 (if (eq buffer-undo-list t)
2639 (user-error "No undo information in this buffer"))
2640 (setq pending-undo-list
2641 (if (and beg end (not (= beg end)))
2642 (undo-make-selective-list (min beg end) (max beg end))
2643 buffer-undo-list)))
2645 ;; The positions given in elements of the undo list are the positions
2646 ;; as of the time that element was recorded to undo history. In
2647 ;; general, subsequent buffer edits render those positions invalid in
2648 ;; the current buffer, unless adjusted according to the intervening
2649 ;; undo elements.
2651 ;; Undo in region is a use case that requires adjustments to undo
2652 ;; elements. It must adjust positions of elements in the region based
2653 ;; on newer elements not in the region so as they may be correctly
2654 ;; applied in the current buffer. undo-make-selective-list
2655 ;; accomplishes this with its undo-deltas list of adjustments. An
2656 ;; example undo history from oldest to newest:
2658 ;; buf pos:
2659 ;; 123456789 buffer-undo-list undo-deltas
2660 ;; --------- ---------------- -----------
2661 ;; aaa (1 . 4) (1 . -3)
2662 ;; aaba (3 . 4) N/A (in region)
2663 ;; ccaaba (1 . 3) (1 . -2)
2664 ;; ccaabaddd (7 . 10) (7 . -3)
2665 ;; ccaabdd ("ad" . 6) (6 . 2)
2666 ;; ccaabaddd (6 . 8) (6 . -2)
2667 ;; | |<-- region: "caab", from 2 to 6
2669 ;; When the user starts a run of undos in region,
2670 ;; undo-make-selective-list is called to create the full list of in
2671 ;; region elements. Each element is adjusted forward chronologically
2672 ;; through undo-deltas to determine if it is in the region.
2674 ;; In the above example, the insertion of "b" is (3 . 4) in the
2675 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2676 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2677 ;; . 6) is assessed as in the region and placed in the selective list.
2678 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2679 ;; due to the selected element. The "b" insertion is the only element
2680 ;; fully in the region, so in this example undo-make-selective-list
2681 ;; returns (nil (5 . 6)).
2683 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2684 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2685 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2686 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2687 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2689 ;; More interesting is how to adjust the "ddd" insertion due to the
2690 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2691 ;; If the reinsertion was a manual retyping of "ad", then the total
2692 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2693 ;; the reinsertion was due to undo, one might expect the first "d"
2694 ;; character would again be a part of the "ddd" text, meaning its
2695 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2697 ;; undo-make-selective-list assumes in this situation that "ad" was a
2698 ;; new edit, even if it was inserted because of an undo.
2699 ;; Consequently, if the user undos in region "8 to 10" of the
2700 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2701 ;; "ccaabad", as though the first "d" became detached from the
2702 ;; original "ddd" insertion. This quirk is a FIXME.
2704 (defun undo-make-selective-list (start end)
2705 "Return a list of undo elements for the region START to END.
2706 The elements come from `buffer-undo-list', but we keep only the
2707 elements inside this region, and discard those outside this
2708 region. The elements' positions are adjusted so as the returned
2709 list can be applied to the current buffer."
2710 (let ((ulist buffer-undo-list)
2711 ;; A list of position adjusted undo elements in the region.
2712 (selective-list (list nil))
2713 ;; A list of undo-deltas for out of region undo elements.
2714 undo-deltas
2715 undo-elt)
2716 (while ulist
2717 (when undo-no-redo
2718 (while (gethash ulist undo-equiv-table)
2719 (setq ulist (gethash ulist undo-equiv-table))))
2720 (setq undo-elt (car ulist))
2721 (cond
2722 ((null undo-elt)
2723 ;; Don't put two nils together in the list
2724 (when (car selective-list)
2725 (push nil selective-list)))
2726 ((and (consp undo-elt) (eq (car undo-elt) t))
2727 ;; This is a "was unmodified" element. Keep it
2728 ;; if we have kept everything thus far.
2729 (when (not undo-deltas)
2730 (push undo-elt selective-list)))
2731 ;; Skip over marker adjustments, instead relying
2732 ;; on finding them after (TEXT . POS) elements
2733 ((markerp (car-safe undo-elt))
2734 nil)
2736 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2737 undo-deltas)))
2738 (if (undo-elt-in-region adjusted-undo-elt start end)
2739 (progn
2740 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2741 (push adjusted-undo-elt selective-list)
2742 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2743 ;; kept. primitive-undo may discard them later.
2744 (when (and (stringp (car-safe adjusted-undo-elt))
2745 (integerp (cdr-safe adjusted-undo-elt)))
2746 (let ((list-i (cdr ulist)))
2747 (while (markerp (car-safe (car list-i)))
2748 (push (pop list-i) selective-list)))))
2749 (let ((delta (undo-delta undo-elt)))
2750 (when (/= 0 (cdr delta))
2751 (push delta undo-deltas)))))))
2752 (pop ulist))
2753 (nreverse selective-list)))
2755 (defun undo-elt-in-region (undo-elt start end)
2756 "Determine whether UNDO-ELT falls inside the region START ... END.
2757 If it crosses the edge, we return nil.
2759 Generally this function is not useful for determining
2760 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2761 because markers can be arbitrarily relocated. Instead, pass the
2762 marker adjustment's corresponding (TEXT . POS) element."
2763 (cond ((integerp undo-elt)
2764 (and (>= undo-elt start)
2765 (<= undo-elt end)))
2766 ((eq undo-elt nil)
2768 ((atom undo-elt)
2769 nil)
2770 ((stringp (car undo-elt))
2771 ;; (TEXT . POSITION)
2772 (and (>= (abs (cdr undo-elt)) start)
2773 (<= (abs (cdr undo-elt)) end)))
2774 ((and (consp undo-elt) (markerp (car undo-elt)))
2775 ;; (MARKER . ADJUSTMENT)
2776 (<= start (car undo-elt) end))
2777 ((null (car undo-elt))
2778 ;; (nil PROPERTY VALUE BEG . END)
2779 (let ((tail (nthcdr 3 undo-elt)))
2780 (and (>= (car tail) start)
2781 (<= (cdr tail) end))))
2782 ((integerp (car undo-elt))
2783 ;; (BEGIN . END)
2784 (and (>= (car undo-elt) start)
2785 (<= (cdr undo-elt) end)))))
2787 (defun undo-elt-crosses-region (undo-elt start end)
2788 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2789 This assumes we have already decided that UNDO-ELT
2790 is not *inside* the region START...END."
2791 (declare (obsolete nil "25.1"))
2792 (cond ((atom undo-elt) nil)
2793 ((null (car undo-elt))
2794 ;; (nil PROPERTY VALUE BEG . END)
2795 (let ((tail (nthcdr 3 undo-elt)))
2796 (and (< (car tail) end)
2797 (> (cdr tail) start))))
2798 ((integerp (car undo-elt))
2799 ;; (BEGIN . END)
2800 (and (< (car undo-elt) end)
2801 (> (cdr undo-elt) start)))))
2803 (defun undo-adjust-elt (elt deltas)
2804 "Return adjustment of undo element ELT by the undo DELTAS
2805 list."
2806 (pcase elt
2807 ;; POSITION
2808 ((pred integerp)
2809 (undo-adjust-pos elt deltas))
2810 ;; (BEG . END)
2811 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2812 (undo-adjust-beg-end beg end deltas))
2813 ;; (TEXT . POSITION)
2814 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2815 (cons text (* (if (< pos 0) -1 1)
2816 (undo-adjust-pos (abs pos) deltas))))
2817 ;; (nil PROPERTY VALUE BEG . END)
2818 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2819 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2820 ;; (apply DELTA START END FUN . ARGS)
2821 ;; FIXME
2822 ;; All others return same elt
2823 (_ elt)))
2825 ;; (BEG . END) can adjust to the same positions, commonly when an
2826 ;; insertion was undone and they are out of region, for example:
2828 ;; buf pos:
2829 ;; 123456789 buffer-undo-list undo-deltas
2830 ;; --------- ---------------- -----------
2831 ;; [...]
2832 ;; abbaa (2 . 4) (2 . -2)
2833 ;; aaa ("bb" . 2) (2 . 2)
2834 ;; [...]
2836 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2837 ;; undo. Further adjustments to such an element should be the same as
2838 ;; for (TEXT . POSITION) elements. The options are:
2840 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2841 ;; analogous to marker insertion-type t.
2843 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2844 ;; marker insertion-type nil.
2846 ;; There was no strong reason to prefer one or the other, except that
2847 ;; the first is more consistent with prior undo in region behavior.
2848 (defun undo-adjust-beg-end (beg end deltas)
2849 "Return cons of adjustments to BEG and END by the undo DELTAS
2850 list."
2851 (let ((adj-beg (undo-adjust-pos beg deltas)))
2852 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2853 (cons adj-beg
2854 (max adj-beg (undo-adjust-pos end deltas t)))))
2856 (defun undo-adjust-pos (pos deltas &optional use-<)
2857 "Return adjustment of POS by the undo DELTAS list, comparing
2858 with < or <= based on USE-<."
2859 (dolist (d deltas pos)
2860 (when (if use-<
2861 (< (car d) pos)
2862 (<= (car d) pos))
2863 (setq pos
2864 ;; Don't allow pos to become less than the undo-delta
2865 ;; position. This edge case is described in the overview
2866 ;; comments.
2867 (max (car d) (- pos (cdr d)))))))
2869 ;; Return the first affected buffer position and the delta for an undo element
2870 ;; delta is defined as the change in subsequent buffer positions if we *did*
2871 ;; the undo.
2872 (defun undo-delta (undo-elt)
2873 (if (consp undo-elt)
2874 (cond ((stringp (car undo-elt))
2875 ;; (TEXT . POSITION)
2876 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2877 ((integerp (car undo-elt))
2878 ;; (BEGIN . END)
2879 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2881 '(0 . 0)))
2882 '(0 . 0)))
2884 ;;; Default undo-boundary addition
2886 ;; This section adds a new undo-boundary at either after a command is
2887 ;; called or in some cases on a timer called after a change is made in
2888 ;; any buffer.
2889 (defvar-local undo-auto--last-boundary-cause nil
2890 "Describe the cause of the last undo-boundary.
2892 If `explicit', the last boundary was caused by an explicit call to
2893 `undo-boundary', that is one not called by the code in this
2894 section.
2896 If it is equal to `timer', then the last boundary was inserted
2897 by `undo-auto--boundary-timer'.
2899 If it is equal to `command', then the last boundary was inserted
2900 automatically after a command, that is by the code defined in
2901 this section.
2903 If it is equal to a list, then the last boundary was inserted by
2904 an amalgamating command. The car of the list is the number of
2905 times an amalgamating command has been called, and the cdr are the
2906 buffers that were changed during the last command.")
2908 (defvar undo-auto-current-boundary-timer nil
2909 "Current timer which will run `undo-auto--boundary-timer' or nil.
2911 If set to non-nil, this will effectively disable the timer.")
2913 (defvar undo-auto--this-command-amalgamating nil
2914 "Non-nil if `this-command' should be amalgamated.
2915 This variable is set to nil by `undo-auto--boundaries' and is set
2916 by `undo-auto-amalgamate'." )
2918 (defun undo-auto--needs-boundary-p ()
2919 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2920 (car-safe buffer-undo-list))
2922 (defun undo-auto--last-boundary-amalgamating-number ()
2923 "Return the number of amalgamating last commands or nil.
2924 Amalgamating commands are, by default, either
2925 `self-insert-command' and `delete-char', but can be any command
2926 that calls `undo-auto-amalgamate'."
2927 (car-safe undo-auto--last-boundary-cause))
2929 (defun undo-auto--ensure-boundary (cause)
2930 "Add an `undo-boundary' to the current buffer if needed.
2931 REASON describes the reason that the boundary is being added; see
2932 `undo-auto--last-boundary' for more information."
2933 (when (and
2934 (undo-auto--needs-boundary-p))
2935 (let ((last-amalgamating
2936 (undo-auto--last-boundary-amalgamating-number)))
2937 (undo-boundary)
2938 (setq undo-auto--last-boundary-cause
2939 (if (eq 'amalgamate cause)
2940 (cons
2941 (if last-amalgamating (1+ last-amalgamating) 0)
2942 undo-auto--undoably-changed-buffers)
2943 cause)))))
2945 (defun undo-auto--boundaries (cause)
2946 "Check recently changed buffers and add a boundary if necessary.
2947 REASON describes the reason that the boundary is being added; see
2948 `undo-last-boundary' for more information."
2949 ;; (Bug #23785) All commands should ensure that there is an undo
2950 ;; boundary whether they have changed the current buffer or not.
2951 (when (eq cause 'command)
2952 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2953 (dolist (b undo-auto--undoably-changed-buffers)
2954 (when (buffer-live-p b)
2955 (with-current-buffer b
2956 (undo-auto--ensure-boundary cause))))
2957 (setq undo-auto--undoably-changed-buffers nil))
2959 (defun undo-auto--boundary-timer ()
2960 "Timer which will run `undo--auto-boundary-timer'."
2961 (setq undo-auto-current-boundary-timer nil)
2962 (undo-auto--boundaries 'timer))
2964 (defun undo-auto--boundary-ensure-timer ()
2965 "Ensure that the `undo-auto-boundary-timer' is set."
2966 (unless undo-auto-current-boundary-timer
2967 (setq undo-auto-current-boundary-timer
2968 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2970 (defvar undo-auto--undoably-changed-buffers nil
2971 "List of buffers that have changed recently.
2973 This list is maintained by `undo-auto--undoable-change' and
2974 `undo-auto--boundaries' and can be affected by changes to their
2975 default values.")
2977 (defun undo-auto--add-boundary ()
2978 "Add an `undo-boundary' in appropriate buffers."
2979 (undo-auto--boundaries
2980 (let ((amal undo-auto--this-command-amalgamating))
2981 (setq undo-auto--this-command-amalgamating nil)
2982 (if amal
2983 'amalgamate
2984 'command))))
2986 (defun undo-auto-amalgamate ()
2987 "Amalgamate undo if necessary.
2988 This function can be called before an amalgamating command. It
2989 removes the previous `undo-boundary' if a series of such calls
2990 have been made. By default `self-insert-command' and
2991 `delete-char' are the only amalgamating commands, although this
2992 function could be called by any command wishing to have this
2993 behavior."
2994 (let ((last-amalgamating-count
2995 (undo-auto--last-boundary-amalgamating-number)))
2996 (setq undo-auto--this-command-amalgamating t)
2997 (when
2998 last-amalgamating-count
3000 (and
3001 (< last-amalgamating-count 20)
3002 (eq this-command last-command))
3003 ;; Amalgamate all buffers that have changed.
3004 (dolist (b (cdr undo-auto--last-boundary-cause))
3005 (when (buffer-live-p b)
3006 (with-current-buffer
3008 (when
3009 ;; The head of `buffer-undo-list' is nil.
3010 ;; `car-safe' doesn't work because
3011 ;; `buffer-undo-list' need not be a list!
3012 (and (listp buffer-undo-list)
3013 (not (car buffer-undo-list)))
3014 (setq buffer-undo-list
3015 (cdr buffer-undo-list))))))
3016 (setq undo-auto--last-boundary-cause 0)))))
3018 (defun undo-auto--undoable-change ()
3019 "Called after every undoable buffer change."
3020 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
3021 (undo-auto--boundary-ensure-timer))
3022 ;; End auto-boundary section
3024 (defun undo-amalgamate-change-group (handle)
3025 "Amalgamate changes in change-group since HANDLE.
3026 Remove all undo boundaries between the state of HANDLE and now.
3027 HANDLE is as returned by `prepare-change-group'."
3028 (dolist (elt handle)
3029 (with-current-buffer (car elt)
3030 (setq elt (cdr elt))
3031 (when (consp buffer-undo-list)
3032 (let ((old-car (car-safe elt))
3033 (old-cdr (cdr-safe elt)))
3034 (unwind-protect
3035 (progn
3036 ;; Temporarily truncate the undo log at ELT.
3037 (when (consp elt)
3038 (setcar elt t) (setcdr elt nil))
3039 (when
3040 (or (null elt) ;The undo-log was empty.
3041 ;; `elt' is still in the log: normal case.
3042 (eq elt (last buffer-undo-list))
3043 ;; `elt' is not in the log any more, but that's because
3044 ;; the log is "all new", so we should remove all
3045 ;; boundaries from it.
3046 (not (eq (last buffer-undo-list) (last old-cdr))))
3047 (cl-callf (lambda (x) (delq nil x))
3048 (if (car buffer-undo-list)
3049 buffer-undo-list
3050 ;; Preserve the undo-boundaries at either ends of the
3051 ;; change-groups.
3052 (cdr buffer-undo-list)))))
3053 ;; Reset the modified cons cell ELT to its original content.
3054 (when (consp elt)
3055 (setcar elt old-car)
3056 (setcdr elt old-cdr))))))))
3059 (defcustom undo-ask-before-discard nil
3060 "If non-nil ask about discarding undo info for the current command.
3061 Normally, Emacs discards the undo info for the current command if
3062 it exceeds `undo-outer-limit'. But if you set this option
3063 non-nil, it asks in the echo area whether to discard the info.
3064 If you answer no, there is a slight risk that Emacs might crash, so
3065 only do it if you really want to undo the command.
3067 This option is mainly intended for debugging. You have to be
3068 careful if you use it for other purposes. Garbage collection is
3069 inhibited while the question is asked, meaning that Emacs might
3070 leak memory. So you should make sure that you do not wait
3071 excessively long before answering the question."
3072 :type 'boolean
3073 :group 'undo
3074 :version "22.1")
3076 (defvar undo-extra-outer-limit nil
3077 "If non-nil, an extra level of size that's ok in an undo item.
3078 We don't ask the user about truncating the undo list until the
3079 current item gets bigger than this amount.
3081 This variable only matters if `undo-ask-before-discard' is non-nil.")
3082 (make-variable-buffer-local 'undo-extra-outer-limit)
3084 ;; When the first undo batch in an undo list is longer than
3085 ;; undo-outer-limit, this function gets called to warn the user that
3086 ;; the undo info for the current command was discarded. Garbage
3087 ;; collection is inhibited around the call, so it had better not do a
3088 ;; lot of consing.
3089 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3090 (defun undo-outer-limit-truncate (size)
3091 (if undo-ask-before-discard
3092 (when (or (null undo-extra-outer-limit)
3093 (> size undo-extra-outer-limit))
3094 ;; Don't ask the question again unless it gets even bigger.
3095 ;; This applies, in particular, if the user quits from the question.
3096 ;; Such a quit quits out of GC, but something else will call GC
3097 ;; again momentarily. It will call this function again,
3098 ;; but we don't want to ask the question again.
3099 (setq undo-extra-outer-limit (+ size 50000))
3100 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3101 (yes-or-no-p (format-message
3102 "Buffer `%s' undo info is %d bytes long; discard it? "
3103 (buffer-name) size)))
3104 (progn (setq buffer-undo-list nil)
3105 (setq undo-extra-outer-limit nil)
3107 nil))
3108 (display-warning '(undo discard-info)
3109 (concat
3110 (format-message
3111 "Buffer `%s' undo info was %d bytes long.\n"
3112 (buffer-name) size)
3113 "The undo info was discarded because it exceeded \
3114 `undo-outer-limit'.
3116 This is normal if you executed a command that made a huge change
3117 to the buffer. In that case, to prevent similar problems in the
3118 future, set `undo-outer-limit' to a value that is large enough to
3119 cover the maximum size of normal changes you expect a single
3120 command to make, but not so large that it might exceed the
3121 maximum memory allotted to Emacs.
3123 If you did not execute any such command, the situation is
3124 probably due to a bug and you should report it.
3126 You can disable the popping up of this buffer by adding the entry
3127 \(undo discard-info) to the user option `warning-suppress-types',
3128 which is defined in the `warnings' library.\n")
3129 :warning)
3130 (setq buffer-undo-list nil)
3133 (defcustom password-word-equivalents
3134 '("password" "passcode" "passphrase" "pass phrase"
3135 ; These are sorted according to the GNU en_US locale.
3136 "암호" ; ko
3137 "パスワード" ; ja
3138 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3139 "ពាក្យសម្ងាត់" ; km
3140 "adgangskode" ; da
3141 "contraseña" ; es
3142 "contrasenya" ; ca
3143 "geslo" ; sl
3144 "hasło" ; pl
3145 "heslo" ; cs, sk
3146 "iphasiwedi" ; zu
3147 "jelszó" ; hu
3148 "lösenord" ; sv
3149 "lozinka" ; hr, sr
3150 "mật khẩu" ; vi
3151 "mot de passe" ; fr
3152 "parola" ; tr
3153 "pasahitza" ; eu
3154 "passord" ; nb
3155 "passwort" ; de
3156 "pasvorto" ; eo
3157 "salasana" ; fi
3158 "senha" ; pt
3159 "slaptažodis" ; lt
3160 "wachtwoord" ; nl
3161 "كلمة السر" ; ar
3162 "ססמה" ; he
3163 "лозинка" ; sr
3164 "пароль" ; kk, ru, uk
3165 "गुप्तशब्द" ; mr
3166 "शब्दकूट" ; hi
3167 "પાસવર્ડ" ; gu
3168 "సంకేతపదము" ; te
3169 "ਪਾਸਵਰਡ" ; pa
3170 "ಗುಪ್ತಪದ" ; kn
3171 "கடவுச்சொல்" ; ta
3172 "അടയാളവാക്ക്" ; ml
3173 "গুপ্তশব্দ" ; as
3174 "পাসওয়ার্ড" ; bn_IN
3175 "රහස්පදය" ; si
3176 "密码" ; zh_CN
3177 "密碼" ; zh_TW
3179 "List of words equivalent to \"password\".
3180 This is used by Shell mode and other parts of Emacs to recognize
3181 password prompts, including prompts in languages other than
3182 English. Different case choices should not be assumed to be
3183 included; callers should bind `case-fold-search' to t."
3184 :type '(repeat string)
3185 :version "24.4"
3186 :group 'processes)
3188 (defvar shell-command-history nil
3189 "History list for some commands that read shell commands.
3191 Maximum length of the history list is determined by the value
3192 of `history-length', which see.")
3194 (defvar shell-command-switch (purecopy "-c")
3195 "Switch used to have the shell execute its command line argument.")
3197 (defvar shell-command-default-error-buffer nil
3198 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3199 This buffer is used when `shell-command' or `shell-command-on-region'
3200 is run interactively. A value of nil means that output to stderr and
3201 stdout will be intermixed in the output stream.")
3203 (declare-function mailcap-file-default-commands "mailcap" (files))
3204 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3206 (defun minibuffer-default-add-shell-commands ()
3207 "Return a list of all commands associated with the current file.
3208 This function is used to add all related commands retrieved by `mailcap'
3209 to the end of the list of defaults just after the default value."
3210 (interactive)
3211 (let* ((filename (if (listp minibuffer-default)
3212 (car minibuffer-default)
3213 minibuffer-default))
3214 (commands (and filename (require 'mailcap nil t)
3215 (mailcap-file-default-commands (list filename)))))
3216 (setq commands (mapcar (lambda (command)
3217 (concat command " " filename))
3218 commands))
3219 (if (listp minibuffer-default)
3220 (append minibuffer-default commands)
3221 (cons minibuffer-default commands))))
3223 (declare-function shell-completion-vars "shell" ())
3225 (defvar minibuffer-local-shell-command-map
3226 (let ((map (make-sparse-keymap)))
3227 (set-keymap-parent map minibuffer-local-map)
3228 (define-key map "\t" 'completion-at-point)
3229 map)
3230 "Keymap used for completing shell commands in minibuffer.")
3232 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3233 "Read a shell command from the minibuffer.
3234 The arguments are the same as the ones of `read-from-minibuffer',
3235 except READ and KEYMAP are missing and HIST defaults
3236 to `shell-command-history'."
3237 (require 'shell)
3238 (minibuffer-with-setup-hook
3239 (lambda ()
3240 (shell-completion-vars)
3241 (set (make-local-variable 'minibuffer-default-add-function)
3242 'minibuffer-default-add-shell-commands))
3243 (apply 'read-from-minibuffer prompt initial-contents
3244 minibuffer-local-shell-command-map
3246 (or hist 'shell-command-history)
3247 args)))
3249 (defcustom async-shell-command-buffer 'confirm-new-buffer
3250 "What to do when the output buffer is used by another shell command.
3251 This option specifies how to resolve the conflict where a new command
3252 wants to direct its output to the buffer `*Async Shell Command*',
3253 but this buffer is already taken by another running shell command.
3255 The value `confirm-kill-process' is used to ask for confirmation before
3256 killing the already running process and running a new process
3257 in the same buffer, `confirm-new-buffer' for confirmation before running
3258 the command in a new buffer with a name other than the default buffer name,
3259 `new-buffer' for doing the same without confirmation,
3260 `confirm-rename-buffer' for confirmation before renaming the existing
3261 output buffer and running a new command in the default buffer,
3262 `rename-buffer' for doing the same without confirmation."
3263 :type '(choice (const :tag "Confirm killing of running command"
3264 confirm-kill-process)
3265 (const :tag "Confirm creation of a new buffer"
3266 confirm-new-buffer)
3267 (const :tag "Create a new buffer"
3268 new-buffer)
3269 (const :tag "Confirm renaming of existing buffer"
3270 confirm-rename-buffer)
3271 (const :tag "Rename the existing buffer"
3272 rename-buffer))
3273 :group 'shell
3274 :version "24.3")
3276 (defcustom async-shell-command-display-buffer t
3277 "Whether to display the command buffer immediately.
3278 If t, display the buffer immediately; if nil, wait until there
3279 is output."
3280 :type '(choice (const :tag "Display buffer immediately"
3282 (const :tag "Display buffer on output"
3283 nil))
3284 :group 'shell
3285 :version "26.1")
3287 (defun shell-command--save-pos-or-erase ()
3288 "Store a buffer position or erase the buffer.
3289 See `shell-command-dont-erase-buffer'."
3290 (let ((sym shell-command-dont-erase-buffer)
3291 pos)
3292 (setq buffer-read-only nil)
3293 ;; Setting buffer-read-only to nil doesn't suffice
3294 ;; if some text has a non-nil read-only property,
3295 ;; which comint sometimes adds for prompts.
3296 (setq pos
3297 (cond ((eq sym 'save-point) (point))
3298 ((eq sym 'beg-last-out) (point-max))
3299 ((not sym)
3300 (let ((inhibit-read-only t))
3301 (erase-buffer) nil))))
3302 (when pos
3303 (goto-char (point-max))
3304 (push (cons (current-buffer) pos)
3305 shell-command-saved-pos))))
3307 (defun shell-command--set-point-after-cmd (&optional buffer)
3308 "Set point in BUFFER after command complete.
3309 BUFFER is the output buffer of the command; if nil, then defaults
3310 to the current BUFFER.
3311 Set point to the `cdr' of the element in `shell-command-saved-pos'
3312 whose `car' is BUFFER."
3313 (when shell-command-dont-erase-buffer
3314 (let* ((sym shell-command-dont-erase-buffer)
3315 (buf (or buffer (current-buffer)))
3316 (pos (alist-get buf shell-command-saved-pos)))
3317 (setq shell-command-saved-pos
3318 (assq-delete-all buf shell-command-saved-pos))
3319 (when (buffer-live-p buf)
3320 (let ((win (car (get-buffer-window-list buf)))
3321 (pmax (with-current-buffer buf (point-max))))
3322 (unless (and pos (memq sym '(save-point beg-last-out)))
3323 (setq pos pmax))
3324 ;; Set point in the window displaying buf, if any; otherwise
3325 ;; display buf temporary in selected frame and set the point.
3326 (if win
3327 (set-window-point win pos)
3328 (save-window-excursion
3329 (let ((win (display-buffer
3331 '(nil (inhibit-switch-frame . t)))))
3332 (set-window-point win pos)))))))))
3334 (defun async-shell-command (command &optional output-buffer error-buffer)
3335 "Execute string COMMAND asynchronously in background.
3337 Like `shell-command', but adds `&' at the end of COMMAND
3338 to execute it asynchronously.
3340 The output appears in the buffer `*Async Shell Command*'.
3341 That buffer is in shell mode.
3343 You can configure `async-shell-command-buffer' to specify what to do in
3344 case when `*Async Shell Command*' buffer is already taken by another
3345 running shell command. To run COMMAND without displaying the output
3346 in a window you can configure `display-buffer-alist' to use the action
3347 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3349 In Elisp, you will often be better served by calling `start-process'
3350 directly, since it offers more control and does not impose the use of a
3351 shell (with its need to quote arguments)."
3352 (interactive
3353 (list
3354 (read-shell-command "Async shell command: " nil nil
3355 (let ((filename
3356 (cond
3357 (buffer-file-name)
3358 ((eq major-mode 'dired-mode)
3359 (dired-get-filename nil t)))))
3360 (and filename (file-relative-name filename))))
3361 current-prefix-arg
3362 shell-command-default-error-buffer))
3363 (unless (string-match "&[ \t]*\\'" command)
3364 (setq command (concat command " &")))
3365 (shell-command command output-buffer error-buffer))
3367 (defun shell-command (command &optional output-buffer error-buffer)
3368 "Execute string COMMAND in inferior shell; display output, if any.
3369 With prefix argument, insert the COMMAND's output at point.
3371 Interactively, prompt for COMMAND in the minibuffer.
3373 If COMMAND ends in `&', execute it asynchronously.
3374 The output appears in the buffer `*Async Shell Command*'.
3375 That buffer is in shell mode. You can also use
3376 `async-shell-command' that automatically adds `&'.
3378 Otherwise, COMMAND is executed synchronously. The output appears in
3379 the buffer `*Shell Command Output*'. If the output is short enough to
3380 display in the echo area (which is determined by the variables
3381 `resize-mini-windows' and `max-mini-window-height'), it is shown
3382 there, but it is nonetheless available in buffer `*Shell Command
3383 Output*' even though that buffer is not automatically displayed.
3385 To specify a coding system for converting non-ASCII characters
3386 in the shell command output, use \\[universal-coding-system-argument] \
3387 before this command.
3389 Noninteractive callers can specify coding systems by binding
3390 `coding-system-for-read' and `coding-system-for-write'.
3392 The optional second argument OUTPUT-BUFFER, if non-nil,
3393 says to put the output in some other buffer.
3394 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3395 and insert the output there; a non-nil value of
3396 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3397 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3398 in current buffer after point leaving mark after it.
3399 This cannot be done asynchronously.
3401 If the command terminates without error, but generates output,
3402 and you did not specify \"insert it in the current buffer\",
3403 the output can be displayed in the echo area or in its buffer.
3404 If the output is short enough to display in the echo area
3405 \(determined by the variable `max-mini-window-height' if
3406 `resize-mini-windows' is non-nil), it is shown there.
3407 Otherwise,the buffer containing the output is displayed.
3409 If there is output and an error, and you did not specify \"insert it
3410 in the current buffer\", a message about the error goes at the end
3411 of the output.
3413 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3414 or buffer name to which to direct the command's standard error output.
3415 If it is nil, error output is mingled with regular output.
3416 In an interactive call, the variable `shell-command-default-error-buffer'
3417 specifies the value of ERROR-BUFFER.
3419 In Elisp, you will often be better served by calling `call-process' or
3420 `start-process' directly, since it offers more control and does not impose
3421 the use of a shell (with its need to quote arguments)."
3423 (interactive
3424 (list
3425 (read-shell-command "Shell command: " nil nil
3426 (let ((filename
3427 (cond
3428 (buffer-file-name)
3429 ((eq major-mode 'dired-mode)
3430 (dired-get-filename nil t)))))
3431 (and filename (file-relative-name filename))))
3432 current-prefix-arg
3433 shell-command-default-error-buffer))
3434 ;; Look for a handler in case default-directory is a remote file name.
3435 (let ((handler
3436 (find-file-name-handler (directory-file-name default-directory)
3437 'shell-command)))
3438 (if handler
3439 (funcall handler 'shell-command command output-buffer error-buffer)
3440 (if (and output-buffer
3441 (not (or (bufferp output-buffer) (stringp output-buffer))))
3442 ;; Output goes in current buffer.
3443 (let ((error-file
3444 (if error-buffer
3445 (make-temp-file
3446 (expand-file-name "scor"
3447 (or small-temporary-file-directory
3448 temporary-file-directory)))
3449 nil)))
3450 (barf-if-buffer-read-only)
3451 (push-mark nil t)
3452 ;; We do not use -f for csh; we will not support broken use of
3453 ;; .cshrcs. Even the BSD csh manual says to use
3454 ;; "if ($?prompt) exit" before things which are not useful
3455 ;; non-interactively. Besides, if someone wants their other
3456 ;; aliases for shell commands then they can still have them.
3457 (call-process shell-file-name nil
3458 (if error-file
3459 (list t error-file)
3461 nil shell-command-switch command)
3462 (when (and error-file (file-exists-p error-file))
3463 (if (< 0 (nth 7 (file-attributes error-file)))
3464 (with-current-buffer (get-buffer-create error-buffer)
3465 (let ((pos-from-end (- (point-max) (point))))
3466 (or (bobp)
3467 (insert "\f\n"))
3468 ;; Do no formatting while reading error file,
3469 ;; because that can run a shell command, and we
3470 ;; don't want that to cause an infinite recursion.
3471 (format-insert-file error-file nil)
3472 ;; Put point after the inserted errors.
3473 (goto-char (- (point-max) pos-from-end)))
3474 (display-buffer (current-buffer))))
3475 (delete-file error-file))
3476 ;; This is like exchange-point-and-mark, but doesn't
3477 ;; activate the mark. It is cleaner to avoid activation,
3478 ;; even though the command loop would deactivate the mark
3479 ;; because we inserted text.
3480 (goto-char (prog1 (mark t)
3481 (set-marker (mark-marker) (point)
3482 (current-buffer)))))
3483 ;; Output goes in a separate buffer.
3484 ;; Preserve the match data in case called from a program.
3485 ;; FIXME: It'd be ridiculous for an Elisp function to call
3486 ;; shell-command and assume that it won't mess the match-data!
3487 (save-match-data
3488 (if (string-match "[ \t]*&[ \t]*\\'" command)
3489 ;; Command ending with ampersand means asynchronous.
3490 (let* ((buffer (get-buffer-create
3491 (or output-buffer "*Async Shell Command*")))
3492 (bname (buffer-name buffer))
3493 (directory default-directory)
3494 proc)
3495 ;; Remove the ampersand.
3496 (setq command (substring command 0 (match-beginning 0)))
3497 ;; Ask the user what to do with already running process.
3498 (setq proc (get-buffer-process buffer))
3499 (when proc
3500 (cond
3501 ((eq async-shell-command-buffer 'confirm-kill-process)
3502 ;; If will kill a process, query first.
3503 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3504 (kill-process proc)
3505 (error "Shell command in progress")))
3506 ((eq async-shell-command-buffer 'confirm-new-buffer)
3507 ;; If will create a new buffer, query first.
3508 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3509 (setq buffer (generate-new-buffer bname))
3510 (error "Shell command in progress")))
3511 ((eq async-shell-command-buffer 'new-buffer)
3512 ;; It will create a new buffer.
3513 (setq buffer (generate-new-buffer bname)))
3514 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3515 ;; If will rename the buffer, query first.
3516 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3517 (progn
3518 (with-current-buffer buffer
3519 (rename-uniquely))
3520 (setq buffer (get-buffer-create bname)))
3521 (error "Shell command in progress")))
3522 ((eq async-shell-command-buffer 'rename-buffer)
3523 ;; It will rename the buffer.
3524 (with-current-buffer buffer
3525 (rename-uniquely))
3526 (setq buffer (get-buffer-create bname)))))
3527 (with-current-buffer buffer
3528 (shell-command--save-pos-or-erase)
3529 (setq default-directory directory)
3530 (setq proc (start-process "Shell" buffer shell-file-name
3531 shell-command-switch command))
3532 (setq mode-line-process '(":%s"))
3533 (require 'shell) (shell-mode)
3534 (set-process-sentinel proc 'shell-command-sentinel)
3535 ;; Use the comint filter for proper handling of
3536 ;; carriage motion (see comint-inhibit-carriage-motion).
3537 (set-process-filter proc 'comint-output-filter)
3538 (if async-shell-command-display-buffer
3539 (display-buffer buffer '(nil (allow-no-window . t)))
3540 (add-function :before (process-filter proc)
3541 (lambda (process _string)
3542 (let ((buf (process-buffer process)))
3543 (when (and (zerop (buffer-size buf))
3544 (string= (buffer-name buf)
3545 bname))
3546 (display-buffer buf))))))))
3547 ;; Otherwise, command is executed synchronously.
3548 (shell-command-on-region (point) (point) command
3549 output-buffer nil error-buffer)))))))
3551 (defun display-message-or-buffer (message &optional buffer-name action frame)
3552 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3553 MESSAGE may be either a string or a buffer.
3555 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3556 for maximum height of the echo area, as defined by `max-mini-window-height'
3557 if `resize-mini-windows' is non-nil.
3559 Returns either the string shown in the echo area, or when a pop-up
3560 buffer is used, the window used to display it.
3562 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3563 name of the buffer used to display it in the case where a pop-up buffer
3564 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3565 string and it is displayed in the echo area, it is not specified whether
3566 the contents are inserted into the buffer anyway.
3568 Optional arguments ACTION and FRAME are as for `display-buffer',
3569 and are only used if a pop-up buffer is displayed."
3570 (cond ((and (stringp message) (not (string-match "\n" message)))
3571 ;; Trivial case where we can use the echo area
3572 (message "%s" message))
3573 ((and (stringp message)
3574 (= (string-match "\n" message) (1- (length message))))
3575 ;; Trivial case where we can just remove single trailing newline
3576 (message "%s" (substring message 0 (1- (length message)))))
3578 ;; General case
3579 (with-current-buffer
3580 (if (bufferp message)
3581 message
3582 (get-buffer-create (or buffer-name "*Message*")))
3584 (unless (bufferp message)
3585 (erase-buffer)
3586 (insert message))
3588 (let ((lines
3589 (if (= (buffer-size) 0)
3591 (count-screen-lines nil nil nil (minibuffer-window)))))
3592 (cond ((= lines 0))
3593 ((and (or (<= lines 1)
3594 (<= lines
3595 (if resize-mini-windows
3596 (cond ((floatp max-mini-window-height)
3597 (* (frame-height)
3598 max-mini-window-height))
3599 ((integerp max-mini-window-height)
3600 max-mini-window-height)
3603 1)))
3604 ;; Don't use the echo area if the output buffer is
3605 ;; already displayed in the selected frame.
3606 (not (get-buffer-window (current-buffer))))
3607 ;; Echo area
3608 (goto-char (point-max))
3609 (when (bolp)
3610 (backward-char 1))
3611 (message "%s" (buffer-substring (point-min) (point))))
3613 ;; Buffer
3614 (goto-char (point-min))
3615 (display-buffer (current-buffer) action frame))))))))
3618 ;; We have a sentinel to prevent insertion of a termination message
3619 ;; in the buffer itself, and to set the point in the buffer when
3620 ;; `shell-command-dont-erase-buffer' is non-nil.
3621 (defun shell-command-sentinel (process signal)
3622 (when (memq (process-status process) '(exit signal))
3623 (shell-command--set-point-after-cmd (process-buffer process))
3624 (message "%s: %s."
3625 (car (cdr (cdr (process-command process))))
3626 (substring signal 0 -1))))
3628 (defun shell-command-on-region (start end command
3629 &optional output-buffer replace
3630 error-buffer display-error-buffer
3631 region-noncontiguous-p)
3632 "Execute string COMMAND in inferior shell with region as input.
3633 Normally display output (if any) in temp buffer `*Shell Command Output*';
3634 Prefix arg means replace the region with it. Return the exit code of
3635 COMMAND.
3637 To specify a coding system for converting non-ASCII characters
3638 in the input and output to the shell command, use \\[universal-coding-system-argument]
3639 before this command. By default, the input (from the current buffer)
3640 is encoded using coding-system specified by `process-coding-system-alist',
3641 falling back to `default-process-coding-system' if no match for COMMAND
3642 is found in `process-coding-system-alist'.
3644 Noninteractive callers can specify coding systems by binding
3645 `coding-system-for-read' and `coding-system-for-write'.
3647 If the command generates output, the output may be displayed
3648 in the echo area or in a buffer.
3649 If the output is short enough to display in the echo area
3650 \(determined by the variable `max-mini-window-height' if
3651 `resize-mini-windows' is non-nil), it is shown there.
3652 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3653 The output is available in that buffer in both cases.
3655 If there is output and an error, a message about the error
3656 appears at the end of the output.
3658 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3659 command's output. If the value is a buffer or buffer name,
3660 erase that buffer and insert the output there; a non-nil value of
3661 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3662 If the value is nil, use the buffer `*Shell Command Output*'.
3663 Any other non-nil value means to insert the output in the
3664 current buffer after START.
3666 Optional fifth arg REPLACE, if non-nil, means to insert the
3667 output in place of text from START to END, putting point and mark
3668 around it.
3670 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3671 or buffer name to which to direct the command's standard error
3672 output. If nil, error output is mingled with regular output.
3673 When called interactively, `shell-command-default-error-buffer'
3674 is used for ERROR-BUFFER.
3676 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3677 display the error buffer if there were any errors. When called
3678 interactively, this is t."
3679 (interactive (let (string)
3680 (unless (mark)
3681 (user-error "The mark is not set now, so there is no region"))
3682 ;; Do this before calling region-beginning
3683 ;; and region-end, in case subprocess output
3684 ;; relocates them while we are in the minibuffer.
3685 (setq string (read-shell-command "Shell command on region: "))
3686 ;; call-interactively recognizes region-beginning and
3687 ;; region-end specially, leaving them in the history.
3688 (list (region-beginning) (region-end)
3689 string
3690 current-prefix-arg
3691 current-prefix-arg
3692 shell-command-default-error-buffer
3694 (region-noncontiguous-p))))
3695 (let ((error-file
3696 (if error-buffer
3697 (make-temp-file
3698 (expand-file-name "scor"
3699 (or small-temporary-file-directory
3700 temporary-file-directory)))
3701 nil))
3702 exit-status)
3703 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3704 (if region-noncontiguous-p
3705 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3706 output)
3707 (with-temp-buffer
3708 (insert input)
3709 (call-process-region (point-min) (point-max)
3710 shell-file-name t t
3711 nil shell-command-switch
3712 command)
3713 (setq output (split-string (buffer-string) "\n")))
3714 (goto-char start)
3715 (funcall region-insert-function output))
3716 (if (or replace
3717 (and output-buffer
3718 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3719 ;; Replace specified region with output from command.
3720 (let ((swap (and replace (< start end))))
3721 ;; Don't muck with mark unless REPLACE says we should.
3722 (goto-char start)
3723 (and replace (push-mark (point) 'nomsg))
3724 (setq exit-status
3725 (call-shell-region start end command replace
3726 (if error-file
3727 (list t error-file)
3728 t)))
3729 ;; It is rude to delete a buffer which the command is not using.
3730 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3731 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3732 ;; (kill-buffer shell-buffer)))
3733 ;; Don't muck with mark unless REPLACE says we should.
3734 (and replace swap (exchange-point-and-mark)))
3735 ;; No prefix argument: put the output in a temp buffer,
3736 ;; replacing its entire contents.
3737 (let ((buffer (get-buffer-create
3738 (or output-buffer "*Shell Command Output*"))))
3739 (unwind-protect
3740 (if (and (eq buffer (current-buffer))
3741 (or (not shell-command-dont-erase-buffer)
3742 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3743 (not (region-active-p)))))
3744 ;; If the input is the same buffer as the output,
3745 ;; delete everything but the specified region,
3746 ;; then replace that region with the output.
3747 (progn (setq buffer-read-only nil)
3748 (delete-region (max start end) (point-max))
3749 (delete-region (point-min) (min start end))
3750 (setq exit-status
3751 (call-process-region (point-min) (point-max)
3752 shell-file-name t
3753 (if error-file
3754 (list t error-file)
3756 nil shell-command-switch
3757 command)))
3758 ;; Clear the output buffer, then run the command with
3759 ;; output there.
3760 (let ((directory default-directory))
3761 (with-current-buffer buffer
3762 (if (not output-buffer)
3763 (setq default-directory directory))
3764 (shell-command--save-pos-or-erase)))
3765 (setq exit-status
3766 (call-shell-region start end command nil
3767 (if error-file
3768 (list buffer error-file)
3769 buffer))))
3770 ;; Report the output.
3771 (with-current-buffer buffer
3772 (setq mode-line-process
3773 (cond ((null exit-status)
3774 " - Error")
3775 ((stringp exit-status)
3776 (format " - Signal [%s]" exit-status))
3777 ((not (equal 0 exit-status))
3778 (format " - Exit [%d]" exit-status)))))
3779 (if (with-current-buffer buffer (> (point-max) (point-min)))
3780 ;; There's some output, display it
3781 (progn
3782 (display-message-or-buffer buffer)
3783 (shell-command--set-point-after-cmd buffer))
3784 ;; No output; error?
3785 (let ((output
3786 (if (and error-file
3787 (< 0 (nth 7 (file-attributes error-file))))
3788 (format "some error output%s"
3789 (if shell-command-default-error-buffer
3790 (format " to the \"%s\" buffer"
3791 shell-command-default-error-buffer)
3792 ""))
3793 "no output")))
3794 (cond ((null exit-status)
3795 (message "(Shell command failed with error)"))
3796 ((equal 0 exit-status)
3797 (message "(Shell command succeeded with %s)"
3798 output))
3799 ((stringp exit-status)
3800 (message "(Shell command killed by signal %s)"
3801 exit-status))
3803 (message "(Shell command failed with code %d and %s)"
3804 exit-status output))))
3805 ;; Don't kill: there might be useful info in the undo-log.
3806 ;; (kill-buffer buffer)
3807 )))))
3809 (when (and error-file (file-exists-p error-file))
3810 (if (< 0 (nth 7 (file-attributes error-file)))
3811 (with-current-buffer (get-buffer-create error-buffer)
3812 (let ((pos-from-end (- (point-max) (point))))
3813 (or (bobp)
3814 (insert "\f\n"))
3815 ;; Do no formatting while reading error file,
3816 ;; because that can run a shell command, and we
3817 ;; don't want that to cause an infinite recursion.
3818 (format-insert-file error-file nil)
3819 ;; Put point after the inserted errors.
3820 (goto-char (- (point-max) pos-from-end)))
3821 (and display-error-buffer
3822 (display-buffer (current-buffer)))))
3823 (delete-file error-file))
3824 exit-status))
3826 (defun shell-command-to-string (command)
3827 "Execute shell command COMMAND and return its output as a string."
3828 (with-output-to-string
3829 (with-current-buffer
3830 standard-output
3831 (process-file shell-file-name nil t nil shell-command-switch command))))
3833 (defun process-file (program &optional infile buffer display &rest args)
3834 "Process files synchronously in a separate process.
3835 Similar to `call-process', but may invoke a file handler based on
3836 `default-directory'. The current working directory of the
3837 subprocess is `default-directory'.
3839 File names in INFILE and BUFFER are handled normally, but file
3840 names in ARGS should be relative to `default-directory', as they
3841 are passed to the process verbatim. (This is a difference to
3842 `call-process' which does not support file handlers for INFILE
3843 and BUFFER.)
3845 Some file handlers might not support all variants, for example
3846 they might behave as if DISPLAY was nil, regardless of the actual
3847 value passed."
3848 (let ((fh (find-file-name-handler default-directory 'process-file))
3849 lc stderr-file)
3850 (unwind-protect
3851 (if fh (apply fh 'process-file program infile buffer display args)
3852 (when infile (setq lc (file-local-copy infile)))
3853 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3854 (make-temp-file "emacs")))
3855 (prog1
3856 (apply 'call-process program
3857 (or lc infile)
3858 (if stderr-file (list (car buffer) stderr-file) buffer)
3859 display args)
3860 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3861 (when stderr-file (delete-file stderr-file))
3862 (when lc (delete-file lc)))))
3864 (defvar process-file-side-effects t
3865 "Whether a call of `process-file' changes remote files.
3867 By default, this variable is always set to t, meaning that a
3868 call of `process-file' could potentially change any file on a
3869 remote host. When set to nil, a file handler could optimize
3870 its behavior with respect to remote file attribute caching.
3872 You should only ever change this variable with a let-binding;
3873 never with `setq'.")
3875 (defun start-file-process (name buffer program &rest program-args)
3876 "Start a program in a subprocess. Return the process object for it.
3878 Similar to `start-process', but may invoke a file handler based on
3879 `default-directory'. See Info node `(elisp)Magic File Names'.
3881 This handler ought to run PROGRAM, perhaps on the local host,
3882 perhaps on a remote host that corresponds to `default-directory'.
3883 In the latter case, the local part of `default-directory' becomes
3884 the working directory of the process.
3886 PROGRAM and PROGRAM-ARGS might be file names. They are not
3887 objects of file handler invocation. File handlers might not
3888 support pty association, if PROGRAM is nil."
3889 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3890 (if fh (apply fh 'start-file-process name buffer program program-args)
3891 (apply 'start-process name buffer program program-args))))
3893 ;;;; Process menu
3895 (defvar tabulated-list-format)
3896 (defvar tabulated-list-entries)
3897 (defvar tabulated-list-sort-key)
3898 (declare-function tabulated-list-init-header "tabulated-list" ())
3899 (declare-function tabulated-list-print "tabulated-list"
3900 (&optional remember-pos update))
3902 (defvar process-menu-query-only nil)
3904 (defvar process-menu-mode-map
3905 (let ((map (make-sparse-keymap)))
3906 (define-key map [?d] 'process-menu-delete-process)
3907 map))
3909 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3910 "Major mode for listing the processes called by Emacs."
3911 (setq tabulated-list-format [("Process" 15 t)
3912 ("PID" 7 t)
3913 ("Status" 7 t)
3914 ("Buffer" 15 t)
3915 ("TTY" 12 t)
3916 ("Command" 0 t)])
3917 (make-local-variable 'process-menu-query-only)
3918 (setq tabulated-list-sort-key (cons "Process" nil))
3919 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3921 (defun process-menu-delete-process ()
3922 "Kill process at point in a `list-processes' buffer."
3923 (interactive)
3924 (let ((pos (point)))
3925 (delete-process (tabulated-list-get-id))
3926 (revert-buffer)
3927 (goto-char (min pos (point-max)))
3928 (if (eobp)
3929 (forward-line -1)
3930 (beginning-of-line))))
3932 (defun list-processes--refresh ()
3933 "Recompute the list of processes for the Process List buffer.
3934 Also, delete any process that is exited or signaled."
3935 (setq tabulated-list-entries nil)
3936 (dolist (p (process-list))
3937 (cond ((memq (process-status p) '(exit signal closed))
3938 (delete-process p))
3939 ((or (not process-menu-query-only)
3940 (process-query-on-exit-flag p))
3941 (let* ((buf (process-buffer p))
3942 (type (process-type p))
3943 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3944 (name (process-name p))
3945 (status (symbol-name (process-status p)))
3946 (buf-label (if (buffer-live-p buf)
3947 `(,(buffer-name buf)
3948 face link
3949 help-echo ,(format-message
3950 "Visit buffer `%s'"
3951 (buffer-name buf))
3952 follow-link t
3953 process-buffer ,buf
3954 action process-menu-visit-buffer)
3955 "--"))
3956 (tty (or (process-tty-name p) "--"))
3957 (cmd
3958 (if (memq type '(network serial))
3959 (let ((contact (process-contact p t)))
3960 (if (eq type 'network)
3961 (format "(%s %s)"
3962 (if (plist-get contact :type)
3963 "datagram"
3964 "network")
3965 (if (plist-get contact :server)
3966 (format "server on %s"
3968 (plist-get contact :host)
3969 (plist-get contact :local)))
3970 (format "connection to %s"
3971 (plist-get contact :host))))
3972 (format "(serial port %s%s)"
3973 (or (plist-get contact :port) "?")
3974 (let ((speed (plist-get contact :speed)))
3975 (if speed
3976 (format " at %s b/s" speed)
3977 "")))))
3978 (mapconcat 'identity (process-command p) " "))))
3979 (push (list p (vector name pid status buf-label tty cmd))
3980 tabulated-list-entries)))))
3981 (tabulated-list-init-header))
3983 (defun process-menu-visit-buffer (button)
3984 (display-buffer (button-get button 'process-buffer)))
3986 (defun list-processes (&optional query-only buffer)
3987 "Display a list of all processes that are Emacs sub-processes.
3988 If optional argument QUERY-ONLY is non-nil, only processes with
3989 the query-on-exit flag set are listed.
3990 Any process listed as exited or signaled is actually eliminated
3991 after the listing is made.
3992 Optional argument BUFFER specifies a buffer to use, instead of
3993 \"*Process List*\".
3994 The return value is always nil.
3996 This function lists only processes that were launched by Emacs. To
3997 see other processes running on the system, use `list-system-processes'."
3998 (interactive)
3999 (or (fboundp 'process-list)
4000 (error "Asynchronous subprocesses are not supported on this system"))
4001 (unless (bufferp buffer)
4002 (setq buffer (get-buffer-create "*Process List*")))
4003 (with-current-buffer buffer
4004 (process-menu-mode)
4005 (setq process-menu-query-only query-only)
4006 (list-processes--refresh)
4007 (tabulated-list-print))
4008 (display-buffer buffer)
4009 nil)
4011 ;;;; Prefix commands
4013 (setq prefix-command--needs-update nil)
4014 (setq prefix-command--last-echo nil)
4016 (defun internal-echo-keystrokes-prefix ()
4017 ;; BEWARE: Called directly from C code.
4018 ;; If the return value is non-nil, it means we are in the middle of
4019 ;; a command with prefix, such as a command invoked with prefix-arg.
4020 (if (not prefix-command--needs-update)
4021 prefix-command--last-echo
4022 (setq prefix-command--last-echo
4023 (let ((strs nil))
4024 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4025 (lambda (fun) (push (funcall fun) strs)))
4026 (setq strs (delq nil strs))
4027 (when strs (mapconcat #'identity strs " "))))))
4029 (defvar prefix-command-echo-keystrokes-functions nil
4030 "Abnormal hook which constructs the description of the current prefix state.
4031 Each function is called with no argument, should return a string or nil.")
4033 (defun prefix-command-update ()
4034 "Update state of prefix commands.
4035 Call it whenever you change the \"prefix command state\"."
4036 (setq prefix-command--needs-update t))
4038 (defvar prefix-command-preserve-state-hook nil
4039 "Normal hook run when a command needs to preserve the prefix.")
4041 (defun prefix-command-preserve-state ()
4042 "Pass the current prefix command state to the next command.
4043 Should be called by all prefix commands.
4044 Runs `prefix-command-preserve-state-hook'."
4045 (run-hooks 'prefix-command-preserve-state-hook)
4046 ;; If the current command is a prefix command, we don't want the next (real)
4047 ;; command to have `last-command' set to, say, `universal-argument'.
4048 (setq this-command last-command)
4049 (setq real-this-command real-last-command)
4050 (prefix-command-update))
4052 (defun reset-this-command-lengths ()
4053 (declare (obsolete prefix-command-preserve-state "25.1"))
4054 nil)
4056 ;;;;; The main prefix command.
4058 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4060 (add-hook 'prefix-command-echo-keystrokes-functions
4061 #'universal-argument--description)
4062 (defun universal-argument--description ()
4063 (when prefix-arg
4064 (concat "C-u"
4065 (pcase prefix-arg
4066 (`(-) " -")
4067 (`(,(and (pred integerp) n))
4068 (let ((str ""))
4069 (while (and (> n 4) (= (mod n 4) 0))
4070 (setq str (concat str " C-u"))
4071 (setq n (/ n 4)))
4072 (if (= n 4) str (format " %s" prefix-arg))))
4073 (_ (format " %s" prefix-arg))))))
4075 (add-hook 'prefix-command-preserve-state-hook
4076 #'universal-argument--preserve)
4077 (defun universal-argument--preserve ()
4078 (setq prefix-arg current-prefix-arg))
4080 (defvar universal-argument-map
4081 (let ((map (make-sparse-keymap))
4082 (universal-argument-minus
4083 ;; For backward compatibility, minus with no modifiers is an ordinary
4084 ;; command if digits have already been entered.
4085 `(menu-item "" negative-argument
4086 :filter ,(lambda (cmd)
4087 (if (integerp prefix-arg) nil cmd)))))
4088 (define-key map [switch-frame]
4089 (lambda (e) (interactive "e")
4090 (handle-switch-frame e) (universal-argument--mode)))
4091 (define-key map [?\C-u] 'universal-argument-more)
4092 (define-key map [?-] universal-argument-minus)
4093 (define-key map [?0] 'digit-argument)
4094 (define-key map [?1] 'digit-argument)
4095 (define-key map [?2] 'digit-argument)
4096 (define-key map [?3] 'digit-argument)
4097 (define-key map [?4] 'digit-argument)
4098 (define-key map [?5] 'digit-argument)
4099 (define-key map [?6] 'digit-argument)
4100 (define-key map [?7] 'digit-argument)
4101 (define-key map [?8] 'digit-argument)
4102 (define-key map [?9] 'digit-argument)
4103 (define-key map [kp-0] 'digit-argument)
4104 (define-key map [kp-1] 'digit-argument)
4105 (define-key map [kp-2] 'digit-argument)
4106 (define-key map [kp-3] 'digit-argument)
4107 (define-key map [kp-4] 'digit-argument)
4108 (define-key map [kp-5] 'digit-argument)
4109 (define-key map [kp-6] 'digit-argument)
4110 (define-key map [kp-7] 'digit-argument)
4111 (define-key map [kp-8] 'digit-argument)
4112 (define-key map [kp-9] 'digit-argument)
4113 (define-key map [kp-subtract] universal-argument-minus)
4114 map)
4115 "Keymap used while processing \\[universal-argument].")
4117 (defun universal-argument--mode ()
4118 (prefix-command-update)
4119 (set-transient-map universal-argument-map nil))
4121 (defun universal-argument ()
4122 "Begin a numeric argument for the following command.
4123 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4124 \\[universal-argument] following the digits or minus sign ends the argument.
4125 \\[universal-argument] without digits or minus sign provides 4 as argument.
4126 Repeating \\[universal-argument] without digits or minus sign
4127 multiplies the argument by 4 each time.
4128 For some commands, just \\[universal-argument] by itself serves as a flag
4129 which is different in effect from any particular numeric argument.
4130 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4131 (interactive)
4132 (prefix-command-preserve-state)
4133 (setq prefix-arg (list 4))
4134 (universal-argument--mode))
4136 (defun universal-argument-more (arg)
4137 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4138 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4139 (interactive "P")
4140 (prefix-command-preserve-state)
4141 (setq prefix-arg (if (consp arg)
4142 (list (* 4 (car arg)))
4143 (if (eq arg '-)
4144 (list -4)
4145 arg)))
4146 (when (consp prefix-arg) (universal-argument--mode)))
4148 (defun negative-argument (arg)
4149 "Begin a negative numeric argument for the next command.
4150 \\[universal-argument] following digits or minus sign ends the argument."
4151 (interactive "P")
4152 (prefix-command-preserve-state)
4153 (setq prefix-arg (cond ((integerp arg) (- arg))
4154 ((eq arg '-) nil)
4155 (t '-)))
4156 (universal-argument--mode))
4158 (defun digit-argument (arg)
4159 "Part of the numeric argument for the next command.
4160 \\[universal-argument] following digits or minus sign ends the argument."
4161 (interactive "P")
4162 (prefix-command-preserve-state)
4163 (let* ((char (if (integerp last-command-event)
4164 last-command-event
4165 (get last-command-event 'ascii-character)))
4166 (digit (- (logand char ?\177) ?0)))
4167 (setq prefix-arg (cond ((integerp arg)
4168 (+ (* arg 10)
4169 (if (< arg 0) (- digit) digit)))
4170 ((eq arg '-)
4171 ;; Treat -0 as just -, so that -01 will work.
4172 (if (zerop digit) '- (- digit)))
4174 digit))))
4175 (universal-argument--mode))
4178 (defvar filter-buffer-substring-functions nil
4179 "This variable is a wrapper hook around `buffer-substring--filter'.
4180 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4181 (make-obsolete-variable 'filter-buffer-substring-functions
4182 'filter-buffer-substring-function "24.4")
4184 (defvar filter-buffer-substring-function #'buffer-substring--filter
4185 "Function to perform the filtering in `filter-buffer-substring'.
4186 The function is called with the same 3 arguments (BEG END DELETE)
4187 that `filter-buffer-substring' received. It should return the
4188 buffer substring between BEG and END, after filtering. If DELETE is
4189 non-nil, it should delete the text between BEG and END from the buffer.")
4191 (defvar buffer-substring-filters nil
4192 "List of filter functions for `buffer-substring--filter'.
4193 Each function must accept a single argument, a string, and return a string.
4194 The buffer substring is passed to the first function in the list,
4195 and the return value of each function is passed to the next.
4196 As a special convention, point is set to the start of the buffer text
4197 being operated on (i.e., the first argument of `buffer-substring--filter')
4198 before these functions are called.")
4199 (make-obsolete-variable 'buffer-substring-filters
4200 'filter-buffer-substring-function "24.1")
4202 (defun filter-buffer-substring (beg end &optional delete)
4203 "Return the buffer substring between BEG and END, after filtering.
4204 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4206 This calls the function that `filter-buffer-substring-function' specifies
4207 \(passing the same three arguments that it received) to do the work,
4208 and returns whatever it does. The default function does no filtering,
4209 unless a hook has been set.
4211 Use `filter-buffer-substring' instead of `buffer-substring',
4212 `buffer-substring-no-properties', or `delete-and-extract-region' when
4213 you want to allow filtering to take place. For example, major or minor
4214 modes can use `filter-buffer-substring-function' to extract characters
4215 that are special to a buffer, and should not be copied into other buffers."
4216 (funcall filter-buffer-substring-function beg end delete))
4218 (defun buffer-substring--filter (beg end &optional delete)
4219 "Default function to use for `filter-buffer-substring-function'.
4220 Its arguments and return value are as specified for `filter-buffer-substring'.
4221 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4222 \(see `with-wrapper-hook' for details about wrapper hooks),
4223 and the abnormal hook `buffer-substring-filters'.
4224 No filtering is done unless a hook says to."
4225 (subr--with-wrapper-hook-no-warnings
4226 filter-buffer-substring-functions (beg end delete)
4227 (cond
4228 ((or delete buffer-substring-filters)
4229 (save-excursion
4230 (goto-char beg)
4231 (let ((string (if delete (delete-and-extract-region beg end)
4232 (buffer-substring beg end))))
4233 (dolist (filter buffer-substring-filters)
4234 (setq string (funcall filter string)))
4235 string)))
4237 (buffer-substring beg end)))))
4240 ;;;; Window system cut and paste hooks.
4242 (defvar interprogram-cut-function #'gui-select-text
4243 "Function to call to make a killed region available to other programs.
4244 Most window systems provide a facility for cutting and pasting
4245 text between different programs, such as the clipboard on X and
4246 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4248 This variable holds a function that Emacs calls whenever text is
4249 put in the kill ring, to make the new kill available to other
4250 programs. The function takes one argument, TEXT, which is a
4251 string containing the text which should be made available.")
4253 (defvar interprogram-paste-function #'gui-selection-value
4254 "Function to call to get text cut from other programs.
4255 Most window systems provide a facility for cutting and pasting
4256 text between different programs, such as the clipboard on X and
4257 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4259 This variable holds a function that Emacs calls to obtain text
4260 that other programs have provided for pasting. The function is
4261 called with no arguments. If no other program has provided text
4262 to paste, the function should return nil (in which case the
4263 caller, usually `current-kill', should use the top of the Emacs
4264 kill ring). If another program has provided text to paste, the
4265 function should return that text as a string (in which case the
4266 caller should put this string in the kill ring as the latest
4267 kill).
4269 The function may also return a list of strings if the window
4270 system supports multiple selections. The first string will be
4271 used as the pasted text, but the other will be placed in the kill
4272 ring for easy access via `yank-pop'.
4274 Note that the function should return a string only if a program
4275 other than Emacs has provided a string for pasting; if Emacs
4276 provided the most recent string, the function should return nil.
4277 If it is difficult to tell whether Emacs or some other program
4278 provided the current string, it is probably good enough to return
4279 nil if the string is equal (according to `string=') to the last
4280 text Emacs provided.")
4284 ;;;; The kill ring data structure.
4286 (defvar kill-ring nil
4287 "List of killed text sequences.
4288 Since the kill ring is supposed to interact nicely with cut-and-paste
4289 facilities offered by window systems, use of this variable should
4290 interact nicely with `interprogram-cut-function' and
4291 `interprogram-paste-function'. The functions `kill-new',
4292 `kill-append', and `current-kill' are supposed to implement this
4293 interaction; you may want to use them instead of manipulating the kill
4294 ring directly.")
4296 (defcustom kill-ring-max 60
4297 "Maximum length of kill ring before oldest elements are thrown away."
4298 :type 'integer
4299 :group 'killing)
4301 (defvar kill-ring-yank-pointer nil
4302 "The tail of the kill ring whose car is the last thing yanked.")
4304 (defcustom save-interprogram-paste-before-kill nil
4305 "Save clipboard strings into kill ring before replacing them.
4306 When one selects something in another program to paste it into Emacs,
4307 but kills something in Emacs before actually pasting it,
4308 this selection is gone unless this variable is non-nil,
4309 in which case the other program's selection is saved in the `kill-ring'
4310 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4311 :type 'boolean
4312 :group 'killing
4313 :version "23.2")
4315 (defcustom kill-do-not-save-duplicates nil
4316 "Do not add a new string to `kill-ring' if it duplicates the last one.
4317 The comparison is done using `equal-including-properties'."
4318 :type 'boolean
4319 :group 'killing
4320 :version "23.2")
4322 (defun kill-new (string &optional replace)
4323 "Make STRING the latest kill in the kill ring.
4324 Set `kill-ring-yank-pointer' to point to it.
4325 If `interprogram-cut-function' is non-nil, apply it to STRING.
4326 Optional second argument REPLACE non-nil means that STRING will replace
4327 the front of the kill ring, rather than being added to the list.
4329 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4330 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4331 STRING.
4333 When the yank handler has a non-nil PARAM element, the original STRING
4334 argument is not used by `insert-for-yank'. However, since Lisp code
4335 may access and use elements from the kill ring directly, the STRING
4336 argument should still be a \"useful\" string for such uses."
4337 (unless (and kill-do-not-save-duplicates
4338 ;; Due to text properties such as 'yank-handler that
4339 ;; can alter the contents to yank, comparison using
4340 ;; `equal' is unsafe.
4341 (equal-including-properties string (car kill-ring)))
4342 (if (fboundp 'menu-bar-update-yank-menu)
4343 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4344 (when save-interprogram-paste-before-kill
4345 (let ((interprogram-paste (and interprogram-paste-function
4346 (funcall interprogram-paste-function))))
4347 (when interprogram-paste
4348 (dolist (s (if (listp interprogram-paste)
4349 (nreverse interprogram-paste)
4350 (list interprogram-paste)))
4351 (unless (and kill-do-not-save-duplicates
4352 (equal-including-properties s (car kill-ring)))
4353 (push s kill-ring))))))
4354 (unless (and kill-do-not-save-duplicates
4355 (equal-including-properties string (car kill-ring)))
4356 (if (and replace kill-ring)
4357 (setcar kill-ring string)
4358 (push string kill-ring)
4359 (if (> (length kill-ring) kill-ring-max)
4360 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4361 (setq kill-ring-yank-pointer kill-ring)
4362 (if interprogram-cut-function
4363 (funcall interprogram-cut-function string)))
4365 ;; It has been argued that this should work similar to `self-insert-command'
4366 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4367 (defcustom kill-append-merge-undo nil
4368 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4369 :type 'boolean
4370 :group 'killing
4371 :version "25.1")
4373 (defun kill-append (string before-p)
4374 "Append STRING to the end of the latest kill in the kill ring.
4375 If BEFORE-P is non-nil, prepend STRING to the kill.
4376 Also removes the last undo boundary in the current buffer,
4377 depending on `kill-append-merge-undo'.
4378 If `interprogram-cut-function' is set, pass the resulting kill to it."
4379 (let* ((cur (car kill-ring)))
4380 (kill-new (if before-p (concat string cur) (concat cur string))
4381 (or (= (length cur) 0)
4382 (equal nil (get-text-property 0 'yank-handler cur))))
4383 (when (and kill-append-merge-undo (not buffer-read-only))
4384 (let ((prev buffer-undo-list)
4385 (next (cdr buffer-undo-list)))
4386 ;; find the next undo boundary
4387 (while (car next)
4388 (pop next)
4389 (pop prev))
4390 ;; remove this undo boundary
4391 (when prev
4392 (setcdr prev (cdr next)))))))
4394 (defcustom yank-pop-change-selection nil
4395 "Whether rotating the kill ring changes the window system selection.
4396 If non-nil, whenever the kill ring is rotated (usually via the
4397 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4398 to copy the new kill to the window system selection."
4399 :type 'boolean
4400 :group 'killing
4401 :version "23.1")
4403 (defun current-kill (n &optional do-not-move)
4404 "Rotate the yanking point by N places, and then return that kill.
4405 If N is zero and `interprogram-paste-function' is set to a
4406 function that returns a string or a list of strings, and if that
4407 function doesn't return nil, then that string (or list) is added
4408 to the front of the kill ring and the string (or first string in
4409 the list) is returned as the latest kill.
4411 If N is not zero, and if `yank-pop-change-selection' is
4412 non-nil, use `interprogram-cut-function' to transfer the
4413 kill at the new yank point into the window system selection.
4415 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4416 move the yanking point; just return the Nth kill forward."
4418 (let ((interprogram-paste (and (= n 0)
4419 interprogram-paste-function
4420 (funcall interprogram-paste-function))))
4421 (if interprogram-paste
4422 (progn
4423 ;; Disable the interprogram cut function when we add the new
4424 ;; text to the kill ring, so Emacs doesn't try to own the
4425 ;; selection, with identical text.
4426 (let ((interprogram-cut-function nil))
4427 (if (listp interprogram-paste)
4428 (mapc 'kill-new (nreverse interprogram-paste))
4429 (kill-new interprogram-paste)))
4430 (car kill-ring))
4431 (or kill-ring (error "Kill ring is empty"))
4432 (let ((ARGth-kill-element
4433 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4434 (length kill-ring))
4435 kill-ring)))
4436 (unless do-not-move
4437 (setq kill-ring-yank-pointer ARGth-kill-element)
4438 (when (and yank-pop-change-selection
4439 (> n 0)
4440 interprogram-cut-function)
4441 (funcall interprogram-cut-function (car ARGth-kill-element))))
4442 (car ARGth-kill-element)))))
4446 ;;;; Commands for manipulating the kill ring.
4448 (defcustom kill-read-only-ok nil
4449 "Non-nil means don't signal an error for killing read-only text."
4450 :type 'boolean
4451 :group 'killing)
4453 (defun kill-region (beg end &optional region)
4454 "Kill (\"cut\") text between point and mark.
4455 This deletes the text from the buffer and saves it in the kill ring.
4456 The command \\[yank] can retrieve it from there.
4457 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4459 If you want to append the killed region to the last killed text,
4460 use \\[append-next-kill] before \\[kill-region].
4462 Any command that calls this function is a \"kill command\".
4463 If the previous command was also a kill command,
4464 the text killed this time appends to the text killed last time
4465 to make one entry in the kill ring.
4467 The killed text is filtered by `filter-buffer-substring' before it is
4468 saved in the kill ring, so the actual saved text might be different
4469 from what was killed.
4471 If the buffer is read-only, Emacs will beep and refrain from deleting
4472 the text, but put the text in the kill ring anyway. This means that
4473 you can use the killing commands to copy text from a read-only buffer.
4475 Lisp programs should use this function for killing text.
4476 (To delete text, use `delete-region'.)
4477 Supply two arguments, character positions BEG and END indicating the
4478 stretch of text to be killed. If the optional argument REGION is
4479 non-nil, the function ignores BEG and END, and kills the current
4480 region instead."
4481 ;; Pass mark first, then point, because the order matters when
4482 ;; calling `kill-append'.
4483 (interactive (list (mark) (point) 'region))
4484 (unless (and beg end)
4485 (user-error "The mark is not set now, so there is no region"))
4486 (condition-case nil
4487 (let ((string (if region
4488 (funcall region-extract-function 'delete)
4489 (filter-buffer-substring beg end 'delete))))
4490 (when string ;STRING is nil if BEG = END
4491 ;; Add that string to the kill ring, one way or another.
4492 (if (eq last-command 'kill-region)
4493 (kill-append string (< end beg))
4494 (kill-new string)))
4495 (when (or string (eq last-command 'kill-region))
4496 (setq this-command 'kill-region))
4497 (setq deactivate-mark t)
4498 nil)
4499 ((buffer-read-only text-read-only)
4500 ;; The code above failed because the buffer, or some of the characters
4501 ;; in the region, are read-only.
4502 ;; We should beep, in case the user just isn't aware of this.
4503 ;; However, there's no harm in putting
4504 ;; the region's text in the kill ring, anyway.
4505 (copy-region-as-kill beg end region)
4506 ;; Set this-command now, so it will be set even if we get an error.
4507 (setq this-command 'kill-region)
4508 ;; This should barf, if appropriate, and give us the correct error.
4509 (if kill-read-only-ok
4510 (progn (message "Read only text copied to kill ring") nil)
4511 ;; Signal an error if the buffer is read-only.
4512 (barf-if-buffer-read-only)
4513 ;; If the buffer isn't read-only, the text is.
4514 (signal 'text-read-only (list (current-buffer)))))))
4516 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4517 ;; to get two copies of the text when the user accidentally types M-w and
4518 ;; then corrects it with the intended C-w.
4519 (defun copy-region-as-kill (beg end &optional region)
4520 "Save the region as if killed, but don't kill it.
4521 In Transient Mark mode, deactivate the mark.
4522 If `interprogram-cut-function' is non-nil, also save the text for a window
4523 system cut and paste.
4525 The copied text is filtered by `filter-buffer-substring' before it is
4526 saved in the kill ring, so the actual saved text might be different
4527 from what was in the buffer.
4529 When called from Lisp, save in the kill ring the stretch of text
4530 between BEG and END, unless the optional argument REGION is
4531 non-nil, in which case ignore BEG and END, and save the current
4532 region instead.
4534 This command's old key binding has been given to `kill-ring-save'."
4535 ;; Pass mark first, then point, because the order matters when
4536 ;; calling `kill-append'.
4537 (interactive (list (mark) (point)
4538 (prefix-numeric-value current-prefix-arg)))
4539 (let ((str (if region
4540 (funcall region-extract-function nil)
4541 (filter-buffer-substring beg end))))
4542 (if (eq last-command 'kill-region)
4543 (kill-append str (< end beg))
4544 (kill-new str)))
4545 (setq deactivate-mark t)
4546 nil)
4548 (defun kill-ring-save (beg end &optional region)
4549 "Save the region as if killed, but don't kill it.
4550 In Transient Mark mode, deactivate the mark.
4551 If `interprogram-cut-function' is non-nil, also save the text for a window
4552 system cut and paste.
4554 If you want to append the killed line to the last killed text,
4555 use \\[append-next-kill] before \\[kill-ring-save].
4557 The copied text is filtered by `filter-buffer-substring' before it is
4558 saved in the kill ring, so the actual saved text might be different
4559 from what was in the buffer.
4561 When called from Lisp, save in the kill ring the stretch of text
4562 between BEG and END, unless the optional argument REGION is
4563 non-nil, in which case ignore BEG and END, and save the current
4564 region instead.
4566 This command is similar to `copy-region-as-kill', except that it gives
4567 visual feedback indicating the extent of the region being copied."
4568 ;; Pass mark first, then point, because the order matters when
4569 ;; calling `kill-append'.
4570 (interactive (list (mark) (point)
4571 (prefix-numeric-value current-prefix-arg)))
4572 (copy-region-as-kill beg end region)
4573 ;; This use of called-interactively-p is correct because the code it
4574 ;; controls just gives the user visual feedback.
4575 (if (called-interactively-p 'interactive)
4576 (indicate-copied-region)))
4578 (defun indicate-copied-region (&optional message-len)
4579 "Indicate that the region text has been copied interactively.
4580 If the mark is visible in the selected window, blink the cursor
4581 between point and mark if there is currently no active region
4582 highlighting.
4584 If the mark lies outside the selected window, display an
4585 informative message containing a sample of the copied text. The
4586 optional argument MESSAGE-LEN, if non-nil, specifies the length
4587 of this sample text; it defaults to 40."
4588 (let ((mark (mark t))
4589 (point (point))
4590 ;; Inhibit quitting so we can make a quit here
4591 ;; look like a C-g typed as a command.
4592 (inhibit-quit t))
4593 (if (pos-visible-in-window-p mark (selected-window))
4594 ;; Swap point-and-mark quickly so as to show the region that
4595 ;; was selected. Don't do it if the region is highlighted.
4596 (unless (and (region-active-p)
4597 (face-background 'region))
4598 ;; Swap point and mark.
4599 (set-marker (mark-marker) (point) (current-buffer))
4600 (goto-char mark)
4601 (sit-for blink-matching-delay)
4602 ;; Swap back.
4603 (set-marker (mark-marker) mark (current-buffer))
4604 (goto-char point)
4605 ;; If user quit, deactivate the mark
4606 ;; as C-g would as a command.
4607 (and quit-flag (region-active-p)
4608 (deactivate-mark)))
4609 (let ((len (min (abs (- mark point))
4610 (or message-len 40))))
4611 (if (< point mark)
4612 ;; Don't say "killed"; that is misleading.
4613 (message "Saved text until \"%s\""
4614 (buffer-substring-no-properties (- mark len) mark))
4615 (message "Saved text from \"%s\""
4616 (buffer-substring-no-properties mark (+ mark len))))))))
4618 (defun append-next-kill (&optional interactive)
4619 "Cause following command, if it kills, to add to previous kill.
4620 If the next command kills forward from point, the kill is
4621 appended to the previous killed text. If the command kills
4622 backward, the kill is prepended. Kill commands that act on the
4623 region, such as `kill-region', are regarded as killing forward if
4624 point is after mark, and killing backward if point is before
4625 mark.
4627 If the next command is not a kill command, `append-next-kill' has
4628 no effect.
4630 The argument is used for internal purposes; do not supply one."
4631 (interactive "p")
4632 ;; We don't use (interactive-p), since that breaks kbd macros.
4633 (if interactive
4634 (progn
4635 (setq this-command 'kill-region)
4636 (message "If the next command is a kill, it will append"))
4637 (setq last-command 'kill-region)))
4639 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4640 "Character set that matches bidirectional formatting control characters.")
4642 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4643 "Character set that matches any character except bidirectional controls.")
4645 (defun squeeze-bidi-context-1 (from to category replacement)
4646 "A subroutine of `squeeze-bidi-context'.
4647 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4648 (let ((pt (copy-marker from))
4649 (limit (copy-marker to))
4650 (old-pt 0)
4651 lim1)
4652 (setq lim1 limit)
4653 (goto-char pt)
4654 (while (< pt limit)
4655 (if (> pt old-pt)
4656 (move-marker lim1
4657 (save-excursion
4658 ;; L and R categories include embedding and
4659 ;; override controls, but we don't want to
4660 ;; replace them, because that might change
4661 ;; the visual order. Likewise with PDF and
4662 ;; isolate controls.
4663 (+ pt (skip-chars-forward
4664 bidi-directional-non-controls-chars
4665 limit)))))
4666 ;; Replace any run of non-RTL characters by a single LRM.
4667 (if (null (re-search-forward category lim1 t))
4668 ;; No more characters of CATEGORY, we are done.
4669 (setq pt limit)
4670 (replace-match replacement nil t)
4671 (move-marker pt (point)))
4672 (setq old-pt pt)
4673 ;; Skip directional controls, if any.
4674 (move-marker
4675 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4677 (defun squeeze-bidi-context (from to)
4678 "Replace characters between FROM and TO while keeping bidi context.
4680 This function replaces the region of text with as few characters
4681 as possible, while preserving the effect that region will have on
4682 bidirectional display before and after the region."
4683 (let ((start (set-marker (make-marker)
4684 (if (> from 0) from (+ (point-max) from))))
4685 (end (set-marker (make-marker) to))
4686 ;; This is for when they copy text with read-only text
4687 ;; properties.
4688 (inhibit-read-only t))
4689 (if (null (marker-position end))
4690 (setq end (point-max-marker)))
4691 ;; Replace each run of non-RTL characters with a single LRM.
4692 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4693 ;; Replace each run of non-LTR characters with a single RLM. Note
4694 ;; that the \cR category includes both the Arabic Letter (AL) and
4695 ;; R characters; here we ignore the distinction between them,
4696 ;; because that distinction only affects Arabic Number (AN)
4697 ;; characters, which are weak and don't affect the reordering.
4698 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4700 (defun line-substring-with-bidi-context (start end &optional no-properties)
4701 "Return buffer text between START and END with its bidi context.
4703 START and END are assumed to belong to the same physical line
4704 of buffer text. This function prepends and appends to the text
4705 between START and END bidi control characters that preserve the
4706 visual order of that text when it is inserted at some other place."
4707 (if (or (< start (point-min))
4708 (> end (point-max)))
4709 (signal 'args-out-of-range (list (current-buffer) start end)))
4710 (let ((buf (current-buffer))
4711 substr para-dir from to)
4712 (save-excursion
4713 (goto-char start)
4714 (setq para-dir (current-bidi-paragraph-direction))
4715 (setq from (line-beginning-position)
4716 to (line-end-position))
4717 (goto-char from)
4718 ;; If we don't have any mixed directional characters in the
4719 ;; entire line, we can just copy the substring without adding
4720 ;; any context.
4721 (if (or (looking-at-p "\\CR*$")
4722 (looking-at-p "\\CL*$"))
4723 (setq substr (if no-properties
4724 (buffer-substring-no-properties start end)
4725 (buffer-substring start end)))
4726 (setq substr
4727 (with-temp-buffer
4728 (if no-properties
4729 (insert-buffer-substring-no-properties buf from to)
4730 (insert-buffer-substring buf from to))
4731 (squeeze-bidi-context 1 (1+ (- start from)))
4732 (squeeze-bidi-context (- end to) nil)
4733 (buffer-substring 1 (point-max)))))
4735 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4736 ;; (1) force the string to have the same base embedding
4737 ;; direction as the paragraph direction at the source, no matter
4738 ;; what is the paragraph direction at destination; and (2) avoid
4739 ;; affecting the visual order of the surrounding text at
4740 ;; destination if there are characters of different
4741 ;; directionality there.
4742 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4743 substr "\x2069"))))
4745 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4746 "Return portion of current buffer between START and END with bidi context.
4748 This function works similar to `buffer-substring', but it prepends and
4749 appends to the text bidi directional control characters necessary to
4750 preserve the visual appearance of the text if it is inserted at another
4751 place. This is useful when the buffer substring includes bidirectional
4752 text and control characters that cause non-trivial reordering on display.
4753 If copied verbatim, such text can have a very different visual appearance,
4754 and can also change the visual appearance of the surrounding text at the
4755 destination of the copy.
4757 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4758 the text properties."
4759 (let (line-end substr)
4760 (if (or (< start (point-min))
4761 (> end (point-max)))
4762 (signal 'args-out-of-range (list (current-buffer) start end)))
4763 (save-excursion
4764 (goto-char start)
4765 (setq line-end (min end (line-end-position)))
4766 (while (< start end)
4767 (setq substr
4768 (concat substr
4769 (if substr "\n" "")
4770 (line-substring-with-bidi-context start line-end
4771 no-properties)))
4772 (forward-line 1)
4773 (setq start (point))
4774 (setq line-end (min end (line-end-position))))
4775 substr)))
4777 ;; Yanking.
4779 (defcustom yank-handled-properties
4780 '((font-lock-face . yank-handle-font-lock-face-property)
4781 (category . yank-handle-category-property))
4782 "List of special text property handling conditions for yanking.
4783 Each element should have the form (PROP . FUN), where PROP is a
4784 property symbol and FUN is a function. When the `yank' command
4785 inserts text into the buffer, it scans the inserted text for
4786 stretches of text that have `eq' values of the text property
4787 PROP; for each such stretch of text, FUN is called with three
4788 arguments: the property's value in that text, and the start and
4789 end positions of the text.
4791 This is done prior to removing the properties specified by
4792 `yank-excluded-properties'."
4793 :group 'killing
4794 :type '(repeat (cons (symbol :tag "property symbol")
4795 function))
4796 :version "24.3")
4798 ;; This is actually used in subr.el but defcustom does not work there.
4799 (defcustom yank-excluded-properties
4800 '(category field follow-link fontified font-lock-face help-echo
4801 intangible invisible keymap local-map mouse-face read-only
4802 yank-handler)
4803 "Text properties to discard when yanking.
4804 The value should be a list of text properties to discard or t,
4805 which means to discard all text properties.
4807 See also `yank-handled-properties'."
4808 :type '(choice (const :tag "All" t) (repeat symbol))
4809 :group 'killing
4810 :version "24.3")
4812 (defvar yank-window-start nil)
4813 (defvar yank-undo-function nil
4814 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4815 Function is called with two parameters, START and END corresponding to
4816 the value of the mark and point; it is guaranteed that START <= END.
4817 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4819 (defun yank-pop (&optional arg)
4820 "Replace just-yanked stretch of killed text with a different stretch.
4821 This command is allowed only immediately after a `yank' or a `yank-pop'.
4822 At such a time, the region contains a stretch of reinserted
4823 previously-killed text. `yank-pop' deletes that text and inserts in its
4824 place a different stretch of killed text.
4826 With no argument, the previous kill is inserted.
4827 With argument N, insert the Nth previous kill.
4828 If N is negative, this is a more recent kill.
4830 The sequence of kills wraps around, so that after the oldest one
4831 comes the newest one.
4833 This command honors the `yank-handled-properties' and
4834 `yank-excluded-properties' variables, and the `yank-handler' text
4835 property, in the way that `yank' does."
4836 (interactive "*p")
4837 (if (not (eq last-command 'yank))
4838 (user-error "Previous command was not a yank"))
4839 (setq this-command 'yank)
4840 (unless arg (setq arg 1))
4841 (let ((inhibit-read-only t)
4842 (before (< (point) (mark t))))
4843 (if before
4844 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4845 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4846 (setq yank-undo-function nil)
4847 (set-marker (mark-marker) (point) (current-buffer))
4848 (insert-for-yank (current-kill arg))
4849 ;; Set the window start back where it was in the yank command,
4850 ;; if possible.
4851 (set-window-start (selected-window) yank-window-start t)
4852 (if before
4853 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4854 ;; It is cleaner to avoid activation, even though the command
4855 ;; loop would deactivate the mark because we inserted text.
4856 (goto-char (prog1 (mark t)
4857 (set-marker (mark-marker) (point) (current-buffer))))))
4858 nil)
4860 (defun yank (&optional arg)
4861 "Reinsert (\"paste\") the last stretch of killed text.
4862 More precisely, reinsert the most recent kill, which is the
4863 stretch of killed text most recently killed OR yanked. Put point
4864 at the end, and set mark at the beginning without activating it.
4865 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4866 With argument N, reinsert the Nth most recent kill.
4868 This command honors the `yank-handled-properties' and
4869 `yank-excluded-properties' variables, and the `yank-handler' text
4870 property, as described below.
4872 Properties listed in `yank-handled-properties' are processed,
4873 then those listed in `yank-excluded-properties' are discarded.
4875 If STRING has a non-nil `yank-handler' property anywhere, the
4876 normal insert behavior is altered, and instead, for each contiguous
4877 segment of STRING that has a given value of the `yank-handler'
4878 property, that value is used as follows:
4880 The value of a `yank-handler' property must be a list of one to four
4881 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4882 FUNCTION, if non-nil, should be a function of one argument (the
4883 object to insert); FUNCTION is called instead of `insert'.
4884 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4885 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4886 PARAM may be a list of strings to insert as a rectangle). If PARAM
4887 is nil, then the current segment of STRING is used.
4888 If NOEXCLUDE is present and non-nil, the normal removal of
4889 `yank-excluded-properties' is not performed; instead FUNCTION is
4890 responsible for the removal. This may be necessary if FUNCTION
4891 adjusts point before or after inserting the object.
4892 UNDO, if present and non-nil, should be a function to be called
4893 by `yank-pop' to undo the insertion of the current PARAM. It is
4894 given two arguments, the start and end of the region. FUNCTION
4895 may set `yank-undo-function' to override UNDO.
4897 See also the command `yank-pop' (\\[yank-pop])."
4898 (interactive "*P")
4899 (setq yank-window-start (window-start))
4900 ;; If we don't get all the way thru, make last-command indicate that
4901 ;; for the following command.
4902 (setq this-command t)
4903 (push-mark)
4904 (insert-for-yank (current-kill (cond
4905 ((listp arg) 0)
4906 ((eq arg '-) -2)
4907 (t (1- arg)))))
4908 (if (consp arg)
4909 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4910 ;; It is cleaner to avoid activation, even though the command
4911 ;; loop would deactivate the mark because we inserted text.
4912 (goto-char (prog1 (mark t)
4913 (set-marker (mark-marker) (point) (current-buffer)))))
4914 ;; If we do get all the way thru, make this-command indicate that.
4915 (if (eq this-command t)
4916 (setq this-command 'yank))
4917 nil)
4919 (defun rotate-yank-pointer (arg)
4920 "Rotate the yanking point in the kill ring.
4921 With ARG, rotate that many kills forward (or backward, if negative)."
4922 (interactive "p")
4923 (current-kill arg))
4925 ;; Some kill commands.
4927 ;; Internal subroutine of delete-char
4928 (defun kill-forward-chars (arg)
4929 (if (listp arg) (setq arg (car arg)))
4930 (if (eq arg '-) (setq arg -1))
4931 (kill-region (point) (+ (point) arg)))
4933 ;; Internal subroutine of backward-delete-char
4934 (defun kill-backward-chars (arg)
4935 (if (listp arg) (setq arg (car arg)))
4936 (if (eq arg '-) (setq arg -1))
4937 (kill-region (point) (- (point) arg)))
4939 (defcustom backward-delete-char-untabify-method 'untabify
4940 "The method for untabifying when deleting backward.
4941 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4942 `hungry' -- delete all whitespace, both tabs and spaces;
4943 `all' -- delete all whitespace, including tabs, spaces and newlines;
4944 nil -- just delete one character."
4945 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4946 :version "20.3"
4947 :group 'killing)
4949 (defun backward-delete-char-untabify (arg &optional killp)
4950 "Delete characters backward, changing tabs into spaces.
4951 The exact behavior depends on `backward-delete-char-untabify-method'.
4952 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4953 Interactively, ARG is the prefix arg (default 1)
4954 and KILLP is t if a prefix arg was specified."
4955 (interactive "*p\nP")
4956 (when (eq backward-delete-char-untabify-method 'untabify)
4957 (let ((count arg))
4958 (save-excursion
4959 (while (and (> count 0) (not (bobp)))
4960 (if (= (preceding-char) ?\t)
4961 (let ((col (current-column)))
4962 (forward-char -1)
4963 (setq col (- col (current-column)))
4964 (insert-char ?\s col)
4965 (delete-char 1)))
4966 (forward-char -1)
4967 (setq count (1- count))))))
4968 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4969 ((eq backward-delete-char-untabify-method 'all)
4970 " \t\n\r")))
4971 (n (if skip
4972 (let* ((oldpt (point))
4973 (wh (- oldpt (save-excursion
4974 (skip-chars-backward skip)
4975 (constrain-to-field nil oldpt)))))
4976 (+ arg (if (zerop wh) 0 (1- wh))))
4977 arg)))
4978 ;; Avoid warning about delete-backward-char
4979 (with-no-warnings (delete-backward-char n killp))))
4981 (defun zap-to-char (arg char)
4982 "Kill up to and including ARGth occurrence of CHAR.
4983 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4984 Goes backward if ARG is negative; error if CHAR not found."
4985 (interactive (list (prefix-numeric-value current-prefix-arg)
4986 (read-char "Zap to char: " t)))
4987 ;; Avoid "obsolete" warnings for translation-table-for-input.
4988 (with-no-warnings
4989 (if (char-table-p translation-table-for-input)
4990 (setq char (or (aref translation-table-for-input char) char))))
4991 (kill-region (point) (progn
4992 (search-forward (char-to-string char) nil nil arg)
4993 (point))))
4995 ;; kill-line and its subroutines.
4997 (defcustom kill-whole-line nil
4998 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4999 :type 'boolean
5000 :group 'killing)
5002 (defun kill-line (&optional arg)
5003 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5004 With prefix argument ARG, kill that many lines from point.
5005 Negative arguments kill lines backward.
5006 With zero argument, kills the text before point on the current line.
5008 When calling from a program, nil means \"no arg\",
5009 a number counts as a prefix arg.
5011 To kill a whole line, when point is not at the beginning, type \
5012 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5014 If `show-trailing-whitespace' is non-nil, this command will just
5015 kill the rest of the current line, even if there are no nonblanks
5016 there.
5018 If option `kill-whole-line' is non-nil, then this command kills the whole line
5019 including its terminating newline, when used at the beginning of a line
5020 with no argument. As a consequence, you can always kill a whole line
5021 by typing \\[move-beginning-of-line] \\[kill-line].
5023 If you want to append the killed line to the last killed text,
5024 use \\[append-next-kill] before \\[kill-line].
5026 If the buffer is read-only, Emacs will beep and refrain from deleting
5027 the line, but put the line in the kill ring anyway. This means that
5028 you can use this command to copy text from a read-only buffer.
5029 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5030 even beep.)"
5031 (interactive "P")
5032 (kill-region (point)
5033 ;; It is better to move point to the other end of the kill
5034 ;; before killing. That way, in a read-only buffer, point
5035 ;; moves across the text that is copied to the kill ring.
5036 ;; The choice has no effect on undo now that undo records
5037 ;; the value of point from before the command was run.
5038 (progn
5039 (if arg
5040 (forward-visible-line (prefix-numeric-value arg))
5041 (if (eobp)
5042 (signal 'end-of-buffer nil))
5043 (let ((end
5044 (save-excursion
5045 (end-of-visible-line) (point))))
5046 (if (or (save-excursion
5047 ;; If trailing whitespace is visible,
5048 ;; don't treat it as nothing.
5049 (unless show-trailing-whitespace
5050 (skip-chars-forward " \t" end))
5051 (= (point) end))
5052 (and kill-whole-line (bolp)))
5053 (forward-visible-line 1)
5054 (goto-char end))))
5055 (point))))
5057 (defun kill-whole-line (&optional arg)
5058 "Kill current line.
5059 With prefix ARG, kill that many lines starting from the current line.
5060 If ARG is negative, kill backward. Also kill the preceding newline.
5061 \(This is meant to make \\[repeat] work well with negative arguments.)
5062 If ARG is zero, kill current line but exclude the trailing newline."
5063 (interactive "p")
5064 (or arg (setq arg 1))
5065 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5066 (signal 'end-of-buffer nil))
5067 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5068 (signal 'beginning-of-buffer nil))
5069 (unless (eq last-command 'kill-region)
5070 (kill-new "")
5071 (setq last-command 'kill-region))
5072 (cond ((zerop arg)
5073 ;; We need to kill in two steps, because the previous command
5074 ;; could have been a kill command, in which case the text
5075 ;; before point needs to be prepended to the current kill
5076 ;; ring entry and the text after point appended. Also, we
5077 ;; need to use save-excursion to avoid copying the same text
5078 ;; twice to the kill ring in read-only buffers.
5079 (save-excursion
5080 (kill-region (point) (progn (forward-visible-line 0) (point))))
5081 (kill-region (point) (progn (end-of-visible-line) (point))))
5082 ((< arg 0)
5083 (save-excursion
5084 (kill-region (point) (progn (end-of-visible-line) (point))))
5085 (kill-region (point)
5086 (progn (forward-visible-line (1+ arg))
5087 (unless (bobp) (backward-char))
5088 (point))))
5090 (save-excursion
5091 (kill-region (point) (progn (forward-visible-line 0) (point))))
5092 (kill-region (point)
5093 (progn (forward-visible-line arg) (point))))))
5095 (defun forward-visible-line (arg)
5096 "Move forward by ARG lines, ignoring currently invisible newlines only.
5097 If ARG is negative, move backward -ARG lines.
5098 If ARG is zero, move to the beginning of the current line."
5099 (condition-case nil
5100 (if (> arg 0)
5101 (progn
5102 (while (> arg 0)
5103 (or (zerop (forward-line 1))
5104 (signal 'end-of-buffer nil))
5105 ;; If the newline we just skipped is invisible,
5106 ;; don't count it.
5107 (let ((prop
5108 (get-char-property (1- (point)) 'invisible)))
5109 (if (if (eq buffer-invisibility-spec t)
5110 prop
5111 (or (memq prop buffer-invisibility-spec)
5112 (assq prop buffer-invisibility-spec)))
5113 (setq arg (1+ arg))))
5114 (setq arg (1- arg)))
5115 ;; If invisible text follows, and it is a number of complete lines,
5116 ;; skip it.
5117 (let ((opoint (point)))
5118 (while (and (not (eobp))
5119 (let ((prop
5120 (get-char-property (point) 'invisible)))
5121 (if (eq buffer-invisibility-spec t)
5122 prop
5123 (or (memq prop buffer-invisibility-spec)
5124 (assq prop buffer-invisibility-spec)))))
5125 (goto-char
5126 (if (get-text-property (point) 'invisible)
5127 (or (next-single-property-change (point) 'invisible)
5128 (point-max))
5129 (next-overlay-change (point)))))
5130 (unless (bolp)
5131 (goto-char opoint))))
5132 (let ((first t))
5133 (while (or first (<= arg 0))
5134 (if first
5135 (beginning-of-line)
5136 (or (zerop (forward-line -1))
5137 (signal 'beginning-of-buffer nil)))
5138 ;; If the newline we just moved to is invisible,
5139 ;; don't count it.
5140 (unless (bobp)
5141 (let ((prop
5142 (get-char-property (1- (point)) 'invisible)))
5143 (unless (if (eq buffer-invisibility-spec t)
5144 prop
5145 (or (memq prop buffer-invisibility-spec)
5146 (assq prop buffer-invisibility-spec)))
5147 (setq arg (1+ arg)))))
5148 (setq first nil))
5149 ;; If invisible text follows, and it is a number of complete lines,
5150 ;; skip it.
5151 (let ((opoint (point)))
5152 (while (and (not (bobp))
5153 (let ((prop
5154 (get-char-property (1- (point)) 'invisible)))
5155 (if (eq buffer-invisibility-spec t)
5156 prop
5157 (or (memq prop buffer-invisibility-spec)
5158 (assq prop buffer-invisibility-spec)))))
5159 (goto-char
5160 (if (get-text-property (1- (point)) 'invisible)
5161 (or (previous-single-property-change (point) 'invisible)
5162 (point-min))
5163 (previous-overlay-change (point)))))
5164 (unless (bolp)
5165 (goto-char opoint)))))
5166 ((beginning-of-buffer end-of-buffer)
5167 nil)))
5169 (defun end-of-visible-line ()
5170 "Move to end of current visible line."
5171 (end-of-line)
5172 ;; If the following character is currently invisible,
5173 ;; skip all characters with that same `invisible' property value,
5174 ;; then find the next newline.
5175 (while (and (not (eobp))
5176 (save-excursion
5177 (skip-chars-forward "^\n")
5178 (let ((prop
5179 (get-char-property (point) 'invisible)))
5180 (if (eq buffer-invisibility-spec t)
5181 prop
5182 (or (memq prop buffer-invisibility-spec)
5183 (assq prop buffer-invisibility-spec))))))
5184 (skip-chars-forward "^\n")
5185 (if (get-text-property (point) 'invisible)
5186 (goto-char (or (next-single-property-change (point) 'invisible)
5187 (point-max)))
5188 (goto-char (next-overlay-change (point))))
5189 (end-of-line)))
5191 (defun kill-current-buffer ()
5192 "Kill the current buffer.
5193 When called in the minibuffer, get out of the minibuffer
5194 using `abort-recursive-edit'.
5196 This is like `kill-this-buffer', but it doesn't have to be invoked
5197 via the menu bar, and pays no attention to the menu-bar's frame."
5198 (interactive)
5199 (let ((frame (selected-frame)))
5200 (if (and (frame-live-p frame)
5201 (not (window-minibuffer-p (frame-selected-window frame))))
5202 (kill-buffer (current-buffer))
5203 (abort-recursive-edit))))
5206 (defun insert-buffer (buffer)
5207 "Insert after point the contents of BUFFER.
5208 Puts mark after the inserted text.
5209 BUFFER may be a buffer or a buffer name."
5210 (declare (interactive-only insert-buffer-substring))
5211 (interactive
5212 (list
5213 (progn
5214 (barf-if-buffer-read-only)
5215 (read-buffer "Insert buffer: "
5216 (if (eq (selected-window) (next-window))
5217 (other-buffer (current-buffer))
5218 (window-buffer (next-window)))
5219 t))))
5220 (push-mark
5221 (save-excursion
5222 (insert-buffer-substring (get-buffer buffer))
5223 (point)))
5224 nil)
5226 (defun append-to-buffer (buffer start end)
5227 "Append to specified buffer the text of the region.
5228 It is inserted into that buffer before its point.
5230 When calling from a program, give three arguments:
5231 BUFFER (or buffer name), START and END.
5232 START and END specify the portion of the current buffer to be copied."
5233 (interactive
5234 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5235 (region-beginning) (region-end)))
5236 (let* ((oldbuf (current-buffer))
5237 (append-to (get-buffer-create buffer))
5238 (windows (get-buffer-window-list append-to t t))
5239 point)
5240 (save-excursion
5241 (with-current-buffer append-to
5242 (setq point (point))
5243 (barf-if-buffer-read-only)
5244 (insert-buffer-substring oldbuf start end)
5245 (dolist (window windows)
5246 (when (= (window-point window) point)
5247 (set-window-point window (point))))))))
5249 (defun prepend-to-buffer (buffer start end)
5250 "Prepend to specified buffer the text of the region.
5251 It is inserted into that buffer after its point.
5253 When calling from a program, give three arguments:
5254 BUFFER (or buffer name), START and END.
5255 START and END specify the portion of the current buffer to be copied."
5256 (interactive "BPrepend to buffer: \nr")
5257 (let ((oldbuf (current-buffer)))
5258 (with-current-buffer (get-buffer-create buffer)
5259 (barf-if-buffer-read-only)
5260 (save-excursion
5261 (insert-buffer-substring oldbuf start end)))))
5263 (defun copy-to-buffer (buffer start end)
5264 "Copy to specified buffer the text of the region.
5265 It is inserted into that buffer, replacing existing text there.
5267 When calling from a program, give three arguments:
5268 BUFFER (or buffer name), START and END.
5269 START and END specify the portion of the current buffer to be copied."
5270 (interactive "BCopy to buffer: \nr")
5271 (let ((oldbuf (current-buffer)))
5272 (with-current-buffer (get-buffer-create buffer)
5273 (barf-if-buffer-read-only)
5274 (erase-buffer)
5275 (save-excursion
5276 (insert-buffer-substring oldbuf start end)))))
5278 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5280 (defvar activate-mark-hook nil
5281 "Hook run when the mark becomes active.
5282 It is also run at the end of a command, if the mark is active and
5283 it is possible that the region may have changed.")
5285 (defvar deactivate-mark-hook nil
5286 "Hook run when the mark becomes inactive.")
5288 (defun mark (&optional force)
5289 "Return this buffer's mark value as integer, or nil if never set.
5291 In Transient Mark mode, this function signals an error if
5292 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5293 or the argument FORCE is non-nil, it disregards whether the mark
5294 is active, and returns an integer or nil in the usual way.
5296 If you are using this in an editing command, you are most likely making
5297 a mistake; see the documentation of `set-mark'."
5298 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5299 (marker-position (mark-marker))
5300 (signal 'mark-inactive nil)))
5302 ;; Behind display-selections-p.
5304 (defun deactivate-mark (&optional force)
5305 "Deactivate the mark.
5306 If Transient Mark mode is disabled, this function normally does
5307 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5309 Deactivating the mark sets `mark-active' to nil, updates the
5310 primary selection according to `select-active-regions', and runs
5311 `deactivate-mark-hook'.
5313 If Transient Mark mode was temporarily enabled, reset the value
5314 of the variable `transient-mark-mode'; if this causes Transient
5315 Mark mode to be disabled, don't change `mark-active' to nil or
5316 run `deactivate-mark-hook'."
5317 (when (or (region-active-p) force)
5318 (when (and (if (eq select-active-regions 'only)
5319 (eq (car-safe transient-mark-mode) 'only)
5320 select-active-regions)
5321 (region-active-p)
5322 (display-selections-p))
5323 ;; The var `saved-region-selection', if non-nil, is the text in
5324 ;; the region prior to the last command modifying the buffer.
5325 ;; Set the selection to that, or to the current region.
5326 (cond (saved-region-selection
5327 (if (gui-backend-selection-owner-p 'PRIMARY)
5328 (gui-set-selection 'PRIMARY saved-region-selection))
5329 (setq saved-region-selection nil))
5330 ;; If another program has acquired the selection, region
5331 ;; deactivation should not clobber it (Bug#11772).
5332 ((and (/= (region-beginning) (region-end))
5333 (or (gui-backend-selection-owner-p 'PRIMARY)
5334 (null (gui-backend-selection-exists-p 'PRIMARY))))
5335 (gui-set-selection 'PRIMARY
5336 (funcall region-extract-function nil)))))
5337 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5338 (cond
5339 ((eq (car-safe transient-mark-mode) 'only)
5340 (setq transient-mark-mode (cdr transient-mark-mode))
5341 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5342 (kill-local-variable 'transient-mark-mode)))
5343 ((eq transient-mark-mode 'lambda)
5344 (kill-local-variable 'transient-mark-mode)))
5345 (setq mark-active nil)
5346 (run-hooks 'deactivate-mark-hook)
5347 (redisplay--update-region-highlight (selected-window))))
5349 (defun activate-mark (&optional no-tmm)
5350 "Activate the mark.
5351 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5352 (when (mark t)
5353 (unless (region-active-p)
5354 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5355 (setq mark-active t)
5356 (unless (or transient-mark-mode no-tmm)
5357 (setq-local transient-mark-mode 'lambda))
5358 (run-hooks 'activate-mark-hook))))
5360 (defun set-mark (pos)
5361 "Set this buffer's mark to POS. Don't use this function!
5362 That is to say, don't use this function unless you want
5363 the user to see that the mark has moved, and you want the previous
5364 mark position to be lost.
5366 Normally, when a new mark is set, the old one should go on the stack.
5367 This is why most applications should use `push-mark', not `set-mark'.
5369 Novice Emacs Lisp programmers often try to use the mark for the wrong
5370 purposes. The mark saves a location for the user's convenience.
5371 Most editing commands should not alter the mark.
5372 To remember a location for internal use in the Lisp program,
5373 store it in a Lisp variable. Example:
5375 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5376 (if pos
5377 (progn
5378 (set-marker (mark-marker) pos (current-buffer))
5379 (activate-mark 'no-tmm))
5380 ;; Normally we never clear mark-active except in Transient Mark mode.
5381 ;; But when we actually clear out the mark value too, we must
5382 ;; clear mark-active in any mode.
5383 (deactivate-mark t)
5384 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5385 ;; it should never be nil if the mark is nil.
5386 (setq mark-active nil)
5387 (set-marker (mark-marker) nil)))
5389 (defun save-mark-and-excursion--save ()
5390 (cons
5391 (let ((mark (mark-marker)))
5392 (and (marker-position mark) (copy-marker mark)))
5393 mark-active))
5395 (defun save-mark-and-excursion--restore (saved-mark-info)
5396 (let ((saved-mark (car saved-mark-info))
5397 (omark (marker-position (mark-marker)))
5398 (nmark nil)
5399 (saved-mark-active (cdr saved-mark-info)))
5400 ;; Mark marker
5401 (if (null saved-mark)
5402 (set-marker (mark-marker) nil)
5403 (setf nmark (marker-position saved-mark))
5404 (set-marker (mark-marker) nmark)
5405 (set-marker saved-mark nil))
5406 ;; Mark active
5407 (let ((cur-mark-active mark-active))
5408 (setq mark-active saved-mark-active)
5409 ;; If mark is active now, and either was not active or was at a
5410 ;; different place, run the activate hook.
5411 (if saved-mark-active
5412 (when (or (not cur-mark-active)
5413 (not (eq omark nmark)))
5414 (run-hooks 'activate-mark-hook))
5415 ;; If mark has ceased to be active, run deactivate hook.
5416 (when cur-mark-active
5417 (run-hooks 'deactivate-mark-hook))))))
5419 (defmacro save-mark-and-excursion (&rest body)
5420 "Like `save-excursion', but also save and restore the mark state.
5421 This macro does what `save-excursion' did before Emacs 25.1."
5422 (declare (indent 0) (debug t))
5423 (let ((saved-marker-sym (make-symbol "saved-marker")))
5424 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5425 (unwind-protect
5426 (save-excursion ,@body)
5427 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5429 (defcustom use-empty-active-region nil
5430 "Whether \"region-aware\" commands should act on empty regions.
5431 If nil, region-aware commands treat the empty region as inactive.
5432 If non-nil, region-aware commands treat the region as active as
5433 long as the mark is active, even if the region is empty.
5435 Region-aware commands are those that act on the region if it is
5436 active and Transient Mark mode is enabled, and on the text near
5437 point otherwise."
5438 :type 'boolean
5439 :version "23.1"
5440 :group 'editing-basics)
5442 (defun use-region-p ()
5443 "Return t if the region is active and it is appropriate to act on it.
5444 This is used by commands that act specially on the region under
5445 Transient Mark mode.
5447 The return value is t if Transient Mark mode is enabled and the
5448 mark is active; furthermore, if `use-empty-active-region' is nil,
5449 the region must not be empty. Otherwise, the return value is nil.
5451 For some commands, it may be appropriate to ignore the value of
5452 `use-empty-active-region'; in that case, use `region-active-p'."
5453 (and (region-active-p)
5454 (or use-empty-active-region (> (region-end) (region-beginning)))))
5456 (defun region-active-p ()
5457 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5459 Some commands act specially on the region when Transient Mark
5460 mode is enabled. Usually, such commands should use
5461 `use-region-p' instead of this function, because `use-region-p'
5462 also checks the value of `use-empty-active-region'."
5463 (and transient-mark-mode mark-active
5464 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5465 ;; without the mark being set (e.g. bug#17324). We really should fix
5466 ;; that problem, but in the mean time, let's make sure we don't say the
5467 ;; region is active when there's no mark.
5468 (progn (cl-assert (mark)) t)))
5470 (defun region-bounds ()
5471 "Return the boundaries of the region as a pair of positions.
5472 Value is a list of cons cells of the form (START . END)."
5473 (funcall region-extract-function 'bounds))
5475 (defun region-noncontiguous-p ()
5476 "Return non-nil if the region contains several pieces.
5477 An example is a rectangular region handled as a list of
5478 separate contiguous regions for each line."
5479 (> (length (region-bounds)) 1))
5481 (defvar redisplay-unhighlight-region-function
5482 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5484 (defvar redisplay-highlight-region-function
5485 (lambda (start end window rol)
5486 (if (not (overlayp rol))
5487 (let ((nrol (make-overlay start end)))
5488 (funcall redisplay-unhighlight-region-function rol)
5489 (overlay-put nrol 'window window)
5490 (overlay-put nrol 'face 'region)
5491 ;; Normal priority so that a large region doesn't hide all the
5492 ;; overlays within it, but high secondary priority so that if it
5493 ;; ends/starts in the middle of a small overlay, that small overlay
5494 ;; won't hide the region's boundaries.
5495 (overlay-put nrol 'priority '(nil . 100))
5496 nrol)
5497 (unless (and (eq (overlay-buffer rol) (current-buffer))
5498 (eq (overlay-start rol) start)
5499 (eq (overlay-end rol) end))
5500 (move-overlay rol start end (current-buffer)))
5501 rol)))
5503 (defun redisplay--update-region-highlight (window)
5504 (let ((rol (window-parameter window 'internal-region-overlay)))
5505 (if (not (and (region-active-p)
5506 (or highlight-nonselected-windows
5507 (eq window (selected-window))
5508 (and (window-minibuffer-p)
5509 (eq window (minibuffer-selected-window))))))
5510 (funcall redisplay-unhighlight-region-function rol)
5511 (let* ((pt (window-point window))
5512 (mark (mark))
5513 (start (min pt mark))
5514 (end (max pt mark))
5515 (new
5516 (funcall redisplay-highlight-region-function
5517 start end window rol)))
5518 (unless (equal new rol)
5519 (set-window-parameter window 'internal-region-overlay
5520 new))))))
5522 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5523 "Hook run just before redisplay.
5524 It is called in each window that is to be redisplayed. It takes one argument,
5525 which is the window that will be redisplayed. When run, the `current-buffer'
5526 is set to the buffer displayed in that window.")
5528 (defun redisplay--pre-redisplay-functions (windows)
5529 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5530 (if (null windows)
5531 (with-current-buffer (window-buffer (selected-window))
5532 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5533 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5534 (with-current-buffer (window-buffer win)
5535 (run-hook-with-args 'pre-redisplay-functions win))))))
5537 (add-function :before pre-redisplay-function
5538 #'redisplay--pre-redisplay-functions)
5541 (defvar-local mark-ring nil
5542 "The list of former marks of the current buffer, most recent first.")
5543 (put 'mark-ring 'permanent-local t)
5545 (defcustom mark-ring-max 16
5546 "Maximum size of mark ring. Start discarding off end if gets this big."
5547 :type 'integer
5548 :group 'editing-basics)
5550 (defvar global-mark-ring nil
5551 "The list of saved global marks, most recent first.")
5553 (defcustom global-mark-ring-max 16
5554 "Maximum size of global mark ring. \
5555 Start discarding off end if gets this big."
5556 :type 'integer
5557 :group 'editing-basics)
5559 (defun pop-to-mark-command ()
5560 "Jump to mark, and pop a new position for mark off the ring.
5561 \(Does not affect global mark ring)."
5562 (interactive)
5563 (if (null (mark t))
5564 (user-error "No mark set in this buffer")
5565 (if (= (point) (mark t))
5566 (message "Mark popped"))
5567 (goto-char (mark t))
5568 (pop-mark)))
5570 (defun push-mark-command (arg &optional nomsg)
5571 "Set mark at where point is.
5572 If no prefix ARG and mark is already set there, just activate it.
5573 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5574 (interactive "P")
5575 (let ((mark (mark t)))
5576 (if (or arg (null mark) (/= mark (point)))
5577 (push-mark nil nomsg t)
5578 (activate-mark 'no-tmm)
5579 (unless nomsg
5580 (message "Mark activated")))))
5582 (defcustom set-mark-command-repeat-pop nil
5583 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5584 That means that C-u \\[set-mark-command] \\[set-mark-command]
5585 will pop the mark twice, and
5586 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5587 will pop the mark three times.
5589 A value of nil means \\[set-mark-command]'s behavior does not change
5590 after C-u \\[set-mark-command]."
5591 :type 'boolean
5592 :group 'editing-basics)
5594 (defun set-mark-command (arg)
5595 "Set the mark where point is, and activate it; or jump to the mark.
5596 Setting the mark also alters the region, which is the text
5597 between point and mark; this is the closest equivalent in
5598 Emacs to what some editors call the \"selection\".
5600 With no prefix argument, set the mark at point, and push the
5601 old mark position on local mark ring. Also push the new mark on
5602 global mark ring, if the previous mark was set in another buffer.
5604 When Transient Mark Mode is off, immediately repeating this
5605 command activates `transient-mark-mode' temporarily.
5607 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5608 jump to the mark, and set the mark from
5609 position popped off the local mark ring (this does not affect the global
5610 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5611 mark ring (see `pop-global-mark').
5613 If `set-mark-command-repeat-pop' is non-nil, repeating
5614 the \\[set-mark-command] command with no prefix argument pops the next position
5615 off the local (or global) mark ring and jumps there.
5617 With \\[universal-argument] \\[universal-argument] as prefix
5618 argument, unconditionally set mark where point is, even if
5619 `set-mark-command-repeat-pop' is non-nil.
5621 Novice Emacs Lisp programmers often try to use the mark for the wrong
5622 purposes. See the documentation of `set-mark' for more information."
5623 (interactive "P")
5624 (cond ((eq transient-mark-mode 'lambda)
5625 (kill-local-variable 'transient-mark-mode))
5626 ((eq (car-safe transient-mark-mode) 'only)
5627 (deactivate-mark)))
5628 (cond
5629 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5630 (push-mark-command nil))
5631 ((not (eq this-command 'set-mark-command))
5632 (if arg
5633 (pop-to-mark-command)
5634 (push-mark-command t)))
5635 ((and set-mark-command-repeat-pop
5636 (eq last-command 'pop-global-mark)
5637 (not arg))
5638 (setq this-command 'pop-global-mark)
5639 (pop-global-mark))
5640 ((or (and set-mark-command-repeat-pop
5641 (eq last-command 'pop-to-mark-command))
5642 arg)
5643 (setq this-command 'pop-to-mark-command)
5644 (pop-to-mark-command))
5645 ((eq last-command 'set-mark-command)
5646 (if (region-active-p)
5647 (progn
5648 (deactivate-mark)
5649 (message "Mark deactivated"))
5650 (activate-mark)
5651 (message "Mark activated")))
5653 (push-mark-command nil))))
5655 (defun push-mark (&optional location nomsg activate)
5656 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5657 If the last global mark pushed was not in the current buffer,
5658 also push LOCATION on the global mark ring.
5659 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5661 Novice Emacs Lisp programmers often try to use the mark for the wrong
5662 purposes. See the documentation of `set-mark' for more information.
5664 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5665 (unless (null (mark t))
5666 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5667 (when (> (length mark-ring) mark-ring-max)
5668 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5669 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5670 (set-marker (mark-marker) (or location (point)) (current-buffer))
5671 ;; Now push the mark on the global mark ring.
5672 (if (and global-mark-ring
5673 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5674 ;; The last global mark pushed was in this same buffer.
5675 ;; Don't push another one.
5677 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5678 (when (> (length global-mark-ring) global-mark-ring-max)
5679 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5680 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5681 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5682 (message "Mark set"))
5683 (if (or activate (not transient-mark-mode))
5684 (set-mark (mark t)))
5685 nil)
5687 (defun pop-mark ()
5688 "Pop off mark ring into the buffer's actual mark.
5689 Does not set point. Does nothing if mark ring is empty."
5690 (when mark-ring
5691 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5692 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5693 (move-marker (car mark-ring) nil)
5694 (if (null (mark t)) (ding))
5695 (setq mark-ring (cdr mark-ring)))
5696 (deactivate-mark))
5698 (define-obsolete-function-alias
5699 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5700 (defun exchange-point-and-mark (&optional arg)
5701 "Put the mark where point is now, and point where the mark is now.
5702 This command works even when the mark is not active,
5703 and it reactivates the mark.
5705 If Transient Mark mode is on, a prefix ARG deactivates the mark
5706 if it is active, and otherwise avoids reactivating it. If
5707 Transient Mark mode is off, a prefix ARG enables Transient Mark
5708 mode temporarily."
5709 (interactive "P")
5710 (let ((omark (mark t))
5711 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5712 (if (null omark)
5713 (user-error "No mark set in this buffer"))
5714 (set-mark (point))
5715 (goto-char omark)
5716 (cond (temp-highlight
5717 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5718 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5719 (not (or arg (region-active-p))))
5720 (deactivate-mark))
5721 (t (activate-mark)))
5722 nil))
5724 (defcustom shift-select-mode t
5725 "When non-nil, shifted motion keys activate the mark momentarily.
5727 While the mark is activated in this way, any shift-translated point
5728 motion key extends the region, and if Transient Mark mode was off, it
5729 is temporarily turned on. Furthermore, the mark will be deactivated
5730 by any subsequent point motion key that was not shift-translated, or
5731 by any action that normally deactivates the mark in Transient Mark mode.
5733 See `this-command-keys-shift-translated' for the meaning of
5734 shift-translation."
5735 :type 'boolean
5736 :group 'editing-basics)
5738 (defun handle-shift-selection ()
5739 "Activate/deactivate mark depending on invocation thru shift translation.
5740 This function is called by `call-interactively' when a command
5741 with a `^' character in its `interactive' spec is invoked, before
5742 running the command itself.
5744 If `shift-select-mode' is enabled and the command was invoked
5745 through shift translation, set the mark and activate the region
5746 temporarily, unless it was already set in this way. See
5747 `this-command-keys-shift-translated' for the meaning of shift
5748 translation.
5750 Otherwise, if the region has been activated temporarily,
5751 deactivate it, and restore the variable `transient-mark-mode' to
5752 its earlier value."
5753 (cond ((and shift-select-mode this-command-keys-shift-translated)
5754 (unless (and mark-active
5755 (eq (car-safe transient-mark-mode) 'only))
5756 (setq-local transient-mark-mode
5757 (cons 'only
5758 (unless (eq transient-mark-mode 'lambda)
5759 transient-mark-mode)))
5760 (push-mark nil nil t)))
5761 ((eq (car-safe transient-mark-mode) 'only)
5762 (setq transient-mark-mode (cdr transient-mark-mode))
5763 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5764 (kill-local-variable 'transient-mark-mode))
5765 (deactivate-mark))))
5767 (define-minor-mode transient-mark-mode
5768 "Toggle Transient Mark mode.
5769 With a prefix argument ARG, enable Transient Mark mode if ARG is
5770 positive, and disable it otherwise. If called from Lisp, enable
5771 Transient Mark mode if ARG is omitted or nil.
5773 Transient Mark mode is a global minor mode. When enabled, the
5774 region is highlighted with the `region' face whenever the mark
5775 is active. The mark is \"deactivated\" by changing the buffer,
5776 and after certain other operations that set the mark but whose
5777 main purpose is something else--for example, incremental search,
5778 \\[beginning-of-buffer], and \\[end-of-buffer].
5780 You can also deactivate the mark by typing \\[keyboard-quit] or
5781 \\[keyboard-escape-quit].
5783 Many commands change their behavior when Transient Mark mode is
5784 in effect and the mark is active, by acting on the region instead
5785 of their usual default part of the buffer's text. Examples of
5786 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5787 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5788 To see the documentation of commands which are sensitive to the
5789 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5790 or \"mark.*active\" at the prompt."
5791 :global t
5792 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5793 :variable (default-value 'transient-mark-mode))
5795 (defvar widen-automatically t
5796 "Non-nil means it is ok for commands to call `widen' when they want to.
5797 Some commands will do this in order to go to positions outside
5798 the current accessible part of the buffer.
5800 If `widen-automatically' is nil, these commands will do something else
5801 as a fallback, and won't change the buffer bounds.")
5803 (defvar non-essential nil
5804 "Whether the currently executing code is performing an essential task.
5805 This variable should be non-nil only when running code which should not
5806 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5807 user for a password when we are simply scanning a set of files in the
5808 background or displaying possible completions before the user even asked
5809 for it.")
5811 (defun pop-global-mark ()
5812 "Pop off global mark ring and jump to the top location."
5813 (interactive)
5814 ;; Pop entries which refer to non-existent buffers.
5815 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5816 (setq global-mark-ring (cdr global-mark-ring)))
5817 (or global-mark-ring
5818 (error "No global mark set"))
5819 (let* ((marker (car global-mark-ring))
5820 (buffer (marker-buffer marker))
5821 (position (marker-position marker)))
5822 (setq global-mark-ring (nconc (cdr global-mark-ring)
5823 (list (car global-mark-ring))))
5824 (set-buffer buffer)
5825 (or (and (>= position (point-min))
5826 (<= position (point-max)))
5827 (if widen-automatically
5828 (widen)
5829 (error "Global mark position is outside accessible part of buffer")))
5830 (goto-char position)
5831 (switch-to-buffer buffer)))
5833 (defcustom next-line-add-newlines nil
5834 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5835 :type 'boolean
5836 :version "21.1"
5837 :group 'editing-basics)
5839 (defun next-line (&optional arg try-vscroll)
5840 "Move cursor vertically down ARG lines.
5841 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5842 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5843 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5844 function will not vscroll.
5846 ARG defaults to 1.
5848 If there is no character in the target line exactly under the current column,
5849 the cursor is positioned after the character in that line which spans this
5850 column, or at the end of the line if it is not long enough.
5851 If there is no line in the buffer after this one, behavior depends on the
5852 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5853 to create a line, and moves the cursor to that line. Otherwise it moves the
5854 cursor to the end of the buffer.
5856 If the variable `line-move-visual' is non-nil, this command moves
5857 by display lines. Otherwise, it moves by buffer lines, without
5858 taking variable-width characters or continued lines into account.
5859 See \\[next-logical-line] for a command that always moves by buffer lines.
5861 The command \\[set-goal-column] can be used to create
5862 a semipermanent goal column for this command.
5863 Then instead of trying to move exactly vertically (or as close as possible),
5864 this command moves to the specified goal column (or as close as possible).
5865 The goal column is stored in the variable `goal-column', which is nil
5866 when there is no goal column. Note that setting `goal-column'
5867 overrides `line-move-visual' and causes this command to move by buffer
5868 lines rather than by display lines."
5869 (declare (interactive-only forward-line))
5870 (interactive "^p\np")
5871 (or arg (setq arg 1))
5872 (if (and next-line-add-newlines (= arg 1))
5873 (if (save-excursion (end-of-line) (eobp))
5874 ;; When adding a newline, don't expand an abbrev.
5875 (let ((abbrev-mode nil))
5876 (end-of-line)
5877 (insert (if use-hard-newlines hard-newline "\n")))
5878 (line-move arg nil nil try-vscroll))
5879 (if (called-interactively-p 'interactive)
5880 (condition-case err
5881 (line-move arg nil nil try-vscroll)
5882 ((beginning-of-buffer end-of-buffer)
5883 (signal (car err) (cdr err))))
5884 (line-move arg nil nil try-vscroll)))
5885 nil)
5887 (defun previous-line (&optional arg try-vscroll)
5888 "Move cursor vertically up ARG lines.
5889 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5890 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5891 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5892 function will not vscroll.
5894 ARG defaults to 1.
5896 If there is no character in the target line exactly over the current column,
5897 the cursor is positioned after the character in that line which spans this
5898 column, or at the end of the line if it is not long enough.
5900 If the variable `line-move-visual' is non-nil, this command moves
5901 by display lines. Otherwise, it moves by buffer lines, without
5902 taking variable-width characters or continued lines into account.
5903 See \\[previous-logical-line] for a command that always moves by buffer lines.
5905 The command \\[set-goal-column] can be used to create
5906 a semipermanent goal column for this command.
5907 Then instead of trying to move exactly vertically (or as close as possible),
5908 this command moves to the specified goal column (or as close as possible).
5909 The goal column is stored in the variable `goal-column', which is nil
5910 when there is no goal column. Note that setting `goal-column'
5911 overrides `line-move-visual' and causes this command to move by buffer
5912 lines rather than by display lines."
5913 (declare (interactive-only
5914 "use `forward-line' with negative argument instead."))
5915 (interactive "^p\np")
5916 (or arg (setq arg 1))
5917 (if (called-interactively-p 'interactive)
5918 (condition-case err
5919 (line-move (- arg) nil nil try-vscroll)
5920 ((beginning-of-buffer end-of-buffer)
5921 (signal (car err) (cdr err))))
5922 (line-move (- arg) nil nil try-vscroll))
5923 nil)
5925 (defcustom track-eol nil
5926 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5927 This means moving to the end of each line moved onto.
5928 The beginning of a blank line does not count as the end of a line.
5929 This has no effect when the variable `line-move-visual' is non-nil."
5930 :type 'boolean
5931 :group 'editing-basics)
5933 (defcustom goal-column nil
5934 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5935 A non-nil setting overrides the variable `line-move-visual', which see."
5936 :type '(choice integer
5937 (const :tag "None" nil))
5938 :group 'editing-basics)
5939 (make-variable-buffer-local 'goal-column)
5941 (defvar temporary-goal-column 0
5942 "Current goal column for vertical motion.
5943 It is the column where point was at the start of the current run
5944 of vertical motion commands.
5946 When moving by visual lines via the function `line-move-visual', it is a cons
5947 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5948 divided by the default column width, and HSCROLL is the number of
5949 columns by which window is scrolled from left margin.
5951 When the `track-eol' feature is doing its job, the value is
5952 `most-positive-fixnum'.")
5954 (defvar last--line-number-width 0
5955 "Last value of width used for displaying line numbers.
5956 Used internally by `line-move-visual'.")
5958 (defcustom line-move-ignore-invisible t
5959 "Non-nil means commands that move by lines ignore invisible newlines.
5960 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5961 as if newlines that are invisible didn't exist, and count
5962 only visible newlines. Thus, moving across 2 newlines
5963 one of which is invisible will be counted as a one-line move.
5964 Also, a non-nil value causes invisible text to be ignored when
5965 counting columns for the purposes of keeping point in the same
5966 column by \\[next-line] and \\[previous-line].
5968 Outline mode sets this."
5969 :type 'boolean
5970 :group 'editing-basics)
5972 (defcustom line-move-visual t
5973 "When non-nil, `line-move' moves point by visual lines.
5974 This movement is based on where the cursor is displayed on the
5975 screen, instead of relying on buffer contents alone. It takes
5976 into account variable-width characters and line continuation.
5977 If nil, `line-move' moves point by logical lines.
5978 A non-nil setting of `goal-column' overrides the value of this variable
5979 and forces movement by logical lines.
5980 A window that is horizontally scrolled also forces movement by logical
5981 lines."
5982 :type 'boolean
5983 :group 'editing-basics
5984 :version "23.1")
5986 ;; Only used if display-graphic-p.
5987 (declare-function font-info "font.c" (name &optional frame))
5989 (defun default-font-height ()
5990 "Return the height in pixels of the current buffer's default face font.
5992 If the default font is remapped (see `face-remapping-alist'), the
5993 function returns the height of the remapped face."
5994 (let ((default-font (face-font 'default)))
5995 (cond
5996 ((and (display-multi-font-p)
5997 ;; Avoid calling font-info if the frame's default font was
5998 ;; not changed since the frame was created. That's because
5999 ;; font-info is expensive for some fonts, see bug #14838.
6000 (not (string= (frame-parameter nil 'font) default-font)))
6001 (aref (font-info default-font) 3))
6002 (t (frame-char-height)))))
6004 (defun default-font-width ()
6005 "Return the width in pixels of the current buffer's default face font.
6007 If the default font is remapped (see `face-remapping-alist'), the
6008 function returns the width of the remapped face."
6009 (let ((default-font (face-font 'default)))
6010 (cond
6011 ((and (display-multi-font-p)
6012 ;; Avoid calling font-info if the frame's default font was
6013 ;; not changed since the frame was created. That's because
6014 ;; font-info is expensive for some fonts, see bug #14838.
6015 (not (string= (frame-parameter nil 'font) default-font)))
6016 (let* ((info (font-info (face-font 'default)))
6017 (width (aref info 11)))
6018 (if (> width 0)
6019 width
6020 (aref info 10))))
6021 (t (frame-char-width)))))
6023 (defun default-line-height ()
6024 "Return the pixel height of current buffer's default-face text line.
6026 The value includes `line-spacing', if any, defined for the buffer
6027 or the frame."
6028 (let ((dfh (default-font-height))
6029 (lsp (if (display-graphic-p)
6030 (or line-spacing
6031 (default-value 'line-spacing)
6032 (frame-parameter nil 'line-spacing)
6034 0)))
6035 (if (floatp lsp)
6036 (setq lsp (truncate (* (frame-char-height) lsp))))
6037 (+ dfh lsp)))
6039 (defun window-screen-lines ()
6040 "Return the number of screen lines in the text area of the selected window.
6042 This is different from `window-text-height' in that this function counts
6043 lines in units of the height of the font used by the default face displayed
6044 in the window, not in units of the frame's default font, and also accounts
6045 for `line-spacing', if any, defined for the window's buffer or frame.
6047 The value is a floating-point number."
6048 (let ((edges (window-inside-pixel-edges))
6049 (dlh (default-line-height)))
6050 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6052 ;; Returns non-nil if partial move was done.
6053 (defun line-move-partial (arg noerror &optional _to-end)
6054 (if (< arg 0)
6055 ;; Move backward (up).
6056 ;; If already vscrolled, reduce vscroll
6057 (let ((vs (window-vscroll nil t))
6058 (dlh (default-line-height)))
6059 (when (> vs dlh)
6060 (set-window-vscroll nil (- vs dlh) t)))
6062 ;; Move forward (down).
6063 (let* ((lh (window-line-height -1))
6064 (rowh (car lh))
6065 (vpos (nth 1 lh))
6066 (ypos (nth 2 lh))
6067 (rbot (nth 3 lh))
6068 (this-lh (window-line-height))
6069 (this-height (car this-lh))
6070 (this-ypos (nth 2 this-lh))
6071 (dlh (default-line-height))
6072 (wslines (window-screen-lines))
6073 (edges (window-inside-pixel-edges))
6074 (winh (- (nth 3 edges) (nth 1 edges) 1))
6075 py vs last-line)
6076 (if (> (mod wslines 1.0) 0.0)
6077 (setq wslines (round (+ wslines 0.5))))
6078 (when (or (null lh)
6079 (>= rbot dlh)
6080 (<= ypos (- dlh))
6081 (null this-lh)
6082 (<= this-ypos (- dlh)))
6083 (unless lh
6084 (let ((wend (pos-visible-in-window-p t nil t)))
6085 (setq rbot (nth 3 wend)
6086 rowh (nth 4 wend)
6087 vpos (nth 5 wend))))
6088 (unless this-lh
6089 (let ((wstart (pos-visible-in-window-p nil nil t)))
6090 (setq this-ypos (nth 2 wstart)
6091 this-height (nth 4 wstart))))
6092 (setq py
6093 (or (nth 1 this-lh)
6094 (let ((ppos (posn-at-point))
6095 col-row)
6096 (setq col-row (posn-actual-col-row ppos))
6097 (if col-row
6098 (- (cdr col-row) (window-vscroll))
6099 (cdr (posn-col-row ppos))))))
6100 ;; VPOS > 0 means the last line is only partially visible.
6101 ;; But if the part that is visible is at least as tall as the
6102 ;; default font, that means the line is actually fully
6103 ;; readable, and something like line-spacing is hidden. So in
6104 ;; that case we accept the last line in the window as still
6105 ;; visible, and consider the margin as starting one line
6106 ;; later.
6107 (if (and vpos (> vpos 0))
6108 (if (and rowh
6109 (>= rowh (default-font-height))
6110 (< rowh dlh))
6111 (setq last-line (min (- wslines scroll-margin) vpos))
6112 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6113 (cond
6114 ;; If last line of window is fully visible, and vscrolling
6115 ;; more would make this line invisible, move forward.
6116 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6117 (null this-height)
6118 (<= this-height dlh))
6119 (or (null rbot) (= rbot 0)))
6120 nil)
6121 ;; If cursor is not in the bottom scroll margin, and the
6122 ;; current line is not too tall, move forward.
6123 ((and (or (null this-height) (<= this-height winh))
6124 vpos
6125 (> vpos 0)
6126 (< py last-line))
6127 nil)
6128 ;; When already vscrolled, we vscroll some more if we can,
6129 ;; or clear vscroll and move forward at end of tall image.
6130 ((> vs 0)
6131 (when (or (and rbot (> rbot 0))
6132 (and this-height (> this-height dlh)))
6133 (set-window-vscroll nil (+ vs dlh) t)))
6134 ;; If cursor just entered the bottom scroll margin, move forward,
6135 ;; but also optionally vscroll one line so redisplay won't recenter.
6136 ((and vpos
6137 (> vpos 0)
6138 (= py last-line))
6139 ;; Don't vscroll if the partially-visible line at window
6140 ;; bottom is not too tall (a.k.a. "just one more text
6141 ;; line"): in that case, we do want redisplay to behave
6142 ;; normally, i.e. recenter or whatever.
6144 ;; Note: ROWH + RBOT from the value returned by
6145 ;; pos-visible-in-window-p give the total height of the
6146 ;; partially-visible glyph row at the end of the window. As
6147 ;; we are dealing with floats, we disregard sub-pixel
6148 ;; discrepancies between that and DLH.
6149 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6150 (set-window-vscroll nil dlh t))
6151 (line-move-1 arg noerror)
6153 ;; If there are lines above the last line, scroll-up one line.
6154 ((and vpos (> vpos 0))
6155 (scroll-up 1)
6157 ;; Finally, start vscroll.
6159 (set-window-vscroll nil dlh t)))))))
6162 ;; This is like line-move-1 except that it also performs
6163 ;; vertical scrolling of tall images if appropriate.
6164 ;; That is not really a clean thing to do, since it mixes
6165 ;; scrolling with cursor motion. But so far we don't have
6166 ;; a cleaner solution to the problem of making C-n do something
6167 ;; useful given a tall image.
6168 (defun line-move (arg &optional noerror _to-end try-vscroll)
6169 "Move forward ARG lines.
6170 If NOERROR, don't signal an error if we can't move ARG lines.
6171 TO-END is unused.
6172 TRY-VSCROLL controls whether to vscroll tall lines: if either
6173 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6174 not vscroll."
6175 (if noninteractive
6176 (line-move-1 arg noerror)
6177 (unless (and auto-window-vscroll try-vscroll
6178 ;; Only vscroll for single line moves
6179 (= (abs arg) 1)
6180 ;; Under scroll-conservatively, the display engine
6181 ;; does this better.
6182 (zerop scroll-conservatively)
6183 ;; But don't vscroll in a keyboard macro.
6184 (not defining-kbd-macro)
6185 (not executing-kbd-macro)
6186 (line-move-partial arg noerror))
6187 (set-window-vscroll nil 0 t)
6188 (if (and line-move-visual
6189 ;; Display-based column are incompatible with goal-column.
6190 (not goal-column)
6191 ;; When the text in the window is scrolled to the left,
6192 ;; display-based motion doesn't make sense (because each
6193 ;; logical line occupies exactly one screen line).
6194 (not (> (window-hscroll) 0))
6195 ;; Likewise when the text _was_ scrolled to the left
6196 ;; when the current run of vertical motion commands
6197 ;; started.
6198 (not (and (memq last-command
6199 `(next-line previous-line ,this-command))
6200 auto-hscroll-mode
6201 (numberp temporary-goal-column)
6202 (>= temporary-goal-column
6203 (- (window-width) hscroll-margin)))))
6204 (prog1 (line-move-visual arg noerror)
6205 ;; If we moved into a tall line, set vscroll to make
6206 ;; scrolling through tall images more smooth.
6207 (let ((lh (line-pixel-height))
6208 (edges (window-inside-pixel-edges))
6209 (dlh (default-line-height))
6210 winh)
6211 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6212 (if (and (< arg 0)
6213 (< (point) (window-start))
6214 (> lh winh))
6215 (set-window-vscroll
6217 (- lh dlh) t))))
6218 (line-move-1 arg noerror)))))
6220 ;; Display-based alternative to line-move-1.
6221 ;; Arg says how many lines to move. The value is t if we can move the
6222 ;; specified number of lines.
6223 (defun line-move-visual (arg &optional noerror)
6224 "Move ARG lines forward.
6225 If NOERROR, don't signal an error if we can't move that many lines."
6226 (let ((opoint (point))
6227 (hscroll (window-hscroll))
6228 (lnum-width (line-number-display-width t))
6229 target-hscroll)
6230 ;; Check if the previous command was a line-motion command, or if
6231 ;; we were called from some other command.
6232 (if (and (consp temporary-goal-column)
6233 (memq last-command `(next-line previous-line ,this-command)))
6234 ;; If so, there's no need to reset `temporary-goal-column',
6235 ;; but we may need to hscroll.
6236 (progn
6237 (if (or (/= (cdr temporary-goal-column) hscroll)
6238 (> (cdr temporary-goal-column) 0))
6239 (setq target-hscroll (cdr temporary-goal-column)))
6240 ;; Update the COLUMN part of temporary-goal-column if the
6241 ;; line-number display changed its width since the last
6242 ;; time.
6243 (setq temporary-goal-column
6244 (cons (+ (car temporary-goal-column)
6245 (/ (float (- lnum-width last--line-number-width))
6246 (frame-char-width)))
6247 (cdr temporary-goal-column)))
6248 (setq last--line-number-width lnum-width))
6249 ;; Otherwise, we should reset `temporary-goal-column'.
6250 (let ((posn (posn-at-point))
6251 x-pos)
6252 (cond
6253 ;; Handle the `overflow-newline-into-fringe' case
6254 ;; (left-fringe is for the R2L case):
6255 ((memq (nth 1 posn) '(right-fringe left-fringe))
6256 (setq temporary-goal-column (cons (window-width) hscroll)))
6257 ((car (posn-x-y posn))
6258 (setq x-pos (car (posn-x-y posn)))
6259 ;; In R2L lines, the X pixel coordinate is measured from the
6260 ;; left edge of the window, but columns are still counted
6261 ;; from the logical-order beginning of the line, i.e. from
6262 ;; the right edge in this case. We need to adjust for that.
6263 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6264 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6265 (setq temporary-goal-column
6266 (cons (/ (float x-pos)
6267 (frame-char-width))
6268 hscroll)))
6269 (executing-kbd-macro
6270 ;; When we move beyond the first/last character visible in
6271 ;; the window, posn-at-point will return nil, so we need to
6272 ;; approximate the goal column as below.
6273 (setq temporary-goal-column
6274 (mod (current-column) (window-text-width)))))))
6275 (if target-hscroll
6276 (set-window-hscroll (selected-window) target-hscroll))
6277 ;; vertical-motion can move more than it was asked to if it moves
6278 ;; across display strings with newlines. We don't want to ring
6279 ;; the bell and announce beginning/end of buffer in that case.
6280 (or (and (or (and (>= arg 0)
6281 (>= (vertical-motion
6282 (cons (or goal-column
6283 (if (consp temporary-goal-column)
6284 (car temporary-goal-column)
6285 temporary-goal-column))
6286 arg))
6287 arg))
6288 (and (< arg 0)
6289 (<= (vertical-motion
6290 (cons (or goal-column
6291 (if (consp temporary-goal-column)
6292 (car temporary-goal-column)
6293 temporary-goal-column))
6294 arg))
6295 arg)))
6296 (or (>= arg 0)
6297 (/= (point) opoint)
6298 ;; If the goal column lies on a display string,
6299 ;; `vertical-motion' advances the cursor to the end
6300 ;; of the string. For arg < 0, this can cause the
6301 ;; cursor to get stuck. (Bug#3020).
6302 (= (vertical-motion arg) arg)))
6303 (unless noerror
6304 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6305 nil)))))
6307 ;; This is the guts of next-line and previous-line.
6308 ;; Arg says how many lines to move.
6309 ;; The value is t if we can move the specified number of lines.
6310 (defun line-move-1 (arg &optional noerror _to-end)
6311 ;; Don't run any point-motion hooks, and disregard intangibility,
6312 ;; for intermediate positions.
6313 (let ((inhibit-point-motion-hooks t)
6314 (opoint (point))
6315 (orig-arg arg))
6316 (if (consp temporary-goal-column)
6317 (setq temporary-goal-column (+ (car temporary-goal-column)
6318 (cdr temporary-goal-column))))
6319 (unwind-protect
6320 (progn
6321 (if (not (memq last-command '(next-line previous-line)))
6322 (setq temporary-goal-column
6323 (if (and track-eol (eolp)
6324 ;; Don't count beg of empty line as end of line
6325 ;; unless we just did explicit end-of-line.
6326 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6327 most-positive-fixnum
6328 (current-column))))
6330 (if (not (or (integerp selective-display)
6331 line-move-ignore-invisible))
6332 ;; Use just newline characters.
6333 ;; Set ARG to 0 if we move as many lines as requested.
6334 (or (if (> arg 0)
6335 (progn (if (> arg 1) (forward-line (1- arg)))
6336 ;; This way of moving forward ARG lines
6337 ;; verifies that we have a newline after the last one.
6338 ;; It doesn't get confused by intangible text.
6339 (end-of-line)
6340 (if (zerop (forward-line 1))
6341 (setq arg 0)))
6342 (and (zerop (forward-line arg))
6343 (bolp)
6344 (setq arg 0)))
6345 (unless noerror
6346 (signal (if (< arg 0)
6347 'beginning-of-buffer
6348 'end-of-buffer)
6349 nil)))
6350 ;; Move by arg lines, but ignore invisible ones.
6351 (let (done)
6352 (while (and (> arg 0) (not done))
6353 ;; If the following character is currently invisible,
6354 ;; skip all characters with that same `invisible' property value.
6355 (while (and (not (eobp)) (invisible-p (point)))
6356 (goto-char (next-char-property-change (point))))
6357 ;; Move a line.
6358 ;; We don't use `end-of-line', since we want to escape
6359 ;; from field boundaries occurring exactly at point.
6360 (goto-char (constrain-to-field
6361 (let ((inhibit-field-text-motion t))
6362 (line-end-position))
6363 (point) t t
6364 'inhibit-line-move-field-capture))
6365 ;; If there's no invisibility here, move over the newline.
6366 (cond
6367 ((eobp)
6368 (if (not noerror)
6369 (signal 'end-of-buffer nil)
6370 (setq done t)))
6371 ((and (> arg 1) ;; Use vertical-motion for last move
6372 (not (integerp selective-display))
6373 (not (invisible-p (point))))
6374 ;; We avoid vertical-motion when possible
6375 ;; because that has to fontify.
6376 (forward-line 1))
6377 ;; Otherwise move a more sophisticated way.
6378 ((zerop (vertical-motion 1))
6379 (if (not noerror)
6380 (signal 'end-of-buffer nil)
6381 (setq done t))))
6382 (unless done
6383 (setq arg (1- arg))))
6384 ;; The logic of this is the same as the loop above,
6385 ;; it just goes in the other direction.
6386 (while (and (< arg 0) (not done))
6387 ;; For completely consistency with the forward-motion
6388 ;; case, we should call beginning-of-line here.
6389 ;; However, if point is inside a field and on a
6390 ;; continued line, the call to (vertical-motion -1)
6391 ;; below won't move us back far enough; then we return
6392 ;; to the same column in line-move-finish, and point
6393 ;; gets stuck -- cyd
6394 (forward-line 0)
6395 (cond
6396 ((bobp)
6397 (if (not noerror)
6398 (signal 'beginning-of-buffer nil)
6399 (setq done t)))
6400 ((and (< arg -1) ;; Use vertical-motion for last move
6401 (not (integerp selective-display))
6402 (not (invisible-p (1- (point)))))
6403 (forward-line -1))
6404 ((zerop (vertical-motion -1))
6405 (if (not noerror)
6406 (signal 'beginning-of-buffer nil)
6407 (setq done t))))
6408 (unless done
6409 (setq arg (1+ arg))
6410 (while (and ;; Don't move over previous invis lines
6411 ;; if our target is the middle of this line.
6412 (or (zerop (or goal-column temporary-goal-column))
6413 (< arg 0))
6414 (not (bobp)) (invisible-p (1- (point))))
6415 (goto-char (previous-char-property-change (point))))))))
6416 ;; This is the value the function returns.
6417 (= arg 0))
6419 (cond ((> arg 0)
6420 ;; If we did not move down as far as desired, at least go
6421 ;; to end of line. Be sure to call point-entered and
6422 ;; point-left-hooks.
6423 (let* ((npoint (prog1 (line-end-position)
6424 (goto-char opoint)))
6425 (inhibit-point-motion-hooks nil))
6426 (goto-char npoint)))
6427 ((< arg 0)
6428 ;; If we did not move up as far as desired,
6429 ;; at least go to beginning of line.
6430 (let* ((npoint (prog1 (line-beginning-position)
6431 (goto-char opoint)))
6432 (inhibit-point-motion-hooks nil))
6433 (goto-char npoint)))
6435 (line-move-finish (or goal-column temporary-goal-column)
6436 opoint (> orig-arg 0)))))))
6438 (defun line-move-finish (column opoint forward)
6439 (let ((repeat t))
6440 (while repeat
6441 ;; Set REPEAT to t to repeat the whole thing.
6442 (setq repeat nil)
6444 (let (new
6445 (old (point))
6446 (line-beg (line-beginning-position))
6447 (line-end
6448 ;; Compute the end of the line
6449 ;; ignoring effectively invisible newlines.
6450 (save-excursion
6451 ;; Like end-of-line but ignores fields.
6452 (skip-chars-forward "^\n")
6453 (while (and (not (eobp)) (invisible-p (point)))
6454 (goto-char (next-char-property-change (point)))
6455 (skip-chars-forward "^\n"))
6456 (point))))
6458 ;; Move to the desired column.
6459 (if (and line-move-visual
6460 (not (or truncate-lines truncate-partial-width-windows)))
6461 ;; Under line-move-visual, goal-column should be
6462 ;; interpreted in units of the frame's canonical character
6463 ;; width, which is exactly what vertical-motion does.
6464 (vertical-motion (cons column 0))
6465 (line-move-to-column (truncate column)))
6467 ;; Corner case: suppose we start out in a field boundary in
6468 ;; the middle of a continued line. When we get to
6469 ;; line-move-finish, point is at the start of a new *screen*
6470 ;; line but the same text line; then line-move-to-column would
6471 ;; move us backwards. Test using C-n with point on the "x" in
6472 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6473 (and forward
6474 (< (point) old)
6475 (goto-char old))
6477 (setq new (point))
6479 ;; Process intangibility within a line.
6480 ;; With inhibit-point-motion-hooks bound to nil, a call to
6481 ;; goto-char moves point past intangible text.
6483 ;; However, inhibit-point-motion-hooks controls both the
6484 ;; intangibility and the point-entered/point-left hooks. The
6485 ;; following hack avoids calling the point-* hooks
6486 ;; unnecessarily. Note that we move *forward* past intangible
6487 ;; text when the initial and final points are the same.
6488 (goto-char new)
6489 (let ((inhibit-point-motion-hooks nil))
6490 (goto-char new)
6492 ;; If intangibility moves us to a different (later) place
6493 ;; in the same line, use that as the destination.
6494 (if (<= (point) line-end)
6495 (setq new (point))
6496 ;; If that position is "too late",
6497 ;; try the previous allowable position.
6498 ;; See if it is ok.
6499 (backward-char)
6500 (if (if forward
6501 ;; If going forward, don't accept the previous
6502 ;; allowable position if it is before the target line.
6503 (< line-beg (point))
6504 ;; If going backward, don't accept the previous
6505 ;; allowable position if it is still after the target line.
6506 (<= (point) line-end))
6507 (setq new (point))
6508 ;; As a last resort, use the end of the line.
6509 (setq new line-end))))
6511 ;; Now move to the updated destination, processing fields
6512 ;; as well as intangibility.
6513 (goto-char opoint)
6514 (let ((inhibit-point-motion-hooks nil))
6515 (goto-char
6516 ;; Ignore field boundaries if the initial and final
6517 ;; positions have the same `field' property, even if the
6518 ;; fields are non-contiguous. This seems to be "nicer"
6519 ;; behavior in many situations.
6520 (if (eq (get-char-property new 'field)
6521 (get-char-property opoint 'field))
6523 (constrain-to-field new opoint t t
6524 'inhibit-line-move-field-capture))))
6526 ;; If all this moved us to a different line,
6527 ;; retry everything within that new line.
6528 (when (or (< (point) line-beg) (> (point) line-end))
6529 ;; Repeat the intangibility and field processing.
6530 (setq repeat t))))))
6532 (defun line-move-to-column (col)
6533 "Try to find column COL, considering invisibility.
6534 This function works only in certain cases,
6535 because what we really need is for `move-to-column'
6536 and `current-column' to be able to ignore invisible text."
6537 (if (zerop col)
6538 (beginning-of-line)
6539 (move-to-column col))
6541 (when (and line-move-ignore-invisible
6542 (not (bolp)) (invisible-p (1- (point))))
6543 (let ((normal-location (point))
6544 (normal-column (current-column)))
6545 ;; If the following character is currently invisible,
6546 ;; skip all characters with that same `invisible' property value.
6547 (while (and (not (eobp))
6548 (invisible-p (point)))
6549 (goto-char (next-char-property-change (point))))
6550 ;; Have we advanced to a larger column position?
6551 (if (> (current-column) normal-column)
6552 ;; We have made some progress towards the desired column.
6553 ;; See if we can make any further progress.
6554 (line-move-to-column (+ (current-column) (- col normal-column)))
6555 ;; Otherwise, go to the place we originally found
6556 ;; and move back over invisible text.
6557 ;; that will get us to the same place on the screen
6558 ;; but with a more reasonable buffer position.
6559 (goto-char normal-location)
6560 (let ((line-beg
6561 ;; We want the real line beginning, so it's consistent
6562 ;; with bolp below, otherwise we might infloop.
6563 (let ((inhibit-field-text-motion t))
6564 (line-beginning-position))))
6565 (while (and (not (bolp)) (invisible-p (1- (point))))
6566 (goto-char (previous-char-property-change (point) line-beg))))))))
6568 (defun move-end-of-line (arg)
6569 "Move point to end of current line as displayed.
6570 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6571 If point reaches the beginning or end of buffer, it stops there.
6573 To ignore the effects of the `intangible' text or overlay
6574 property, bind `inhibit-point-motion-hooks' to t.
6575 If there is an image in the current line, this function
6576 disregards newlines that are part of the text on which the image
6577 rests."
6578 (interactive "^p")
6579 (or arg (setq arg 1))
6580 (let (done)
6581 (while (not done)
6582 (let ((newpos
6583 (save-excursion
6584 (let ((goal-column 0)
6585 (line-move-visual nil))
6586 (and (line-move arg t)
6587 ;; With bidi reordering, we may not be at bol,
6588 ;; so make sure we are.
6589 (skip-chars-backward "^\n")
6590 (not (bobp))
6591 (progn
6592 (while (and (not (bobp)) (invisible-p (1- (point))))
6593 (goto-char (previous-single-char-property-change
6594 (point) 'invisible)))
6595 (backward-char 1)))
6596 (point)))))
6597 (goto-char newpos)
6598 (if (and (> (point) newpos)
6599 (eq (preceding-char) ?\n))
6600 (backward-char 1)
6601 (if (and (> (point) newpos) (not (eobp))
6602 (not (eq (following-char) ?\n)))
6603 ;; If we skipped something intangible and now we're not
6604 ;; really at eol, keep going.
6605 (setq arg 1)
6606 (setq done t)))))))
6608 (defun move-beginning-of-line (arg)
6609 "Move point to beginning of current line as displayed.
6610 \(If there's an image in the line, this disregards newlines
6611 which are part of the text that the image rests on.)
6613 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6614 If point reaches the beginning or end of buffer, it stops there.
6615 \(But if the buffer doesn't end in a newline, it stops at the
6616 beginning of the last line.)
6617 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6618 (interactive "^p")
6619 (or arg (setq arg 1))
6621 (let ((orig (point))
6622 first-vis first-vis-field-value)
6624 ;; Move by lines, if ARG is not 1 (the default).
6625 (if (/= arg 1)
6626 (let ((line-move-visual nil))
6627 (line-move (1- arg) t)))
6629 ;; Move to beginning-of-line, ignoring fields and invisible text.
6630 (skip-chars-backward "^\n")
6631 (while (and (not (bobp)) (invisible-p (1- (point))))
6632 (goto-char (previous-char-property-change (point)))
6633 (skip-chars-backward "^\n"))
6635 ;; Now find first visible char in the line.
6636 (while (and (< (point) orig) (invisible-p (point)))
6637 (goto-char (next-char-property-change (point) orig)))
6638 (setq first-vis (point))
6640 ;; See if fields would stop us from reaching FIRST-VIS.
6641 (setq first-vis-field-value
6642 (constrain-to-field first-vis orig (/= arg 1) t nil))
6644 (goto-char (if (/= first-vis-field-value first-vis)
6645 ;; If yes, obey them.
6646 first-vis-field-value
6647 ;; Otherwise, move to START with attention to fields.
6648 ;; (It is possible that fields never matter in this case.)
6649 (constrain-to-field (point) orig
6650 (/= arg 1) t nil)))))
6653 ;; Many people have said they rarely use this feature, and often type
6654 ;; it by accident. Maybe it shouldn't even be on a key.
6655 (put 'set-goal-column 'disabled t)
6657 (defun set-goal-column (arg)
6658 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6659 Those commands will move to this position in the line moved to
6660 rather than trying to keep the same horizontal position.
6661 With a non-nil argument ARG, clears out the goal column
6662 so that \\[next-line] and \\[previous-line] resume vertical motion.
6663 The goal column is stored in the variable `goal-column'.
6664 This is a buffer-local setting."
6665 (interactive "P")
6666 (if arg
6667 (progn
6668 (setq goal-column nil)
6669 (message "No goal column"))
6670 (setq goal-column (current-column))
6671 ;; The older method below can be erroneous if `set-goal-column' is bound
6672 ;; to a sequence containing %
6673 ;;(message (substitute-command-keys
6674 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6675 ;;goal-column)
6676 (message "%s"
6677 (concat
6678 (format "Goal column %d " goal-column)
6679 (substitute-command-keys
6680 "(use \\[set-goal-column] with an arg to unset it)")))
6683 nil)
6685 ;;; Editing based on visual lines, as opposed to logical lines.
6687 (defun end-of-visual-line (&optional n)
6688 "Move point to end of current visual line.
6689 With argument N not nil or 1, move forward N - 1 visual lines first.
6690 If point reaches the beginning or end of buffer, it stops there.
6691 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6692 (interactive "^p")
6693 (or n (setq n 1))
6694 (if (/= n 1)
6695 (let ((line-move-visual t))
6696 (line-move (1- n) t)))
6697 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6698 ;; constrain to field boundaries, so we don't either.
6699 (vertical-motion (cons (window-width) 0)))
6701 (defun beginning-of-visual-line (&optional n)
6702 "Move point to beginning of current visual line.
6703 With argument N not nil or 1, move forward N - 1 visual lines first.
6704 If point reaches the beginning or end of buffer, it stops there.
6705 \(But if the buffer doesn't end in a newline, it stops at the
6706 beginning of the last visual line.)
6707 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6708 (interactive "^p")
6709 (or n (setq n 1))
6710 (let ((opoint (point)))
6711 (if (/= n 1)
6712 (let ((line-move-visual t))
6713 (line-move (1- n) t)))
6714 (vertical-motion 0)
6715 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6716 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6718 (defun kill-visual-line (&optional arg)
6719 "Kill the rest of the visual line.
6720 With prefix argument ARG, kill that many visual lines from point.
6721 If ARG is negative, kill visual lines backward.
6722 If ARG is zero, kill the text before point on the current visual
6723 line.
6725 If you want to append the killed line to the last killed text,
6726 use \\[append-next-kill] before \\[kill-line].
6728 If the buffer is read-only, Emacs will beep and refrain from deleting
6729 the line, but put the line in the kill ring anyway. This means that
6730 you can use this command to copy text from a read-only buffer.
6731 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6732 even beep.)"
6733 (interactive "P")
6734 ;; Like in `kill-line', it's better to move point to the other end
6735 ;; of the kill before killing.
6736 (let ((opoint (point))
6737 (kill-whole-line (and kill-whole-line (bolp))))
6738 (if arg
6739 (vertical-motion (prefix-numeric-value arg))
6740 (end-of-visual-line 1)
6741 (if (= (point) opoint)
6742 (vertical-motion 1)
6743 ;; Skip any trailing whitespace at the end of the visual line.
6744 ;; We used to do this only if `show-trailing-whitespace' is
6745 ;; nil, but that's wrong; the correct thing would be to check
6746 ;; whether the trailing whitespace is highlighted. But, it's
6747 ;; OK to just do this unconditionally.
6748 (skip-chars-forward " \t")))
6749 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6750 (1+ (point))
6751 (point)))))
6753 (defun next-logical-line (&optional arg try-vscroll)
6754 "Move cursor vertically down ARG lines.
6755 This is identical to `next-line', except that it always moves
6756 by logical lines instead of visual lines, ignoring the value of
6757 the variable `line-move-visual'."
6758 (interactive "^p\np")
6759 (let ((line-move-visual nil))
6760 (with-no-warnings
6761 (next-line arg try-vscroll))))
6763 (defun previous-logical-line (&optional arg try-vscroll)
6764 "Move cursor vertically up ARG lines.
6765 This is identical to `previous-line', except that it always moves
6766 by logical lines instead of visual lines, ignoring the value of
6767 the variable `line-move-visual'."
6768 (interactive "^p\np")
6769 (let ((line-move-visual nil))
6770 (with-no-warnings
6771 (previous-line arg try-vscroll))))
6773 (defgroup visual-line nil
6774 "Editing based on visual lines."
6775 :group 'convenience
6776 :version "23.1")
6778 (defvar visual-line-mode-map
6779 (let ((map (make-sparse-keymap)))
6780 (define-key map [remap kill-line] 'kill-visual-line)
6781 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6782 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6783 ;; These keybindings interfere with xterm function keys. Are
6784 ;; there any other suitable bindings?
6785 ;; (define-key map "\M-[" 'previous-logical-line)
6786 ;; (define-key map "\M-]" 'next-logical-line)
6787 map))
6789 (defcustom visual-line-fringe-indicators '(nil nil)
6790 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6791 The value should be a list of the form (LEFT RIGHT), where LEFT
6792 and RIGHT are symbols representing the bitmaps to display, to
6793 indicate wrapped lines, in the left and right fringes respectively.
6794 See also `fringe-indicator-alist'.
6795 The default is not to display fringe indicators for wrapped lines.
6796 This variable does not affect fringe indicators displayed for
6797 other purposes."
6798 :type '(list (choice (const :tag "Hide left indicator" nil)
6799 (const :tag "Left curly arrow" left-curly-arrow)
6800 (symbol :tag "Other bitmap"))
6801 (choice (const :tag "Hide right indicator" nil)
6802 (const :tag "Right curly arrow" right-curly-arrow)
6803 (symbol :tag "Other bitmap")))
6804 :set (lambda (symbol value)
6805 (dolist (buf (buffer-list))
6806 (with-current-buffer buf
6807 (when (and (boundp 'visual-line-mode)
6808 (symbol-value 'visual-line-mode))
6809 (setq fringe-indicator-alist
6810 (cons (cons 'continuation value)
6811 (assq-delete-all
6812 'continuation
6813 (copy-tree fringe-indicator-alist)))))))
6814 (set-default symbol value)))
6816 (defvar visual-line--saved-state nil)
6818 (define-minor-mode visual-line-mode
6819 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6820 Interactively, with a prefix argument, enable
6821 Visual Line mode if the prefix argument is positive,
6822 and disable it otherwise. If called from Lisp, toggle
6823 the mode if ARG is `toggle', disable the mode if ARG is
6824 a non-positive integer, and enable the mode otherwise
6825 \(including if ARG is omitted or nil or a positive integer).
6827 When Visual Line mode is enabled, `word-wrap' is turned on in
6828 this buffer, and simple editing commands are redefined to act on
6829 visual lines, not logical lines. See Info node `Visual Line
6830 Mode' for details."
6831 :keymap visual-line-mode-map
6832 :group 'visual-line
6833 :lighter " Wrap"
6834 (if visual-line-mode
6835 (progn
6836 (set (make-local-variable 'visual-line--saved-state) nil)
6837 ;; Save the local values of some variables, to be restored if
6838 ;; visual-line-mode is turned off.
6839 (dolist (var '(line-move-visual truncate-lines
6840 truncate-partial-width-windows
6841 word-wrap fringe-indicator-alist))
6842 (if (local-variable-p var)
6843 (push (cons var (symbol-value var))
6844 visual-line--saved-state)))
6845 (set (make-local-variable 'line-move-visual) t)
6846 (set (make-local-variable 'truncate-partial-width-windows) nil)
6847 (setq truncate-lines nil
6848 word-wrap t
6849 fringe-indicator-alist
6850 (cons (cons 'continuation visual-line-fringe-indicators)
6851 fringe-indicator-alist)))
6852 (kill-local-variable 'line-move-visual)
6853 (kill-local-variable 'word-wrap)
6854 (kill-local-variable 'truncate-lines)
6855 (kill-local-variable 'truncate-partial-width-windows)
6856 (kill-local-variable 'fringe-indicator-alist)
6857 (dolist (saved visual-line--saved-state)
6858 (set (make-local-variable (car saved)) (cdr saved)))
6859 (kill-local-variable 'visual-line--saved-state)))
6861 (defun turn-on-visual-line-mode ()
6862 (visual-line-mode 1))
6864 (define-globalized-minor-mode global-visual-line-mode
6865 visual-line-mode turn-on-visual-line-mode)
6868 (defun transpose-chars (arg)
6869 "Interchange characters around point, moving forward one character.
6870 With prefix arg ARG, effect is to take character before point
6871 and drag it forward past ARG other characters (backward if ARG negative).
6872 If no argument and at end of line, the previous two chars are exchanged."
6873 (interactive "*P")
6874 (when (and (null arg) (eolp) (not (bobp))
6875 (not (get-text-property (1- (point)) 'read-only)))
6876 (forward-char -1))
6877 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6879 (defun transpose-words (arg)
6880 "Interchange words around point, leaving point at end of them.
6881 With prefix arg ARG, effect is to take word before or around point
6882 and drag it forward past ARG other words (backward if ARG negative).
6883 If ARG is zero, the words around or after point and around or after mark
6884 are interchanged."
6885 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6886 (interactive "*p")
6887 (transpose-subr 'forward-word arg))
6889 (defun transpose-sexps (arg)
6890 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6891 Unlike `transpose-words', point must be between the two sexps and not
6892 in the middle of a sexp to be transposed.
6893 With non-zero prefix arg ARG, effect is to take the sexp before point
6894 and drag it forward past ARG other sexps (backward if ARG is negative).
6895 If ARG is zero, the sexps ending at or after point and at or after mark
6896 are interchanged."
6897 (interactive "*p")
6898 (transpose-subr
6899 (lambda (arg)
6900 ;; Here we should try to simulate the behavior of
6901 ;; (cons (progn (forward-sexp x) (point))
6902 ;; (progn (forward-sexp (- x)) (point)))
6903 ;; Except that we don't want to rely on the second forward-sexp
6904 ;; putting us back to where we want to be, since forward-sexp-function
6905 ;; might do funny things like infix-precedence.
6906 (if (if (> arg 0)
6907 (looking-at "\\sw\\|\\s_")
6908 (and (not (bobp))
6909 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6910 ;; Jumping over a symbol. We might be inside it, mind you.
6911 (progn (funcall (if (> arg 0)
6912 'skip-syntax-backward 'skip-syntax-forward)
6913 "w_")
6914 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6915 ;; Otherwise, we're between sexps. Take a step back before jumping
6916 ;; to make sure we'll obey the same precedence no matter which direction
6917 ;; we're going.
6918 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6919 (cons (save-excursion (forward-sexp arg) (point))
6920 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6921 (not (zerop (funcall (if (> arg 0)
6922 'skip-syntax-forward
6923 'skip-syntax-backward)
6924 ".")))))
6925 (point)))))
6926 arg 'special))
6928 (defun transpose-lines (arg)
6929 "Exchange current line and previous line, leaving point after both.
6930 With argument ARG, takes previous line and moves it past ARG lines.
6931 With argument 0, interchanges line point is in with line mark is in."
6932 (interactive "*p")
6933 (transpose-subr (function
6934 (lambda (arg)
6935 (if (> arg 0)
6936 (progn
6937 ;; Move forward over ARG lines,
6938 ;; but create newlines if necessary.
6939 (setq arg (forward-line arg))
6940 (if (/= (preceding-char) ?\n)
6941 (setq arg (1+ arg)))
6942 (if (> arg 0)
6943 (newline arg)))
6944 (forward-line arg))))
6945 arg))
6947 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6948 ;; which seems inconsistent with the ARG /= 0 case.
6949 ;; FIXME document SPECIAL.
6950 (defun transpose-subr (mover arg &optional special)
6951 "Subroutine to do the work of transposing objects.
6952 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6953 moves forward by units of the given object (e.g. forward-sentence,
6954 forward-paragraph). If ARG is zero, exchanges the current object
6955 with the one containing mark. If ARG is an integer, moves the
6956 current object past ARG following (if ARG is positive) or
6957 preceding (if ARG is negative) objects, leaving point after the
6958 current object."
6959 (let ((aux (if special mover
6960 (lambda (x)
6961 (cons (progn (funcall mover x) (point))
6962 (progn (funcall mover (- x)) (point))))))
6963 pos1 pos2)
6964 (cond
6965 ((= arg 0)
6966 (save-excursion
6967 (setq pos1 (funcall aux 1))
6968 (goto-char (or (mark) (error "No mark set in this buffer")))
6969 (setq pos2 (funcall aux 1))
6970 (transpose-subr-1 pos1 pos2))
6971 (exchange-point-and-mark))
6972 ((> arg 0)
6973 (setq pos1 (funcall aux -1))
6974 (setq pos2 (funcall aux arg))
6975 (transpose-subr-1 pos1 pos2)
6976 (goto-char (car pos2)))
6978 (setq pos1 (funcall aux -1))
6979 (goto-char (car pos1))
6980 (setq pos2 (funcall aux arg))
6981 (transpose-subr-1 pos1 pos2)
6982 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6984 (defun transpose-subr-1 (pos1 pos2)
6985 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6986 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6987 (when (> (car pos1) (car pos2))
6988 (let ((swap pos1))
6989 (setq pos1 pos2 pos2 swap)))
6990 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6991 (atomic-change-group
6992 ;; This sequence of insertions attempts to preserve marker
6993 ;; positions at the start and end of the transposed objects.
6994 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6995 (len1 (- (cdr pos1) (car pos1)))
6996 (len2 (length word))
6997 (boundary (make-marker)))
6998 (set-marker boundary (car pos2))
6999 (goto-char (cdr pos1))
7000 (insert-before-markers word)
7001 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7002 (goto-char boundary)
7003 (insert word)
7004 (goto-char (+ boundary len1))
7005 (delete-region (point) (+ (point) len2))
7006 (set-marker boundary nil))))
7008 (defun backward-word (&optional arg)
7009 "Move backward until encountering the beginning of a word.
7010 With argument ARG, do this that many times.
7011 If ARG is omitted or nil, move point backward one word.
7013 The word boundaries are normally determined by the buffer's syntax
7014 table, but `find-word-boundary-function-table', such as set up
7015 by `subword-mode', can change that. If a Lisp program needs to
7016 move by words determined strictly by the syntax table, it should
7017 use `backward-word-strictly' instead."
7018 (interactive "^p")
7019 (forward-word (- (or arg 1))))
7021 (defun mark-word (&optional arg allow-extend)
7022 "Set mark ARG words away from point.
7023 The place mark goes is the same place \\[forward-word] would
7024 move to with the same argument.
7025 Interactively, if this command is repeated
7026 or (in Transient Mark mode) if the mark is active,
7027 it marks the next ARG words after the ones already marked."
7028 (interactive "P\np")
7029 (cond ((and allow-extend
7030 (or (and (eq last-command this-command) (mark t))
7031 (region-active-p)))
7032 (setq arg (if arg (prefix-numeric-value arg)
7033 (if (< (mark) (point)) -1 1)))
7034 (set-mark
7035 (save-excursion
7036 (goto-char (mark))
7037 (forward-word arg)
7038 (point))))
7040 (push-mark
7041 (save-excursion
7042 (forward-word (prefix-numeric-value arg))
7043 (point))
7044 nil t))))
7046 (defun kill-word (arg)
7047 "Kill characters forward until encountering the end of a word.
7048 With argument ARG, do this that many times."
7049 (interactive "p")
7050 (kill-region (point) (progn (forward-word arg) (point))))
7052 (defun backward-kill-word (arg)
7053 "Kill characters backward until encountering the beginning of a word.
7054 With argument ARG, do this that many times."
7055 (interactive "p")
7056 (kill-word (- arg)))
7058 (defun current-word (&optional strict really-word)
7059 "Return the word at or near point, as a string.
7060 The return value includes no text properties.
7062 If optional arg STRICT is non-nil, return nil unless point is
7063 within or adjacent to a word, otherwise look for a word within
7064 point's line. If there is no word anywhere on point's line, the
7065 value is nil regardless of STRICT.
7067 By default, this function treats as a single word any sequence of
7068 characters that have either word or symbol syntax. If optional
7069 arg REALLY-WORD is non-nil, only characters of word syntax can
7070 constitute a word."
7071 (save-excursion
7072 (let* ((oldpoint (point)) (start (point)) (end (point))
7073 (syntaxes (if really-word "w" "w_"))
7074 (not-syntaxes (concat "^" syntaxes)))
7075 (skip-syntax-backward syntaxes) (setq start (point))
7076 (goto-char oldpoint)
7077 (skip-syntax-forward syntaxes) (setq end (point))
7078 (when (and (eq start oldpoint) (eq end oldpoint)
7079 ;; Point is neither within nor adjacent to a word.
7080 (not strict))
7081 ;; Look for preceding word in same line.
7082 (skip-syntax-backward not-syntaxes (line-beginning-position))
7083 (if (bolp)
7084 ;; No preceding word in same line.
7085 ;; Look for following word in same line.
7086 (progn
7087 (skip-syntax-forward not-syntaxes (line-end-position))
7088 (setq start (point))
7089 (skip-syntax-forward syntaxes)
7090 (setq end (point)))
7091 (setq end (point))
7092 (skip-syntax-backward syntaxes)
7093 (setq start (point))))
7094 ;; If we found something nonempty, return it as a string.
7095 (unless (= start end)
7096 (buffer-substring-no-properties start end)))))
7098 (defcustom fill-prefix nil
7099 "String for filling to insert at front of new line, or nil for none."
7100 :type '(choice (const :tag "None" nil)
7101 string)
7102 :group 'fill)
7103 (make-variable-buffer-local 'fill-prefix)
7104 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7106 (defcustom auto-fill-inhibit-regexp nil
7107 "Regexp to match lines which should not be auto-filled."
7108 :type '(choice (const :tag "None" nil)
7109 regexp)
7110 :group 'fill)
7112 (defun do-auto-fill ()
7113 "The default value for `normal-auto-fill-function'.
7114 This is the default auto-fill function, some major modes use a different one.
7115 Returns t if it really did any work."
7116 (let (fc justify give-up
7117 (fill-prefix fill-prefix))
7118 (if (or (not (setq justify (current-justification)))
7119 (null (setq fc (current-fill-column)))
7120 (and (eq justify 'left)
7121 (<= (current-column) fc))
7122 (and auto-fill-inhibit-regexp
7123 (save-excursion (beginning-of-line)
7124 (looking-at auto-fill-inhibit-regexp))))
7125 nil ;; Auto-filling not required
7126 (if (memq justify '(full center right))
7127 (save-excursion (unjustify-current-line)))
7129 ;; Choose a fill-prefix automatically.
7130 (when (and adaptive-fill-mode
7131 (or (null fill-prefix) (string= fill-prefix "")))
7132 (let ((prefix
7133 (fill-context-prefix
7134 (save-excursion (fill-forward-paragraph -1) (point))
7135 (save-excursion (fill-forward-paragraph 1) (point)))))
7136 (and prefix (not (equal prefix ""))
7137 ;; Use auto-indentation rather than a guessed empty prefix.
7138 (not (and fill-indent-according-to-mode
7139 (string-match "\\`[ \t]*\\'" prefix)))
7140 (setq fill-prefix prefix))))
7142 (while (and (not give-up) (> (current-column) fc))
7143 ;; Determine where to split the line.
7144 (let ((fill-point
7145 (save-excursion
7146 (beginning-of-line)
7147 ;; Don't split earlier in the line than the length of the
7148 ;; fill prefix, since the resulting line would be longer.
7149 (when fill-prefix
7150 (move-to-column (string-width fill-prefix)))
7151 (let ((after-prefix (point)))
7152 (move-to-column (1+ fc))
7153 (fill-move-to-break-point after-prefix)
7154 (point)))))
7156 ;; See whether the place we found is any good.
7157 (if (save-excursion
7158 (goto-char fill-point)
7159 (or (bolp)
7160 ;; There is no use breaking at end of line.
7161 (save-excursion (skip-chars-forward " ") (eolp))
7162 ;; Don't split right after a comment starter
7163 ;; since we would just make another comment starter.
7164 (and comment-start-skip
7165 (let ((limit (point)))
7166 (beginning-of-line)
7167 (and (re-search-forward comment-start-skip
7168 limit t)
7169 (eq (point) limit))))))
7170 ;; No good place to break => stop trying.
7171 (setq give-up t)
7172 ;; Ok, we have a useful place to break the line. Do it.
7173 (let ((prev-column (current-column)))
7174 ;; If point is at the fill-point, do not `save-excursion'.
7175 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7176 ;; point will end up before it rather than after it.
7177 (if (save-excursion
7178 (skip-chars-backward " \t")
7179 (= (point) fill-point))
7180 (default-indent-new-line t)
7181 (save-excursion
7182 (goto-char fill-point)
7183 (default-indent-new-line t)))
7184 ;; Now do justification, if required
7185 (if (not (eq justify 'left))
7186 (save-excursion
7187 (end-of-line 0)
7188 (justify-current-line justify nil t)))
7189 ;; If making the new line didn't reduce the hpos of
7190 ;; the end of the line, then give up now;
7191 ;; trying again will not help.
7192 (if (>= (current-column) prev-column)
7193 (setq give-up t))))))
7194 ;; Justify last line.
7195 (justify-current-line justify t t)
7196 t)))
7198 (defvar comment-line-break-function 'comment-indent-new-line
7199 "Mode-specific function which line breaks and continues a comment.
7200 This function is called during auto-filling when a comment syntax
7201 is defined.
7202 The function should take a single optional argument, which is a flag
7203 indicating whether it should use soft newlines.")
7205 (defun default-indent-new-line (&optional soft)
7206 "Break line at point and indent.
7207 If a comment syntax is defined, call `comment-indent-new-line'.
7209 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7210 unless optional argument SOFT is non-nil."
7211 (interactive)
7212 (if comment-start
7213 (funcall comment-line-break-function soft)
7214 ;; Insert the newline before removing empty space so that markers
7215 ;; get preserved better.
7216 (if soft (insert-and-inherit ?\n) (newline 1))
7217 (save-excursion (forward-char -1) (delete-horizontal-space))
7218 (delete-horizontal-space)
7220 (if (and fill-prefix (not adaptive-fill-mode))
7221 ;; Blindly trust a non-adaptive fill-prefix.
7222 (progn
7223 (indent-to-left-margin)
7224 (insert-before-markers-and-inherit fill-prefix))
7226 (cond
7227 ;; If there's an adaptive prefix, use it unless we're inside
7228 ;; a comment and the prefix is not a comment starter.
7229 (fill-prefix
7230 (indent-to-left-margin)
7231 (insert-and-inherit fill-prefix))
7232 ;; If we're not inside a comment, just try to indent.
7233 (t (indent-according-to-mode))))))
7235 (defun internal-auto-fill ()
7236 "The function called by `self-insert-command' to perform auto-filling."
7237 (when (or (not comment-start)
7238 (not comment-auto-fill-only-comments)
7239 (nth 4 (syntax-ppss)))
7240 (funcall auto-fill-function)))
7242 (defvar normal-auto-fill-function 'do-auto-fill
7243 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7244 Some major modes set this.")
7246 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7247 ;; `functions' and `hooks' are usually unsafe to set, but setting
7248 ;; auto-fill-function to nil in a file-local setting is safe and
7249 ;; can be useful to prevent auto-filling.
7250 (put 'auto-fill-function 'safe-local-variable 'null)
7252 (define-minor-mode auto-fill-mode
7253 "Toggle automatic line breaking (Auto Fill mode).
7254 Interactively, with a prefix argument, enable
7255 Auto Fill mode if the prefix argument is positive,
7256 and disable it otherwise. If called from Lisp, toggle
7257 the mode if ARG is `toggle', disable the mode if ARG is
7258 a non-positive integer, and enable the mode otherwise
7259 \(including if ARG is omitted or nil or a positive integer).
7261 When Auto Fill mode is enabled, inserting a space at a column
7262 beyond `current-fill-column' automatically breaks the line at a
7263 previous space.
7265 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7266 non-nil.
7268 The value of `normal-auto-fill-function' specifies the function to use
7269 for `auto-fill-function' when turning Auto Fill mode on."
7270 :variable (auto-fill-function
7271 . (lambda (v) (setq auto-fill-function
7272 (if v normal-auto-fill-function)))))
7274 ;; This holds a document string used to document auto-fill-mode.
7275 (defun auto-fill-function ()
7276 "Automatically break line at a previous space, in insertion of text."
7277 nil)
7279 (defun turn-on-auto-fill ()
7280 "Unconditionally turn on Auto Fill mode."
7281 (auto-fill-mode 1))
7283 (defun turn-off-auto-fill ()
7284 "Unconditionally turn off Auto Fill mode."
7285 (auto-fill-mode -1))
7287 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7289 (defun set-fill-column (arg)
7290 "Set `fill-column' to specified argument.
7291 Use \\[universal-argument] followed by a number to specify a column.
7292 Just \\[universal-argument] as argument means to use the current column."
7293 (interactive
7294 (list (or current-prefix-arg
7295 ;; We used to use current-column silently, but C-x f is too easily
7296 ;; typed as a typo for C-x C-f, so we turned it into an error and
7297 ;; now an interactive prompt.
7298 (read-number "Set fill-column to: " (current-column)))))
7299 (if (consp arg)
7300 (setq arg (current-column)))
7301 (if (not (integerp arg))
7302 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7303 (error "set-fill-column requires an explicit argument")
7304 (message "Fill column set to %d (was %d)" arg fill-column)
7305 (setq fill-column arg)))
7307 (defun set-selective-display (arg)
7308 "Set `selective-display' to ARG; clear it if no arg.
7309 When the value of `selective-display' is a number > 0,
7310 lines whose indentation is >= that value are not displayed.
7311 The variable `selective-display' has a separate value for each buffer."
7312 (interactive "P")
7313 (if (eq selective-display t)
7314 (error "selective-display already in use for marked lines"))
7315 (let ((current-vpos
7316 (save-restriction
7317 (narrow-to-region (point-min) (point))
7318 (goto-char (window-start))
7319 (vertical-motion (window-height)))))
7320 (setq selective-display
7321 (and arg (prefix-numeric-value arg)))
7322 (recenter current-vpos))
7323 (set-window-start (selected-window) (window-start))
7324 (princ "selective-display set to " t)
7325 (prin1 selective-display t)
7326 (princ "." t))
7328 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7330 (defun toggle-truncate-lines (&optional arg)
7331 "Toggle truncating of long lines for the current buffer.
7332 When truncating is off, long lines are folded.
7333 With prefix argument ARG, truncate long lines if ARG is positive,
7334 otherwise fold them. Note that in side-by-side windows, this
7335 command has no effect if `truncate-partial-width-windows' is
7336 non-nil."
7337 (interactive "P")
7338 (setq truncate-lines
7339 (if (null arg)
7340 (not truncate-lines)
7341 (> (prefix-numeric-value arg) 0)))
7342 (force-mode-line-update)
7343 (unless truncate-lines
7344 (let ((buffer (current-buffer)))
7345 (walk-windows (lambda (window)
7346 (if (eq buffer (window-buffer window))
7347 (set-window-hscroll window 0)))
7348 nil t)))
7349 (message "Truncate long lines %s"
7350 (if truncate-lines "enabled" "disabled")))
7352 (defun toggle-word-wrap (&optional arg)
7353 "Toggle whether to use word-wrapping for continuation lines.
7354 With prefix argument ARG, wrap continuation lines at word boundaries
7355 if ARG is positive, otherwise wrap them at the right screen edge.
7356 This command toggles the value of `word-wrap'. It has no effect
7357 if long lines are truncated."
7358 (interactive "P")
7359 (setq word-wrap
7360 (if (null arg)
7361 (not word-wrap)
7362 (> (prefix-numeric-value arg) 0)))
7363 (force-mode-line-update)
7364 (message "Word wrapping %s"
7365 (if word-wrap "enabled" "disabled")))
7367 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7368 "The string displayed in the mode line when in overwrite mode.")
7369 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7370 "The string displayed in the mode line when in binary overwrite mode.")
7372 (define-minor-mode overwrite-mode
7373 "Toggle Overwrite mode.
7374 With a prefix argument ARG, enable Overwrite mode if ARG is
7375 positive, and disable it otherwise. If called from Lisp, enable
7376 the mode if ARG is omitted or nil.
7378 When Overwrite mode is enabled, printing characters typed in
7379 replace existing text on a one-for-one basis, rather than pushing
7380 it to the right. At the end of a line, such characters extend
7381 the line. Before a tab, such characters insert until the tab is
7382 filled in. \\[quoted-insert] still inserts characters in
7383 overwrite mode; this is supposed to make it easier to insert
7384 characters when necessary."
7385 :variable (overwrite-mode
7386 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7388 (define-minor-mode binary-overwrite-mode
7389 "Toggle Binary Overwrite mode.
7390 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7391 is positive, and disable it otherwise. If called from Lisp,
7392 enable the mode if ARG is omitted or nil.
7394 When Binary Overwrite mode is enabled, printing characters typed
7395 in replace existing text. Newlines are not treated specially, so
7396 typing at the end of a line joins the line to the next, with the
7397 typed character between them. Typing before a tab character
7398 simply replaces the tab with the character typed.
7399 \\[quoted-insert] replaces the text at the cursor, just as
7400 ordinary typing characters do.
7402 Note that Binary Overwrite mode is not its own minor mode; it is
7403 a specialization of overwrite mode, entered by setting the
7404 `overwrite-mode' variable to `overwrite-mode-binary'."
7405 :variable (overwrite-mode
7406 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7408 (define-minor-mode line-number-mode
7409 "Toggle line number display in the mode line (Line Number mode).
7410 With a prefix argument ARG, enable Line Number mode if ARG is
7411 positive, and disable it otherwise. If called from Lisp, enable
7412 the mode if ARG is omitted or nil.
7414 Line numbers do not appear for very large buffers and buffers
7415 with very long lines; see variables `line-number-display-limit'
7416 and `line-number-display-limit-width'."
7417 :init-value t :global t :group 'mode-line)
7419 (define-minor-mode column-number-mode
7420 "Toggle column number display in the mode line (Column Number mode).
7421 With a prefix argument ARG, enable Column Number mode if ARG is
7422 positive, and disable it otherwise.
7424 If called from Lisp, enable the mode if ARG is omitted or nil."
7425 :global t :group 'mode-line)
7427 (define-minor-mode size-indication-mode
7428 "Toggle buffer size display in the mode line (Size Indication mode).
7429 With a prefix argument ARG, enable Size Indication mode if ARG is
7430 positive, and disable it otherwise.
7432 If called from Lisp, enable the mode if ARG is omitted or nil."
7433 :global t :group 'mode-line)
7435 (define-minor-mode auto-save-mode
7436 "Toggle auto-saving in the current buffer (Auto Save mode).
7437 With a prefix argument ARG, enable Auto Save mode if ARG is
7438 positive, and disable it otherwise.
7440 If called from Lisp, enable the mode if ARG is omitted or nil."
7441 :variable ((and buffer-auto-save-file-name
7442 ;; If auto-save is off because buffer has shrunk,
7443 ;; then toggling should turn it on.
7444 (>= buffer-saved-size 0))
7445 . (lambda (val)
7446 (setq buffer-auto-save-file-name
7447 (cond
7448 ((null val) nil)
7449 ((and buffer-file-name auto-save-visited-file-name
7450 (not buffer-read-only))
7451 buffer-file-name)
7452 (t (make-auto-save-file-name))))))
7453 ;; If -1 was stored here, to temporarily turn off saving,
7454 ;; turn it back on.
7455 (and (< buffer-saved-size 0)
7456 (setq buffer-saved-size 0)))
7458 (defgroup paren-blinking nil
7459 "Blinking matching of parens and expressions."
7460 :prefix "blink-matching-"
7461 :group 'paren-matching)
7463 (defcustom blink-matching-paren t
7464 "Non-nil means show matching open-paren when close-paren is inserted.
7465 If t, highlight the paren. If `jump', briefly move cursor to its
7466 position. If `jump-offscreen', move cursor there even if the
7467 position is off screen. With any other non-nil value, the
7468 off-screen position of the opening paren will be shown in the
7469 echo area."
7470 :type '(choice
7471 (const :tag "Disable" nil)
7472 (const :tag "Highlight" t)
7473 (const :tag "Move cursor" jump)
7474 (const :tag "Move cursor, even if off screen" jump-offscreen))
7475 :group 'paren-blinking)
7477 (defcustom blink-matching-paren-on-screen t
7478 "Non-nil means show matching open-paren when it is on screen.
7479 If nil, don't show it (but the open-paren can still be shown
7480 in the echo area when it is off screen).
7482 This variable has no effect if `blink-matching-paren' is nil.
7483 \(In that case, the open-paren is never shown.)
7484 It is also ignored if `show-paren-mode' is enabled."
7485 :type 'boolean
7486 :group 'paren-blinking)
7488 (defcustom blink-matching-paren-distance (* 100 1024)
7489 "If non-nil, maximum distance to search backwards for matching open-paren.
7490 If nil, search stops at the beginning of the accessible portion of the buffer."
7491 :version "23.2" ; 25->100k
7492 :type '(choice (const nil) integer)
7493 :group 'paren-blinking)
7495 (defcustom blink-matching-delay 1
7496 "Time in seconds to delay after showing a matching paren."
7497 :type 'number
7498 :group 'paren-blinking)
7500 (defcustom blink-matching-paren-dont-ignore-comments nil
7501 "If nil, `blink-matching-paren' ignores comments.
7502 More precisely, when looking for the matching parenthesis,
7503 it skips the contents of comments that end before point."
7504 :type 'boolean
7505 :group 'paren-blinking)
7507 (defun blink-matching-check-mismatch (start end)
7508 "Return whether or not START...END are matching parens.
7509 END is the current point and START is the blink position.
7510 START might be nil if no matching starter was found.
7511 Returns non-nil if we find there is a mismatch."
7512 (let* ((end-syntax (syntax-after (1- end)))
7513 (matching-paren (and (consp end-syntax)
7514 (eq (syntax-class end-syntax) 5)
7515 (cdr end-syntax))))
7516 ;; For self-matched chars like " and $, we can't know when they're
7517 ;; mismatched or unmatched, so we can only do it for parens.
7518 (when matching-paren
7519 (not (and start
7521 (eq (char-after start) matching-paren)
7522 ;; The cdr might hold a new paren-class info rather than
7523 ;; a matching-char info, in which case the two CDRs
7524 ;; should match.
7525 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7527 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7528 "Function to check parentheses mismatches.
7529 The function takes two arguments (START and END) where START is the
7530 position just before the opening token and END is the position right after.
7531 START can be nil, if it was not found.
7532 The function should return non-nil if the two tokens do not match.")
7534 (defvar blink-matching--overlay
7535 (let ((ol (make-overlay (point) (point) nil t)))
7536 (overlay-put ol 'face 'show-paren-match)
7537 (delete-overlay ol)
7539 "Overlay used to highlight the matching paren.")
7541 (defun blink-matching-open ()
7542 "Momentarily highlight the beginning of the sexp before point."
7543 (interactive)
7544 (when (and (not (bobp))
7545 blink-matching-paren)
7546 (let* ((oldpos (point))
7547 (message-log-max nil) ; Don't log messages about paren matching.
7548 (blinkpos
7549 (save-excursion
7550 (save-restriction
7551 (if blink-matching-paren-distance
7552 (narrow-to-region
7553 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7554 (- (point) blink-matching-paren-distance))
7555 oldpos))
7556 (let ((parse-sexp-ignore-comments
7557 (and parse-sexp-ignore-comments
7558 (not blink-matching-paren-dont-ignore-comments))))
7559 (condition-case ()
7560 (progn
7561 (syntax-propertize (point))
7562 (forward-sexp -1)
7563 ;; backward-sexp skips backward over prefix chars,
7564 ;; so move back to the matching paren.
7565 (while (and (< (point) (1- oldpos))
7566 (let ((code (syntax-after (point))))
7567 (or (eq (syntax-class code) 6)
7568 (eq (logand 1048576 (car code))
7569 1048576))))
7570 (forward-char 1))
7571 (point))
7572 (error nil))))))
7573 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7574 (cond
7575 (mismatch
7576 (if blinkpos
7577 (if (minibufferp)
7578 (minibuffer-message "Mismatched parentheses")
7579 (message "Mismatched parentheses"))
7580 (if (minibufferp)
7581 (minibuffer-message "No matching parenthesis found")
7582 (message "No matching parenthesis found"))))
7583 ((not blinkpos) nil)
7584 ((or
7585 (eq blink-matching-paren 'jump-offscreen)
7586 (pos-visible-in-window-p blinkpos))
7587 ;; Matching open within window, temporarily move to or highlight
7588 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7589 ;; is non-nil.
7590 (and blink-matching-paren-on-screen
7591 (not show-paren-mode)
7592 (if (memq blink-matching-paren '(jump jump-offscreen))
7593 (save-excursion
7594 (goto-char blinkpos)
7595 (sit-for blink-matching-delay))
7596 (unwind-protect
7597 (progn
7598 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7599 (current-buffer))
7600 (sit-for blink-matching-delay))
7601 (delete-overlay blink-matching--overlay)))))
7603 (let ((open-paren-line-string
7604 (save-excursion
7605 (goto-char blinkpos)
7606 ;; Show what precedes the open in its line, if anything.
7607 (cond
7608 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7609 (buffer-substring (line-beginning-position)
7610 (1+ blinkpos)))
7611 ;; Show what follows the open in its line, if anything.
7612 ((save-excursion
7613 (forward-char 1)
7614 (skip-chars-forward " \t")
7615 (not (eolp)))
7616 (buffer-substring blinkpos
7617 (line-end-position)))
7618 ;; Otherwise show the previous nonblank line,
7619 ;; if there is one.
7620 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7621 (concat
7622 (buffer-substring (progn
7623 (skip-chars-backward "\n \t")
7624 (line-beginning-position))
7625 (progn (end-of-line)
7626 (skip-chars-backward " \t")
7627 (point)))
7628 ;; Replace the newline and other whitespace with `...'.
7629 "..."
7630 (buffer-substring blinkpos (1+ blinkpos))))
7631 ;; There is nothing to show except the char itself.
7632 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7633 (minibuffer-message
7634 "Matches %s"
7635 (substring-no-properties open-paren-line-string))))))))
7637 (defvar blink-paren-function 'blink-matching-open
7638 "Function called, if non-nil, whenever a close parenthesis is inserted.
7639 More precisely, a char with closeparen syntax is self-inserted.")
7641 (defun blink-paren-post-self-insert-function ()
7642 (when (and (eq (char-before) last-command-event) ; Sanity check.
7643 (memq (char-syntax last-command-event) '(?\) ?\$))
7644 blink-paren-function
7645 (not executing-kbd-macro)
7646 (not noninteractive)
7647 ;; Verify an even number of quoting characters precede the close.
7648 ;; FIXME: Also check if this parenthesis closes a comment as
7649 ;; can happen in Pascal and SML.
7650 (= 1 (logand 1 (- (point)
7651 (save-excursion
7652 (forward-char -1)
7653 (skip-syntax-backward "/\\")
7654 (point))))))
7655 (funcall blink-paren-function)))
7657 (put 'blink-paren-post-self-insert-function 'priority 100)
7659 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7660 ;; Most likely, this hook is nil, so this arg doesn't matter,
7661 ;; but I use it as a reminder that this function usually
7662 ;; likes to be run after others since it does
7663 ;; `sit-for'. That's also the reason it get a `priority' prop
7664 ;; of 100.
7665 'append)
7667 ;; This executes C-g typed while Emacs is waiting for a command.
7668 ;; Quitting out of a program does not go through here;
7669 ;; that happens in the maybe_quit function at the C code level.
7670 (defun keyboard-quit ()
7671 "Signal a `quit' condition.
7672 During execution of Lisp code, this character causes a quit directly.
7673 At top-level, as an editor command, this simply beeps."
7674 (interactive)
7675 ;; Avoid adding the region to the window selection.
7676 (setq saved-region-selection nil)
7677 (let (select-active-regions)
7678 (deactivate-mark))
7679 (if (fboundp 'kmacro-keyboard-quit)
7680 (kmacro-keyboard-quit))
7681 (when completion-in-region-mode
7682 (completion-in-region-mode -1))
7683 ;; Force the next redisplay cycle to remove the "Def" indicator from
7684 ;; all the mode lines.
7685 (if defining-kbd-macro
7686 (force-mode-line-update t))
7687 (setq defining-kbd-macro nil)
7688 (let ((debug-on-quit nil))
7689 (signal 'quit nil)))
7691 (defvar buffer-quit-function nil
7692 "Function to call to \"quit\" the current buffer, or nil if none.
7693 \\[keyboard-escape-quit] calls this function when its more local actions
7694 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7696 (defun keyboard-escape-quit ()
7697 "Exit the current \"mode\" (in a generalized sense of the word).
7698 This command can exit an interactive command such as `query-replace',
7699 can clear out a prefix argument or a region,
7700 can get out of the minibuffer or other recursive edit,
7701 cancel the use of the current buffer (for special-purpose buffers),
7702 or go back to just one window (by deleting all but the selected window)."
7703 (interactive)
7704 (cond ((eq last-command 'mode-exited) nil)
7705 ((region-active-p)
7706 (deactivate-mark))
7707 ((> (minibuffer-depth) 0)
7708 (abort-recursive-edit))
7709 (current-prefix-arg
7710 nil)
7711 ((> (recursion-depth) 0)
7712 (exit-recursive-edit))
7713 (buffer-quit-function
7714 (funcall buffer-quit-function))
7715 ((not (one-window-p t))
7716 (delete-other-windows))
7717 ((string-match "^ \\*" (buffer-name (current-buffer)))
7718 (bury-buffer))))
7720 (defun play-sound-file (file &optional volume device)
7721 "Play sound stored in FILE.
7722 VOLUME and DEVICE correspond to the keywords of the sound
7723 specification for `play-sound'."
7724 (interactive "fPlay sound file: ")
7725 (let ((sound (list :file file)))
7726 (if volume
7727 (plist-put sound :volume volume))
7728 (if device
7729 (plist-put sound :device device))
7730 (push 'sound sound)
7731 (play-sound sound)))
7734 (defcustom read-mail-command 'rmail
7735 "Your preference for a mail reading package.
7736 This is used by some keybindings which support reading mail.
7737 See also `mail-user-agent' concerning sending mail."
7738 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7739 (function-item :tag "Gnus" :format "%t\n" gnus)
7740 (function-item :tag "Emacs interface to MH"
7741 :format "%t\n" mh-rmail)
7742 (function :tag "Other"))
7743 :version "21.1"
7744 :group 'mail)
7746 (defcustom mail-user-agent 'message-user-agent
7747 "Your preference for a mail composition package.
7748 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7749 outgoing email message. This variable lets you specify which
7750 mail-sending package you prefer.
7752 Valid values include:
7754 `message-user-agent' -- use the Message package.
7755 See Info node `(message)'.
7756 `sendmail-user-agent' -- use the Mail package.
7757 See Info node `(emacs)Sending Mail'.
7758 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7759 See Info node `(mh-e)'.
7760 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7761 paraphernalia if Gnus is running, particularly
7762 the Gcc: header for archiving.
7764 Additional valid symbols may be available; check with the author of
7765 your package for details. The function should return non-nil if it
7766 succeeds.
7768 See also `read-mail-command' concerning reading mail."
7769 :type '(radio (function-item :tag "Message package"
7770 :format "%t\n"
7771 message-user-agent)
7772 (function-item :tag "Mail package"
7773 :format "%t\n"
7774 sendmail-user-agent)
7775 (function-item :tag "Emacs interface to MH"
7776 :format "%t\n"
7777 mh-e-user-agent)
7778 (function-item :tag "Message with full Gnus features"
7779 :format "%t\n"
7780 gnus-user-agent)
7781 (function :tag "Other"))
7782 :version "23.2" ; sendmail->message
7783 :group 'mail)
7785 (defcustom compose-mail-user-agent-warnings t
7786 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7787 If the value of `mail-user-agent' is the default, and the user
7788 appears to have customizations applying to the old default,
7789 `compose-mail' issues a warning."
7790 :type 'boolean
7791 :version "23.2"
7792 :group 'mail)
7794 (defun rfc822-goto-eoh ()
7795 "If the buffer starts with a mail header, move point to the header's end.
7796 Otherwise, moves to `point-min'.
7797 The end of the header is the start of the next line, if there is one,
7798 else the end of the last line. This function obeys RFC822."
7799 (goto-char (point-min))
7800 (when (re-search-forward
7801 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7802 (goto-char (match-beginning 0))))
7804 ;; Used by Rmail (e.g., rmail-forward).
7805 (defvar mail-encode-mml nil
7806 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7807 the outgoing message before sending it.")
7809 (defun compose-mail (&optional to subject other-headers continue
7810 switch-function yank-action send-actions
7811 return-action)
7812 "Start composing a mail message to send.
7813 This uses the user's chosen mail composition package
7814 as selected with the variable `mail-user-agent'.
7815 The optional arguments TO and SUBJECT specify recipients
7816 and the initial Subject field, respectively.
7818 OTHER-HEADERS is an alist specifying additional
7819 header fields. Elements look like (HEADER . VALUE) where both
7820 HEADER and VALUE are strings.
7822 CONTINUE, if non-nil, says to continue editing a message already
7823 being composed. Interactively, CONTINUE is the prefix argument.
7825 SWITCH-FUNCTION, if non-nil, is a function to use to
7826 switch to and display the buffer used for mail composition.
7828 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7829 to insert the raw text of the message being replied to.
7830 It has the form (FUNCTION . ARGS). The user agent will apply
7831 FUNCTION to ARGS, to insert the raw text of the original message.
7832 \(The user agent will also run `mail-citation-hook', *after* the
7833 original text has been inserted in this way.)
7835 SEND-ACTIONS is a list of actions to call when the message is sent.
7836 Each action has the form (FUNCTION . ARGS).
7838 RETURN-ACTION, if non-nil, is an action for returning to the
7839 caller. It has the form (FUNCTION . ARGS). The function is
7840 called after the mail has been sent or put aside, and the mail
7841 buffer buried."
7842 (interactive
7843 (list nil nil nil current-prefix-arg))
7845 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7846 ;; from sendmail-user-agent to message-user-agent. Some users may
7847 ;; encounter incompatibilities. This hack tries to detect problems
7848 ;; and warn about them.
7849 (and compose-mail-user-agent-warnings
7850 (eq mail-user-agent 'message-user-agent)
7851 (let (warn-vars)
7852 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7853 mail-yank-hooks mail-archive-file-name
7854 mail-default-reply-to mail-mailing-lists
7855 mail-self-blind))
7856 (and (boundp var)
7857 (symbol-value var)
7858 (push var warn-vars)))
7859 (when warn-vars
7860 (display-warning 'mail
7861 (format-message "\
7862 The default mail mode is now Message mode.
7863 You have the following Mail mode variable%s customized:
7864 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7865 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7866 (if (> (length warn-vars) 1) "s" "")
7867 (mapconcat 'symbol-name
7868 warn-vars " "))))))
7870 (let ((function (get mail-user-agent 'composefunc)))
7871 (funcall function to subject other-headers continue switch-function
7872 yank-action send-actions return-action)))
7874 (defun compose-mail-other-window (&optional to subject other-headers continue
7875 yank-action send-actions
7876 return-action)
7877 "Like \\[compose-mail], but edit the outgoing message in another window."
7878 (interactive (list nil nil nil current-prefix-arg))
7879 (compose-mail to subject other-headers continue
7880 'switch-to-buffer-other-window yank-action send-actions
7881 return-action))
7883 (defun compose-mail-other-frame (&optional to subject other-headers continue
7884 yank-action send-actions
7885 return-action)
7886 "Like \\[compose-mail], but edit the outgoing message in another frame."
7887 (interactive (list nil nil nil current-prefix-arg))
7888 (compose-mail to subject other-headers continue
7889 'switch-to-buffer-other-frame yank-action send-actions
7890 return-action))
7893 (defvar set-variable-value-history nil
7894 "History of values entered with `set-variable'.
7896 Maximum length of the history list is determined by the value
7897 of `history-length', which see.")
7899 (defun set-variable (variable value &optional make-local)
7900 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7901 VARIABLE should be a user option variable name, a Lisp variable
7902 meant to be customized by users. You should enter VALUE in Lisp syntax,
7903 so if you want VALUE to be a string, you must surround it with doublequotes.
7904 VALUE is used literally, not evaluated.
7906 If VARIABLE has a `variable-interactive' property, that is used as if
7907 it were the arg to `interactive' (which see) to interactively read VALUE.
7909 If VARIABLE has been defined with `defcustom', then the type information
7910 in the definition is used to check that VALUE is valid.
7912 Note that this function is at heart equivalent to the basic `set' function.
7913 For a variable defined with `defcustom', it does not pay attention to
7914 any :set property that the variable might have (if you want that, use
7915 \\[customize-set-variable] instead).
7917 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7918 (interactive
7919 (let* ((default-var (variable-at-point))
7920 (var (if (custom-variable-p default-var)
7921 (read-variable (format "Set variable (default %s): " default-var)
7922 default-var)
7923 (read-variable "Set variable: ")))
7924 (minibuffer-help-form '(describe-variable var))
7925 (prop (get var 'variable-interactive))
7926 (obsolete (car (get var 'byte-obsolete-variable)))
7927 (prompt (format "Set %s %s to value: " var
7928 (cond ((local-variable-p var)
7929 "(buffer-local)")
7930 ((or current-prefix-arg
7931 (local-variable-if-set-p var))
7932 "buffer-locally")
7933 (t "globally"))))
7934 (val (progn
7935 (when obsolete
7936 (message (concat "`%S' is obsolete; "
7937 (if (symbolp obsolete) "use `%S' instead" "%s"))
7938 var obsolete)
7939 (sit-for 3))
7940 (if prop
7941 ;; Use VAR's `variable-interactive' property
7942 ;; as an interactive spec for prompting.
7943 (call-interactively `(lambda (arg)
7944 (interactive ,prop)
7945 arg))
7946 (read-from-minibuffer prompt nil
7947 read-expression-map t
7948 'set-variable-value-history
7949 (format "%S" (symbol-value var)))))))
7950 (list var val current-prefix-arg)))
7952 (and (custom-variable-p variable)
7953 (not (get variable 'custom-type))
7954 (custom-load-symbol variable))
7955 (let ((type (get variable 'custom-type)))
7956 (when type
7957 ;; Match with custom type.
7958 (require 'cus-edit)
7959 (setq type (widget-convert type))
7960 (unless (widget-apply type :match value)
7961 (user-error "Value `%S' does not match type %S of %S"
7962 value (car type) variable))))
7964 (if make-local
7965 (make-local-variable variable))
7967 (set variable value)
7969 ;; Force a thorough redisplay for the case that the variable
7970 ;; has an effect on the display, like `tab-width' has.
7971 (force-mode-line-update))
7973 ;; Define the major mode for lists of completions.
7975 (defvar completion-list-mode-map
7976 (let ((map (make-sparse-keymap)))
7977 (define-key map [mouse-2] 'choose-completion)
7978 (define-key map [follow-link] 'mouse-face)
7979 (define-key map [down-mouse-2] nil)
7980 (define-key map "\C-m" 'choose-completion)
7981 (define-key map "\e\e\e" 'delete-completion-window)
7982 (define-key map [left] 'previous-completion)
7983 (define-key map [right] 'next-completion)
7984 (define-key map [?\t] 'next-completion)
7985 (define-key map [backtab] 'previous-completion)
7986 (define-key map "q" 'quit-window)
7987 (define-key map "z" 'kill-current-buffer)
7988 map)
7989 "Local map for completion list buffers.")
7991 ;; Completion mode is suitable only for specially formatted data.
7992 (put 'completion-list-mode 'mode-class 'special)
7994 (defvar completion-reference-buffer nil
7995 "Record the buffer that was current when the completion list was requested.
7996 This is a local variable in the completion list buffer.
7997 Initial value is nil to avoid some compiler warnings.")
7999 (defvar completion-no-auto-exit nil
8000 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8001 This also applies to other functions such as `choose-completion'.")
8003 (defvar completion-base-position nil
8004 "Position of the base of the text corresponding to the shown completions.
8005 This variable is used in the *Completions* buffers.
8006 Its value is a list of the form (START END) where START is the place
8007 where the completion should be inserted and END (if non-nil) is the end
8008 of the text to replace. If END is nil, point is used instead.")
8010 (defvar completion-list-insert-choice-function #'completion--replace
8011 "Function to use to insert the text chosen in *Completions*.
8012 Called with three arguments (BEG END TEXT), it should replace the text
8013 between BEG and END with TEXT. Expected to be set buffer-locally
8014 in the *Completions* buffer.")
8016 (defvar completion-base-size nil
8017 "Number of chars before point not involved in completion.
8018 This is a local variable in the completion list buffer.
8019 It refers to the chars in the minibuffer if completing in the
8020 minibuffer, or in `completion-reference-buffer' otherwise.
8021 Only characters in the field at point are included.
8023 If nil, Emacs determines which part of the tail end of the
8024 buffer's text is involved in completion by comparing the text
8025 directly.")
8026 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8028 (defun delete-completion-window ()
8029 "Delete the completion list window.
8030 Go to the window from which completion was requested."
8031 (interactive)
8032 (let ((buf completion-reference-buffer))
8033 (if (one-window-p t)
8034 (if (window-dedicated-p) (delete-frame))
8035 (delete-window (selected-window))
8036 (if (get-buffer-window buf)
8037 (select-window (get-buffer-window buf))))))
8039 (defun previous-completion (n)
8040 "Move to the previous item in the completion list."
8041 (interactive "p")
8042 (next-completion (- n)))
8044 (defun next-completion (n)
8045 "Move to the next item in the completion list.
8046 With prefix argument N, move N items (negative N means move backward)."
8047 (interactive "p")
8048 (let ((beg (point-min)) (end (point-max)))
8049 (while (and (> n 0) (not (eobp)))
8050 ;; If in a completion, move to the end of it.
8051 (when (get-text-property (point) 'mouse-face)
8052 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8053 ;; Move to start of next one.
8054 (unless (get-text-property (point) 'mouse-face)
8055 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8056 (setq n (1- n)))
8057 (while (and (< n 0) (not (bobp)))
8058 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8059 ;; If in a completion, move to the start of it.
8060 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8061 (goto-char (previous-single-property-change
8062 (point) 'mouse-face nil beg)))
8063 ;; Move to end of the previous completion.
8064 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8065 (goto-char (previous-single-property-change
8066 (point) 'mouse-face nil beg)))
8067 ;; Move to the start of that one.
8068 (goto-char (previous-single-property-change
8069 (point) 'mouse-face nil beg))
8070 (setq n (1+ n))))))
8072 (defun choose-completion (&optional event)
8073 "Choose the completion at point.
8074 If EVENT, use EVENT's position to determine the starting position."
8075 (interactive (list last-nonmenu-event))
8076 ;; In case this is run via the mouse, give temporary modes such as
8077 ;; isearch a chance to turn off.
8078 (run-hooks 'mouse-leave-buffer-hook)
8079 (with-current-buffer (window-buffer (posn-window (event-start event)))
8080 (let ((buffer completion-reference-buffer)
8081 (base-size completion-base-size)
8082 (base-position completion-base-position)
8083 (insert-function completion-list-insert-choice-function)
8084 (choice
8085 (save-excursion
8086 (goto-char (posn-point (event-start event)))
8087 (let (beg end)
8088 (cond
8089 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8090 (setq end (point) beg (1+ (point))))
8091 ((and (not (bobp))
8092 (get-text-property (1- (point)) 'mouse-face))
8093 (setq end (1- (point)) beg (point)))
8094 (t (error "No completion here")))
8095 (setq beg (previous-single-property-change beg 'mouse-face))
8096 (setq end (or (next-single-property-change end 'mouse-face)
8097 (point-max)))
8098 (buffer-substring-no-properties beg end)))))
8100 (unless (buffer-live-p buffer)
8101 (error "Destination buffer is dead"))
8102 (quit-window nil (posn-window (event-start event)))
8104 (with-current-buffer buffer
8105 (choose-completion-string
8106 choice buffer
8107 (or base-position
8108 (when base-size
8109 ;; Someone's using old completion code that doesn't know
8110 ;; about base-position yet.
8111 (list (+ base-size (field-beginning))))
8112 ;; If all else fails, just guess.
8113 (list (choose-completion-guess-base-position choice)))
8114 insert-function)))))
8116 ;; Delete the longest partial match for STRING
8117 ;; that can be found before POINT.
8118 (defun choose-completion-guess-base-position (string)
8119 (save-excursion
8120 (let ((opoint (point))
8121 len)
8122 ;; Try moving back by the length of the string.
8123 (goto-char (max (- (point) (length string))
8124 (minibuffer-prompt-end)))
8125 ;; See how far back we were actually able to move. That is the
8126 ;; upper bound on how much we can match and delete.
8127 (setq len (- opoint (point)))
8128 (if completion-ignore-case
8129 (setq string (downcase string)))
8130 (while (and (> len 0)
8131 (let ((tail (buffer-substring (point) opoint)))
8132 (if completion-ignore-case
8133 (setq tail (downcase tail)))
8134 (not (string= tail (substring string 0 len)))))
8135 (setq len (1- len))
8136 (forward-char 1))
8137 (point))))
8139 (defun choose-completion-delete-max-match (string)
8140 (declare (obsolete choose-completion-guess-base-position "23.2"))
8141 (delete-region (choose-completion-guess-base-position string) (point)))
8143 (defvar choose-completion-string-functions nil
8144 "Functions that may override the normal insertion of a completion choice.
8145 These functions are called in order with three arguments:
8146 CHOICE - the string to insert in the buffer,
8147 BUFFER - the buffer in which the choice should be inserted,
8148 BASE-POSITION - where to insert the completion.
8150 If a function in the list returns non-nil, that function is supposed
8151 to have inserted the CHOICE in the BUFFER, and possibly exited
8152 the minibuffer; no further functions will be called.
8154 If all functions in the list return nil, that means to use
8155 the default method of inserting the completion in BUFFER.")
8157 (defun choose-completion-string (choice &optional
8158 buffer base-position insert-function)
8159 "Switch to BUFFER and insert the completion choice CHOICE.
8160 BASE-POSITION says where to insert the completion.
8161 INSERT-FUNCTION says how to insert the completion and falls
8162 back on `completion-list-insert-choice-function' when nil."
8164 ;; If BUFFER is the minibuffer, exit the minibuffer
8165 ;; unless it is reading a file name and CHOICE is a directory,
8166 ;; or completion-no-auto-exit is non-nil.
8168 ;; Some older code may call us passing `base-size' instead of
8169 ;; `base-position'. It's difficult to make any use of `base-size',
8170 ;; so we just ignore it.
8171 (unless (consp base-position)
8172 (message "Obsolete `base-size' passed to choose-completion-string")
8173 (setq base-position nil))
8175 (let* ((buffer (or buffer completion-reference-buffer))
8176 (mini-p (minibufferp buffer)))
8177 ;; If BUFFER is a minibuffer, barf unless it's the currently
8178 ;; active minibuffer.
8179 (if (and mini-p
8180 (not (and (active-minibuffer-window)
8181 (equal buffer
8182 (window-buffer (active-minibuffer-window))))))
8183 (error "Minibuffer is not active for completion")
8184 ;; Set buffer so buffer-local choose-completion-string-functions works.
8185 (set-buffer buffer)
8186 (unless (run-hook-with-args-until-success
8187 'choose-completion-string-functions
8188 ;; The fourth arg used to be `mini-p' but was useless
8189 ;; (since minibufferp can be used on the `buffer' arg)
8190 ;; and indeed unused. The last used to be `base-size', so we
8191 ;; keep it to try and avoid breaking old code.
8192 choice buffer base-position nil)
8193 ;; This remove-text-properties should be unnecessary since `choice'
8194 ;; comes from buffer-substring-no-properties.
8195 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8196 ;; Insert the completion into the buffer where it was requested.
8197 (funcall (or insert-function completion-list-insert-choice-function)
8198 (or (car base-position) (point))
8199 (or (cadr base-position) (point))
8200 choice)
8201 ;; Update point in the window that BUFFER is showing in.
8202 (let ((window (get-buffer-window buffer t)))
8203 (set-window-point window (point)))
8204 ;; If completing for the minibuffer, exit it with this choice.
8205 (and (not completion-no-auto-exit)
8206 (minibufferp buffer)
8207 minibuffer-completion-table
8208 ;; If this is reading a file name, and the file name chosen
8209 ;; is a directory, don't exit the minibuffer.
8210 (let* ((result (buffer-substring (field-beginning) (point)))
8211 (bounds
8212 (completion-boundaries result minibuffer-completion-table
8213 minibuffer-completion-predicate
8214 "")))
8215 (if (eq (car bounds) (length result))
8216 ;; The completion chosen leads to a new set of completions
8217 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8218 (let ((mini (active-minibuffer-window)))
8219 (select-window mini)
8220 (when minibuffer-auto-raise
8221 (raise-frame (window-frame mini))))
8222 (exit-minibuffer))))))))
8224 (define-derived-mode completion-list-mode nil "Completion List"
8225 "Major mode for buffers showing lists of possible completions.
8226 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8227 to select the completion near point.
8228 Or click to select one with the mouse.
8230 \\{completion-list-mode-map}"
8231 (set (make-local-variable 'completion-base-size) nil))
8233 (defun completion-list-mode-finish ()
8234 "Finish setup of the completions buffer.
8235 Called from `temp-buffer-show-hook'."
8236 (when (eq major-mode 'completion-list-mode)
8237 (setq buffer-read-only t)))
8239 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8242 ;; Variables and faces used in `completion-setup-function'.
8244 (defcustom completion-show-help t
8245 "Non-nil means show help message in *Completions* buffer."
8246 :type 'boolean
8247 :version "22.1"
8248 :group 'completion)
8250 ;; This function goes in completion-setup-hook, so that it is called
8251 ;; after the text of the completion list buffer is written.
8252 (defun completion-setup-function ()
8253 (let* ((mainbuf (current-buffer))
8254 (base-dir
8255 ;; FIXME: This is a bad hack. We try to set the default-directory
8256 ;; in the *Completions* buffer so that the relative file names
8257 ;; displayed there can be treated as valid file names, independently
8258 ;; from the completion context. But this suffers from many problems:
8259 ;; - It's not clear when the completions are file names. With some
8260 ;; completion tables (e.g. bzr revision specs), the listed
8261 ;; completions can mix file names and other things.
8262 ;; - It doesn't pay attention to possible quoting.
8263 ;; - With fancy completion styles, the code below will not always
8264 ;; find the right base directory.
8265 (if minibuffer-completing-file-name
8266 (file-name-as-directory
8267 (expand-file-name
8268 (buffer-substring (minibuffer-prompt-end)
8269 (- (point) (or completion-base-size 0))))))))
8270 (with-current-buffer standard-output
8271 (let ((base-size completion-base-size) ;Read before killing localvars.
8272 (base-position completion-base-position)
8273 (insert-fun completion-list-insert-choice-function))
8274 (completion-list-mode)
8275 (set (make-local-variable 'completion-base-size) base-size)
8276 (set (make-local-variable 'completion-base-position) base-position)
8277 (set (make-local-variable 'completion-list-insert-choice-function)
8278 insert-fun))
8279 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8280 (if base-dir (setq default-directory base-dir))
8281 ;; Maybe insert help string.
8282 (when completion-show-help
8283 (goto-char (point-min))
8284 (if (display-mouse-p)
8285 (insert "Click on a completion to select it.\n"))
8286 (insert (substitute-command-keys
8287 "In this buffer, type \\[choose-completion] to \
8288 select the completion near point.\n\n"))))))
8290 (add-hook 'completion-setup-hook 'completion-setup-function)
8292 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8293 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8295 (defun switch-to-completions ()
8296 "Select the completion list window."
8297 (interactive)
8298 (let ((window (or (get-buffer-window "*Completions*" 0)
8299 ;; Make sure we have a completions window.
8300 (progn (minibuffer-completion-help)
8301 (get-buffer-window "*Completions*" 0)))))
8302 (when window
8303 (select-window window)
8304 ;; In the new buffer, go to the first completion.
8305 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8306 (when (bobp)
8307 (next-completion 1)))))
8309 ;;; Support keyboard commands to turn on various modifiers.
8311 ;; These functions -- which are not commands -- each add one modifier
8312 ;; to the following event.
8314 (defun event-apply-alt-modifier (_ignore-prompt)
8315 "\\<function-key-map>Add the Alt modifier to the following event.
8316 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8317 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8318 (defun event-apply-super-modifier (_ignore-prompt)
8319 "\\<function-key-map>Add the Super modifier to the following event.
8320 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8321 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8322 (defun event-apply-hyper-modifier (_ignore-prompt)
8323 "\\<function-key-map>Add the Hyper modifier to the following event.
8324 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8325 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8326 (defun event-apply-shift-modifier (_ignore-prompt)
8327 "\\<function-key-map>Add the Shift modifier to the following event.
8328 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8329 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8330 (defun event-apply-control-modifier (_ignore-prompt)
8331 "\\<function-key-map>Add the Ctrl modifier to the following event.
8332 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8333 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8334 (defun event-apply-meta-modifier (_ignore-prompt)
8335 "\\<function-key-map>Add the Meta modifier to the following event.
8336 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8337 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8339 (defun event-apply-modifier (event symbol lshiftby prefix)
8340 "Apply a modifier flag to event EVENT.
8341 SYMBOL is the name of this modifier, as a symbol.
8342 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8343 PREFIX is the string that represents this modifier in an event type symbol."
8344 (if (numberp event)
8345 (cond ((eq symbol 'control)
8346 (if (and (<= (downcase event) ?z)
8347 (>= (downcase event) ?a))
8348 (- (downcase event) ?a -1)
8349 (if (and (<= (downcase event) ?Z)
8350 (>= (downcase event) ?A))
8351 (- (downcase event) ?A -1)
8352 (logior (lsh 1 lshiftby) event))))
8353 ((eq symbol 'shift)
8354 (if (and (<= (downcase event) ?z)
8355 (>= (downcase event) ?a))
8356 (upcase event)
8357 (logior (lsh 1 lshiftby) event)))
8359 (logior (lsh 1 lshiftby) event)))
8360 (if (memq symbol (event-modifiers event))
8361 event
8362 (let ((event-type (if (symbolp event) event (car event))))
8363 (setq event-type (intern (concat prefix (symbol-name event-type))))
8364 (if (symbolp event)
8365 event-type
8366 (cons event-type (cdr event)))))))
8368 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8369 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8370 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8371 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8372 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8373 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8375 ;;;; Keypad support.
8377 ;; Make the keypad keys act like ordinary typing keys. If people add
8378 ;; bindings for the function key symbols, then those bindings will
8379 ;; override these, so this shouldn't interfere with any existing
8380 ;; bindings.
8382 ;; Also tell read-char how to handle these keys.
8383 (mapc
8384 (lambda (keypad-normal)
8385 (let ((keypad (nth 0 keypad-normal))
8386 (normal (nth 1 keypad-normal)))
8387 (put keypad 'ascii-character normal)
8388 (define-key function-key-map (vector keypad) (vector normal))))
8389 ;; See also kp-keys bound in bindings.el.
8390 '((kp-space ?\s)
8391 (kp-tab ?\t)
8392 (kp-enter ?\r)
8393 (kp-separator ?,)
8394 (kp-equal ?=)
8395 ;; Do the same for various keys that are represented as symbols under
8396 ;; GUIs but naturally correspond to characters.
8397 (backspace 127)
8398 (delete 127)
8399 (tab ?\t)
8400 (linefeed ?\n)
8401 (clear ?\C-l)
8402 (return ?\C-m)
8403 (escape ?\e)
8406 ;;;;
8407 ;;;; forking a twin copy of a buffer.
8408 ;;;;
8410 (defvar clone-buffer-hook nil
8411 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8413 (defvar clone-indirect-buffer-hook nil
8414 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8416 (defun clone-process (process &optional newname)
8417 "Create a twin copy of PROCESS.
8418 If NEWNAME is nil, it defaults to PROCESS' name;
8419 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8420 If PROCESS is associated with a buffer, the new process will be associated
8421 with the current buffer instead.
8422 Returns nil if PROCESS has already terminated."
8423 (setq newname (or newname (process-name process)))
8424 (if (string-match "<[0-9]+>\\'" newname)
8425 (setq newname (substring newname 0 (match-beginning 0))))
8426 (when (memq (process-status process) '(run stop open))
8427 (let* ((process-connection-type (process-tty-name process))
8428 (new-process
8429 (if (memq (process-status process) '(open))
8430 (let ((args (process-contact process t)))
8431 (setq args (plist-put args :name newname))
8432 (setq args (plist-put args :buffer
8433 (if (process-buffer process)
8434 (current-buffer))))
8435 (apply 'make-network-process args))
8436 (apply 'start-process newname
8437 (if (process-buffer process) (current-buffer))
8438 (process-command process)))))
8439 (set-process-query-on-exit-flag
8440 new-process (process-query-on-exit-flag process))
8441 (set-process-inherit-coding-system-flag
8442 new-process (process-inherit-coding-system-flag process))
8443 (set-process-filter new-process (process-filter process))
8444 (set-process-sentinel new-process (process-sentinel process))
8445 (set-process-plist new-process (copy-sequence (process-plist process)))
8446 new-process)))
8448 ;; things to maybe add (currently partly covered by `funcall mode'):
8449 ;; - syntax-table
8450 ;; - overlays
8451 (defun clone-buffer (&optional newname display-flag)
8452 "Create and return a twin copy of the current buffer.
8453 Unlike an indirect buffer, the new buffer can be edited
8454 independently of the old one (if it is not read-only).
8455 NEWNAME is the name of the new buffer. It may be modified by
8456 adding or incrementing <N> at the end as necessary to create a
8457 unique buffer name. If nil, it defaults to the name of the
8458 current buffer, with the proper suffix. If DISPLAY-FLAG is
8459 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8460 clone a file-visiting buffer, or a buffer whose major mode symbol
8461 has a non-nil `no-clone' property, results in an error.
8463 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8464 current buffer with appropriate suffix. However, if a prefix
8465 argument is given, then the command prompts for NEWNAME in the
8466 minibuffer.
8468 This runs the normal hook `clone-buffer-hook' in the new buffer
8469 after it has been set up properly in other respects."
8470 (interactive
8471 (progn
8472 (if buffer-file-name
8473 (error "Cannot clone a file-visiting buffer"))
8474 (if (get major-mode 'no-clone)
8475 (error "Cannot clone a buffer in %s mode" mode-name))
8476 (list (if current-prefix-arg
8477 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8478 t)))
8479 (if buffer-file-name
8480 (error "Cannot clone a file-visiting buffer"))
8481 (if (get major-mode 'no-clone)
8482 (error "Cannot clone a buffer in %s mode" mode-name))
8483 (setq newname (or newname (buffer-name)))
8484 (if (string-match "<[0-9]+>\\'" newname)
8485 (setq newname (substring newname 0 (match-beginning 0))))
8486 (let ((buf (current-buffer))
8487 (ptmin (point-min))
8488 (ptmax (point-max))
8489 (pt (point))
8490 (mk (if mark-active (mark t)))
8491 (modified (buffer-modified-p))
8492 (mode major-mode)
8493 (lvars (buffer-local-variables))
8494 (process (get-buffer-process (current-buffer)))
8495 (new (generate-new-buffer (or newname (buffer-name)))))
8496 (save-restriction
8497 (widen)
8498 (with-current-buffer new
8499 (insert-buffer-substring buf)))
8500 (with-current-buffer new
8501 (narrow-to-region ptmin ptmax)
8502 (goto-char pt)
8503 (if mk (set-mark mk))
8504 (set-buffer-modified-p modified)
8506 ;; Clone the old buffer's process, if any.
8507 (when process (clone-process process))
8509 ;; Now set up the major mode.
8510 (funcall mode)
8512 ;; Set up other local variables.
8513 (mapc (lambda (v)
8514 (condition-case () ;in case var is read-only
8515 (if (symbolp v)
8516 (makunbound v)
8517 (set (make-local-variable (car v)) (cdr v)))
8518 (error nil)))
8519 lvars)
8521 ;; Run any hooks (typically set up by the major mode
8522 ;; for cloning to work properly).
8523 (run-hooks 'clone-buffer-hook))
8524 (if display-flag
8525 ;; Presumably the current buffer is shown in the selected frame, so
8526 ;; we want to display the clone elsewhere.
8527 (let ((same-window-regexps nil)
8528 (same-window-buffer-names))
8529 (pop-to-buffer new)))
8530 new))
8533 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8534 "Create an indirect buffer that is a twin copy of the current buffer.
8536 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8537 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8538 or if not called with a prefix arg, NEWNAME defaults to the current
8539 buffer's name. The name is modified by adding a `<N>' suffix to it
8540 or by incrementing the N in an existing suffix. Trying to clone a
8541 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8542 property results in an error.
8544 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8545 This is always done when called interactively.
8547 Optional third arg NORECORD non-nil means do not put this buffer at the
8548 front of the list of recently selected ones.
8550 Returns the newly created indirect buffer."
8551 (interactive
8552 (progn
8553 (if (get major-mode 'no-clone-indirect)
8554 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8555 (list (if current-prefix-arg
8556 (read-buffer "Name of indirect buffer: " (current-buffer)))
8557 t)))
8558 (if (get major-mode 'no-clone-indirect)
8559 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8560 (setq newname (or newname (buffer-name)))
8561 (if (string-match "<[0-9]+>\\'" newname)
8562 (setq newname (substring newname 0 (match-beginning 0))))
8563 (let* ((name (generate-new-buffer-name newname))
8564 (buffer (make-indirect-buffer (current-buffer) name t)))
8565 (with-current-buffer buffer
8566 (run-hooks 'clone-indirect-buffer-hook))
8567 (when display-flag
8568 (pop-to-buffer buffer nil norecord))
8569 buffer))
8572 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8573 "Like `clone-indirect-buffer' but display in another window."
8574 (interactive
8575 (progn
8576 (if (get major-mode 'no-clone-indirect)
8577 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8578 (list (if current-prefix-arg
8579 (read-buffer "Name of indirect buffer: " (current-buffer)))
8580 t)))
8581 (let ((pop-up-windows t))
8582 (clone-indirect-buffer newname display-flag norecord)))
8585 ;;; Handling of Backspace and Delete keys.
8587 (defcustom normal-erase-is-backspace 'maybe
8588 "Set the default behavior of the Delete and Backspace keys.
8590 If set to t, Delete key deletes forward and Backspace key deletes
8591 backward.
8593 If set to nil, both Delete and Backspace keys delete backward.
8595 If set to `maybe' (which is the default), Emacs automatically
8596 selects a behavior. On window systems, the behavior depends on
8597 the keyboard used. If the keyboard has both a Backspace key and
8598 a Delete key, and both are mapped to their usual meanings, the
8599 option's default value is set to t, so that Backspace can be used
8600 to delete backward, and Delete can be used to delete forward.
8602 If not running under a window system, customizing this option
8603 accomplishes a similar effect by mapping C-h, which is usually
8604 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8605 via `keyboard-translate'. The former functionality of C-h is
8606 available on the F1 key. You should probably not use this
8607 setting if you don't have both Backspace, Delete and F1 keys.
8609 Setting this variable with setq doesn't take effect. Programmatically,
8610 call `normal-erase-is-backspace-mode' (which see) instead."
8611 :type '(choice (const :tag "Off" nil)
8612 (const :tag "Maybe" maybe)
8613 (other :tag "On" t))
8614 :group 'editing-basics
8615 :version "21.1"
8616 :set (lambda (symbol value)
8617 ;; The fboundp is because of a problem with :set when
8618 ;; dumping Emacs. It doesn't really matter.
8619 (if (fboundp 'normal-erase-is-backspace-mode)
8620 (normal-erase-is-backspace-mode (or value 0))
8621 (set-default symbol value))))
8623 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8624 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8625 (unless frame (setq frame (selected-frame)))
8626 (with-selected-frame frame
8627 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8628 (normal-erase-is-backspace-mode
8629 (if (if (eq normal-erase-is-backspace 'maybe)
8630 (and (not noninteractive)
8631 (or (memq system-type '(ms-dos windows-nt))
8632 (memq window-system '(w32 ns))
8633 (and (memq window-system '(x))
8634 (fboundp 'x-backspace-delete-keys-p)
8635 (x-backspace-delete-keys-p))
8636 ;; If the terminal Emacs is running on has erase char
8637 ;; set to ^H, use the Backspace key for deleting
8638 ;; backward, and the Delete key for deleting forward.
8639 (and (null window-system)
8640 (eq tty-erase-char ?\^H))))
8641 normal-erase-is-backspace)
8642 1 0)))))
8644 (define-minor-mode normal-erase-is-backspace-mode
8645 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8646 With a prefix argument ARG, enable this feature if ARG is
8647 positive, and disable it otherwise. If called from Lisp, enable
8648 the mode if ARG is omitted or nil.
8650 On window systems, when this mode is on, Delete is mapped to C-d
8651 and Backspace is mapped to DEL; when this mode is off, both
8652 Delete and Backspace are mapped to DEL. (The remapping goes via
8653 `local-function-key-map', so binding Delete or Backspace in the
8654 global or local keymap will override that.)
8656 In addition, on window systems, the bindings of C-Delete, M-Delete,
8657 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8658 the global keymap in accordance with the functionality of Delete and
8659 Backspace. For example, if Delete is remapped to C-d, which deletes
8660 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8661 to DEL, which deletes backward, C-Delete is bound to
8662 `backward-kill-word'.
8664 If not running on a window system, a similar effect is accomplished by
8665 remapping C-h (normally produced by the Backspace key) and DEL via
8666 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8667 to C-d; if it's off, the keys are not remapped.
8669 When not running on a window system, and this mode is turned on, the
8670 former functionality of C-h is available on the F1 key. You should
8671 probably not turn on this mode on a text-only terminal if you don't
8672 have both Backspace, Delete and F1 keys.
8674 See also `normal-erase-is-backspace'."
8675 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8676 . (lambda (v)
8677 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8678 (if v 1 0))))
8679 (let ((enabled (eq 1 (terminal-parameter
8680 nil 'normal-erase-is-backspace))))
8682 (cond ((or (memq window-system '(x w32 ns pc))
8683 (memq system-type '(ms-dos windows-nt)))
8684 (let ((bindings
8685 `(([M-delete] [M-backspace])
8686 ([C-M-delete] [C-M-backspace])
8687 ([?\e C-delete] [?\e C-backspace]))))
8689 (if enabled
8690 (progn
8691 (define-key local-function-key-map [delete] [deletechar])
8692 (define-key local-function-key-map [kp-delete] [deletechar])
8693 (define-key local-function-key-map [backspace] [?\C-?])
8694 (dolist (b bindings)
8695 ;; Not sure if input-decode-map is really right, but
8696 ;; keyboard-translate-table (used below) only works
8697 ;; for integer events, and key-translation-table is
8698 ;; global (like the global-map, used earlier).
8699 (define-key input-decode-map (car b) nil)
8700 (define-key input-decode-map (cadr b) nil)))
8701 (define-key local-function-key-map [delete] [?\C-?])
8702 (define-key local-function-key-map [kp-delete] [?\C-?])
8703 (define-key local-function-key-map [backspace] [?\C-?])
8704 (dolist (b bindings)
8705 (define-key input-decode-map (car b) (cadr b))
8706 (define-key input-decode-map (cadr b) (car b))))))
8708 (if enabled
8709 (progn
8710 (keyboard-translate ?\C-h ?\C-?)
8711 (keyboard-translate ?\C-? ?\C-d))
8712 (keyboard-translate ?\C-h ?\C-h)
8713 (keyboard-translate ?\C-? ?\C-?))))
8715 (if (called-interactively-p 'interactive)
8716 (message "Delete key deletes %s"
8717 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8718 "forward" "backward")))))
8720 (defvar vis-mode-saved-buffer-invisibility-spec nil
8721 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8723 (define-minor-mode read-only-mode
8724 "Change whether the current buffer is read-only.
8725 With prefix argument ARG, make the buffer read-only if ARG is
8726 positive, otherwise make it writable. If buffer is read-only
8727 and `view-read-only' is non-nil, enter view mode.
8729 Do not call this from a Lisp program unless you really intend to
8730 do the same thing as the \\[read-only-mode] command, including
8731 possibly enabling or disabling View mode. Also, note that this
8732 command works by setting the variable `buffer-read-only', which
8733 does not affect read-only regions caused by text properties. To
8734 ignore read-only status in a Lisp program (whether due to text
8735 properties or buffer state), bind `inhibit-read-only' temporarily
8736 to a non-nil value."
8737 :variable buffer-read-only
8738 (cond
8739 ((and (not buffer-read-only) view-mode)
8740 (View-exit-and-edit)
8741 (make-local-variable 'view-read-only)
8742 (setq view-read-only t)) ; Must leave view mode.
8743 ((and buffer-read-only view-read-only
8744 ;; If view-mode is already active, `view-mode-enter' is a nop.
8745 (not view-mode)
8746 (not (eq (get major-mode 'mode-class) 'special)))
8747 (view-mode-enter))))
8749 (define-minor-mode visible-mode
8750 "Toggle making all invisible text temporarily visible (Visible mode).
8751 With a prefix argument ARG, enable Visible mode if ARG is
8752 positive, and disable it otherwise. If called from Lisp, enable
8753 the mode if ARG is omitted or nil.
8755 This mode works by saving the value of `buffer-invisibility-spec'
8756 and setting it to nil."
8757 :lighter " Vis"
8758 :group 'editing-basics
8759 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8760 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8761 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8762 (when visible-mode
8763 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8764 buffer-invisibility-spec)
8765 (setq buffer-invisibility-spec nil)))
8767 (defvar messages-buffer-mode-map
8768 (let ((map (make-sparse-keymap)))
8769 (set-keymap-parent map special-mode-map)
8770 (define-key map "g" nil) ; nothing to revert
8771 map))
8773 (define-derived-mode messages-buffer-mode special-mode "Messages"
8774 "Major mode used in the \"*Messages*\" buffer.")
8776 (defun messages-buffer ()
8777 "Return the \"*Messages*\" buffer.
8778 If it does not exist, create and it switch it to `messages-buffer-mode'."
8779 (or (get-buffer "*Messages*")
8780 (with-current-buffer (get-buffer-create "*Messages*")
8781 (messages-buffer-mode)
8782 (current-buffer))))
8785 ;; Minibuffer prompt stuff.
8787 ;;(defun minibuffer-prompt-modification (start end)
8788 ;; (error "You cannot modify the prompt"))
8791 ;;(defun minibuffer-prompt-insertion (start end)
8792 ;; (let ((inhibit-modification-hooks t))
8793 ;; (delete-region start end)
8794 ;; ;; Discard undo information for the text insertion itself
8795 ;; ;; and for the text deletion.above.
8796 ;; (when (consp buffer-undo-list)
8797 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8798 ;; (message "You cannot modify the prompt")))
8801 ;;(setq minibuffer-prompt-properties
8802 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8803 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8806 ;;;; Problematic external packages.
8808 ;; rms says this should be done by specifying symbols that define
8809 ;; versions together with bad values. This is therefore not as
8810 ;; flexible as it could be. See the thread:
8811 ;; https://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8812 (defconst bad-packages-alist
8813 ;; Not sure exactly which semantic versions have problems.
8814 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8815 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8816 "The version of `semantic' loaded does not work in Emacs 22.
8817 It can cause constant high CPU load.
8818 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8819 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8820 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8821 ;; provided the `CUA-mode' feature. Since this is no longer true,
8822 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8823 (CUA-mode t nil
8824 "CUA-mode is now part of the standard GNU Emacs distribution,
8825 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8827 You have loaded an older version of CUA-mode which does not work
8828 correctly with this version of Emacs. You should remove the old
8829 version and use the one distributed with Emacs."))
8830 "Alist of packages known to cause problems in this version of Emacs.
8831 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8832 PACKAGE is either a regular expression to match file names, or a
8833 symbol (a feature name), like for `with-eval-after-load'.
8834 SYMBOL is either the name of a string variable, or t. Upon
8835 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8836 warning using STRING as the message.")
8838 (defun bad-package-check (package)
8839 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8840 (condition-case nil
8841 (let* ((list (assoc package bad-packages-alist))
8842 (symbol (nth 1 list)))
8843 (and list
8844 (boundp symbol)
8845 (or (eq symbol t)
8846 (and (stringp (setq symbol (eval symbol)))
8847 (string-match-p (nth 2 list) symbol)))
8848 (display-warning package (nth 3 list) :warning)))
8849 (error nil)))
8851 (dolist (elem bad-packages-alist)
8852 (let ((pkg (car elem)))
8853 (with-eval-after-load pkg
8854 (bad-package-check pkg))))
8857 ;;; Generic dispatcher commands
8859 ;; Macro `define-alternatives' is used to create generic commands.
8860 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8861 ;; that can have different alternative implementations where choosing
8862 ;; among them is exclusively a matter of user preference.
8864 ;; (define-alternatives COMMAND) creates a new interactive command
8865 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8866 ;; Typically, the user will not need to customize this variable; packages
8867 ;; wanting to add alternative implementations should use
8869 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8871 (defmacro define-alternatives (command &rest customizations)
8872 "Define the new command `COMMAND'.
8874 The argument `COMMAND' should be a symbol.
8876 Running `M-x COMMAND RET' for the first time prompts for which
8877 alternative to use and records the selected command as a custom
8878 variable.
8880 Running `C-u M-x COMMAND RET' prompts again for an alternative
8881 and overwrites the previous choice.
8883 The variable `COMMAND-alternatives' contains an alist with
8884 alternative implementations of COMMAND. `define-alternatives'
8885 does not have any effect until this variable is set.
8887 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8888 `defcustom' keywords and values to add to the declaration of
8889 `COMMAND-alternatives' (typically :group and :version)."
8890 (let* ((command-name (symbol-name command))
8891 (varalt-name (concat command-name "-alternatives"))
8892 (varalt-sym (intern varalt-name))
8893 (varimp-sym (intern (concat command-name "--implementation"))))
8894 `(progn
8896 (defcustom ,varalt-sym nil
8897 ,(format "Alist of alternative implementations for the `%s' command.
8899 Each entry must be a pair (ALTNAME . ALTFUN), where:
8900 ALTNAME - The name shown at user to describe the alternative implementation.
8901 ALTFUN - The function called to implement this alternative."
8902 command-name)
8903 :type '(alist :key-type string :value-type function)
8904 ,@customizations)
8906 (put ',varalt-sym 'definition-name ',command)
8907 (defvar ,varimp-sym nil "Internal use only.")
8909 (defun ,command (&optional arg)
8910 ,(format "Run generic command `%s'.
8911 If used for the first time, or with interactive ARG, ask the user which
8912 implementation to use for `%s'. The variable `%s'
8913 contains the list of implementations currently supported for this command."
8914 command-name command-name varalt-name)
8915 (interactive "P")
8916 (when (or arg (null ,varimp-sym))
8917 (let ((val (completing-read
8918 ,(format-message
8919 "Select implementation for command `%s': "
8920 command-name)
8921 ,varalt-sym nil t)))
8922 (unless (string-equal val "")
8923 (when (null ,varimp-sym)
8924 (message
8925 "Use C-u M-x %s RET`to select another implementation"
8926 ,command-name)
8927 (sit-for 3))
8928 (customize-save-variable ',varimp-sym
8929 (cdr (assoc-string val ,varalt-sym))))))
8930 (if ,varimp-sym
8931 (call-interactively ,varimp-sym)
8932 (message "%s" ,(format-message
8933 "No implementation selected for command `%s'"
8934 command-name)))))))
8937 ;;; Functions for changing capitalization that Do What I Mean
8938 (defun upcase-dwim (arg)
8939 "Upcase words in the region, if active; if not, upcase word at point.
8940 If the region is active, this function calls `upcase-region'.
8941 Otherwise, it calls `upcase-word', with prefix argument passed to it
8942 to upcase ARG words."
8943 (interactive "*p")
8944 (if (use-region-p)
8945 (upcase-region (region-beginning) (region-end))
8946 (upcase-word arg)))
8948 (defun downcase-dwim (arg)
8949 "Downcase words in the region, if active; if not, downcase word at point.
8950 If the region is active, this function calls `downcase-region'.
8951 Otherwise, it calls `downcase-word', with prefix argument passed to it
8952 to downcase ARG words."
8953 (interactive "*p")
8954 (if (use-region-p)
8955 (downcase-region (region-beginning) (region-end))
8956 (downcase-word arg)))
8958 (defun capitalize-dwim (arg)
8959 "Capitalize words in the region, if active; if not, capitalize word at point.
8960 If the region is active, this function calls `capitalize-region'.
8961 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8962 to capitalize ARG words."
8963 (interactive "*p")
8964 (if (use-region-p)
8965 (capitalize-region (region-beginning) (region-end))
8966 (capitalize-word arg)))
8970 (provide 'simple)
8972 ;;; simple.el ends here