]> code.delx.au - gnu-emacs/blob - lisp/simple.el
Fix bug#21766 and add test
[gnu-emacs] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1985-1987, 1993-2015 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl-lib))
32
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
35
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
39
40 (defcustom idle-update-delay 0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
44 :type 'number
45 :group 'display
46 :version "22.1")
47
48 (defgroup killing nil
49 "Killing and yanking commands."
50 :group 'editing)
51
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
54 :group 'matching)
55 \f
56 ;;; next-error support framework
57
58 (defgroup next-error nil
59 "`next-error' support framework."
60 :group 'compilation
61 :version "22.1")
62
63 (defface next-error
64 '((t (:inherit region)))
65 "Face used to highlight next error locus."
66 :group 'next-error
67 :version "22.1")
68
69 (defcustom next-error-highlight 0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow
77 indefinitely until some other locus replaces it."
78 :type '(choice (number :tag "Highlight for specified time")
79 (const :tag "Semipermanent highlighting" t)
80 (const :tag "No highlighting" nil)
81 (const :tag "Fringe arrow" fringe-arrow))
82 :group 'next-error
83 :version "22.1")
84
85 (defcustom next-error-highlight-no-select 0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow
91 indefinitely until some other locus replaces it."
92 :type '(choice (number :tag "Highlight for specified time")
93 (const :tag "Semipermanent highlighting" t)
94 (const :tag "No highlighting" nil)
95 (const :tag "Fringe arrow" fringe-arrow))
96 :group 'next-error
97 :version "22.1")
98
99 (defcustom next-error-recenter nil
100 "Display the line in the visited source file recentered as specified.
101 If non-nil, the value is passed directly to `recenter'."
102 :type '(choice (integer :tag "Line to recenter to")
103 (const :tag "Center of window" (4))
104 (const :tag "No recentering" nil))
105 :group 'next-error
106 :version "23.1")
107
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
110 :type 'hook
111 :group 'next-error)
112
113 (defvar next-error-highlight-timer nil)
114
115 (defvar next-error-overlay-arrow-position nil)
116 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
117 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
118
119 (defvar next-error-last-buffer nil
120 "The most recent `next-error' buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
124
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
133 to navigate in it.")
134 (make-variable-buffer-local 'next-error-function)
135
136 (defvar next-error-move-function nil
137 "Function to use to move to an error locus.
138 It takes two arguments, a buffer position in the error buffer
139 and a buffer position in the error locus buffer.
140 The buffer for the error locus should already be current.
141 nil means use goto-char using the second argument position.")
142 (make-variable-buffer-local 'next-error-move-function)
143
144 (defsubst next-error-buffer-p (buffer
145 &optional avoid-current
146 extra-test-inclusive
147 extra-test-exclusive)
148 "Test if BUFFER is a `next-error' capable buffer.
149
150 If AVOID-CURRENT is non-nil, treat the current buffer
151 as an absolute last resort only.
152
153 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
154 that normally would not qualify. If it returns t, the buffer
155 in question is treated as usable.
156
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
158 that would normally be considered usable. If it returns nil,
159 that buffer is rejected."
160 (and (buffer-name buffer) ;First make sure it's live.
161 (not (and avoid-current (eq buffer (current-buffer))))
162 (with-current-buffer buffer
163 (if next-error-function ; This is the normal test.
164 ;; Optionally reject some buffers.
165 (if extra-test-exclusive
166 (funcall extra-test-exclusive)
167 t)
168 ;; Optionally accept some other buffers.
169 (and extra-test-inclusive
170 (funcall extra-test-inclusive))))))
171
172 (defun next-error-find-buffer (&optional avoid-current
173 extra-test-inclusive
174 extra-test-exclusive)
175 "Return a `next-error' capable buffer.
176
177 If AVOID-CURRENT is non-nil, treat the current buffer
178 as an absolute last resort only.
179
180 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 that normally would not qualify. If it returns t, the buffer
182 in question is treated as usable.
183
184 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 that would normally be considered usable. If it returns nil,
186 that buffer is rejected."
187 (or
188 ;; 1. If one window on the selected frame displays such buffer, return it.
189 (let ((window-buffers
190 (delete-dups
191 (delq nil (mapcar (lambda (w)
192 (if (next-error-buffer-p
193 (window-buffer w)
194 avoid-current
195 extra-test-inclusive extra-test-exclusive)
196 (window-buffer w)))
197 (window-list))))))
198 (if (eq (length window-buffers) 1)
199 (car window-buffers)))
200 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201 (if (and next-error-last-buffer
202 (next-error-buffer-p next-error-last-buffer avoid-current
203 extra-test-inclusive extra-test-exclusive))
204 next-error-last-buffer)
205 ;; 3. If the current buffer is acceptable, choose it.
206 (if (next-error-buffer-p (current-buffer) avoid-current
207 extra-test-inclusive extra-test-exclusive)
208 (current-buffer))
209 ;; 4. Look for any acceptable buffer.
210 (let ((buffers (buffer-list)))
211 (while (and buffers
212 (not (next-error-buffer-p
213 (car buffers) avoid-current
214 extra-test-inclusive extra-test-exclusive)))
215 (setq buffers (cdr buffers)))
216 (car buffers))
217 ;; 5. Use the current buffer as a last resort if it qualifies,
218 ;; even despite AVOID-CURRENT.
219 (and avoid-current
220 (next-error-buffer-p (current-buffer) nil
221 extra-test-inclusive extra-test-exclusive)
222 (progn
223 (message "This is the only buffer with error message locations")
224 (current-buffer)))
225 ;; 6. Give up.
226 (error "No buffers contain error message locations")))
227
228 (defun next-error (&optional arg reset)
229 "Visit next `next-error' message and corresponding source code.
230
231 If all the error messages parsed so far have been processed already,
232 the message buffer is checked for new ones.
233
234 A prefix ARG specifies how many error messages to move;
235 negative means move back to previous error messages.
236 Just \\[universal-argument] as a prefix means reparse the error message buffer
237 and start at the first error.
238
239 The RESET argument specifies that we should restart from the beginning.
240
241 \\[next-error] normally uses the most recently started
242 compilation, grep, or occur buffer. It can also operate on any
243 buffer with output from the \\[compile], \\[grep] commands, or,
244 more generally, on any buffer in Compilation mode or with
245 Compilation Minor mode enabled, or any buffer in which
246 `next-error-function' is bound to an appropriate function.
247 To specify use of a particular buffer for error messages, type
248 \\[next-error] in that buffer when it is the only one displayed
249 in the current frame.
250
251 Once \\[next-error] has chosen the buffer for error messages, it
252 runs `next-error-hook' with `run-hooks', and stays with that buffer
253 until you use it in some other buffer which uses Compilation mode
254 or Compilation Minor mode.
255
256 To control which errors are matched, customize the variable
257 `compilation-error-regexp-alist'."
258 (interactive "P")
259 (if (consp arg) (setq reset t arg nil))
260 (when (setq next-error-last-buffer (next-error-find-buffer))
261 ;; we know here that next-error-function is a valid symbol we can funcall
262 (with-current-buffer next-error-last-buffer
263 (funcall next-error-function (prefix-numeric-value arg) reset)
264 (when next-error-recenter
265 (recenter next-error-recenter))
266 (run-hooks 'next-error-hook))))
267
268 (defun next-error-internal ()
269 "Visit the source code corresponding to the `next-error' message at point."
270 (setq next-error-last-buffer (current-buffer))
271 ;; we know here that next-error-function is a valid symbol we can funcall
272 (with-current-buffer next-error-last-buffer
273 (funcall next-error-function 0 nil)
274 (when next-error-recenter
275 (recenter next-error-recenter))
276 (run-hooks 'next-error-hook)))
277
278 (defalias 'goto-next-locus 'next-error)
279 (defalias 'next-match 'next-error)
280
281 (defun previous-error (&optional n)
282 "Visit previous `next-error' message and corresponding source code.
283
284 Prefix arg N says how many error messages to move backwards (or
285 forwards, if negative).
286
287 This operates on the output from the \\[compile] and \\[grep] commands."
288 (interactive "p")
289 (next-error (- (or n 1))))
290
291 (defun first-error (&optional n)
292 "Restart at the first error.
293 Visit corresponding source code.
294 With prefix arg N, visit the source code of the Nth error.
295 This operates on the output from the \\[compile] command, for instance."
296 (interactive "p")
297 (next-error n t))
298
299 (defun next-error-no-select (&optional n)
300 "Move point to the next error in the `next-error' buffer and highlight match.
301 Prefix arg N says how many error messages to move forwards (or
302 backwards, if negative).
303 Finds and highlights the source line like \\[next-error], but does not
304 select the source buffer."
305 (interactive "p")
306 (let ((next-error-highlight next-error-highlight-no-select))
307 (next-error n))
308 (pop-to-buffer next-error-last-buffer))
309
310 (defun previous-error-no-select (&optional n)
311 "Move point to the previous error in the `next-error' buffer and highlight match.
312 Prefix arg N says how many error messages to move backwards (or
313 forwards, if negative).
314 Finds and highlights the source line like \\[previous-error], but does not
315 select the source buffer."
316 (interactive "p")
317 (next-error-no-select (- (or n 1))))
318
319 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 (defvar next-error-follow-last-line nil)
321
322 (define-minor-mode next-error-follow-minor-mode
323 "Minor mode for compilation, occur and diff modes.
324 With a prefix argument ARG, enable mode if ARG is positive, and
325 disable it otherwise. If called from Lisp, enable mode if ARG is
326 omitted or nil.
327 When turned on, cursor motion in the compilation, grep, occur or diff
328 buffer causes automatic display of the corresponding source code location."
329 :group 'next-error :init-value nil :lighter " Fol"
330 (if (not next-error-follow-minor-mode)
331 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
332 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
333 (make-local-variable 'next-error-follow-last-line)))
334
335 ;; Used as a `post-command-hook' by `next-error-follow-mode'
336 ;; for the *Compilation* *grep* and *Occur* buffers.
337 (defun next-error-follow-mode-post-command-hook ()
338 (unless (equal next-error-follow-last-line (line-number-at-pos))
339 (setq next-error-follow-last-line (line-number-at-pos))
340 (condition-case nil
341 (let ((compilation-context-lines nil))
342 (setq compilation-current-error (point))
343 (next-error-no-select 0))
344 (error t))))
345
346 \f
347 ;;;
348
349 (defun fundamental-mode ()
350 "Major mode not specialized for anything in particular.
351 Other major modes are defined by comparison with this one."
352 (interactive)
353 (kill-all-local-variables)
354 (run-mode-hooks))
355
356 ;; Special major modes to view specially formatted data rather than files.
357
358 (defvar special-mode-map
359 (let ((map (make-sparse-keymap)))
360 (suppress-keymap map)
361 (define-key map "q" 'quit-window)
362 (define-key map " " 'scroll-up-command)
363 (define-key map [?\S-\ ] 'scroll-down-command)
364 (define-key map "\C-?" 'scroll-down-command)
365 (define-key map "?" 'describe-mode)
366 (define-key map "h" 'describe-mode)
367 (define-key map ">" 'end-of-buffer)
368 (define-key map "<" 'beginning-of-buffer)
369 (define-key map "g" 'revert-buffer)
370 map))
371
372 (put 'special-mode 'mode-class 'special)
373 (define-derived-mode special-mode nil "Special"
374 "Parent major mode from which special major modes should inherit."
375 (setq buffer-read-only t))
376
377 ;; Making and deleting lines.
378
379 (defvar self-insert-uses-region-functions nil
380 "Special hook to tell if `self-insert-command' will use the region.
381 It must be called via `run-hook-with-args-until-success' with no arguments.
382 Any `post-self-insert-command' which consumes the region should
383 register a function on this hook so that things like `delete-selection-mode'
384 can refrain from consuming the region.")
385
386 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
387 "Propertized string representing a hard newline character.")
388
389 (defun newline (&optional arg interactive)
390 "Insert a newline, and move to left margin of the new line if it's blank.
391 If option `use-hard-newlines' is non-nil, the newline is marked with the
392 text-property `hard'.
393 With ARG, insert that many newlines.
394
395 If `electric-indent-mode' is enabled, this indents the final new line
396 that it adds, and reindents the preceding line. To just insert
397 a newline, use \\[electric-indent-just-newline].
398
399 Calls `auto-fill-function' if the current column number is greater
400 than the value of `fill-column' and ARG is nil.
401 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
402 (interactive "*P\np")
403 (barf-if-buffer-read-only)
404 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
405 ;; Set last-command-event to tell self-insert what to insert.
406 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
407 (beforepos (point))
408 (last-command-event ?\n)
409 ;; Don't auto-fill if we have a numeric argument.
410 (auto-fill-function (if arg nil auto-fill-function))
411 (postproc
412 ;; Do the rest in post-self-insert-hook, because we want to do it
413 ;; *before* other functions on that hook.
414 (lambda ()
415 (cl-assert (eq ?\n (char-before)))
416 ;; Mark the newline(s) `hard'.
417 (if use-hard-newlines
418 (set-hard-newline-properties
419 (- (point) (prefix-numeric-value arg)) (point)))
420 ;; If the newline leaves the previous line blank, and we
421 ;; have a left margin, delete that from the blank line.
422 (save-excursion
423 (goto-char beforepos)
424 (beginning-of-line)
425 (and (looking-at "[ \t]$")
426 (> (current-left-margin) 0)
427 (delete-region (point)
428 (line-end-position))))
429 ;; Indent the line after the newline, except in one case:
430 ;; when we added the newline at the beginning of a line which
431 ;; starts a page.
432 (or was-page-start
433 (move-to-left-margin nil t)))))
434 (unwind-protect
435 (if (not interactive)
436 ;; FIXME: For non-interactive uses, many calls actually just want
437 ;; (insert "\n"), so maybe we should do just that, so as to avoid
438 ;; the risk of filling or running abbrevs unexpectedly.
439 (let ((post-self-insert-hook (list postproc)))
440 (self-insert-command (prefix-numeric-value arg)))
441 (unwind-protect
442 (progn
443 (add-hook 'post-self-insert-hook postproc nil t)
444 (self-insert-command (prefix-numeric-value arg)))
445 ;; We first used let-binding to protect the hook, but that was naive
446 ;; since add-hook affects the symbol-default value of the variable,
447 ;; whereas the let-binding might only protect the buffer-local value.
448 (remove-hook 'post-self-insert-hook postproc t)))
449 (cl-assert (not (member postproc post-self-insert-hook)))
450 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
451 nil)
452
453 (defun set-hard-newline-properties (from to)
454 (let ((sticky (get-text-property from 'rear-nonsticky)))
455 (put-text-property from to 'hard 't)
456 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
457 (if (and (listp sticky) (not (memq 'hard sticky)))
458 (put-text-property from (point) 'rear-nonsticky
459 (cons 'hard sticky)))))
460
461 (declare-function electric-indent-just-newline "electric")
462 (defun open-line (n &optional interactive)
463 "Insert a newline and leave point before it.
464 If `electric-indent-mode' is enabled, indent the new line if it's
465 not empty.
466 If there is a fill prefix and/or a `left-margin', insert them on
467 the new line. If the old line would have been blank, insert them
468 on the old line as well.
469
470 With arg N, insert N newlines.
471 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
472 (interactive "*p\np")
473 (let* ((do-fill-prefix (and fill-prefix (bolp)))
474 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
475 (loc (point-marker))
476 ;; Don't expand an abbrev before point.
477 (abbrev-mode nil))
478 (if (and interactive
479 (looking-at-p "[[:space:]]*$"))
480 (electric-indent-just-newline n)
481 (newline n interactive))
482 (goto-char loc)
483 (while (> n 0)
484 (cond ((bolp)
485 (if do-left-margin (indent-to (current-left-margin)))
486 (if do-fill-prefix (insert-and-inherit fill-prefix))))
487 (forward-line 1)
488 (setq n (1- n)))
489 (goto-char loc)
490 ;; Necessary in case a margin or prefix was inserted.
491 (end-of-line)))
492
493 (defun split-line (&optional arg)
494 "Split current line, moving portion beyond point vertically down.
495 If the current line starts with `fill-prefix', insert it on the new
496 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
497
498 When called from Lisp code, ARG may be a prefix string to copy."
499 (interactive "*P")
500 (skip-chars-forward " \t")
501 (let* ((col (current-column))
502 (pos (point))
503 ;; What prefix should we check for (nil means don't).
504 (prefix (cond ((stringp arg) arg)
505 (arg nil)
506 (t fill-prefix)))
507 ;; Does this line start with it?
508 (have-prfx (and prefix
509 (save-excursion
510 (beginning-of-line)
511 (looking-at (regexp-quote prefix))))))
512 (newline 1)
513 (if have-prfx (insert-and-inherit prefix))
514 (indent-to col 0)
515 (goto-char pos)))
516
517 (defun delete-indentation (&optional arg)
518 "Join this line to previous and fix up whitespace at join.
519 If there is a fill prefix, delete it from the beginning of this line.
520 With argument, join this line to following line."
521 (interactive "*P")
522 (beginning-of-line)
523 (if arg (forward-line 1))
524 (if (eq (preceding-char) ?\n)
525 (progn
526 (delete-region (point) (1- (point)))
527 ;; If the second line started with the fill prefix,
528 ;; delete the prefix.
529 (if (and fill-prefix
530 (<= (+ (point) (length fill-prefix)) (point-max))
531 (string= fill-prefix
532 (buffer-substring (point)
533 (+ (point) (length fill-prefix)))))
534 (delete-region (point) (+ (point) (length fill-prefix))))
535 (fixup-whitespace))))
536
537 (defalias 'join-line #'delete-indentation) ; easier to find
538
539 (defun delete-blank-lines ()
540 "On blank line, delete all surrounding blank lines, leaving just one.
541 On isolated blank line, delete that one.
542 On nonblank line, delete any immediately following blank lines."
543 (interactive "*")
544 (let (thisblank singleblank)
545 (save-excursion
546 (beginning-of-line)
547 (setq thisblank (looking-at "[ \t]*$"))
548 ;; Set singleblank if there is just one blank line here.
549 (setq singleblank
550 (and thisblank
551 (not (looking-at "[ \t]*\n[ \t]*$"))
552 (or (bobp)
553 (progn (forward-line -1)
554 (not (looking-at "[ \t]*$")))))))
555 ;; Delete preceding blank lines, and this one too if it's the only one.
556 (if thisblank
557 (progn
558 (beginning-of-line)
559 (if singleblank (forward-line 1))
560 (delete-region (point)
561 (if (re-search-backward "[^ \t\n]" nil t)
562 (progn (forward-line 1) (point))
563 (point-min)))))
564 ;; Delete following blank lines, unless the current line is blank
565 ;; and there are no following blank lines.
566 (if (not (and thisblank singleblank))
567 (save-excursion
568 (end-of-line)
569 (forward-line 1)
570 (delete-region (point)
571 (if (re-search-forward "[^ \t\n]" nil t)
572 (progn (beginning-of-line) (point))
573 (point-max)))))
574 ;; Handle the special case where point is followed by newline and eob.
575 ;; Delete the line, leaving point at eob.
576 (if (looking-at "^[ \t]*\n\\'")
577 (delete-region (point) (point-max)))))
578
579 (defcustom delete-trailing-lines t
580 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
581 Trailing lines are deleted only if `delete-trailing-whitespace'
582 is called on the entire buffer (rather than an active region)."
583 :type 'boolean
584 :group 'editing
585 :version "24.3")
586
587 (defun delete-trailing-whitespace (&optional start end)
588 "Delete trailing whitespace between START and END.
589 If called interactively, START and END are the start/end of the
590 region if the mark is active, or of the buffer's accessible
591 portion if the mark is inactive.
592
593 This command deletes whitespace characters after the last
594 non-whitespace character in each line between START and END. It
595 does not consider formfeed characters to be whitespace.
596
597 If this command acts on the entire buffer (i.e. if called
598 interactively with the mark inactive, or called from Lisp with
599 END nil), it also deletes all trailing lines at the end of the
600 buffer if the variable `delete-trailing-lines' is non-nil."
601 (interactive (progn
602 (barf-if-buffer-read-only)
603 (if (use-region-p)
604 (list (region-beginning) (region-end))
605 (list nil nil))))
606 (save-match-data
607 (save-excursion
608 (let ((end-marker (copy-marker (or end (point-max))))
609 (start (or start (point-min))))
610 (goto-char start)
611 (while (re-search-forward "\\s-$" end-marker t)
612 (save-match-data
613 (skip-syntax-backward "-" (line-beginning-position)))
614 ;; Don't delete formfeeds, even if they are considered whitespace.
615 (if (looking-at-p ".*\f")
616 (goto-char (match-end 0)))
617 (delete-region (point) (match-end 0)))
618 ;; Delete trailing empty lines.
619 (goto-char end-marker)
620 (when (and (not end)
621 delete-trailing-lines
622 ;; Really the end of buffer.
623 (= (point-max) (1+ (buffer-size)))
624 (<= (skip-chars-backward "\n") -2))
625 (delete-region (1+ (point)) end-marker))
626 (set-marker end-marker nil))))
627 ;; Return nil for the benefit of `write-file-functions'.
628 nil)
629
630 (defun newline-and-indent ()
631 "Insert a newline, then indent according to major mode.
632 Indentation is done using the value of `indent-line-function'.
633 In programming language modes, this is the same as TAB.
634 In some text modes, where TAB inserts a tab, this command indents to the
635 column specified by the function `current-left-margin'."
636 (interactive "*")
637 (delete-horizontal-space t)
638 (newline nil t)
639 (indent-according-to-mode))
640
641 (defun reindent-then-newline-and-indent ()
642 "Reindent current line, insert newline, then indent the new line.
643 Indentation of both lines is done according to the current major mode,
644 which means calling the current value of `indent-line-function'.
645 In programming language modes, this is the same as TAB.
646 In some text modes, where TAB inserts a tab, this indents to the
647 column specified by the function `current-left-margin'."
648 (interactive "*")
649 (let ((pos (point)))
650 ;; Be careful to insert the newline before indenting the line.
651 ;; Otherwise, the indentation might be wrong.
652 (newline)
653 (save-excursion
654 (goto-char pos)
655 ;; We are at EOL before the call to indent-according-to-mode, and
656 ;; after it we usually are as well, but not always. We tried to
657 ;; address it with `save-excursion' but that uses a normal marker
658 ;; whereas we need `move after insertion', so we do the save/restore
659 ;; by hand.
660 (setq pos (copy-marker pos t))
661 (indent-according-to-mode)
662 (goto-char pos)
663 ;; Remove the trailing white-space after indentation because
664 ;; indentation may introduce the whitespace.
665 (delete-horizontal-space t))
666 (indent-according-to-mode)))
667
668 (defcustom read-quoted-char-radix 8
669 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
670 Legitimate radix values are 8, 10 and 16."
671 :type '(choice (const 8) (const 10) (const 16))
672 :group 'editing-basics)
673
674 (defun read-quoted-char (&optional prompt)
675 "Like `read-char', but do not allow quitting.
676 Also, if the first character read is an octal digit,
677 we read any number of octal digits and return the
678 specified character code. Any nondigit terminates the sequence.
679 If the terminator is RET, it is discarded;
680 any other terminator is used itself as input.
681
682 The optional argument PROMPT specifies a string to use to prompt the user.
683 The variable `read-quoted-char-radix' controls which radix to use
684 for numeric input."
685 (let ((message-log-max nil)
686 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
687 help-event-list)))
688 done (first t) (code 0) translated)
689 (while (not done)
690 (let ((inhibit-quit first)
691 ;; Don't let C-h or other help chars get the help
692 ;; message--only help function keys. See bug#16617.
693 (help-char nil)
694 (help-event-list help-events)
695 (help-form
696 "Type the special character you want to use,
697 or the octal character code.
698 RET terminates the character code and is discarded;
699 any other non-digit terminates the character code and is then used as input."))
700 (setq translated (read-key (and prompt (format "%s-" prompt))))
701 (if inhibit-quit (setq quit-flag nil)))
702 (if (integerp translated)
703 (setq translated (char-resolve-modifiers translated)))
704 (cond ((null translated))
705 ((not (integerp translated))
706 (setq unread-command-events
707 (nconc (listify-key-sequence (this-single-command-raw-keys))
708 unread-command-events)
709 done t))
710 ((/= (logand translated ?\M-\^@) 0)
711 ;; Turn a meta-character into a character with the 0200 bit set.
712 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
713 done t))
714 ((and (<= ?0 translated)
715 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
716 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
717 (and prompt (setq prompt (message "%s %c" prompt translated))))
718 ((and (<= ?a (downcase translated))
719 (< (downcase translated)
720 (+ ?a -10 (min 36 read-quoted-char-radix))))
721 (setq code (+ (* code read-quoted-char-radix)
722 (+ 10 (- (downcase translated) ?a))))
723 (and prompt (setq prompt (message "%s %c" prompt translated))))
724 ((and (not first) (eq translated ?\C-m))
725 (setq done t))
726 ((not first)
727 (setq unread-command-events
728 (nconc (listify-key-sequence (this-single-command-raw-keys))
729 unread-command-events)
730 done t))
731 (t (setq code translated
732 done t)))
733 (setq first nil))
734 code))
735
736 (defun quoted-insert (arg)
737 "Read next input character and insert it.
738 This is useful for inserting control characters.
739 With argument, insert ARG copies of the character.
740
741 If the first character you type after this command is an octal digit,
742 you should type a sequence of octal digits which specify a character code.
743 Any nondigit terminates the sequence. If the terminator is a RET,
744 it is discarded; any other terminator is used itself as input.
745 The variable `read-quoted-char-radix' specifies the radix for this feature;
746 set it to 10 or 16 to use decimal or hex instead of octal.
747
748 In overwrite mode, this function inserts the character anyway, and
749 does not handle octal digits specially. This means that if you use
750 overwrite as your normal editing mode, you can use this function to
751 insert characters when necessary.
752
753 In binary overwrite mode, this function does overwrite, and octal
754 digits are interpreted as a character code. This is intended to be
755 useful for editing binary files."
756 (interactive "*p")
757 (let* ((char
758 ;; Avoid "obsolete" warnings for translation-table-for-input.
759 (with-no-warnings
760 (let (translation-table-for-input input-method-function)
761 (if (or (not overwrite-mode)
762 (eq overwrite-mode 'overwrite-mode-binary))
763 (read-quoted-char)
764 (read-char))))))
765 ;; This used to assume character codes 0240 - 0377 stand for
766 ;; characters in some single-byte character set, and converted them
767 ;; to Emacs characters. But in 23.1 this feature is deprecated
768 ;; in favor of inserting the corresponding Unicode characters.
769 ;; (if (and enable-multibyte-characters
770 ;; (>= char ?\240)
771 ;; (<= char ?\377))
772 ;; (setq char (unibyte-char-to-multibyte char)))
773 (unless (characterp char)
774 (user-error "%s is not a valid character"
775 (key-description (vector char))))
776 (if (> arg 0)
777 (if (eq overwrite-mode 'overwrite-mode-binary)
778 (delete-char arg)))
779 (while (> arg 0)
780 (insert-and-inherit char)
781 (setq arg (1- arg)))))
782
783 (defun forward-to-indentation (&optional arg)
784 "Move forward ARG lines and position at first nonblank character."
785 (interactive "^p")
786 (forward-line (or arg 1))
787 (skip-chars-forward " \t"))
788
789 (defun backward-to-indentation (&optional arg)
790 "Move backward ARG lines and position at first nonblank character."
791 (interactive "^p")
792 (forward-line (- (or arg 1)))
793 (skip-chars-forward " \t"))
794
795 (defun back-to-indentation ()
796 "Move point to the first non-whitespace character on this line."
797 (interactive "^")
798 (beginning-of-line 1)
799 (skip-syntax-forward " " (line-end-position))
800 ;; Move back over chars that have whitespace syntax but have the p flag.
801 (backward-prefix-chars))
802
803 (defun fixup-whitespace ()
804 "Fixup white space between objects around point.
805 Leave one space or none, according to the context."
806 (interactive "*")
807 (save-excursion
808 (delete-horizontal-space)
809 (if (or (looking-at "^\\|\\s)")
810 (save-excursion (forward-char -1)
811 (looking-at "$\\|\\s(\\|\\s'")))
812 nil
813 (insert ?\s))))
814
815 (defun delete-horizontal-space (&optional backward-only)
816 "Delete all spaces and tabs around point.
817 If BACKWARD-ONLY is non-nil, only delete them before point."
818 (interactive "*P")
819 (let ((orig-pos (point)))
820 (delete-region
821 (if backward-only
822 orig-pos
823 (progn
824 (skip-chars-forward " \t")
825 (constrain-to-field nil orig-pos t)))
826 (progn
827 (skip-chars-backward " \t")
828 (constrain-to-field nil orig-pos)))))
829
830 (defun just-one-space (&optional n)
831 "Delete all spaces and tabs around point, leaving one space (or N spaces).
832 If N is negative, delete newlines as well, leaving -N spaces.
833 See also `cycle-spacing'."
834 (interactive "*p")
835 (cycle-spacing n nil 'single-shot))
836
837 (defvar cycle-spacing--context nil
838 "Store context used in consecutive calls to `cycle-spacing' command.
839 The first time `cycle-spacing' runs, it saves in this variable:
840 its N argument, the original point position, and the original spacing
841 around point.")
842
843 (defun cycle-spacing (&optional n preserve-nl-back mode)
844 "Manipulate whitespace around point in a smart way.
845 In interactive use, this function behaves differently in successive
846 consecutive calls.
847
848 The first call in a sequence acts like `just-one-space'.
849 It deletes all spaces and tabs around point, leaving one space
850 \(or N spaces). N is the prefix argument. If N is negative,
851 it deletes newlines as well, leaving -N spaces.
852 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
853
854 The second call in a sequence deletes all spaces.
855
856 The third call in a sequence restores the original whitespace (and point).
857
858 If MODE is `single-shot', it only performs the first step in the sequence.
859 If MODE is `fast' and the first step would not result in any change
860 \(i.e., there are exactly (abs N) spaces around point),
861 the function goes straight to the second step.
862
863 Repeatedly calling the function with different values of N starts a
864 new sequence each time."
865 (interactive "*p")
866 (let ((orig-pos (point))
867 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
868 (num (abs (or n 1))))
869 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
870 (constrain-to-field nil orig-pos)
871 (cond
872 ;; Command run for the first time, single-shot mode or different argument
873 ((or (eq 'single-shot mode)
874 (not (equal last-command this-command))
875 (not cycle-spacing--context)
876 (not (eq (car cycle-spacing--context) n)))
877 (let* ((start (point))
878 (num (- num (skip-chars-forward " " (+ num (point)))))
879 (mid (point))
880 (end (progn
881 (skip-chars-forward skip-characters)
882 (constrain-to-field nil orig-pos t))))
883 (setq cycle-spacing--context ;; Save for later.
884 ;; Special handling for case where there was no space at all.
885 (unless (= start end)
886 (cons n (cons orig-pos (buffer-substring start (point))))))
887 ;; If this run causes no change in buffer content, delete all spaces,
888 ;; otherwise delete all excess spaces.
889 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
890 start mid) end)
891 (insert (make-string num ?\s))))
892
893 ;; Command run for the second time.
894 ((not (equal orig-pos (point)))
895 (delete-region (point) orig-pos))
896
897 ;; Command run for the third time.
898 (t
899 (insert (cddr cycle-spacing--context))
900 (goto-char (cadr cycle-spacing--context))
901 (setq cycle-spacing--context nil)))))
902 \f
903 (defun beginning-of-buffer (&optional arg)
904 "Move point to the beginning of the buffer.
905 With numeric arg N, put point N/10 of the way from the beginning.
906 If the buffer is narrowed, this command uses the beginning of the
907 accessible part of the buffer.
908
909 If Transient Mark mode is disabled, leave mark at previous
910 position, unless a \\[universal-argument] prefix is supplied."
911 (declare (interactive-only "use `(goto-char (point-min))' instead."))
912 (interactive "^P")
913 (or (consp arg)
914 (region-active-p)
915 (push-mark))
916 (let ((size (- (point-max) (point-min))))
917 (goto-char (if (and arg (not (consp arg)))
918 (+ (point-min)
919 (if (> size 10000)
920 ;; Avoid overflow for large buffer sizes!
921 (* (prefix-numeric-value arg)
922 (/ size 10))
923 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
924 (point-min))))
925 (if (and arg (not (consp arg))) (forward-line 1)))
926
927 (defun end-of-buffer (&optional arg)
928 "Move point to the end of the buffer.
929 With numeric arg N, put point N/10 of the way from the end.
930 If the buffer is narrowed, this command uses the end of the
931 accessible part of the buffer.
932
933 If Transient Mark mode is disabled, leave mark at previous
934 position, unless a \\[universal-argument] prefix is supplied."
935 (declare (interactive-only "use `(goto-char (point-max))' instead."))
936 (interactive "^P")
937 (or (consp arg) (region-active-p) (push-mark))
938 (let ((size (- (point-max) (point-min))))
939 (goto-char (if (and arg (not (consp arg)))
940 (- (point-max)
941 (if (> size 10000)
942 ;; Avoid overflow for large buffer sizes!
943 (* (prefix-numeric-value arg)
944 (/ size 10))
945 (/ (* size (prefix-numeric-value arg)) 10)))
946 (point-max))))
947 ;; If we went to a place in the middle of the buffer,
948 ;; adjust it to the beginning of a line.
949 (cond ((and arg (not (consp arg))) (forward-line 1))
950 ((and (eq (current-buffer) (window-buffer))
951 (> (point) (window-end nil t)))
952 ;; If the end of the buffer is not already on the screen,
953 ;; then scroll specially to put it near, but not at, the bottom.
954 (overlay-recenter (point))
955 (recenter -3))))
956
957 (defcustom delete-active-region t
958 "Whether single-char deletion commands delete an active region.
959 This has an effect only if Transient Mark mode is enabled, and
960 affects `delete-forward-char' and `delete-backward-char', though
961 not `delete-char'.
962
963 If the value is the symbol `kill', the active region is killed
964 instead of deleted."
965 :type '(choice (const :tag "Delete active region" t)
966 (const :tag "Kill active region" kill)
967 (const :tag "Do ordinary deletion" nil))
968 :group 'killing
969 :version "24.1")
970
971 (defvar region-extract-function
972 (lambda (delete)
973 (when (region-beginning)
974 (if (eq delete 'delete-only)
975 (delete-region (region-beginning) (region-end))
976 (filter-buffer-substring (region-beginning) (region-end) delete))))
977 "Function to get the region's content.
978 Called with one argument DELETE.
979 If DELETE is `delete-only', then only delete the region and the return value
980 is undefined. If DELETE is nil, just return the content as a string.
981 If anything else, delete the region and return its content as a string.")
982
983 (defun delete-backward-char (n &optional killflag)
984 "Delete the previous N characters (following if N is negative).
985 If Transient Mark mode is enabled, the mark is active, and N is 1,
986 delete the text in the region and deactivate the mark instead.
987 To disable this, set option `delete-active-region' to nil.
988
989 Optional second arg KILLFLAG, if non-nil, means to kill (save in
990 kill ring) instead of delete. Interactively, N is the prefix
991 arg, and KILLFLAG is set if N is explicitly specified.
992
993 In Overwrite mode, single character backward deletion may replace
994 tabs with spaces so as to back over columns, unless point is at
995 the end of the line."
996 (declare (interactive-only delete-char))
997 (interactive "p\nP")
998 (unless (integerp n)
999 (signal 'wrong-type-argument (list 'integerp n)))
1000 (cond ((and (use-region-p)
1001 delete-active-region
1002 (= n 1))
1003 ;; If a region is active, kill or delete it.
1004 (if (eq delete-active-region 'kill)
1005 (kill-region (region-beginning) (region-end) 'region)
1006 (funcall region-extract-function 'delete-only)))
1007 ;; In Overwrite mode, maybe untabify while deleting
1008 ((null (or (null overwrite-mode)
1009 (<= n 0)
1010 (memq (char-before) '(?\t ?\n))
1011 (eobp)
1012 (eq (char-after) ?\n)))
1013 (let ((ocol (current-column)))
1014 (delete-char (- n) killflag)
1015 (save-excursion
1016 (insert-char ?\s (- ocol (current-column)) nil))))
1017 ;; Otherwise, do simple deletion.
1018 (t (delete-char (- n) killflag))))
1019
1020 (defun delete-forward-char (n &optional killflag)
1021 "Delete the following N characters (previous if N is negative).
1022 If Transient Mark mode is enabled, the mark is active, and N is 1,
1023 delete the text in the region and deactivate the mark instead.
1024 To disable this, set variable `delete-active-region' to nil.
1025
1026 Optional second arg KILLFLAG non-nil means to kill (save in kill
1027 ring) instead of delete. Interactively, N is the prefix arg, and
1028 KILLFLAG is set if N was explicitly specified."
1029 (declare (interactive-only delete-char))
1030 (interactive "p\nP")
1031 (unless (integerp n)
1032 (signal 'wrong-type-argument (list 'integerp n)))
1033 (cond ((and (use-region-p)
1034 delete-active-region
1035 (= n 1))
1036 ;; If a region is active, kill or delete it.
1037 (if (eq delete-active-region 'kill)
1038 (kill-region (region-beginning) (region-end) 'region)
1039 (funcall region-extract-function 'delete-only)))
1040
1041 ;; Otherwise, do simple deletion.
1042 (t (delete-char n killflag))))
1043
1044 (defun mark-whole-buffer ()
1045 "Put point at beginning and mark at end of buffer.
1046 If narrowing is in effect, only uses the accessible part of the buffer.
1047 You probably should not use this function in Lisp programs;
1048 it is usually a mistake for a Lisp function to use any subroutine
1049 that uses or sets the mark."
1050 (declare (interactive-only t))
1051 (interactive)
1052 (push-mark (point))
1053 (push-mark (point-max) nil t)
1054 (goto-char (point-min)))
1055 \f
1056
1057 ;; Counting lines, one way or another.
1058
1059 (defun goto-line (line &optional buffer)
1060 "Go to LINE, counting from line 1 at beginning of buffer.
1061 If called interactively, a numeric prefix argument specifies
1062 LINE; without a numeric prefix argument, read LINE from the
1063 minibuffer.
1064
1065 If optional argument BUFFER is non-nil, switch to that buffer and
1066 move to line LINE there. If called interactively with \\[universal-argument]
1067 as argument, BUFFER is the most recently selected other buffer.
1068
1069 Prior to moving point, this function sets the mark (without
1070 activating it), unless Transient Mark mode is enabled and the
1071 mark is already active.
1072
1073 This function is usually the wrong thing to use in a Lisp program.
1074 What you probably want instead is something like:
1075 (goto-char (point-min))
1076 (forward-line (1- N))
1077 If at all possible, an even better solution is to use char counts
1078 rather than line counts."
1079 (declare (interactive-only forward-line))
1080 (interactive
1081 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1082 (list (prefix-numeric-value current-prefix-arg))
1083 ;; Look for a default, a number in the buffer at point.
1084 (let* ((default
1085 (save-excursion
1086 (skip-chars-backward "0-9")
1087 (if (looking-at "[0-9]")
1088 (string-to-number
1089 (buffer-substring-no-properties
1090 (point)
1091 (progn (skip-chars-forward "0-9")
1092 (point)))))))
1093 ;; Decide if we're switching buffers.
1094 (buffer
1095 (if (consp current-prefix-arg)
1096 (other-buffer (current-buffer) t)))
1097 (buffer-prompt
1098 (if buffer
1099 (concat " in " (buffer-name buffer))
1100 "")))
1101 ;; Read the argument, offering that number (if any) as default.
1102 (list (read-number (format "Goto line%s: " buffer-prompt)
1103 (list default (line-number-at-pos)))
1104 buffer))))
1105 ;; Switch to the desired buffer, one way or another.
1106 (if buffer
1107 (let ((window (get-buffer-window buffer)))
1108 (if window (select-window window)
1109 (switch-to-buffer-other-window buffer))))
1110 ;; Leave mark at previous position
1111 (or (region-active-p) (push-mark))
1112 ;; Move to the specified line number in that buffer.
1113 (save-restriction
1114 (widen)
1115 (goto-char (point-min))
1116 (if (eq selective-display t)
1117 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1118 (forward-line (1- line)))))
1119
1120 (defun count-words-region (start end &optional arg)
1121 "Count the number of words in the region.
1122 If called interactively, print a message reporting the number of
1123 lines, words, and characters in the region (whether or not the
1124 region is active); with prefix ARG, report for the entire buffer
1125 rather than the region.
1126
1127 If called from Lisp, return the number of words between positions
1128 START and END."
1129 (interactive (if current-prefix-arg
1130 (list nil nil current-prefix-arg)
1131 (list (region-beginning) (region-end) nil)))
1132 (cond ((not (called-interactively-p 'any))
1133 (count-words start end))
1134 (arg
1135 (count-words--buffer-message))
1136 (t
1137 (count-words--message "Region" start end))))
1138
1139 (defun count-words (start end)
1140 "Count words between START and END.
1141 If called interactively, START and END are normally the start and
1142 end of the buffer; but if the region is active, START and END are
1143 the start and end of the region. Print a message reporting the
1144 number of lines, words, and chars.
1145
1146 If called from Lisp, return the number of words between START and
1147 END, without printing any message."
1148 (interactive (list nil nil))
1149 (cond ((not (called-interactively-p 'any))
1150 (let ((words 0))
1151 (save-excursion
1152 (save-restriction
1153 (narrow-to-region start end)
1154 (goto-char (point-min))
1155 (while (forward-word 1)
1156 (setq words (1+ words)))))
1157 words))
1158 ((use-region-p)
1159 (call-interactively 'count-words-region))
1160 (t
1161 (count-words--buffer-message))))
1162
1163 (defun count-words--buffer-message ()
1164 (count-words--message
1165 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1166 (point-min) (point-max)))
1167
1168 (defun count-words--message (str start end)
1169 (let ((lines (count-lines start end))
1170 (words (count-words start end))
1171 (chars (- end start)))
1172 (message "%s has %d line%s, %d word%s, and %d character%s."
1173 str
1174 lines (if (= lines 1) "" "s")
1175 words (if (= words 1) "" "s")
1176 chars (if (= chars 1) "" "s"))))
1177
1178 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1179
1180 (defun what-line ()
1181 "Print the current buffer line number and narrowed line number of point."
1182 (interactive)
1183 (let ((start (point-min))
1184 (n (line-number-at-pos)))
1185 (if (= start 1)
1186 (message "Line %d" n)
1187 (save-excursion
1188 (save-restriction
1189 (widen)
1190 (message "line %d (narrowed line %d)"
1191 (+ n (line-number-at-pos start) -1) n))))))
1192
1193 (defun count-lines (start end)
1194 "Return number of lines between START and END.
1195 This is usually the number of newlines between them,
1196 but can be one more if START is not equal to END
1197 and the greater of them is not at the start of a line."
1198 (save-excursion
1199 (save-restriction
1200 (narrow-to-region start end)
1201 (goto-char (point-min))
1202 (if (eq selective-display t)
1203 (save-match-data
1204 (let ((done 0))
1205 (while (re-search-forward "[\n\C-m]" nil t 40)
1206 (setq done (+ 40 done)))
1207 (while (re-search-forward "[\n\C-m]" nil t 1)
1208 (setq done (+ 1 done)))
1209 (goto-char (point-max))
1210 (if (and (/= start end)
1211 (not (bolp)))
1212 (1+ done)
1213 done)))
1214 (- (buffer-size) (forward-line (buffer-size)))))))
1215
1216 (defun line-number-at-pos (&optional pos)
1217 "Return (narrowed) buffer line number at position POS.
1218 If POS is nil, use current buffer location.
1219 Counting starts at (point-min), so the value refers
1220 to the contents of the accessible portion of the buffer."
1221 (let ((opoint (or pos (point))) start)
1222 (save-excursion
1223 (goto-char (point-min))
1224 (setq start (point))
1225 (goto-char opoint)
1226 (forward-line 0)
1227 (1+ (count-lines start (point))))))
1228
1229 (defun what-cursor-position (&optional detail)
1230 "Print info on cursor position (on screen and within buffer).
1231 Also describe the character after point, and give its character code
1232 in octal, decimal and hex.
1233
1234 For a non-ASCII multibyte character, also give its encoding in the
1235 buffer's selected coding system if the coding system encodes the
1236 character safely. If the character is encoded into one byte, that
1237 code is shown in hex. If the character is encoded into more than one
1238 byte, just \"...\" is shown.
1239
1240 In addition, with prefix argument, show details about that character
1241 in *Help* buffer. See also the command `describe-char'."
1242 (interactive "P")
1243 (let* ((char (following-char))
1244 (bidi-fixer
1245 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1246 ;; start a directional embedding, which could completely
1247 ;; disrupt the rest of the line (e.g., RLO will display the
1248 ;; rest of the line right-to-left). So we put an invisible
1249 ;; PDF character after these characters, to end the
1250 ;; embedding, which eliminates any effects on the rest of
1251 ;; the line. For RLE and RLO we also append an invisible
1252 ;; LRM, to avoid reordering the following numerical
1253 ;; characters. For LRI/RLI/FSI we append a PDI.
1254 (cond ((memq char '(?\x202a ?\x202d))
1255 (propertize (string ?\x202c) 'invisible t))
1256 ((memq char '(?\x202b ?\x202e))
1257 (propertize (string ?\x202c ?\x200e) 'invisible t))
1258 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1259 (propertize (string ?\x2069) 'invisible t))
1260 ;; Strong right-to-left characters cause reordering of
1261 ;; the following numerical characters which show the
1262 ;; codepoint, so append LRM to countermand that.
1263 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1264 (propertize (string ?\x200e) 'invisible t))
1265 (t
1266 "")))
1267 (beg (point-min))
1268 (end (point-max))
1269 (pos (point))
1270 (total (buffer-size))
1271 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1272 (hscroll (if (= (window-hscroll) 0)
1273 ""
1274 (format " Hscroll=%d" (window-hscroll))))
1275 (col (current-column)))
1276 (if (= pos end)
1277 (if (or (/= beg 1) (/= end (1+ total)))
1278 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1279 pos total percent beg end col hscroll)
1280 (message "point=%d of %d (EOB) column=%d%s"
1281 pos total col hscroll))
1282 (let ((coding buffer-file-coding-system)
1283 encoded encoding-msg display-prop under-display)
1284 (if (or (not coding)
1285 (eq (coding-system-type coding) t))
1286 (setq coding (default-value 'buffer-file-coding-system)))
1287 (if (eq (char-charset char) 'eight-bit)
1288 (setq encoding-msg
1289 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1290 ;; Check if the character is displayed with some `display'
1291 ;; text property. In that case, set under-display to the
1292 ;; buffer substring covered by that property.
1293 (setq display-prop (get-char-property pos 'display))
1294 (if display-prop
1295 (let ((to (or (next-single-char-property-change pos 'display)
1296 (point-max))))
1297 (if (< to (+ pos 4))
1298 (setq under-display "")
1299 (setq under-display "..."
1300 to (+ pos 4)))
1301 (setq under-display
1302 (concat (buffer-substring-no-properties pos to)
1303 under-display)))
1304 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1305 (setq encoding-msg
1306 (if display-prop
1307 (if (not (stringp display-prop))
1308 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1309 char char char under-display)
1310 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1311 char char char under-display display-prop))
1312 (if encoded
1313 (format "(%d, #o%o, #x%x, file %s)"
1314 char char char
1315 (if (> (length encoded) 1)
1316 "..."
1317 (encoded-string-description encoded coding)))
1318 (format "(%d, #o%o, #x%x)" char char char)))))
1319 (if detail
1320 ;; We show the detailed information about CHAR.
1321 (describe-char (point)))
1322 (if (or (/= beg 1) (/= end (1+ total)))
1323 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1324 (if (< char 256)
1325 (single-key-description char)
1326 (buffer-substring-no-properties (point) (1+ (point))))
1327 bidi-fixer
1328 encoding-msg pos total percent beg end col hscroll)
1329 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1330 (if enable-multibyte-characters
1331 (if (< char 128)
1332 (single-key-description char)
1333 (buffer-substring-no-properties (point) (1+ (point))))
1334 (single-key-description char))
1335 bidi-fixer encoding-msg pos total percent col hscroll))))))
1336 \f
1337 ;; Initialize read-expression-map. It is defined at C level.
1338 (defvar read-expression-map
1339 (let ((m (make-sparse-keymap)))
1340 (define-key m "\M-\t" 'completion-at-point)
1341 ;; Might as well bind TAB to completion, since inserting a TAB char is
1342 ;; much too rarely useful.
1343 (define-key m "\t" 'completion-at-point)
1344 (set-keymap-parent m minibuffer-local-map)
1345 m))
1346
1347 (defun read-minibuffer (prompt &optional initial-contents)
1348 "Return a Lisp object read using the minibuffer, unevaluated.
1349 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1350 is a string to insert in the minibuffer before reading.
1351 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1352 Such arguments are used as in `read-from-minibuffer'.)"
1353 ;; Used for interactive spec `x'.
1354 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1355 t 'minibuffer-history))
1356
1357 (defun eval-minibuffer (prompt &optional initial-contents)
1358 "Return value of Lisp expression read using the minibuffer.
1359 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1360 is a string to insert in the minibuffer before reading.
1361 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1362 Such arguments are used as in `read-from-minibuffer'.)"
1363 ;; Used for interactive spec `X'.
1364 (eval (read--expression prompt initial-contents)))
1365
1366 (defvar minibuffer-completing-symbol nil
1367 "Non-nil means completing a Lisp symbol in the minibuffer.")
1368 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1369
1370 (defvar minibuffer-default nil
1371 "The current default value or list of default values in the minibuffer.
1372 The functions `read-from-minibuffer' and `completing-read' bind
1373 this variable locally.")
1374
1375 (defcustom eval-expression-print-level 4
1376 "Value for `print-level' while printing value in `eval-expression'.
1377 A value of nil means no limit."
1378 :group 'lisp
1379 :type '(choice (const :tag "No Limit" nil) integer)
1380 :version "21.1")
1381
1382 (defcustom eval-expression-print-length 12
1383 "Value for `print-length' while printing value in `eval-expression'.
1384 A value of nil means no limit."
1385 :group 'lisp
1386 :type '(choice (const :tag "No Limit" nil) integer)
1387 :version "21.1")
1388
1389 (defcustom eval-expression-debug-on-error t
1390 "If non-nil set `debug-on-error' to t in `eval-expression'.
1391 If nil, don't change the value of `debug-on-error'."
1392 :group 'lisp
1393 :type 'boolean
1394 :version "21.1")
1395
1396 (defun eval-expression-print-format (value)
1397 "Format VALUE as a result of evaluated expression.
1398 Return a formatted string which is displayed in the echo area
1399 in addition to the value printed by prin1 in functions which
1400 display the result of expression evaluation."
1401 (if (and (integerp value)
1402 (or (eq standard-output t)
1403 (zerop (prefix-numeric-value current-prefix-arg))))
1404 (let ((char-string
1405 (if (and (characterp value)
1406 (char-displayable-p value))
1407 (prin1-char value))))
1408 (if char-string
1409 (format " (#o%o, #x%x, %s)" value value char-string)
1410 (format " (#o%o, #x%x)" value value)))))
1411
1412 (defvar eval-expression-minibuffer-setup-hook nil
1413 "Hook run by `eval-expression' when entering the minibuffer.")
1414
1415 (defun read--expression (prompt &optional initial-contents)
1416 (let ((minibuffer-completing-symbol t))
1417 (minibuffer-with-setup-hook
1418 (lambda ()
1419 ;; FIXME: call emacs-lisp-mode?
1420 (add-function :before-until (local 'eldoc-documentation-function)
1421 #'elisp-eldoc-documentation-function)
1422 (add-hook 'completion-at-point-functions
1423 #'elisp-completion-at-point nil t)
1424 (run-hooks 'eval-expression-minibuffer-setup-hook))
1425 (read-from-minibuffer prompt initial-contents
1426 read-expression-map t
1427 'read-expression-history))))
1428
1429 ;; We define this, rather than making `eval' interactive,
1430 ;; for the sake of completion of names like eval-region, eval-buffer.
1431 (defun eval-expression (exp &optional insert-value)
1432 "Evaluate EXP and print value in the echo area.
1433 When called interactively, read an Emacs Lisp expression and evaluate it.
1434 Value is also consed on to front of the variable `values'.
1435 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1436 argument) means insert the result into the current buffer instead of
1437 printing it in the echo area.
1438
1439 Normally, this function truncates long output according to the value
1440 of the variables `eval-expression-print-length' and
1441 `eval-expression-print-level'. With a prefix argument of zero,
1442 however, there is no such truncation. Such a prefix argument
1443 also causes integers to be printed in several additional formats
1444 \(octal, hexadecimal, and character).
1445
1446 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1447 minibuffer.
1448
1449 If `eval-expression-debug-on-error' is non-nil, which is the default,
1450 this command arranges for all errors to enter the debugger."
1451 (interactive
1452 (list (read--expression "Eval: ")
1453 current-prefix-arg))
1454
1455 (if (null eval-expression-debug-on-error)
1456 (push (eval exp lexical-binding) values)
1457 (let ((old-value (make-symbol "t")) new-value)
1458 ;; Bind debug-on-error to something unique so that we can
1459 ;; detect when evalled code changes it.
1460 (let ((debug-on-error old-value))
1461 (push (eval (macroexpand-all exp) lexical-binding) values)
1462 (setq new-value debug-on-error))
1463 ;; If evalled code has changed the value of debug-on-error,
1464 ;; propagate that change to the global binding.
1465 (unless (eq old-value new-value)
1466 (setq debug-on-error new-value))))
1467
1468 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1469 eval-expression-print-length))
1470 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1471 eval-expression-print-level))
1472 (deactivate-mark))
1473 (if insert-value
1474 (with-no-warnings
1475 (let ((standard-output (current-buffer)))
1476 (prog1
1477 (prin1 (car values))
1478 (when (zerop (prefix-numeric-value insert-value))
1479 (let ((str (eval-expression-print-format (car values))))
1480 (if str (princ str)))))))
1481 (prog1
1482 (prin1 (car values) t)
1483 (let ((str (eval-expression-print-format (car values))))
1484 (if str (princ str t)))))))
1485
1486 (defun edit-and-eval-command (prompt command)
1487 "Prompting with PROMPT, let user edit COMMAND and eval result.
1488 COMMAND is a Lisp expression. Let user edit that expression in
1489 the minibuffer, then read and evaluate the result."
1490 (let ((command
1491 (let ((print-level nil)
1492 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1493 (unwind-protect
1494 (read-from-minibuffer prompt
1495 (prin1-to-string command)
1496 read-expression-map t
1497 'command-history)
1498 ;; If command was added to command-history as a string,
1499 ;; get rid of that. We want only evaluable expressions there.
1500 (if (stringp (car command-history))
1501 (setq command-history (cdr command-history)))))))
1502
1503 ;; If command to be redone does not match front of history,
1504 ;; add it to the history.
1505 (or (equal command (car command-history))
1506 (setq command-history (cons command command-history)))
1507 (eval command)))
1508
1509 (defun repeat-complex-command (arg)
1510 "Edit and re-evaluate last complex command, or ARGth from last.
1511 A complex command is one which used the minibuffer.
1512 The command is placed in the minibuffer as a Lisp form for editing.
1513 The result is executed, repeating the command as changed.
1514 If the command has been changed or is not the most recent previous
1515 command it is added to the front of the command history.
1516 You can use the minibuffer history commands \
1517 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1518 to get different commands to edit and resubmit."
1519 (interactive "p")
1520 (let ((elt (nth (1- arg) command-history))
1521 newcmd)
1522 (if elt
1523 (progn
1524 (setq newcmd
1525 (let ((print-level nil)
1526 (minibuffer-history-position arg)
1527 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1528 (unwind-protect
1529 (read-from-minibuffer
1530 "Redo: " (prin1-to-string elt) read-expression-map t
1531 (cons 'command-history arg))
1532
1533 ;; If command was added to command-history as a
1534 ;; string, get rid of that. We want only
1535 ;; evaluable expressions there.
1536 (if (stringp (car command-history))
1537 (setq command-history (cdr command-history))))))
1538
1539 ;; If command to be redone does not match front of history,
1540 ;; add it to the history.
1541 (or (equal newcmd (car command-history))
1542 (setq command-history (cons newcmd command-history)))
1543 (apply #'funcall-interactively
1544 (car newcmd)
1545 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1546 (if command-history
1547 (error "Argument %d is beyond length of command history" arg)
1548 (error "There are no previous complex commands to repeat")))))
1549
1550
1551 (defvar extended-command-history nil)
1552 (defvar execute-extended-command--last-typed nil)
1553
1554 (defun read-extended-command ()
1555 "Read command name to invoke in `execute-extended-command'."
1556 (minibuffer-with-setup-hook
1557 (lambda ()
1558 (add-hook 'post-self-insert-hook
1559 (lambda ()
1560 (setq execute-extended-command--last-typed
1561 (minibuffer-contents)))
1562 nil 'local)
1563 (set (make-local-variable 'minibuffer-default-add-function)
1564 (lambda ()
1565 ;; Get a command name at point in the original buffer
1566 ;; to propose it after M-n.
1567 (with-current-buffer (window-buffer (minibuffer-selected-window))
1568 (and (commandp (function-called-at-point))
1569 (format "%S" (function-called-at-point)))))))
1570 ;; Read a string, completing from and restricting to the set of
1571 ;; all defined commands. Don't provide any initial input.
1572 ;; Save the command read on the extended-command history list.
1573 (completing-read
1574 (concat (cond
1575 ((eq current-prefix-arg '-) "- ")
1576 ((and (consp current-prefix-arg)
1577 (eq (car current-prefix-arg) 4)) "C-u ")
1578 ((and (consp current-prefix-arg)
1579 (integerp (car current-prefix-arg)))
1580 (format "%d " (car current-prefix-arg)))
1581 ((integerp current-prefix-arg)
1582 (format "%d " current-prefix-arg)))
1583 ;; This isn't strictly correct if `execute-extended-command'
1584 ;; is bound to anything else (e.g. [menu]).
1585 ;; It could use (key-description (this-single-command-keys)),
1586 ;; but actually a prompt other than "M-x" would be confusing,
1587 ;; because "M-x" is a well-known prompt to read a command
1588 ;; and it serves as a shorthand for "Extended command: ".
1589 "M-x ")
1590 (lambda (string pred action)
1591 (let ((pred
1592 (if (memq action '(nil t))
1593 ;; Exclude obsolete commands from completions.
1594 (lambda (sym)
1595 (and (funcall pred sym)
1596 (or (equal string (symbol-name sym))
1597 (not (get sym 'byte-obsolete-info)))))
1598 pred)))
1599 (complete-with-action action obarray string pred)))
1600 #'commandp t nil 'extended-command-history)))
1601
1602 (defcustom suggest-key-bindings t
1603 "Non-nil means show the equivalent key-binding when M-x command has one.
1604 The value can be a length of time to show the message for.
1605 If the value is non-nil and not a number, we wait 2 seconds."
1606 :group 'keyboard
1607 :type '(choice (const :tag "off" nil)
1608 (integer :tag "time" 2)
1609 (other :tag "on")))
1610
1611 (defun execute-extended-command--shorter-1 (name length)
1612 (cond
1613 ((zerop length) (list ""))
1614 ((equal name "") nil)
1615 (t
1616 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1617 (execute-extended-command--shorter-1
1618 (substring name 1) (1- length)))
1619 (when (string-match "\\`\\(-\\)?[^-]*" name)
1620 (execute-extended-command--shorter-1
1621 (substring name (match-end 0)) length))))))
1622
1623 (defun execute-extended-command--shorter (name typed)
1624 (let ((candidates '())
1625 (max (length typed))
1626 (len 1)
1627 binding)
1628 (while (and (not binding)
1629 (progn
1630 (unless candidates
1631 (setq len (1+ len))
1632 (setq candidates (execute-extended-command--shorter-1
1633 name len)))
1634 ;; Don't show the help message if the binding isn't
1635 ;; significantly shorter than the M-x command the user typed.
1636 (< len (- max 5))))
1637 (let ((candidate (pop candidates)))
1638 (when (equal name
1639 (car-safe (completion-try-completion
1640 candidate obarray 'commandp len)))
1641 (setq binding candidate))))
1642 binding))
1643
1644 (defun execute-extended-command (prefixarg &optional command-name typed)
1645 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1646 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1647 "Read a command name, then read the arguments and call the command.
1648 To pass a prefix argument to the command you are
1649 invoking, give a prefix argument to `execute-extended-command'."
1650 (declare (interactive-only command-execute))
1651 ;; FIXME: Remember the actual text typed by the user before completion,
1652 ;; so that we don't later on suggest the same shortening.
1653 (interactive
1654 (let ((execute-extended-command--last-typed nil))
1655 (list current-prefix-arg
1656 (read-extended-command)
1657 execute-extended-command--last-typed)))
1658 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1659 (unless command-name
1660 (let ((current-prefix-arg prefixarg) ; for prompt
1661 (execute-extended-command--last-typed nil))
1662 (setq command-name (read-extended-command))
1663 (setq typed execute-extended-command--last-typed)))
1664 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1665 (binding (and suggest-key-bindings
1666 (not executing-kbd-macro)
1667 (where-is-internal function overriding-local-map t))))
1668 (unless (commandp function)
1669 (error "`%s' is not a valid command name" command-name))
1670 (setq this-command function)
1671 ;; Normally `real-this-command' should never be changed, but here we really
1672 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1673 ;; binding" for <cmd>, so the command the user really wanted to run is
1674 ;; `function' and not `execute-extended-command'. The difference is
1675 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1676 (setq real-this-command function)
1677 (let ((prefix-arg prefixarg))
1678 (command-execute function 'record))
1679 ;; If enabled, show which key runs this command.
1680 ;; But first wait, and skip the message if there is input.
1681 (let* ((waited
1682 ;; If this command displayed something in the echo area;
1683 ;; wait a few seconds, then display our suggestion message.
1684 ;; FIXME: Wait *after* running post-command-hook!
1685 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1686 ;; find a better answer anyway!
1687 (when suggest-key-bindings
1688 (sit-for (cond
1689 ((zerop (length (current-message))) 0)
1690 ((numberp suggest-key-bindings) suggest-key-bindings)
1691 (t 2))))))
1692 (when (and waited (not (consp unread-command-events)))
1693 (unless (or binding executing-kbd-macro (not (symbolp function))
1694 (<= (length (symbol-name function)) 2))
1695 ;; There's no binding for CMD. Let's try and find the shortest
1696 ;; string to use in M-x.
1697 ;; FIXME: Can be slow. Cache it maybe?
1698 (while-no-input
1699 (setq binding (execute-extended-command--shorter
1700 (symbol-name function) typed))))
1701 (when binding
1702 (with-temp-message
1703 (format-message "You can run the command `%s' with %s"
1704 function
1705 (if (stringp binding)
1706 (concat "M-x " binding " RET")
1707 (key-description binding)))
1708 (sit-for (if (numberp suggest-key-bindings)
1709 suggest-key-bindings
1710 2))))))))
1711
1712 (defun command-execute (cmd &optional record-flag keys special)
1713 ;; BEWARE: Called directly from the C code.
1714 "Execute CMD as an editor command.
1715 CMD must be a symbol that satisfies the `commandp' predicate.
1716 Optional second arg RECORD-FLAG non-nil
1717 means unconditionally put this command in the variable `command-history'.
1718 Otherwise, that is done only if an arg is read using the minibuffer.
1719 The argument KEYS specifies the value to use instead of (this-command-keys)
1720 when reading the arguments; if it is nil, (this-command-keys) is used.
1721 The argument SPECIAL, if non-nil, means that this command is executing
1722 a special event, so ignore the prefix argument and don't clear it."
1723 (setq debug-on-next-call nil)
1724 (let ((prefixarg (unless special
1725 ;; FIXME: This should probably be done around
1726 ;; pre-command-hook rather than here!
1727 (prog1 prefix-arg
1728 (setq current-prefix-arg prefix-arg)
1729 (setq prefix-arg nil)
1730 (when current-prefix-arg
1731 (prefix-command-update))))))
1732 (if (and (symbolp cmd)
1733 (get cmd 'disabled)
1734 disabled-command-function)
1735 ;; FIXME: Weird calling convention!
1736 (run-hooks 'disabled-command-function)
1737 (let ((final cmd))
1738 (while
1739 (progn
1740 (setq final (indirect-function final))
1741 (if (autoloadp final)
1742 (setq final (autoload-do-load final cmd)))))
1743 (cond
1744 ((arrayp final)
1745 ;; If requested, place the macro in the command history. For
1746 ;; other sorts of commands, call-interactively takes care of this.
1747 (when record-flag
1748 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1749 ;; Don't keep command history around forever.
1750 (when (and (numberp history-length) (> history-length 0))
1751 (let ((cell (nthcdr history-length command-history)))
1752 (if (consp cell) (setcdr cell nil)))))
1753 (execute-kbd-macro final prefixarg))
1754 (t
1755 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1756 (prog1 (call-interactively cmd record-flag keys)
1757 (when (and (symbolp cmd)
1758 (get cmd 'byte-obsolete-info)
1759 (not (get cmd 'command-execute-obsolete-warned)))
1760 (put cmd 'command-execute-obsolete-warned t)
1761 (message "%s" (macroexp--obsolete-warning
1762 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1763 \f
1764 (defvar minibuffer-history nil
1765 "Default minibuffer history list.
1766 This is used for all minibuffer input
1767 except when an alternate history list is specified.
1768
1769 Maximum length of the history list is determined by the value
1770 of `history-length', which see.")
1771 (defvar minibuffer-history-sexp-flag nil
1772 "Control whether history list elements are expressions or strings.
1773 If the value of this variable equals current minibuffer depth,
1774 they are expressions; otherwise they are strings.
1775 \(That convention is designed to do the right thing for
1776 recursive uses of the minibuffer.)")
1777 (setq minibuffer-history-variable 'minibuffer-history)
1778 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1779 (defvar minibuffer-history-search-history nil)
1780
1781 (defvar minibuffer-text-before-history nil
1782 "Text that was in this minibuffer before any history commands.
1783 This is nil if there have not yet been any history commands
1784 in this use of the minibuffer.")
1785
1786 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1787
1788 (defun minibuffer-history-initialize ()
1789 (setq minibuffer-text-before-history nil))
1790
1791 (defun minibuffer-avoid-prompt (_new _old)
1792 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1793 (declare (obsolete cursor-intangible-mode "25.1"))
1794 (constrain-to-field nil (point-max)))
1795
1796 (defcustom minibuffer-history-case-insensitive-variables nil
1797 "Minibuffer history variables for which matching should ignore case.
1798 If a history variable is a member of this list, then the
1799 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1800 commands ignore case when searching it, regardless of `case-fold-search'."
1801 :type '(repeat variable)
1802 :group 'minibuffer)
1803
1804 (defun previous-matching-history-element (regexp n)
1805 "Find the previous history element that matches REGEXP.
1806 \(Previous history elements refer to earlier actions.)
1807 With prefix argument N, search for Nth previous match.
1808 If N is negative, find the next or Nth next match.
1809 Normally, history elements are matched case-insensitively if
1810 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1811 makes the search case-sensitive.
1812 See also `minibuffer-history-case-insensitive-variables'."
1813 (interactive
1814 (let* ((enable-recursive-minibuffers t)
1815 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1816 nil
1817 minibuffer-local-map
1818 nil
1819 'minibuffer-history-search-history
1820 (car minibuffer-history-search-history))))
1821 ;; Use the last regexp specified, by default, if input is empty.
1822 (list (if (string= regexp "")
1823 (if minibuffer-history-search-history
1824 (car minibuffer-history-search-history)
1825 (user-error "No previous history search regexp"))
1826 regexp)
1827 (prefix-numeric-value current-prefix-arg))))
1828 (unless (zerop n)
1829 (if (and (zerop minibuffer-history-position)
1830 (null minibuffer-text-before-history))
1831 (setq minibuffer-text-before-history
1832 (minibuffer-contents-no-properties)))
1833 (let ((history (symbol-value minibuffer-history-variable))
1834 (case-fold-search
1835 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1836 ;; On some systems, ignore case for file names.
1837 (if (memq minibuffer-history-variable
1838 minibuffer-history-case-insensitive-variables)
1839 t
1840 ;; Respect the user's setting for case-fold-search:
1841 case-fold-search)
1842 nil))
1843 prevpos
1844 match-string
1845 match-offset
1846 (pos minibuffer-history-position))
1847 (while (/= n 0)
1848 (setq prevpos pos)
1849 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1850 (when (= pos prevpos)
1851 (user-error (if (= pos 1)
1852 "No later matching history item"
1853 "No earlier matching history item")))
1854 (setq match-string
1855 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1856 (let ((print-level nil))
1857 (prin1-to-string (nth (1- pos) history)))
1858 (nth (1- pos) history)))
1859 (setq match-offset
1860 (if (< n 0)
1861 (and (string-match regexp match-string)
1862 (match-end 0))
1863 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1864 (match-beginning 1))))
1865 (when match-offset
1866 (setq n (+ n (if (< n 0) 1 -1)))))
1867 (setq minibuffer-history-position pos)
1868 (goto-char (point-max))
1869 (delete-minibuffer-contents)
1870 (insert match-string)
1871 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1872 (if (memq (car (car command-history)) '(previous-matching-history-element
1873 next-matching-history-element))
1874 (setq command-history (cdr command-history))))
1875
1876 (defun next-matching-history-element (regexp n)
1877 "Find the next history element that matches REGEXP.
1878 \(The next history element refers to a more recent action.)
1879 With prefix argument N, search for Nth next match.
1880 If N is negative, find the previous or Nth previous match.
1881 Normally, history elements are matched case-insensitively if
1882 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1883 makes the search case-sensitive."
1884 (interactive
1885 (let* ((enable-recursive-minibuffers t)
1886 (regexp (read-from-minibuffer "Next element matching (regexp): "
1887 nil
1888 minibuffer-local-map
1889 nil
1890 'minibuffer-history-search-history
1891 (car minibuffer-history-search-history))))
1892 ;; Use the last regexp specified, by default, if input is empty.
1893 (list (if (string= regexp "")
1894 (if minibuffer-history-search-history
1895 (car minibuffer-history-search-history)
1896 (user-error "No previous history search regexp"))
1897 regexp)
1898 (prefix-numeric-value current-prefix-arg))))
1899 (previous-matching-history-element regexp (- n)))
1900
1901 (defvar minibuffer-temporary-goal-position nil)
1902
1903 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1904 "Function run by `goto-history-element' before consuming default values.
1905 This is useful to dynamically add more elements to the list of default values
1906 when `goto-history-element' reaches the end of this list.
1907 Before calling this function `goto-history-element' sets the variable
1908 `minibuffer-default-add-done' to t, so it will call this function only
1909 once. In special cases, when this function needs to be called more
1910 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1911 overriding the setting of this variable to t in `goto-history-element'.")
1912
1913 (defvar minibuffer-default-add-done nil
1914 "When nil, add more elements to the end of the list of default values.
1915 The value nil causes `goto-history-element' to add more elements to
1916 the list of defaults when it reaches the end of this list. It does
1917 this by calling a function defined by `minibuffer-default-add-function'.")
1918
1919 (make-variable-buffer-local 'minibuffer-default-add-done)
1920
1921 (defun minibuffer-default-add-completions ()
1922 "Return a list of all completions without the default value.
1923 This function is used to add all elements of the completion table to
1924 the end of the list of defaults just after the default value."
1925 (let ((def minibuffer-default)
1926 (all (all-completions ""
1927 minibuffer-completion-table
1928 minibuffer-completion-predicate)))
1929 (if (listp def)
1930 (append def all)
1931 (cons def (delete def all)))))
1932
1933 (defun goto-history-element (nabs)
1934 "Puts element of the minibuffer history in the minibuffer.
1935 The argument NABS specifies the absolute history position."
1936 (interactive "p")
1937 (when (and (not minibuffer-default-add-done)
1938 (functionp minibuffer-default-add-function)
1939 (< nabs (- (if (listp minibuffer-default)
1940 (length minibuffer-default)
1941 1))))
1942 (setq minibuffer-default-add-done t
1943 minibuffer-default (funcall minibuffer-default-add-function)))
1944 (let ((minimum (if minibuffer-default
1945 (- (if (listp minibuffer-default)
1946 (length minibuffer-default)
1947 1))
1948 0))
1949 elt minibuffer-returned-to-present)
1950 (if (and (zerop minibuffer-history-position)
1951 (null minibuffer-text-before-history))
1952 (setq minibuffer-text-before-history
1953 (minibuffer-contents-no-properties)))
1954 (if (< nabs minimum)
1955 (user-error (if minibuffer-default
1956 "End of defaults; no next item"
1957 "End of history; no default available")))
1958 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
1959 (length (symbol-value minibuffer-history-variable))
1960 0))
1961 (user-error "Beginning of history; no preceding item"))
1962 (unless (memq last-command '(next-history-element
1963 previous-history-element))
1964 (let ((prompt-end (minibuffer-prompt-end)))
1965 (set (make-local-variable 'minibuffer-temporary-goal-position)
1966 (cond ((<= (point) prompt-end) prompt-end)
1967 ((eobp) nil)
1968 (t (point))))))
1969 (goto-char (point-max))
1970 (delete-minibuffer-contents)
1971 (setq minibuffer-history-position nabs)
1972 (cond ((< nabs 0)
1973 (setq elt (if (listp minibuffer-default)
1974 (nth (1- (abs nabs)) minibuffer-default)
1975 minibuffer-default)))
1976 ((= nabs 0)
1977 (setq elt (or minibuffer-text-before-history ""))
1978 (setq minibuffer-returned-to-present t)
1979 (setq minibuffer-text-before-history nil))
1980 (t (setq elt (nth (1- minibuffer-history-position)
1981 (symbol-value minibuffer-history-variable)))))
1982 (insert
1983 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1984 (not minibuffer-returned-to-present))
1985 (let ((print-level nil))
1986 (prin1-to-string elt))
1987 elt))
1988 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1989
1990 (defun next-history-element (n)
1991 "Puts next element of the minibuffer history in the minibuffer.
1992 With argument N, it uses the Nth following element."
1993 (interactive "p")
1994 (or (zerop n)
1995 (goto-history-element (- minibuffer-history-position n))))
1996
1997 (defun previous-history-element (n)
1998 "Puts previous element of the minibuffer history in the minibuffer.
1999 With argument N, it uses the Nth previous element."
2000 (interactive "p")
2001 (or (zerop n)
2002 (goto-history-element (+ minibuffer-history-position n))))
2003
2004 (defun next-line-or-history-element (&optional arg)
2005 "Move cursor vertically down ARG lines, or to the next history element.
2006 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2007 next element of the minibuffer history in the minibuffer."
2008 (interactive "^p")
2009 (or arg (setq arg 1))
2010 (let* ((old-point (point))
2011 ;; Remember the original goal column of possibly multi-line input
2012 ;; excluding the length of the prompt on the first line.
2013 (prompt-end (minibuffer-prompt-end))
2014 (old-column (unless (and (eolp) (> (point) prompt-end))
2015 (if (= (line-number-at-pos) 1)
2016 (max (- (current-column) (1- prompt-end)) 0)
2017 (current-column)))))
2018 (condition-case nil
2019 (with-no-warnings
2020 (next-line arg))
2021 (end-of-buffer
2022 ;; Restore old position since `line-move-visual' moves point to
2023 ;; the end of the line when it fails to go to the next line.
2024 (goto-char old-point)
2025 (next-history-element arg)
2026 ;; Restore the original goal column on the last line
2027 ;; of possibly multi-line input.
2028 (goto-char (point-max))
2029 (when old-column
2030 (if (= (line-number-at-pos) 1)
2031 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2032 (move-to-column old-column)))))))
2033
2034 (defun previous-line-or-history-element (&optional arg)
2035 "Move cursor vertically up ARG lines, or to the previous history element.
2036 When point moves over the top line of multi-line minibuffer, puts ARGth
2037 previous element of the minibuffer history in the minibuffer."
2038 (interactive "^p")
2039 (or arg (setq arg 1))
2040 (let* ((old-point (point))
2041 ;; Remember the original goal column of possibly multi-line input
2042 ;; excluding the length of the prompt on the first line.
2043 (prompt-end (minibuffer-prompt-end))
2044 (old-column (unless (and (eolp) (> (point) prompt-end))
2045 (if (= (line-number-at-pos) 1)
2046 (max (- (current-column) (1- prompt-end)) 0)
2047 (current-column)))))
2048 (condition-case nil
2049 (with-no-warnings
2050 (previous-line arg))
2051 (beginning-of-buffer
2052 ;; Restore old position since `line-move-visual' moves point to
2053 ;; the beginning of the line when it fails to go to the previous line.
2054 (goto-char old-point)
2055 (previous-history-element arg)
2056 ;; Restore the original goal column on the first line
2057 ;; of possibly multi-line input.
2058 (goto-char (minibuffer-prompt-end))
2059 (if old-column
2060 (if (= (line-number-at-pos) 1)
2061 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2062 (move-to-column old-column))
2063 (goto-char (line-end-position)))))))
2064
2065 (defun next-complete-history-element (n)
2066 "Get next history element which completes the minibuffer before the point.
2067 The contents of the minibuffer after the point are deleted, and replaced
2068 by the new completion."
2069 (interactive "p")
2070 (let ((point-at-start (point)))
2071 (next-matching-history-element
2072 (concat
2073 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2074 n)
2075 ;; next-matching-history-element always puts us at (point-min).
2076 ;; Move to the position we were at before changing the buffer contents.
2077 ;; This is still sensible, because the text before point has not changed.
2078 (goto-char point-at-start)))
2079
2080 (defun previous-complete-history-element (n)
2081 "\
2082 Get previous history element which completes the minibuffer before the point.
2083 The contents of the minibuffer after the point are deleted, and replaced
2084 by the new completion."
2085 (interactive "p")
2086 (next-complete-history-element (- n)))
2087
2088 ;; For compatibility with the old subr of the same name.
2089 (defun minibuffer-prompt-width ()
2090 "Return the display width of the minibuffer prompt.
2091 Return 0 if current buffer is not a minibuffer."
2092 ;; Return the width of everything before the field at the end of
2093 ;; the buffer; this should be 0 for normal buffers.
2094 (1- (minibuffer-prompt-end)))
2095 \f
2096 ;; isearch minibuffer history
2097 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2098
2099 (defvar minibuffer-history-isearch-message-overlay)
2100 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2101
2102 (defun minibuffer-history-isearch-setup ()
2103 "Set up a minibuffer for using isearch to search the minibuffer history.
2104 Intended to be added to `minibuffer-setup-hook'."
2105 (set (make-local-variable 'isearch-search-fun-function)
2106 'minibuffer-history-isearch-search)
2107 (set (make-local-variable 'isearch-message-function)
2108 'minibuffer-history-isearch-message)
2109 (set (make-local-variable 'isearch-wrap-function)
2110 'minibuffer-history-isearch-wrap)
2111 (set (make-local-variable 'isearch-push-state-function)
2112 'minibuffer-history-isearch-push-state)
2113 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2114
2115 (defun minibuffer-history-isearch-end ()
2116 "Clean up the minibuffer after terminating isearch in the minibuffer."
2117 (if minibuffer-history-isearch-message-overlay
2118 (delete-overlay minibuffer-history-isearch-message-overlay)))
2119
2120 (defun minibuffer-history-isearch-search ()
2121 "Return the proper search function, for isearch in minibuffer history."
2122 (lambda (string bound noerror)
2123 (let ((search-fun
2124 ;; Use standard functions to search within minibuffer text
2125 (isearch-search-fun-default))
2126 found)
2127 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2128 ;; searching forward. Lazy-highlight calls this lambda with the
2129 ;; bound arg, so skip the minibuffer prompt.
2130 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2131 (goto-char (minibuffer-prompt-end)))
2132 (or
2133 ;; 1. First try searching in the initial minibuffer text
2134 (funcall search-fun string
2135 (if isearch-forward bound (minibuffer-prompt-end))
2136 noerror)
2137 ;; 2. If the above search fails, start putting next/prev history
2138 ;; elements in the minibuffer successively, and search the string
2139 ;; in them. Do this only when bound is nil (i.e. not while
2140 ;; lazy-highlighting search strings in the current minibuffer text).
2141 (unless bound
2142 (condition-case nil
2143 (progn
2144 (while (not found)
2145 (cond (isearch-forward
2146 (next-history-element 1)
2147 (goto-char (minibuffer-prompt-end)))
2148 (t
2149 (previous-history-element 1)
2150 (goto-char (point-max))))
2151 (setq isearch-barrier (point) isearch-opoint (point))
2152 ;; After putting the next/prev history element, search
2153 ;; the string in them again, until next-history-element
2154 ;; or previous-history-element raises an error at the
2155 ;; beginning/end of history.
2156 (setq found (funcall search-fun string
2157 (unless isearch-forward
2158 ;; For backward search, don't search
2159 ;; in the minibuffer prompt
2160 (minibuffer-prompt-end))
2161 noerror)))
2162 ;; Return point of the new search result
2163 (point))
2164 ;; Return nil when next(prev)-history-element fails
2165 (error nil)))))))
2166
2167 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2168 "Display the minibuffer history search prompt.
2169 If there are no search errors, this function displays an overlay with
2170 the isearch prompt which replaces the original minibuffer prompt.
2171 Otherwise, it displays the standard isearch message returned from
2172 the function `isearch-message'."
2173 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2174 ;; Use standard function `isearch-message' when not in the minibuffer,
2175 ;; or search fails, or has an error (like incomplete regexp).
2176 ;; This function overwrites minibuffer text with isearch message,
2177 ;; so it's possible to see what is wrong in the search string.
2178 (isearch-message c-q-hack ellipsis)
2179 ;; Otherwise, put the overlay with the standard isearch prompt over
2180 ;; the initial minibuffer prompt.
2181 (if (overlayp minibuffer-history-isearch-message-overlay)
2182 (move-overlay minibuffer-history-isearch-message-overlay
2183 (point-min) (minibuffer-prompt-end))
2184 (setq minibuffer-history-isearch-message-overlay
2185 (make-overlay (point-min) (minibuffer-prompt-end)))
2186 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2187 (overlay-put minibuffer-history-isearch-message-overlay
2188 'display (isearch-message-prefix c-q-hack ellipsis))
2189 ;; And clear any previous isearch message.
2190 (message "")))
2191
2192 (defun minibuffer-history-isearch-wrap ()
2193 "Wrap the minibuffer history search when search fails.
2194 Move point to the first history element for a forward search,
2195 or to the last history element for a backward search."
2196 ;; When `minibuffer-history-isearch-search' fails on reaching the
2197 ;; beginning/end of the history, wrap the search to the first/last
2198 ;; minibuffer history element.
2199 (if isearch-forward
2200 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2201 (goto-history-element 0))
2202 (setq isearch-success t)
2203 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2204
2205 (defun minibuffer-history-isearch-push-state ()
2206 "Save a function restoring the state of minibuffer history search.
2207 Save `minibuffer-history-position' to the additional state parameter
2208 in the search status stack."
2209 (let ((pos minibuffer-history-position))
2210 (lambda (cmd)
2211 (minibuffer-history-isearch-pop-state cmd pos))))
2212
2213 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2214 "Restore the minibuffer history search state.
2215 Go to the history element by the absolute history position HIST-POS."
2216 (goto-history-element hist-pos))
2217
2218 \f
2219 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2220 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2221
2222 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2223 "Table mapping redo records to the corresponding undo one.
2224 A redo record for undo-in-region maps to t.
2225 A redo record for ordinary undo maps to the following (earlier) undo.")
2226
2227 (defvar undo-in-region nil
2228 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2229
2230 (defvar undo-no-redo nil
2231 "If t, `undo' doesn't go through redo entries.")
2232
2233 (defvar pending-undo-list nil
2234 "Within a run of consecutive undo commands, list remaining to be undone.
2235 If t, we undid all the way to the end of it.")
2236
2237 (defun undo (&optional arg)
2238 "Undo some previous changes.
2239 Repeat this command to undo more changes.
2240 A numeric ARG serves as a repeat count.
2241
2242 In Transient Mark mode when the mark is active, only undo changes within
2243 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2244 as an argument limits undo to changes within the current region."
2245 (interactive "*P")
2246 ;; Make last-command indicate for the next command that this was an undo.
2247 ;; That way, another undo will undo more.
2248 ;; If we get to the end of the undo history and get an error,
2249 ;; another undo command will find the undo history empty
2250 ;; and will get another error. To begin undoing the undos,
2251 ;; you must type some other command.
2252 (let* ((modified (buffer-modified-p))
2253 ;; For an indirect buffer, look in the base buffer for the
2254 ;; auto-save data.
2255 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2256 (recent-save (with-current-buffer base-buffer
2257 (recent-auto-save-p)))
2258 message)
2259 ;; If we get an error in undo-start,
2260 ;; the next command should not be a "consecutive undo".
2261 ;; So set `this-command' to something other than `undo'.
2262 (setq this-command 'undo-start)
2263
2264 (unless (and (eq last-command 'undo)
2265 (or (eq pending-undo-list t)
2266 ;; If something (a timer or filter?) changed the buffer
2267 ;; since the previous command, don't continue the undo seq.
2268 (let ((list buffer-undo-list))
2269 (while (eq (car list) nil)
2270 (setq list (cdr list)))
2271 ;; If the last undo record made was made by undo
2272 ;; it shows nothing else happened in between.
2273 (gethash list undo-equiv-table))))
2274 (setq undo-in-region
2275 (or (region-active-p) (and arg (not (numberp arg)))))
2276 (if undo-in-region
2277 (undo-start (region-beginning) (region-end))
2278 (undo-start))
2279 ;; get rid of initial undo boundary
2280 (undo-more 1))
2281 ;; If we got this far, the next command should be a consecutive undo.
2282 (setq this-command 'undo)
2283 ;; Check to see whether we're hitting a redo record, and if
2284 ;; so, ask the user whether she wants to skip the redo/undo pair.
2285 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2286 (or (eq (selected-window) (minibuffer-window))
2287 (setq message (format "%s%s!"
2288 (if (or undo-no-redo (not equiv))
2289 "Undo" "Redo")
2290 (if undo-in-region " in region" ""))))
2291 (when (and (consp equiv) undo-no-redo)
2292 ;; The equiv entry might point to another redo record if we have done
2293 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2294 (while (let ((next (gethash equiv undo-equiv-table)))
2295 (if next (setq equiv next))))
2296 (setq pending-undo-list equiv)))
2297 (undo-more
2298 (if (numberp arg)
2299 (prefix-numeric-value arg)
2300 1))
2301 ;; Record the fact that the just-generated undo records come from an
2302 ;; undo operation--that is, they are redo records.
2303 ;; In the ordinary case (not within a region), map the redo
2304 ;; record to the following undos.
2305 ;; I don't know how to do that in the undo-in-region case.
2306 (let ((list buffer-undo-list))
2307 ;; Strip any leading undo boundaries there might be, like we do
2308 ;; above when checking.
2309 (while (eq (car list) nil)
2310 (setq list (cdr list)))
2311 (puthash list
2312 ;; Prevent identity mapping. This can happen if
2313 ;; consecutive nils are erroneously in undo list.
2314 (if (or undo-in-region (eq list pending-undo-list))
2315 t
2316 pending-undo-list)
2317 undo-equiv-table))
2318 ;; Don't specify a position in the undo record for the undo command.
2319 ;; Instead, undoing this should move point to where the change is.
2320 (let ((tail buffer-undo-list)
2321 (prev nil))
2322 (while (car tail)
2323 (when (integerp (car tail))
2324 (let ((pos (car tail)))
2325 (if prev
2326 (setcdr prev (cdr tail))
2327 (setq buffer-undo-list (cdr tail)))
2328 (setq tail (cdr tail))
2329 (while (car tail)
2330 (if (eq pos (car tail))
2331 (if prev
2332 (setcdr prev (cdr tail))
2333 (setq buffer-undo-list (cdr tail)))
2334 (setq prev tail))
2335 (setq tail (cdr tail)))
2336 (setq tail nil)))
2337 (setq prev tail tail (cdr tail))))
2338 ;; Record what the current undo list says,
2339 ;; so the next command can tell if the buffer was modified in between.
2340 (and modified (not (buffer-modified-p))
2341 (with-current-buffer base-buffer
2342 (delete-auto-save-file-if-necessary recent-save)))
2343 ;; Display a message announcing success.
2344 (if message
2345 (message "%s" message))))
2346
2347 (defun buffer-disable-undo (&optional buffer)
2348 "Make BUFFER stop keeping undo information.
2349 No argument or nil as argument means do this for the current buffer."
2350 (interactive)
2351 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2352 (setq buffer-undo-list t)))
2353
2354 (defun undo-only (&optional arg)
2355 "Undo some previous changes.
2356 Repeat this command to undo more changes.
2357 A numeric ARG serves as a repeat count.
2358 Contrary to `undo', this will not redo a previous undo."
2359 (interactive "*p")
2360 (let ((undo-no-redo t)) (undo arg)))
2361
2362 (defvar undo-in-progress nil
2363 "Non-nil while performing an undo.
2364 Some change-hooks test this variable to do something different.")
2365
2366 (defun undo-more (n)
2367 "Undo back N undo-boundaries beyond what was already undone recently.
2368 Call `undo-start' to get ready to undo recent changes,
2369 then call `undo-more' one or more times to undo them."
2370 (or (listp pending-undo-list)
2371 (user-error (concat "No further undo information"
2372 (and undo-in-region " for region"))))
2373 (let ((undo-in-progress t))
2374 ;; Note: The following, while pulling elements off
2375 ;; `pending-undo-list' will call primitive change functions which
2376 ;; will push more elements onto `buffer-undo-list'.
2377 (setq pending-undo-list (primitive-undo n pending-undo-list))
2378 (if (null pending-undo-list)
2379 (setq pending-undo-list t))))
2380
2381 (defun primitive-undo (n list)
2382 "Undo N records from the front of the list LIST.
2383 Return what remains of the list."
2384
2385 ;; This is a good feature, but would make undo-start
2386 ;; unable to do what is expected.
2387 ;;(when (null (car (list)))
2388 ;; ;; If the head of the list is a boundary, it is the boundary
2389 ;; ;; preceding this command. Get rid of it and don't count it.
2390 ;; (setq list (cdr list))))
2391
2392 (let ((arg n)
2393 ;; In a writable buffer, enable undoing read-only text that is
2394 ;; so because of text properties.
2395 (inhibit-read-only t)
2396 ;; Don't let `intangible' properties interfere with undo.
2397 (inhibit-point-motion-hooks t)
2398 ;; We use oldlist only to check for EQ. ++kfs
2399 (oldlist buffer-undo-list)
2400 (did-apply nil)
2401 (next nil))
2402 (while (> arg 0)
2403 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2404 ;; Handle an integer by setting point to that value.
2405 (pcase next
2406 ((pred integerp) (goto-char next))
2407 ;; Element (t . TIME) records previous modtime.
2408 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2409 ;; UNKNOWN_MODTIME_NSECS.
2410 (`(t . ,time)
2411 ;; If this records an obsolete save
2412 ;; (not matching the actual disk file)
2413 ;; then don't mark unmodified.
2414 (when (or (equal time (visited-file-modtime))
2415 (and (consp time)
2416 (equal (list (car time) (cdr time))
2417 (visited-file-modtime))))
2418 (when (fboundp 'unlock-buffer)
2419 (unlock-buffer))
2420 (set-buffer-modified-p nil)))
2421 ;; Element (nil PROP VAL BEG . END) is property change.
2422 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2423 (when (or (> (point-min) beg) (< (point-max) end))
2424 (error "Changes to be undone are outside visible portion of buffer"))
2425 (put-text-property beg end prop val))
2426 ;; Element (BEG . END) means range was inserted.
2427 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2428 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2429 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2430 (when (or (> (point-min) beg) (< (point-max) end))
2431 (error "Changes to be undone are outside visible portion of buffer"))
2432 ;; Set point first thing, so that undoing this undo
2433 ;; does not send point back to where it is now.
2434 (goto-char beg)
2435 (delete-region beg end))
2436 ;; Element (apply FUN . ARGS) means call FUN to undo.
2437 (`(apply . ,fun-args)
2438 (let ((currbuff (current-buffer)))
2439 (if (integerp (car fun-args))
2440 ;; Long format: (apply DELTA START END FUN . ARGS).
2441 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2442 (start-mark (copy-marker start nil))
2443 (end-mark (copy-marker end t)))
2444 (when (or (> (point-min) start) (< (point-max) end))
2445 (error "Changes to be undone are outside visible portion of buffer"))
2446 (apply fun args) ;; Use `save-current-buffer'?
2447 ;; Check that the function did what the entry
2448 ;; said it would do.
2449 (unless (and (= start start-mark)
2450 (= (+ delta end) end-mark))
2451 (error "Changes to be undone by function different than announced"))
2452 (set-marker start-mark nil)
2453 (set-marker end-mark nil))
2454 (apply fun-args))
2455 (unless (eq currbuff (current-buffer))
2456 (error "Undo function switched buffer"))
2457 (setq did-apply t)))
2458 ;; Element (STRING . POS) means STRING was deleted.
2459 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2460 (when (let ((apos (abs pos)))
2461 (or (< apos (point-min)) (> apos (point-max))))
2462 (error "Changes to be undone are outside visible portion of buffer"))
2463 (let (valid-marker-adjustments)
2464 ;; Check that marker adjustments which were recorded
2465 ;; with the (STRING . POS) record are still valid, ie
2466 ;; the markers haven't moved. We check their validity
2467 ;; before reinserting the string so as we don't need to
2468 ;; mind marker insertion-type.
2469 (while (and (markerp (car-safe (car list)))
2470 (integerp (cdr-safe (car list))))
2471 (let* ((marker-adj (pop list))
2472 (m (car marker-adj)))
2473 (and (eq (marker-buffer m) (current-buffer))
2474 (= pos m)
2475 (push marker-adj valid-marker-adjustments))))
2476 ;; Insert string and adjust point
2477 (if (< pos 0)
2478 (progn
2479 (goto-char (- pos))
2480 (insert string))
2481 (goto-char pos)
2482 (insert string)
2483 (goto-char pos))
2484 ;; Adjust the valid marker adjustments
2485 (dolist (adj valid-marker-adjustments)
2486 (set-marker (car adj)
2487 (- (car adj) (cdr adj))))))
2488 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2489 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2490 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2491 next)
2492 ;; Even though these elements are not expected in the undo
2493 ;; list, adjust them to be conservative for the 24.4
2494 ;; release. (Bug#16818)
2495 (when (marker-buffer marker)
2496 (set-marker marker
2497 (- marker offset)
2498 (marker-buffer marker))))
2499 (_ (error "Unrecognized entry in undo list %S" next))))
2500 (setq arg (1- arg)))
2501 ;; Make sure an apply entry produces at least one undo entry,
2502 ;; so the test in `undo' for continuing an undo series
2503 ;; will work right.
2504 (if (and did-apply
2505 (eq oldlist buffer-undo-list))
2506 (setq buffer-undo-list
2507 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2508 list)
2509
2510 ;; Deep copy of a list
2511 (defun undo-copy-list (list)
2512 "Make a copy of undo list LIST."
2513 (mapcar 'undo-copy-list-1 list))
2514
2515 (defun undo-copy-list-1 (elt)
2516 (if (consp elt)
2517 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2518 elt))
2519
2520 (defun undo-start (&optional beg end)
2521 "Set `pending-undo-list' to the front of the undo list.
2522 The next call to `undo-more' will undo the most recently made change.
2523 If BEG and END are specified, then only undo elements
2524 that apply to text between BEG and END are used; other undo elements
2525 are ignored. If BEG and END are nil, all undo elements are used."
2526 (if (eq buffer-undo-list t)
2527 (user-error "No undo information in this buffer"))
2528 (setq pending-undo-list
2529 (if (and beg end (not (= beg end)))
2530 (undo-make-selective-list (min beg end) (max beg end))
2531 buffer-undo-list)))
2532
2533 ;; The positions given in elements of the undo list are the positions
2534 ;; as of the time that element was recorded to undo history. In
2535 ;; general, subsequent buffer edits render those positions invalid in
2536 ;; the current buffer, unless adjusted according to the intervening
2537 ;; undo elements.
2538 ;;
2539 ;; Undo in region is a use case that requires adjustments to undo
2540 ;; elements. It must adjust positions of elements in the region based
2541 ;; on newer elements not in the region so as they may be correctly
2542 ;; applied in the current buffer. undo-make-selective-list
2543 ;; accomplishes this with its undo-deltas list of adjustments. An
2544 ;; example undo history from oldest to newest:
2545 ;;
2546 ;; buf pos:
2547 ;; 123456789 buffer-undo-list undo-deltas
2548 ;; --------- ---------------- -----------
2549 ;; aaa (1 . 4) (1 . -3)
2550 ;; aaba (3 . 4) N/A (in region)
2551 ;; ccaaba (1 . 3) (1 . -2)
2552 ;; ccaabaddd (7 . 10) (7 . -3)
2553 ;; ccaabdd ("ad" . 6) (6 . 2)
2554 ;; ccaabaddd (6 . 8) (6 . -2)
2555 ;; | |<-- region: "caab", from 2 to 6
2556 ;;
2557 ;; When the user starts a run of undos in region,
2558 ;; undo-make-selective-list is called to create the full list of in
2559 ;; region elements. Each element is adjusted forward chronologically
2560 ;; through undo-deltas to determine if it is in the region.
2561 ;;
2562 ;; In the above example, the insertion of "b" is (3 . 4) in the
2563 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2564 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2565 ;; . 6) is assessed as in the region and placed in the selective list.
2566 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2567 ;; due to the selected element. The "b" insertion is the only element
2568 ;; fully in the region, so in this example undo-make-selective-list
2569 ;; returns (nil (5 . 6)).
2570 ;;
2571 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2572 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2573 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2574 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2575 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2576 ;;
2577 ;; More interesting is how to adjust the "ddd" insertion due to the
2578 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2579 ;; If the reinsertion was a manual retyping of "ad", then the total
2580 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2581 ;; the reinsertion was due to undo, one might expect the first "d"
2582 ;; character would again be a part of the "ddd" text, meaning its
2583 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2584 ;;
2585 ;; undo-make-selective-list assumes in this situation that "ad" was a
2586 ;; new edit, even if it was inserted because of an undo.
2587 ;; Consequently, if the user undos in region "8 to 10" of the
2588 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2589 ;; "ccaabad", as though the first "d" became detached from the
2590 ;; original "ddd" insertion. This quirk is a FIXME.
2591
2592 (defun undo-make-selective-list (start end)
2593 "Return a list of undo elements for the region START to END.
2594 The elements come from `buffer-undo-list', but we keep only the
2595 elements inside this region, and discard those outside this
2596 region. The elements' positions are adjusted so as the returned
2597 list can be applied to the current buffer."
2598 (let ((ulist buffer-undo-list)
2599 ;; A list of position adjusted undo elements in the region.
2600 (selective-list (list nil))
2601 ;; A list of undo-deltas for out of region undo elements.
2602 undo-deltas
2603 undo-elt)
2604 (while ulist
2605 (when undo-no-redo
2606 (while (gethash ulist undo-equiv-table)
2607 (setq ulist (gethash ulist undo-equiv-table))))
2608 (setq undo-elt (car ulist))
2609 (cond
2610 ((null undo-elt)
2611 ;; Don't put two nils together in the list
2612 (when (car selective-list)
2613 (push nil selective-list)))
2614 ((and (consp undo-elt) (eq (car undo-elt) t))
2615 ;; This is a "was unmodified" element. Keep it
2616 ;; if we have kept everything thus far.
2617 (when (not undo-deltas)
2618 (push undo-elt selective-list)))
2619 ;; Skip over marker adjustments, instead relying
2620 ;; on finding them after (TEXT . POS) elements
2621 ((markerp (car-safe undo-elt))
2622 nil)
2623 (t
2624 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2625 undo-deltas)))
2626 (if (undo-elt-in-region adjusted-undo-elt start end)
2627 (progn
2628 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2629 (push adjusted-undo-elt selective-list)
2630 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2631 ;; kept. primitive-undo may discard them later.
2632 (when (and (stringp (car-safe adjusted-undo-elt))
2633 (integerp (cdr-safe adjusted-undo-elt)))
2634 (let ((list-i (cdr ulist)))
2635 (while (markerp (car-safe (car list-i)))
2636 (push (pop list-i) selective-list)))))
2637 (let ((delta (undo-delta undo-elt)))
2638 (when (/= 0 (cdr delta))
2639 (push delta undo-deltas)))))))
2640 (pop ulist))
2641 (nreverse selective-list)))
2642
2643 (defun undo-elt-in-region (undo-elt start end)
2644 "Determine whether UNDO-ELT falls inside the region START ... END.
2645 If it crosses the edge, we return nil.
2646
2647 Generally this function is not useful for determining
2648 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2649 because markers can be arbitrarily relocated. Instead, pass the
2650 marker adjustment's corresponding (TEXT . POS) element."
2651 (cond ((integerp undo-elt)
2652 (and (>= undo-elt start)
2653 (<= undo-elt end)))
2654 ((eq undo-elt nil)
2655 t)
2656 ((atom undo-elt)
2657 nil)
2658 ((stringp (car undo-elt))
2659 ;; (TEXT . POSITION)
2660 (and (>= (abs (cdr undo-elt)) start)
2661 (<= (abs (cdr undo-elt)) end)))
2662 ((and (consp undo-elt) (markerp (car undo-elt)))
2663 ;; (MARKER . ADJUSTMENT)
2664 (<= start (car undo-elt) end))
2665 ((null (car undo-elt))
2666 ;; (nil PROPERTY VALUE BEG . END)
2667 (let ((tail (nthcdr 3 undo-elt)))
2668 (and (>= (car tail) start)
2669 (<= (cdr tail) end))))
2670 ((integerp (car undo-elt))
2671 ;; (BEGIN . END)
2672 (and (>= (car undo-elt) start)
2673 (<= (cdr undo-elt) end)))))
2674
2675 (defun undo-elt-crosses-region (undo-elt start end)
2676 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2677 This assumes we have already decided that UNDO-ELT
2678 is not *inside* the region START...END."
2679 (declare (obsolete nil "25.1"))
2680 (cond ((atom undo-elt) nil)
2681 ((null (car undo-elt))
2682 ;; (nil PROPERTY VALUE BEG . END)
2683 (let ((tail (nthcdr 3 undo-elt)))
2684 (and (< (car tail) end)
2685 (> (cdr tail) start))))
2686 ((integerp (car undo-elt))
2687 ;; (BEGIN . END)
2688 (and (< (car undo-elt) end)
2689 (> (cdr undo-elt) start)))))
2690
2691 (defun undo-adjust-elt (elt deltas)
2692 "Return adjustment of undo element ELT by the undo DELTAS
2693 list."
2694 (pcase elt
2695 ;; POSITION
2696 ((pred integerp)
2697 (undo-adjust-pos elt deltas))
2698 ;; (BEG . END)
2699 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2700 (undo-adjust-beg-end beg end deltas))
2701 ;; (TEXT . POSITION)
2702 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2703 (cons text (* (if (< pos 0) -1 1)
2704 (undo-adjust-pos (abs pos) deltas))))
2705 ;; (nil PROPERTY VALUE BEG . END)
2706 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2707 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2708 ;; (apply DELTA START END FUN . ARGS)
2709 ;; FIXME
2710 ;; All others return same elt
2711 (_ elt)))
2712
2713 ;; (BEG . END) can adjust to the same positions, commonly when an
2714 ;; insertion was undone and they are out of region, for example:
2715 ;;
2716 ;; buf pos:
2717 ;; 123456789 buffer-undo-list undo-deltas
2718 ;; --------- ---------------- -----------
2719 ;; [...]
2720 ;; abbaa (2 . 4) (2 . -2)
2721 ;; aaa ("bb" . 2) (2 . 2)
2722 ;; [...]
2723 ;;
2724 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2725 ;; undo. Further adjustments to such an element should be the same as
2726 ;; for (TEXT . POSITION) elements. The options are:
2727 ;;
2728 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2729 ;; analogous to marker insertion-type t.
2730 ;;
2731 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2732 ;; marker insertion-type nil.
2733 ;;
2734 ;; There was no strong reason to prefer one or the other, except that
2735 ;; the first is more consistent with prior undo in region behavior.
2736 (defun undo-adjust-beg-end (beg end deltas)
2737 "Return cons of adjustments to BEG and END by the undo DELTAS
2738 list."
2739 (let ((adj-beg (undo-adjust-pos beg deltas)))
2740 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2741 (cons adj-beg
2742 (max adj-beg (undo-adjust-pos end deltas t)))))
2743
2744 (defun undo-adjust-pos (pos deltas &optional use-<)
2745 "Return adjustment of POS by the undo DELTAS list, comparing
2746 with < or <= based on USE-<."
2747 (dolist (d deltas pos)
2748 (when (if use-<
2749 (< (car d) pos)
2750 (<= (car d) pos))
2751 (setq pos
2752 ;; Don't allow pos to become less than the undo-delta
2753 ;; position. This edge case is described in the overview
2754 ;; comments.
2755 (max (car d) (- pos (cdr d)))))))
2756
2757 ;; Return the first affected buffer position and the delta for an undo element
2758 ;; delta is defined as the change in subsequent buffer positions if we *did*
2759 ;; the undo.
2760 (defun undo-delta (undo-elt)
2761 (if (consp undo-elt)
2762 (cond ((stringp (car undo-elt))
2763 ;; (TEXT . POSITION)
2764 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2765 ((integerp (car undo-elt))
2766 ;; (BEGIN . END)
2767 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2768 (t
2769 '(0 . 0)))
2770 '(0 . 0)))
2771
2772 (defcustom undo-ask-before-discard nil
2773 "If non-nil ask about discarding undo info for the current command.
2774 Normally, Emacs discards the undo info for the current command if
2775 it exceeds `undo-outer-limit'. But if you set this option
2776 non-nil, it asks in the echo area whether to discard the info.
2777 If you answer no, there is a slight risk that Emacs might crash, so
2778 only do it if you really want to undo the command.
2779
2780 This option is mainly intended for debugging. You have to be
2781 careful if you use it for other purposes. Garbage collection is
2782 inhibited while the question is asked, meaning that Emacs might
2783 leak memory. So you should make sure that you do not wait
2784 excessively long before answering the question."
2785 :type 'boolean
2786 :group 'undo
2787 :version "22.1")
2788
2789 (defvar undo-extra-outer-limit nil
2790 "If non-nil, an extra level of size that's ok in an undo item.
2791 We don't ask the user about truncating the undo list until the
2792 current item gets bigger than this amount.
2793
2794 This variable only matters if `undo-ask-before-discard' is non-nil.")
2795 (make-variable-buffer-local 'undo-extra-outer-limit)
2796
2797 ;; When the first undo batch in an undo list is longer than
2798 ;; undo-outer-limit, this function gets called to warn the user that
2799 ;; the undo info for the current command was discarded. Garbage
2800 ;; collection is inhibited around the call, so it had better not do a
2801 ;; lot of consing.
2802 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2803 (defun undo-outer-limit-truncate (size)
2804 (if undo-ask-before-discard
2805 (when (or (null undo-extra-outer-limit)
2806 (> size undo-extra-outer-limit))
2807 ;; Don't ask the question again unless it gets even bigger.
2808 ;; This applies, in particular, if the user quits from the question.
2809 ;; Such a quit quits out of GC, but something else will call GC
2810 ;; again momentarily. It will call this function again,
2811 ;; but we don't want to ask the question again.
2812 (setq undo-extra-outer-limit (+ size 50000))
2813 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2814 (yes-or-no-p (format-message
2815 "Buffer `%s' undo info is %d bytes long; discard it? "
2816 (buffer-name) size)))
2817 (progn (setq buffer-undo-list nil)
2818 (setq undo-extra-outer-limit nil)
2819 t)
2820 nil))
2821 (display-warning '(undo discard-info)
2822 (concat
2823 (format-message
2824 "Buffer `%s' undo info was %d bytes long.\n"
2825 (buffer-name) size)
2826 "The undo info was discarded because it exceeded \
2827 `undo-outer-limit'.
2828
2829 This is normal if you executed a command that made a huge change
2830 to the buffer. In that case, to prevent similar problems in the
2831 future, set `undo-outer-limit' to a value that is large enough to
2832 cover the maximum size of normal changes you expect a single
2833 command to make, but not so large that it might exceed the
2834 maximum memory allotted to Emacs.
2835
2836 If you did not execute any such command, the situation is
2837 probably due to a bug and you should report it.
2838
2839 You can disable the popping up of this buffer by adding the entry
2840 \(undo discard-info) to the user option `warning-suppress-types',
2841 which is defined in the `warnings' library.\n")
2842 :warning)
2843 (setq buffer-undo-list nil)
2844 t))
2845 \f
2846 (defcustom password-word-equivalents
2847 '("password" "passcode" "passphrase" "pass phrase"
2848 ; These are sorted according to the GNU en_US locale.
2849 "암호" ; ko
2850 "パスワード" ; ja
2851 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
2852 "ពាក្យសម្ងាត់" ; km
2853 "adgangskode" ; da
2854 "contraseña" ; es
2855 "contrasenya" ; ca
2856 "geslo" ; sl
2857 "hasło" ; pl
2858 "heslo" ; cs, sk
2859 "iphasiwedi" ; zu
2860 "jelszó" ; hu
2861 "lösenord" ; sv
2862 "lozinka" ; hr, sr
2863 "mật khẩu" ; vi
2864 "mot de passe" ; fr
2865 "parola" ; tr
2866 "pasahitza" ; eu
2867 "passord" ; nb
2868 "passwort" ; de
2869 "pasvorto" ; eo
2870 "salasana" ; fi
2871 "senha" ; pt
2872 "slaptažodis" ; lt
2873 "wachtwoord" ; nl
2874 "كلمة السر" ; ar
2875 "ססמה" ; he
2876 "лозинка" ; sr
2877 "пароль" ; kk, ru, uk
2878 "गुप्तशब्द" ; mr
2879 "शब्दकूट" ; hi
2880 "પાસવર્ડ" ; gu
2881 "సంకేతపదము" ; te
2882 "ਪਾਸਵਰਡ" ; pa
2883 "ಗುಪ್ತಪದ" ; kn
2884 "கடவுச்சொல்" ; ta
2885 "അടയാളവാക്ക്" ; ml
2886 "গুপ্তশব্দ" ; as
2887 "পাসওয়ার্ড" ; bn_IN
2888 "රහස්පදය" ; si
2889 "密码" ; zh_CN
2890 "密碼" ; zh_TW
2891 )
2892 "List of words equivalent to \"password\".
2893 This is used by Shell mode and other parts of Emacs to recognize
2894 password prompts, including prompts in languages other than
2895 English. Different case choices should not be assumed to be
2896 included; callers should bind `case-fold-search' to t."
2897 :type '(repeat string)
2898 :version "24.4"
2899 :group 'processes)
2900
2901 (defvar shell-command-history nil
2902 "History list for some commands that read shell commands.
2903
2904 Maximum length of the history list is determined by the value
2905 of `history-length', which see.")
2906
2907 (defvar shell-command-switch (purecopy "-c")
2908 "Switch used to have the shell execute its command line argument.")
2909
2910 (defvar shell-command-default-error-buffer nil
2911 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2912 This buffer is used when `shell-command' or `shell-command-on-region'
2913 is run interactively. A value of nil means that output to stderr and
2914 stdout will be intermixed in the output stream.")
2915
2916 (declare-function mailcap-file-default-commands "mailcap" (files))
2917 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2918
2919 (defun minibuffer-default-add-shell-commands ()
2920 "Return a list of all commands associated with the current file.
2921 This function is used to add all related commands retrieved by `mailcap'
2922 to the end of the list of defaults just after the default value."
2923 (interactive)
2924 (let* ((filename (if (listp minibuffer-default)
2925 (car minibuffer-default)
2926 minibuffer-default))
2927 (commands (and filename (require 'mailcap nil t)
2928 (mailcap-file-default-commands (list filename)))))
2929 (setq commands (mapcar (lambda (command)
2930 (concat command " " filename))
2931 commands))
2932 (if (listp minibuffer-default)
2933 (append minibuffer-default commands)
2934 (cons minibuffer-default commands))))
2935
2936 (declare-function shell-completion-vars "shell" ())
2937
2938 (defvar minibuffer-local-shell-command-map
2939 (let ((map (make-sparse-keymap)))
2940 (set-keymap-parent map minibuffer-local-map)
2941 (define-key map "\t" 'completion-at-point)
2942 map)
2943 "Keymap used for completing shell commands in minibuffer.")
2944
2945 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2946 "Read a shell command from the minibuffer.
2947 The arguments are the same as the ones of `read-from-minibuffer',
2948 except READ and KEYMAP are missing and HIST defaults
2949 to `shell-command-history'."
2950 (require 'shell)
2951 (minibuffer-with-setup-hook
2952 (lambda ()
2953 (shell-completion-vars)
2954 (set (make-local-variable 'minibuffer-default-add-function)
2955 'minibuffer-default-add-shell-commands))
2956 (apply 'read-from-minibuffer prompt initial-contents
2957 minibuffer-local-shell-command-map
2958 nil
2959 (or hist 'shell-command-history)
2960 args)))
2961
2962 (defcustom async-shell-command-buffer 'confirm-new-buffer
2963 "What to do when the output buffer is used by another shell command.
2964 This option specifies how to resolve the conflict where a new command
2965 wants to direct its output to the buffer `*Async Shell Command*',
2966 but this buffer is already taken by another running shell command.
2967
2968 The value `confirm-kill-process' is used to ask for confirmation before
2969 killing the already running process and running a new process
2970 in the same buffer, `confirm-new-buffer' for confirmation before running
2971 the command in a new buffer with a name other than the default buffer name,
2972 `new-buffer' for doing the same without confirmation,
2973 `confirm-rename-buffer' for confirmation before renaming the existing
2974 output buffer and running a new command in the default buffer,
2975 `rename-buffer' for doing the same without confirmation."
2976 :type '(choice (const :tag "Confirm killing of running command"
2977 confirm-kill-process)
2978 (const :tag "Confirm creation of a new buffer"
2979 confirm-new-buffer)
2980 (const :tag "Create a new buffer"
2981 new-buffer)
2982 (const :tag "Confirm renaming of existing buffer"
2983 confirm-rename-buffer)
2984 (const :tag "Rename the existing buffer"
2985 rename-buffer))
2986 :group 'shell
2987 :version "24.3")
2988
2989 (defun async-shell-command (command &optional output-buffer error-buffer)
2990 "Execute string COMMAND asynchronously in background.
2991
2992 Like `shell-command', but adds `&' at the end of COMMAND
2993 to execute it asynchronously.
2994
2995 The output appears in the buffer `*Async Shell Command*'.
2996 That buffer is in shell mode.
2997
2998 You can configure `async-shell-command-buffer' to specify what to do in
2999 case when `*Async Shell Command*' buffer is already taken by another
3000 running shell command. To run COMMAND without displaying the output
3001 in a window you can configure `display-buffer-alist' to use the action
3002 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3003
3004 In Elisp, you will often be better served by calling `start-process'
3005 directly, since it offers more control and does not impose the use of a
3006 shell (with its need to quote arguments)."
3007 (interactive
3008 (list
3009 (read-shell-command "Async shell command: " nil nil
3010 (let ((filename
3011 (cond
3012 (buffer-file-name)
3013 ((eq major-mode 'dired-mode)
3014 (dired-get-filename nil t)))))
3015 (and filename (file-relative-name filename))))
3016 current-prefix-arg
3017 shell-command-default-error-buffer))
3018 (unless (string-match "&[ \t]*\\'" command)
3019 (setq command (concat command " &")))
3020 (shell-command command output-buffer error-buffer))
3021
3022 (defun shell-command (command &optional output-buffer error-buffer)
3023 "Execute string COMMAND in inferior shell; display output, if any.
3024 With prefix argument, insert the COMMAND's output at point.
3025
3026 If COMMAND ends in `&', execute it asynchronously.
3027 The output appears in the buffer `*Async Shell Command*'.
3028 That buffer is in shell mode. You can also use
3029 `async-shell-command' that automatically adds `&'.
3030
3031 Otherwise, COMMAND is executed synchronously. The output appears in
3032 the buffer `*Shell Command Output*'. If the output is short enough to
3033 display in the echo area (which is determined by the variables
3034 `resize-mini-windows' and `max-mini-window-height'), it is shown
3035 there, but it is nonetheless available in buffer `*Shell Command
3036 Output*' even though that buffer is not automatically displayed.
3037
3038 To specify a coding system for converting non-ASCII characters
3039 in the shell command output, use \\[universal-coding-system-argument] \
3040 before this command.
3041
3042 Noninteractive callers can specify coding systems by binding
3043 `coding-system-for-read' and `coding-system-for-write'.
3044
3045 The optional second argument OUTPUT-BUFFER, if non-nil,
3046 says to put the output in some other buffer.
3047 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3048 If OUTPUT-BUFFER is not a buffer and not nil,
3049 insert output in current buffer. (This cannot be done asynchronously.)
3050 In either case, the buffer is first erased, and the output is
3051 inserted after point (leaving mark after it).
3052
3053 If the command terminates without error, but generates output,
3054 and you did not specify \"insert it in the current buffer\",
3055 the output can be displayed in the echo area or in its buffer.
3056 If the output is short enough to display in the echo area
3057 \(determined by the variable `max-mini-window-height' if
3058 `resize-mini-windows' is non-nil), it is shown there.
3059 Otherwise,the buffer containing the output is displayed.
3060
3061 If there is output and an error, and you did not specify \"insert it
3062 in the current buffer\", a message about the error goes at the end
3063 of the output.
3064
3065 If there is no output, or if output is inserted in the current buffer,
3066 then `*Shell Command Output*' is deleted.
3067
3068 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3069 or buffer name to which to direct the command's standard error output.
3070 If it is nil, error output is mingled with regular output.
3071 In an interactive call, the variable `shell-command-default-error-buffer'
3072 specifies the value of ERROR-BUFFER.
3073
3074 In Elisp, you will often be better served by calling `call-process' or
3075 `start-process' directly, since it offers more control and does not impose
3076 the use of a shell (with its need to quote arguments)."
3077
3078 (interactive
3079 (list
3080 (read-shell-command "Shell command: " nil nil
3081 (let ((filename
3082 (cond
3083 (buffer-file-name)
3084 ((eq major-mode 'dired-mode)
3085 (dired-get-filename nil t)))))
3086 (and filename (file-relative-name filename))))
3087 current-prefix-arg
3088 shell-command-default-error-buffer))
3089 ;; Look for a handler in case default-directory is a remote file name.
3090 (let ((handler
3091 (find-file-name-handler (directory-file-name default-directory)
3092 'shell-command)))
3093 (if handler
3094 (funcall handler 'shell-command command output-buffer error-buffer)
3095 (if (and output-buffer
3096 (not (or (bufferp output-buffer) (stringp output-buffer))))
3097 ;; Output goes in current buffer.
3098 (let ((error-file
3099 (if error-buffer
3100 (make-temp-file
3101 (expand-file-name "scor"
3102 (or small-temporary-file-directory
3103 temporary-file-directory)))
3104 nil)))
3105 (barf-if-buffer-read-only)
3106 (push-mark nil t)
3107 ;; We do not use -f for csh; we will not support broken use of
3108 ;; .cshrcs. Even the BSD csh manual says to use
3109 ;; "if ($?prompt) exit" before things which are not useful
3110 ;; non-interactively. Besides, if someone wants their other
3111 ;; aliases for shell commands then they can still have them.
3112 (call-process shell-file-name nil
3113 (if error-file
3114 (list t error-file)
3115 t)
3116 nil shell-command-switch command)
3117 (when (and error-file (file-exists-p error-file))
3118 (if (< 0 (nth 7 (file-attributes error-file)))
3119 (with-current-buffer (get-buffer-create error-buffer)
3120 (let ((pos-from-end (- (point-max) (point))))
3121 (or (bobp)
3122 (insert "\f\n"))
3123 ;; Do no formatting while reading error file,
3124 ;; because that can run a shell command, and we
3125 ;; don't want that to cause an infinite recursion.
3126 (format-insert-file error-file nil)
3127 ;; Put point after the inserted errors.
3128 (goto-char (- (point-max) pos-from-end)))
3129 (display-buffer (current-buffer))))
3130 (delete-file error-file))
3131 ;; This is like exchange-point-and-mark, but doesn't
3132 ;; activate the mark. It is cleaner to avoid activation,
3133 ;; even though the command loop would deactivate the mark
3134 ;; because we inserted text.
3135 (goto-char (prog1 (mark t)
3136 (set-marker (mark-marker) (point)
3137 (current-buffer)))))
3138 ;; Output goes in a separate buffer.
3139 ;; Preserve the match data in case called from a program.
3140 (save-match-data
3141 (if (string-match "[ \t]*&[ \t]*\\'" command)
3142 ;; Command ending with ampersand means asynchronous.
3143 (let ((buffer (get-buffer-create
3144 (or output-buffer "*Async Shell Command*")))
3145 (directory default-directory)
3146 proc)
3147 ;; Remove the ampersand.
3148 (setq command (substring command 0 (match-beginning 0)))
3149 ;; Ask the user what to do with already running process.
3150 (setq proc (get-buffer-process buffer))
3151 (when proc
3152 (cond
3153 ((eq async-shell-command-buffer 'confirm-kill-process)
3154 ;; If will kill a process, query first.
3155 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3156 (kill-process proc)
3157 (error "Shell command in progress")))
3158 ((eq async-shell-command-buffer 'confirm-new-buffer)
3159 ;; If will create a new buffer, query first.
3160 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3161 (setq buffer (generate-new-buffer
3162 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3163 output-buffer "*Async Shell Command*")))
3164 (error "Shell command in progress")))
3165 ((eq async-shell-command-buffer 'new-buffer)
3166 ;; It will create a new buffer.
3167 (setq buffer (generate-new-buffer
3168 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3169 output-buffer "*Async Shell Command*"))))
3170 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3171 ;; If will rename the buffer, query first.
3172 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3173 (progn
3174 (with-current-buffer buffer
3175 (rename-uniquely))
3176 (setq buffer (get-buffer-create
3177 (or output-buffer "*Async Shell Command*"))))
3178 (error "Shell command in progress")))
3179 ((eq async-shell-command-buffer 'rename-buffer)
3180 ;; It will rename the buffer.
3181 (with-current-buffer buffer
3182 (rename-uniquely))
3183 (setq buffer (get-buffer-create
3184 (or output-buffer "*Async Shell Command*"))))))
3185 (with-current-buffer buffer
3186 (setq buffer-read-only nil)
3187 ;; Setting buffer-read-only to nil doesn't suffice
3188 ;; if some text has a non-nil read-only property,
3189 ;; which comint sometimes adds for prompts.
3190 (let ((inhibit-read-only t))
3191 (erase-buffer))
3192 (display-buffer buffer '(nil (allow-no-window . t)))
3193 (setq default-directory directory)
3194 (setq proc (start-process "Shell" buffer shell-file-name
3195 shell-command-switch command))
3196 (setq mode-line-process '(":%s"))
3197 (require 'shell) (shell-mode)
3198 (set-process-sentinel proc 'shell-command-sentinel)
3199 ;; Use the comint filter for proper handling of carriage motion
3200 ;; (see `comint-inhibit-carriage-motion'),.
3201 (set-process-filter proc 'comint-output-filter)
3202 ))
3203 ;; Otherwise, command is executed synchronously.
3204 (shell-command-on-region (point) (point) command
3205 output-buffer nil error-buffer)))))))
3206
3207 (defun display-message-or-buffer (message
3208 &optional buffer-name not-this-window frame)
3209 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3210 MESSAGE may be either a string or a buffer.
3211
3212 A buffer is displayed using `display-buffer' if MESSAGE is too long for
3213 the maximum height of the echo area, as defined by `max-mini-window-height'
3214 if `resize-mini-windows' is non-nil.
3215
3216 Returns either the string shown in the echo area, or when a pop-up
3217 buffer is used, the window used to display it.
3218
3219 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3220 name of the buffer used to display it in the case where a pop-up buffer
3221 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3222 string and it is displayed in the echo area, it is not specified whether
3223 the contents are inserted into the buffer anyway.
3224
3225 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
3226 and only used if a buffer is displayed."
3227 (cond ((and (stringp message) (not (string-match "\n" message)))
3228 ;; Trivial case where we can use the echo area
3229 (message "%s" message))
3230 ((and (stringp message)
3231 (= (string-match "\n" message) (1- (length message))))
3232 ;; Trivial case where we can just remove single trailing newline
3233 (message "%s" (substring message 0 (1- (length message)))))
3234 (t
3235 ;; General case
3236 (with-current-buffer
3237 (if (bufferp message)
3238 message
3239 (get-buffer-create (or buffer-name "*Message*")))
3240
3241 (unless (bufferp message)
3242 (erase-buffer)
3243 (insert message))
3244
3245 (let ((lines
3246 (if (= (buffer-size) 0)
3247 0
3248 (count-screen-lines nil nil nil (minibuffer-window)))))
3249 (cond ((= lines 0))
3250 ((and (or (<= lines 1)
3251 (<= lines
3252 (if resize-mini-windows
3253 (cond ((floatp max-mini-window-height)
3254 (* (frame-height)
3255 max-mini-window-height))
3256 ((integerp max-mini-window-height)
3257 max-mini-window-height)
3258 (t
3259 1))
3260 1)))
3261 ;; Don't use the echo area if the output buffer is
3262 ;; already displayed in the selected frame.
3263 (not (get-buffer-window (current-buffer))))
3264 ;; Echo area
3265 (goto-char (point-max))
3266 (when (bolp)
3267 (backward-char 1))
3268 (message "%s" (buffer-substring (point-min) (point))))
3269 (t
3270 ;; Buffer
3271 (goto-char (point-min))
3272 (display-buffer (current-buffer)
3273 not-this-window frame))))))))
3274
3275
3276 ;; We have a sentinel to prevent insertion of a termination message
3277 ;; in the buffer itself.
3278 (defun shell-command-sentinel (process signal)
3279 (if (memq (process-status process) '(exit signal))
3280 (message "%s: %s."
3281 (car (cdr (cdr (process-command process))))
3282 (substring signal 0 -1))))
3283
3284 (defun shell-command-on-region (start end command
3285 &optional output-buffer replace
3286 error-buffer display-error-buffer)
3287 "Execute string COMMAND in inferior shell with region as input.
3288 Normally display output (if any) in temp buffer `*Shell Command Output*';
3289 Prefix arg means replace the region with it. Return the exit code of
3290 COMMAND.
3291
3292 To specify a coding system for converting non-ASCII characters
3293 in the input and output to the shell command, use \\[universal-coding-system-argument]
3294 before this command. By default, the input (from the current buffer)
3295 is encoded using coding-system specified by `process-coding-system-alist',
3296 falling back to `default-process-coding-system' if no match for COMMAND
3297 is found in `process-coding-system-alist'.
3298
3299 Noninteractive callers can specify coding systems by binding
3300 `coding-system-for-read' and `coding-system-for-write'.
3301
3302 If the command generates output, the output may be displayed
3303 in the echo area or in a buffer.
3304 If the output is short enough to display in the echo area
3305 \(determined by the variable `max-mini-window-height' if
3306 `resize-mini-windows' is non-nil), it is shown there.
3307 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3308 The output is available in that buffer in both cases.
3309
3310 If there is output and an error, a message about the error
3311 appears at the end of the output. If there is no output, or if
3312 output is inserted in the current buffer, the buffer `*Shell
3313 Command Output*' is deleted.
3314
3315 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3316 command's output. If the value is a buffer or buffer name,
3317 put the output there. If the value is nil, use the buffer
3318 `*Shell Command Output*'. Any other value, excluding nil,
3319 means to insert the output in the current buffer. In either case,
3320 the output is inserted after point (leaving mark after it).
3321
3322 Optional fifth arg REPLACE, if non-nil, means to insert the
3323 output in place of text from START to END, putting point and mark
3324 around it.
3325
3326 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3327 or buffer name to which to direct the command's standard error
3328 output. If nil, error output is mingled with regular output.
3329 When called interactively, `shell-command-default-error-buffer'
3330 is used for ERROR-BUFFER.
3331
3332 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3333 display the error buffer if there were any errors. When called
3334 interactively, this is t."
3335 (interactive (let (string)
3336 (unless (mark)
3337 (user-error "The mark is not set now, so there is no region"))
3338 ;; Do this before calling region-beginning
3339 ;; and region-end, in case subprocess output
3340 ;; relocates them while we are in the minibuffer.
3341 (setq string (read-shell-command "Shell command on region: "))
3342 ;; call-interactively recognizes region-beginning and
3343 ;; region-end specially, leaving them in the history.
3344 (list (region-beginning) (region-end)
3345 string
3346 current-prefix-arg
3347 current-prefix-arg
3348 shell-command-default-error-buffer
3349 t)))
3350 (let ((error-file
3351 (if error-buffer
3352 (make-temp-file
3353 (expand-file-name "scor"
3354 (or small-temporary-file-directory
3355 temporary-file-directory)))
3356 nil))
3357 exit-status)
3358 (if (or replace
3359 (and output-buffer
3360 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3361 ;; Replace specified region with output from command.
3362 (let ((swap (and replace (< start end))))
3363 ;; Don't muck with mark unless REPLACE says we should.
3364 (goto-char start)
3365 (and replace (push-mark (point) 'nomsg))
3366 (setq exit-status
3367 (call-process-region start end shell-file-name replace
3368 (if error-file
3369 (list t error-file)
3370 t)
3371 nil shell-command-switch command))
3372 ;; It is rude to delete a buffer which the command is not using.
3373 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3374 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3375 ;; (kill-buffer shell-buffer)))
3376 ;; Don't muck with mark unless REPLACE says we should.
3377 (and replace swap (exchange-point-and-mark)))
3378 ;; No prefix argument: put the output in a temp buffer,
3379 ;; replacing its entire contents.
3380 (let ((buffer (get-buffer-create
3381 (or output-buffer "*Shell Command Output*"))))
3382 (unwind-protect
3383 (if (eq buffer (current-buffer))
3384 ;; If the input is the same buffer as the output,
3385 ;; delete everything but the specified region,
3386 ;; then replace that region with the output.
3387 (progn (setq buffer-read-only nil)
3388 (delete-region (max start end) (point-max))
3389 (delete-region (point-min) (min start end))
3390 (setq exit-status
3391 (call-process-region (point-min) (point-max)
3392 shell-file-name t
3393 (if error-file
3394 (list t error-file)
3395 t)
3396 nil shell-command-switch
3397 command)))
3398 ;; Clear the output buffer, then run the command with
3399 ;; output there.
3400 (let ((directory default-directory))
3401 (with-current-buffer buffer
3402 (setq buffer-read-only nil)
3403 (if (not output-buffer)
3404 (setq default-directory directory))
3405 (erase-buffer)))
3406 (setq exit-status
3407 (call-process-region start end shell-file-name nil
3408 (if error-file
3409 (list buffer error-file)
3410 buffer)
3411 nil shell-command-switch command)))
3412 ;; Report the output.
3413 (with-current-buffer buffer
3414 (setq mode-line-process
3415 (cond ((null exit-status)
3416 " - Error")
3417 ((stringp exit-status)
3418 (format " - Signal [%s]" exit-status))
3419 ((not (equal 0 exit-status))
3420 (format " - Exit [%d]" exit-status)))))
3421 (if (with-current-buffer buffer (> (point-max) (point-min)))
3422 ;; There's some output, display it
3423 (display-message-or-buffer buffer)
3424 ;; No output; error?
3425 (let ((output
3426 (if (and error-file
3427 (< 0 (nth 7 (file-attributes error-file))))
3428 (format "some error output%s"
3429 (if shell-command-default-error-buffer
3430 (format " to the \"%s\" buffer"
3431 shell-command-default-error-buffer)
3432 ""))
3433 "no output")))
3434 (cond ((null exit-status)
3435 (message "(Shell command failed with error)"))
3436 ((equal 0 exit-status)
3437 (message "(Shell command succeeded with %s)"
3438 output))
3439 ((stringp exit-status)
3440 (message "(Shell command killed by signal %s)"
3441 exit-status))
3442 (t
3443 (message "(Shell command failed with code %d and %s)"
3444 exit-status output))))
3445 ;; Don't kill: there might be useful info in the undo-log.
3446 ;; (kill-buffer buffer)
3447 ))))
3448
3449 (when (and error-file (file-exists-p error-file))
3450 (if (< 0 (nth 7 (file-attributes error-file)))
3451 (with-current-buffer (get-buffer-create error-buffer)
3452 (let ((pos-from-end (- (point-max) (point))))
3453 (or (bobp)
3454 (insert "\f\n"))
3455 ;; Do no formatting while reading error file,
3456 ;; because that can run a shell command, and we
3457 ;; don't want that to cause an infinite recursion.
3458 (format-insert-file error-file nil)
3459 ;; Put point after the inserted errors.
3460 (goto-char (- (point-max) pos-from-end)))
3461 (and display-error-buffer
3462 (display-buffer (current-buffer)))))
3463 (delete-file error-file))
3464 exit-status))
3465
3466 (defun shell-command-to-string (command)
3467 "Execute shell command COMMAND and return its output as a string."
3468 (with-output-to-string
3469 (with-current-buffer
3470 standard-output
3471 (process-file shell-file-name nil t nil shell-command-switch command))))
3472
3473 (defun process-file (program &optional infile buffer display &rest args)
3474 "Process files synchronously in a separate process.
3475 Similar to `call-process', but may invoke a file handler based on
3476 `default-directory'. The current working directory of the
3477 subprocess is `default-directory'.
3478
3479 File names in INFILE and BUFFER are handled normally, but file
3480 names in ARGS should be relative to `default-directory', as they
3481 are passed to the process verbatim. (This is a difference to
3482 `call-process' which does not support file handlers for INFILE
3483 and BUFFER.)
3484
3485 Some file handlers might not support all variants, for example
3486 they might behave as if DISPLAY was nil, regardless of the actual
3487 value passed."
3488 (let ((fh (find-file-name-handler default-directory 'process-file))
3489 lc stderr-file)
3490 (unwind-protect
3491 (if fh (apply fh 'process-file program infile buffer display args)
3492 (when infile (setq lc (file-local-copy infile)))
3493 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3494 (make-temp-file "emacs")))
3495 (prog1
3496 (apply 'call-process program
3497 (or lc infile)
3498 (if stderr-file (list (car buffer) stderr-file) buffer)
3499 display args)
3500 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3501 (when stderr-file (delete-file stderr-file))
3502 (when lc (delete-file lc)))))
3503
3504 (defvar process-file-side-effects t
3505 "Whether a call of `process-file' changes remote files.
3506
3507 By default, this variable is always set to t, meaning that a
3508 call of `process-file' could potentially change any file on a
3509 remote host. When set to nil, a file handler could optimize
3510 its behavior with respect to remote file attribute caching.
3511
3512 You should only ever change this variable with a let-binding;
3513 never with `setq'.")
3514
3515 (defun start-file-process (name buffer program &rest program-args)
3516 "Start a program in a subprocess. Return the process object for it.
3517
3518 Similar to `start-process', but may invoke a file handler based on
3519 `default-directory'. See Info node `(elisp)Magic File Names'.
3520
3521 This handler ought to run PROGRAM, perhaps on the local host,
3522 perhaps on a remote host that corresponds to `default-directory'.
3523 In the latter case, the local part of `default-directory' becomes
3524 the working directory of the process.
3525
3526 PROGRAM and PROGRAM-ARGS might be file names. They are not
3527 objects of file handler invocation. File handlers might not
3528 support pty association, if PROGRAM is nil."
3529 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3530 (if fh (apply fh 'start-file-process name buffer program program-args)
3531 (apply 'start-process name buffer program program-args))))
3532 \f
3533 ;;;; Process menu
3534
3535 (defvar tabulated-list-format)
3536 (defvar tabulated-list-entries)
3537 (defvar tabulated-list-sort-key)
3538 (declare-function tabulated-list-init-header "tabulated-list" ())
3539 (declare-function tabulated-list-print "tabulated-list"
3540 (&optional remember-pos update))
3541
3542 (defvar process-menu-query-only nil)
3543
3544 (defvar process-menu-mode-map
3545 (let ((map (make-sparse-keymap)))
3546 (define-key map [?d] 'process-menu-delete-process)
3547 map))
3548
3549 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3550 "Major mode for listing the processes called by Emacs."
3551 (setq tabulated-list-format [("Process" 15 t)
3552 ("Status" 7 t)
3553 ("Buffer" 15 t)
3554 ("TTY" 12 t)
3555 ("Command" 0 t)])
3556 (make-local-variable 'process-menu-query-only)
3557 (setq tabulated-list-sort-key (cons "Process" nil))
3558 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3559 (tabulated-list-init-header))
3560
3561 (defun process-menu-delete-process ()
3562 "Kill process at point in a `list-processes' buffer."
3563 (interactive)
3564 (delete-process (tabulated-list-get-id))
3565 (revert-buffer))
3566
3567 (defun list-processes--refresh ()
3568 "Recompute the list of processes for the Process List buffer.
3569 Also, delete any process that is exited or signaled."
3570 (setq tabulated-list-entries nil)
3571 (dolist (p (process-list))
3572 (cond ((memq (process-status p) '(exit signal closed))
3573 (delete-process p))
3574 ((or (not process-menu-query-only)
3575 (process-query-on-exit-flag p))
3576 (let* ((buf (process-buffer p))
3577 (type (process-type p))
3578 (name (process-name p))
3579 (status (symbol-name (process-status p)))
3580 (buf-label (if (buffer-live-p buf)
3581 `(,(buffer-name buf)
3582 face link
3583 help-echo ,(format-message
3584 "Visit buffer `%s'"
3585 (buffer-name buf))
3586 follow-link t
3587 process-buffer ,buf
3588 action process-menu-visit-buffer)
3589 "--"))
3590 (tty (or (process-tty-name p) "--"))
3591 (cmd
3592 (if (memq type '(network serial))
3593 (let ((contact (process-contact p t)))
3594 (if (eq type 'network)
3595 (format "(%s %s)"
3596 (if (plist-get contact :type)
3597 "datagram"
3598 "network")
3599 (if (plist-get contact :server)
3600 (format "server on %s"
3601 (or
3602 (plist-get contact :host)
3603 (plist-get contact :local)))
3604 (format "connection to %s"
3605 (plist-get contact :host))))
3606 (format "(serial port %s%s)"
3607 (or (plist-get contact :port) "?")
3608 (let ((speed (plist-get contact :speed)))
3609 (if speed
3610 (format " at %s b/s" speed)
3611 "")))))
3612 (mapconcat 'identity (process-command p) " "))))
3613 (push (list p (vector name status buf-label tty cmd))
3614 tabulated-list-entries))))))
3615
3616 (defun process-menu-visit-buffer (button)
3617 (display-buffer (button-get button 'process-buffer)))
3618
3619 (defun list-processes (&optional query-only buffer)
3620 "Display a list of all processes that are Emacs sub-processes.
3621 If optional argument QUERY-ONLY is non-nil, only processes with
3622 the query-on-exit flag set are listed.
3623 Any process listed as exited or signaled is actually eliminated
3624 after the listing is made.
3625 Optional argument BUFFER specifies a buffer to use, instead of
3626 \"*Process List*\".
3627 The return value is always nil.
3628
3629 This function lists only processes that were launched by Emacs. To
3630 see other processes running on the system, use `list-system-processes'."
3631 (interactive)
3632 (or (fboundp 'process-list)
3633 (error "Asynchronous subprocesses are not supported on this system"))
3634 (unless (bufferp buffer)
3635 (setq buffer (get-buffer-create "*Process List*")))
3636 (with-current-buffer buffer
3637 (process-menu-mode)
3638 (setq process-menu-query-only query-only)
3639 (list-processes--refresh)
3640 (tabulated-list-print))
3641 (display-buffer buffer)
3642 nil)
3643 \f
3644 ;;;; Prefix commands
3645
3646 (setq prefix-command--needs-update nil)
3647 (setq prefix-command--last-echo nil)
3648
3649 (defun internal-echo-keystrokes-prefix ()
3650 ;; BEWARE: Called directly from the C code.
3651 (if (not prefix-command--needs-update)
3652 prefix-command--last-echo
3653 (setq prefix-command--last-echo
3654 (let ((strs nil))
3655 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3656 (lambda (fun) (push (funcall fun) strs)))
3657 (setq strs (delq nil strs))
3658 (when strs (mapconcat #'identity strs " "))))))
3659
3660 (defvar prefix-command-echo-keystrokes-functions nil
3661 "Abnormal hook which constructs the description of the current prefix state.
3662 Each function is called with no argument, should return a string or nil.")
3663
3664 (defun prefix-command-update ()
3665 "Update state of prefix commands.
3666 Call it whenever you change the \"prefix command state\"."
3667 (setq prefix-command--needs-update t))
3668
3669 (defvar prefix-command-preserve-state-hook nil
3670 "Normal hook run when a command needs to preserve the prefix.")
3671
3672 (defun prefix-command-preserve-state ()
3673 "Pass the current prefix command state to the next command.
3674 Should be called by all prefix commands.
3675 Runs `prefix-command-preserve-state-hook'."
3676 (run-hooks 'prefix-command-preserve-state-hook)
3677 ;; If the current command is a prefix command, we don't want the next (real)
3678 ;; command to have `last-command' set to, say, `universal-argument'.
3679 (setq this-command last-command)
3680 (setq real-this-command real-last-command)
3681 (prefix-command-update))
3682
3683 (defun reset-this-command-lengths ()
3684 (declare (obsolete prefix-command-preserve-state "25.1"))
3685 nil)
3686
3687 ;;;;; The main prefix command.
3688
3689 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3690
3691 (add-hook 'prefix-command-echo-keystrokes-functions
3692 #'universal-argument--description)
3693 (defun universal-argument--description ()
3694 (when prefix-arg
3695 (concat "C-u"
3696 (pcase prefix-arg
3697 (`(-) " -")
3698 (`(,(and (pred integerp) n))
3699 (let ((str ""))
3700 (while (and (> n 4) (= (mod n 4) 0))
3701 (setq str (concat str " C-u"))
3702 (setq n (/ n 4)))
3703 (if (= n 4) str (format " %s" prefix-arg))))
3704 (_ (format " %s" prefix-arg))))))
3705
3706 (add-hook 'prefix-command-preserve-state-hook
3707 #'universal-argument--preserve)
3708 (defun universal-argument--preserve ()
3709 (setq prefix-arg current-prefix-arg))
3710
3711 (defvar universal-argument-map
3712 (let ((map (make-sparse-keymap))
3713 (universal-argument-minus
3714 ;; For backward compatibility, minus with no modifiers is an ordinary
3715 ;; command if digits have already been entered.
3716 `(menu-item "" negative-argument
3717 :filter ,(lambda (cmd)
3718 (if (integerp prefix-arg) nil cmd)))))
3719 (define-key map [switch-frame]
3720 (lambda (e) (interactive "e")
3721 (handle-switch-frame e) (universal-argument--mode)))
3722 (define-key map [?\C-u] 'universal-argument-more)
3723 (define-key map [?-] universal-argument-minus)
3724 (define-key map [?0] 'digit-argument)
3725 (define-key map [?1] 'digit-argument)
3726 (define-key map [?2] 'digit-argument)
3727 (define-key map [?3] 'digit-argument)
3728 (define-key map [?4] 'digit-argument)
3729 (define-key map [?5] 'digit-argument)
3730 (define-key map [?6] 'digit-argument)
3731 (define-key map [?7] 'digit-argument)
3732 (define-key map [?8] 'digit-argument)
3733 (define-key map [?9] 'digit-argument)
3734 (define-key map [kp-0] 'digit-argument)
3735 (define-key map [kp-1] 'digit-argument)
3736 (define-key map [kp-2] 'digit-argument)
3737 (define-key map [kp-3] 'digit-argument)
3738 (define-key map [kp-4] 'digit-argument)
3739 (define-key map [kp-5] 'digit-argument)
3740 (define-key map [kp-6] 'digit-argument)
3741 (define-key map [kp-7] 'digit-argument)
3742 (define-key map [kp-8] 'digit-argument)
3743 (define-key map [kp-9] 'digit-argument)
3744 (define-key map [kp-subtract] universal-argument-minus)
3745 map)
3746 "Keymap used while processing \\[universal-argument].")
3747
3748 (defun universal-argument--mode ()
3749 (prefix-command-update)
3750 (set-transient-map universal-argument-map nil))
3751
3752 (defun universal-argument ()
3753 "Begin a numeric argument for the following command.
3754 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3755 \\[universal-argument] following the digits or minus sign ends the argument.
3756 \\[universal-argument] without digits or minus sign provides 4 as argument.
3757 Repeating \\[universal-argument] without digits or minus sign
3758 multiplies the argument by 4 each time.
3759 For some commands, just \\[universal-argument] by itself serves as a flag
3760 which is different in effect from any particular numeric argument.
3761 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3762 (interactive)
3763 (prefix-command-preserve-state)
3764 (setq prefix-arg (list 4))
3765 (universal-argument--mode))
3766
3767 (defun universal-argument-more (arg)
3768 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3769 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3770 (interactive "P")
3771 (prefix-command-preserve-state)
3772 (setq prefix-arg (if (consp arg)
3773 (list (* 4 (car arg)))
3774 (if (eq arg '-)
3775 (list -4)
3776 arg)))
3777 (when (consp prefix-arg) (universal-argument--mode)))
3778
3779 (defun negative-argument (arg)
3780 "Begin a negative numeric argument for the next command.
3781 \\[universal-argument] following digits or minus sign ends the argument."
3782 (interactive "P")
3783 (prefix-command-preserve-state)
3784 (setq prefix-arg (cond ((integerp arg) (- arg))
3785 ((eq arg '-) nil)
3786 (t '-)))
3787 (universal-argument--mode))
3788
3789 (defun digit-argument (arg)
3790 "Part of the numeric argument for the next command.
3791 \\[universal-argument] following digits or minus sign ends the argument."
3792 (interactive "P")
3793 (prefix-command-preserve-state)
3794 (let* ((char (if (integerp last-command-event)
3795 last-command-event
3796 (get last-command-event 'ascii-character)))
3797 (digit (- (logand char ?\177) ?0)))
3798 (setq prefix-arg (cond ((integerp arg)
3799 (+ (* arg 10)
3800 (if (< arg 0) (- digit) digit)))
3801 ((eq arg '-)
3802 ;; Treat -0 as just -, so that -01 will work.
3803 (if (zerop digit) '- (- digit)))
3804 (t
3805 digit))))
3806 (universal-argument--mode))
3807 \f
3808
3809 (defvar filter-buffer-substring-functions nil
3810 "This variable is a wrapper hook around `buffer-substring--filter'.")
3811 (make-obsolete-variable 'filter-buffer-substring-functions
3812 'filter-buffer-substring-function "24.4")
3813
3814 (defvar filter-buffer-substring-function #'buffer-substring--filter
3815 "Function to perform the filtering in `filter-buffer-substring'.
3816 The function is called with the same 3 arguments (BEG END DELETE)
3817 that `filter-buffer-substring' received. It should return the
3818 buffer substring between BEG and END, after filtering. If DELETE is
3819 non-nil, it should delete the text between BEG and END from the buffer.")
3820
3821 (defvar buffer-substring-filters nil
3822 "List of filter functions for `buffer-substring--filter'.
3823 Each function must accept a single argument, a string, and return a string.
3824 The buffer substring is passed to the first function in the list,
3825 and the return value of each function is passed to the next.
3826 As a special convention, point is set to the start of the buffer text
3827 being operated on (i.e., the first argument of `buffer-substring--filter')
3828 before these functions are called.")
3829 (make-obsolete-variable 'buffer-substring-filters
3830 'filter-buffer-substring-function "24.1")
3831
3832 (defun filter-buffer-substring (beg end &optional delete)
3833 "Return the buffer substring between BEG and END, after filtering.
3834 If DELETE is non-nil, delete the text between BEG and END from the buffer.
3835
3836 This calls the function that `filter-buffer-substring-function' specifies
3837 \(passing the same three arguments that it received) to do the work,
3838 and returns whatever it does. The default function does no filtering,
3839 unless a hook has been set.
3840
3841 Use `filter-buffer-substring' instead of `buffer-substring',
3842 `buffer-substring-no-properties', or `delete-and-extract-region' when
3843 you want to allow filtering to take place. For example, major or minor
3844 modes can use `filter-buffer-substring-function' to extract characters
3845 that are special to a buffer, and should not be copied into other buffers."
3846 (funcall filter-buffer-substring-function beg end delete))
3847
3848 (defun buffer-substring--filter (beg end &optional delete)
3849 "Default function to use for `filter-buffer-substring-function'.
3850 Its arguments and return value are as specified for `filter-buffer-substring'.
3851 This respects the wrapper hook `filter-buffer-substring-functions',
3852 and the abnormal hook `buffer-substring-filters'.
3853 No filtering is done unless a hook says to."
3854 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
3855 (cond
3856 ((or delete buffer-substring-filters)
3857 (save-excursion
3858 (goto-char beg)
3859 (let ((string (if delete (delete-and-extract-region beg end)
3860 (buffer-substring beg end))))
3861 (dolist (filter buffer-substring-filters)
3862 (setq string (funcall filter string)))
3863 string)))
3864 (t
3865 (buffer-substring beg end)))))
3866
3867
3868 ;;;; Window system cut and paste hooks.
3869
3870 (defvar interprogram-cut-function #'gui-select-text
3871 "Function to call to make a killed region available to other programs.
3872 Most window systems provide a facility for cutting and pasting
3873 text between different programs, such as the clipboard on X and
3874 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3875
3876 This variable holds a function that Emacs calls whenever text is
3877 put in the kill ring, to make the new kill available to other
3878 programs. The function takes one argument, TEXT, which is a
3879 string containing the text which should be made available.")
3880
3881 (defvar interprogram-paste-function #'gui-selection-value
3882 "Function to call to get text cut from other programs.
3883 Most window systems provide a facility for cutting and pasting
3884 text between different programs, such as the clipboard on X and
3885 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3886
3887 This variable holds a function that Emacs calls to obtain text
3888 that other programs have provided for pasting. The function is
3889 called with no arguments. If no other program has provided text
3890 to paste, the function should return nil (in which case the
3891 caller, usually `current-kill', should use the top of the Emacs
3892 kill ring). If another program has provided text to paste, the
3893 function should return that text as a string (in which case the
3894 caller should put this string in the kill ring as the latest
3895 kill).
3896
3897 The function may also return a list of strings if the window
3898 system supports multiple selections. The first string will be
3899 used as the pasted text, but the other will be placed in the kill
3900 ring for easy access via `yank-pop'.
3901
3902 Note that the function should return a string only if a program
3903 other than Emacs has provided a string for pasting; if Emacs
3904 provided the most recent string, the function should return nil.
3905 If it is difficult to tell whether Emacs or some other program
3906 provided the current string, it is probably good enough to return
3907 nil if the string is equal (according to `string=') to the last
3908 text Emacs provided.")
3909 \f
3910
3911
3912 ;;;; The kill ring data structure.
3913
3914 (defvar kill-ring nil
3915 "List of killed text sequences.
3916 Since the kill ring is supposed to interact nicely with cut-and-paste
3917 facilities offered by window systems, use of this variable should
3918 interact nicely with `interprogram-cut-function' and
3919 `interprogram-paste-function'. The functions `kill-new',
3920 `kill-append', and `current-kill' are supposed to implement this
3921 interaction; you may want to use them instead of manipulating the kill
3922 ring directly.")
3923
3924 (defcustom kill-ring-max 60
3925 "Maximum length of kill ring before oldest elements are thrown away."
3926 :type 'integer
3927 :group 'killing)
3928
3929 (defvar kill-ring-yank-pointer nil
3930 "The tail of the kill ring whose car is the last thing yanked.")
3931
3932 (defcustom save-interprogram-paste-before-kill nil
3933 "Save clipboard strings into kill ring before replacing them.
3934 When one selects something in another program to paste it into Emacs,
3935 but kills something in Emacs before actually pasting it,
3936 this selection is gone unless this variable is non-nil,
3937 in which case the other program's selection is saved in the `kill-ring'
3938 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3939 :type 'boolean
3940 :group 'killing
3941 :version "23.2")
3942
3943 (defcustom kill-do-not-save-duplicates nil
3944 "Do not add a new string to `kill-ring' if it duplicates the last one.
3945 The comparison is done using `equal-including-properties'."
3946 :type 'boolean
3947 :group 'killing
3948 :version "23.2")
3949
3950 (defun kill-new (string &optional replace)
3951 "Make STRING the latest kill in the kill ring.
3952 Set `kill-ring-yank-pointer' to point to it.
3953 If `interprogram-cut-function' is non-nil, apply it to STRING.
3954 Optional second argument REPLACE non-nil means that STRING will replace
3955 the front of the kill ring, rather than being added to the list.
3956
3957 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3958 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3959 STRING.
3960
3961 When the yank handler has a non-nil PARAM element, the original STRING
3962 argument is not used by `insert-for-yank'. However, since Lisp code
3963 may access and use elements from the kill ring directly, the STRING
3964 argument should still be a \"useful\" string for such uses."
3965 (unless (and kill-do-not-save-duplicates
3966 ;; Due to text properties such as 'yank-handler that
3967 ;; can alter the contents to yank, comparison using
3968 ;; `equal' is unsafe.
3969 (equal-including-properties string (car kill-ring)))
3970 (if (fboundp 'menu-bar-update-yank-menu)
3971 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3972 (when save-interprogram-paste-before-kill
3973 (let ((interprogram-paste (and interprogram-paste-function
3974 (funcall interprogram-paste-function))))
3975 (when interprogram-paste
3976 (dolist (s (if (listp interprogram-paste)
3977 (nreverse interprogram-paste)
3978 (list interprogram-paste)))
3979 (unless (and kill-do-not-save-duplicates
3980 (equal-including-properties s (car kill-ring)))
3981 (push s kill-ring))))))
3982 (unless (and kill-do-not-save-duplicates
3983 (equal-including-properties string (car kill-ring)))
3984 (if (and replace kill-ring)
3985 (setcar kill-ring string)
3986 (push string kill-ring)
3987 (if (> (length kill-ring) kill-ring-max)
3988 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3989 (setq kill-ring-yank-pointer kill-ring)
3990 (if interprogram-cut-function
3991 (funcall interprogram-cut-function string)))
3992
3993 ;; It has been argued that this should work similar to `self-insert-command'
3994 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
3995 (defcustom kill-append-merge-undo nil
3996 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
3997 :type 'boolean
3998 :group 'killing
3999 :version "25.1")
4000
4001 (defun kill-append (string before-p)
4002 "Append STRING to the end of the latest kill in the kill ring.
4003 If BEFORE-P is non-nil, prepend STRING to the kill.
4004 Also removes the last undo boundary in the current buffer,
4005 depending on `kill-append-merge-undo'.
4006 If `interprogram-cut-function' is set, pass the resulting kill to it."
4007 (let* ((cur (car kill-ring)))
4008 (kill-new (if before-p (concat string cur) (concat cur string))
4009 (or (= (length cur) 0)
4010 (equal nil (get-text-property 0 'yank-handler cur))))
4011 (when (and kill-append-merge-undo (not buffer-read-only))
4012 (let ((prev buffer-undo-list)
4013 (next (cdr buffer-undo-list)))
4014 ;; find the next undo boundary
4015 (while (car next)
4016 (pop next)
4017 (pop prev))
4018 ;; remove this undo boundary
4019 (when prev
4020 (setcdr prev (cdr next)))))))
4021
4022 (defcustom yank-pop-change-selection nil
4023 "Whether rotating the kill ring changes the window system selection.
4024 If non-nil, whenever the kill ring is rotated (usually via the
4025 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4026 to copy the new kill to the window system selection."
4027 :type 'boolean
4028 :group 'killing
4029 :version "23.1")
4030
4031 (defun current-kill (n &optional do-not-move)
4032 "Rotate the yanking point by N places, and then return that kill.
4033 If N is zero and `interprogram-paste-function' is set to a
4034 function that returns a string or a list of strings, and if that
4035 function doesn't return nil, then that string (or list) is added
4036 to the front of the kill ring and the string (or first string in
4037 the list) is returned as the latest kill.
4038
4039 If N is not zero, and if `yank-pop-change-selection' is
4040 non-nil, use `interprogram-cut-function' to transfer the
4041 kill at the new yank point into the window system selection.
4042
4043 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4044 move the yanking point; just return the Nth kill forward."
4045
4046 (let ((interprogram-paste (and (= n 0)
4047 interprogram-paste-function
4048 (funcall interprogram-paste-function))))
4049 (if interprogram-paste
4050 (progn
4051 ;; Disable the interprogram cut function when we add the new
4052 ;; text to the kill ring, so Emacs doesn't try to own the
4053 ;; selection, with identical text.
4054 (let ((interprogram-cut-function nil))
4055 (if (listp interprogram-paste)
4056 (mapc 'kill-new (nreverse interprogram-paste))
4057 (kill-new interprogram-paste)))
4058 (car kill-ring))
4059 (or kill-ring (error "Kill ring is empty"))
4060 (let ((ARGth-kill-element
4061 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4062 (length kill-ring))
4063 kill-ring)))
4064 (unless do-not-move
4065 (setq kill-ring-yank-pointer ARGth-kill-element)
4066 (when (and yank-pop-change-selection
4067 (> n 0)
4068 interprogram-cut-function)
4069 (funcall interprogram-cut-function (car ARGth-kill-element))))
4070 (car ARGth-kill-element)))))
4071
4072
4073
4074 ;;;; Commands for manipulating the kill ring.
4075
4076 (defcustom kill-read-only-ok nil
4077 "Non-nil means don't signal an error for killing read-only text."
4078 :type 'boolean
4079 :group 'killing)
4080
4081 (defun kill-region (beg end &optional region)
4082 "Kill (\"cut\") text between point and mark.
4083 This deletes the text from the buffer and saves it in the kill ring.
4084 The command \\[yank] can retrieve it from there.
4085 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4086
4087 If you want to append the killed region to the last killed text,
4088 use \\[append-next-kill] before \\[kill-region].
4089
4090 If the buffer is read-only, Emacs will beep and refrain from deleting
4091 the text, but put the text in the kill ring anyway. This means that
4092 you can use the killing commands to copy text from a read-only buffer.
4093
4094 Lisp programs should use this function for killing text.
4095 (To delete text, use `delete-region'.)
4096 Supply two arguments, character positions indicating the stretch of text
4097 to be killed.
4098 Any command that calls this function is a \"kill command\".
4099 If the previous command was also a kill command,
4100 the text killed this time appends to the text killed last time
4101 to make one entry in the kill ring.
4102
4103 The optional argument REGION if non-nil, indicates that we're not just killing
4104 some text between BEG and END, but we're killing the region."
4105 ;; Pass mark first, then point, because the order matters when
4106 ;; calling `kill-append'.
4107 (interactive (list (mark) (point) 'region))
4108 (unless (and beg end)
4109 (user-error "The mark is not set now, so there is no region"))
4110 (condition-case nil
4111 (let ((string (if region
4112 (funcall region-extract-function 'delete)
4113 (filter-buffer-substring beg end 'delete))))
4114 (when string ;STRING is nil if BEG = END
4115 ;; Add that string to the kill ring, one way or another.
4116 (if (eq last-command 'kill-region)
4117 (kill-append string (< end beg))
4118 (kill-new string)))
4119 (when (or string (eq last-command 'kill-region))
4120 (setq this-command 'kill-region))
4121 (setq deactivate-mark t)
4122 nil)
4123 ((buffer-read-only text-read-only)
4124 ;; The code above failed because the buffer, or some of the characters
4125 ;; in the region, are read-only.
4126 ;; We should beep, in case the user just isn't aware of this.
4127 ;; However, there's no harm in putting
4128 ;; the region's text in the kill ring, anyway.
4129 (copy-region-as-kill beg end region)
4130 ;; Set this-command now, so it will be set even if we get an error.
4131 (setq this-command 'kill-region)
4132 ;; This should barf, if appropriate, and give us the correct error.
4133 (if kill-read-only-ok
4134 (progn (message "Read only text copied to kill ring") nil)
4135 ;; Signal an error if the buffer is read-only.
4136 (barf-if-buffer-read-only)
4137 ;; If the buffer isn't read-only, the text is.
4138 (signal 'text-read-only (list (current-buffer)))))))
4139
4140 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4141 ;; to get two copies of the text when the user accidentally types M-w and
4142 ;; then corrects it with the intended C-w.
4143 (defun copy-region-as-kill (beg end &optional region)
4144 "Save the region as if killed, but don't kill it.
4145 In Transient Mark mode, deactivate the mark.
4146 If `interprogram-cut-function' is non-nil, also save the text for a window
4147 system cut and paste.
4148
4149 The optional argument REGION if non-nil, indicates that we're not just copying
4150 some text between BEG and END, but we're copying the region.
4151
4152 This command's old key binding has been given to `kill-ring-save'."
4153 ;; Pass mark first, then point, because the order matters when
4154 ;; calling `kill-append'.
4155 (interactive (list (mark) (point)
4156 (prefix-numeric-value current-prefix-arg)))
4157 (let ((str (if region
4158 (funcall region-extract-function nil)
4159 (filter-buffer-substring beg end))))
4160 (if (eq last-command 'kill-region)
4161 (kill-append str (< end beg))
4162 (kill-new str)))
4163 (setq deactivate-mark t)
4164 nil)
4165
4166 (defun kill-ring-save (beg end &optional region)
4167 "Save the region as if killed, but don't kill it.
4168 In Transient Mark mode, deactivate the mark.
4169 If `interprogram-cut-function' is non-nil, also save the text for a window
4170 system cut and paste.
4171
4172 If you want to append the killed line to the last killed text,
4173 use \\[append-next-kill] before \\[kill-ring-save].
4174
4175 The optional argument REGION if non-nil, indicates that we're not just copying
4176 some text between BEG and END, but we're copying the region.
4177
4178 This command is similar to `copy-region-as-kill', except that it gives
4179 visual feedback indicating the extent of the region being copied."
4180 ;; Pass mark first, then point, because the order matters when
4181 ;; calling `kill-append'.
4182 (interactive (list (mark) (point)
4183 (prefix-numeric-value current-prefix-arg)))
4184 (copy-region-as-kill beg end region)
4185 ;; This use of called-interactively-p is correct because the code it
4186 ;; controls just gives the user visual feedback.
4187 (if (called-interactively-p 'interactive)
4188 (indicate-copied-region)))
4189
4190 (defun indicate-copied-region (&optional message-len)
4191 "Indicate that the region text has been copied interactively.
4192 If the mark is visible in the selected window, blink the cursor
4193 between point and mark if there is currently no active region
4194 highlighting.
4195
4196 If the mark lies outside the selected window, display an
4197 informative message containing a sample of the copied text. The
4198 optional argument MESSAGE-LEN, if non-nil, specifies the length
4199 of this sample text; it defaults to 40."
4200 (let ((mark (mark t))
4201 (point (point))
4202 ;; Inhibit quitting so we can make a quit here
4203 ;; look like a C-g typed as a command.
4204 (inhibit-quit t))
4205 (if (pos-visible-in-window-p mark (selected-window))
4206 ;; Swap point-and-mark quickly so as to show the region that
4207 ;; was selected. Don't do it if the region is highlighted.
4208 (unless (and (region-active-p)
4209 (face-background 'region))
4210 ;; Swap point and mark.
4211 (set-marker (mark-marker) (point) (current-buffer))
4212 (goto-char mark)
4213 (sit-for blink-matching-delay)
4214 ;; Swap back.
4215 (set-marker (mark-marker) mark (current-buffer))
4216 (goto-char point)
4217 ;; If user quit, deactivate the mark
4218 ;; as C-g would as a command.
4219 (and quit-flag (region-active-p)
4220 (deactivate-mark)))
4221 (let ((len (min (abs (- mark point))
4222 (or message-len 40))))
4223 (if (< point mark)
4224 ;; Don't say "killed"; that is misleading.
4225 (message "Saved text until \"%s\""
4226 (buffer-substring-no-properties (- mark len) mark))
4227 (message "Saved text from \"%s\""
4228 (buffer-substring-no-properties mark (+ mark len))))))))
4229
4230 (defun append-next-kill (&optional interactive)
4231 "Cause following command, if it kills, to add to previous kill.
4232 If the next command kills forward from point, the kill is
4233 appended to the previous killed text. If the command kills
4234 backward, the kill is prepended. Kill commands that act on the
4235 region, such as `kill-region', are regarded as killing forward if
4236 point is after mark, and killing backward if point is before
4237 mark.
4238
4239 If the next command is not a kill command, `append-next-kill' has
4240 no effect.
4241
4242 The argument is used for internal purposes; do not supply one."
4243 (interactive "p")
4244 ;; We don't use (interactive-p), since that breaks kbd macros.
4245 (if interactive
4246 (progn
4247 (setq this-command 'kill-region)
4248 (message "If the next command is a kill, it will append"))
4249 (setq last-command 'kill-region)))
4250
4251 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4252 "Character set that matches bidirectional formatting control characters.")
4253
4254 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4255 "Character set that matches any character except bidirectional controls.")
4256
4257 (defun squeeze-bidi-context-1 (from to category replacement)
4258 "A subroutine of `squeeze-bidi-context'.
4259 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4260 (let ((pt (copy-marker from))
4261 (limit (copy-marker to))
4262 (old-pt 0)
4263 lim1)
4264 (setq lim1 limit)
4265 (goto-char pt)
4266 (while (< pt limit)
4267 (if (> pt old-pt)
4268 (move-marker lim1
4269 (save-excursion
4270 ;; L and R categories include embedding and
4271 ;; override controls, but we don't want to
4272 ;; replace them, because that might change
4273 ;; the visual order. Likewise with PDF and
4274 ;; isolate controls.
4275 (+ pt (skip-chars-forward
4276 bidi-directional-non-controls-chars
4277 limit)))))
4278 ;; Replace any run of non-RTL characters by a single LRM.
4279 (if (null (re-search-forward category lim1 t))
4280 ;; No more characters of CATEGORY, we are done.
4281 (setq pt limit)
4282 (replace-match replacement nil t)
4283 (move-marker pt (point)))
4284 (setq old-pt pt)
4285 ;; Skip directional controls, if any.
4286 (move-marker
4287 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4288
4289 (defun squeeze-bidi-context (from to)
4290 "Replace characters between FROM and TO while keeping bidi context.
4291
4292 This function replaces the region of text with as few characters
4293 as possible, while preserving the effect that region will have on
4294 bidirectional display before and after the region."
4295 (let ((start (set-marker (make-marker)
4296 (if (> from 0) from (+ (point-max) from))))
4297 (end (set-marker (make-marker) to))
4298 ;; This is for when they copy text with read-only text
4299 ;; properties.
4300 (inhibit-read-only t))
4301 (if (null (marker-position end))
4302 (setq end (point-max-marker)))
4303 ;; Replace each run of non-RTL characters with a single LRM.
4304 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4305 ;; Replace each run of non-LTR characters with a single RLM. Note
4306 ;; that the \cR category includes both the Arabic Letter (AL) and
4307 ;; R characters; here we ignore the distinction between them,
4308 ;; because that distinction only affects Arabic Number (AN)
4309 ;; characters, which are weak and don't affect the reordering.
4310 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4311
4312 (defun line-substring-with-bidi-context (start end &optional no-properties)
4313 "Return buffer text between START and END with its bidi context.
4314
4315 START and END are assumed to belong to the same physical line
4316 of buffer text. This function prepends and appends to the text
4317 between START and END bidi control characters that preserve the
4318 visual order of that text when it is inserted at some other place."
4319 (if (or (< start (point-min))
4320 (> end (point-max)))
4321 (signal 'args-out-of-range (list (current-buffer) start end)))
4322 (let ((buf (current-buffer))
4323 substr para-dir from to)
4324 (save-excursion
4325 (goto-char start)
4326 (setq para-dir (current-bidi-paragraph-direction))
4327 (setq from (line-beginning-position)
4328 to (line-end-position))
4329 (goto-char from)
4330 ;; If we don't have any mixed directional characters in the
4331 ;; entire line, we can just copy the substring without adding
4332 ;; any context.
4333 (if (or (looking-at-p "\\CR*$")
4334 (looking-at-p "\\CL*$"))
4335 (setq substr (if no-properties
4336 (buffer-substring-no-properties start end)
4337 (buffer-substring start end)))
4338 (setq substr
4339 (with-temp-buffer
4340 (if no-properties
4341 (insert-buffer-substring-no-properties buf from to)
4342 (insert-buffer-substring buf from to))
4343 (squeeze-bidi-context 1 (1+ (- start from)))
4344 (squeeze-bidi-context (- end to) nil)
4345 (buffer-substring 1 (point-max)))))
4346
4347 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4348 ;; (1) force the string to have the same base embedding
4349 ;; direction as the paragraph direction at the source, no matter
4350 ;; what is the paragraph direction at destination; and (2) avoid
4351 ;; affecting the visual order of the surrounding text at
4352 ;; destination if there are characters of different
4353 ;; directionality there.
4354 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4355 substr "\x2069"))))
4356
4357 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4358 "Return portion of current buffer between START and END with bidi context.
4359
4360 This function works similar to `buffer-substring', but it prepends and
4361 appends to the text bidi directional control characters necessary to
4362 preserve the visual appearance of the text if it is inserted at another
4363 place. This is useful when the buffer substring includes bidirectional
4364 text and control characters that cause non-trivial reordering on display.
4365 If copied verbatim, such text can have a very different visual appearance,
4366 and can also change the visual appearance of the surrounding text at the
4367 destination of the copy.
4368
4369 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4370 the text properties."
4371 (let (line-end substr)
4372 (if (or (< start (point-min))
4373 (> end (point-max)))
4374 (signal 'args-out-of-range (list (current-buffer) start end)))
4375 (save-excursion
4376 (goto-char start)
4377 (setq line-end (min end (line-end-position)))
4378 (while (< start end)
4379 (setq substr
4380 (concat substr
4381 (if substr "\n" "")
4382 (line-substring-with-bidi-context start line-end
4383 no-properties)))
4384 (forward-line 1)
4385 (setq start (point))
4386 (setq line-end (min end (line-end-position))))
4387 substr)))
4388 \f
4389 ;; Yanking.
4390
4391 (defcustom yank-handled-properties
4392 '((font-lock-face . yank-handle-font-lock-face-property)
4393 (category . yank-handle-category-property))
4394 "List of special text property handling conditions for yanking.
4395 Each element should have the form (PROP . FUN), where PROP is a
4396 property symbol and FUN is a function. When the `yank' command
4397 inserts text into the buffer, it scans the inserted text for
4398 stretches of text that have `eq' values of the text property
4399 PROP; for each such stretch of text, FUN is called with three
4400 arguments: the property's value in that text, and the start and
4401 end positions of the text.
4402
4403 This is done prior to removing the properties specified by
4404 `yank-excluded-properties'."
4405 :group 'killing
4406 :type '(repeat (cons (symbol :tag "property symbol")
4407 function))
4408 :version "24.3")
4409
4410 ;; This is actually used in subr.el but defcustom does not work there.
4411 (defcustom yank-excluded-properties
4412 '(category field follow-link fontified font-lock-face help-echo
4413 intangible invisible keymap local-map mouse-face read-only
4414 yank-handler)
4415 "Text properties to discard when yanking.
4416 The value should be a list of text properties to discard or t,
4417 which means to discard all text properties.
4418
4419 See also `yank-handled-properties'."
4420 :type '(choice (const :tag "All" t) (repeat symbol))
4421 :group 'killing
4422 :version "24.3")
4423
4424 (defvar yank-window-start nil)
4425 (defvar yank-undo-function nil
4426 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4427 Function is called with two parameters, START and END corresponding to
4428 the value of the mark and point; it is guaranteed that START <= END.
4429 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4430
4431 (defun yank-pop (&optional arg)
4432 "Replace just-yanked stretch of killed text with a different stretch.
4433 This command is allowed only immediately after a `yank' or a `yank-pop'.
4434 At such a time, the region contains a stretch of reinserted
4435 previously-killed text. `yank-pop' deletes that text and inserts in its
4436 place a different stretch of killed text.
4437
4438 With no argument, the previous kill is inserted.
4439 With argument N, insert the Nth previous kill.
4440 If N is negative, this is a more recent kill.
4441
4442 The sequence of kills wraps around, so that after the oldest one
4443 comes the newest one.
4444
4445 When this command inserts killed text into the buffer, it honors
4446 `yank-excluded-properties' and `yank-handler' as described in the
4447 doc string for `insert-for-yank-1', which see."
4448 (interactive "*p")
4449 (if (not (eq last-command 'yank))
4450 (user-error "Previous command was not a yank"))
4451 (setq this-command 'yank)
4452 (unless arg (setq arg 1))
4453 (let ((inhibit-read-only t)
4454 (before (< (point) (mark t))))
4455 (if before
4456 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4457 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4458 (setq yank-undo-function nil)
4459 (set-marker (mark-marker) (point) (current-buffer))
4460 (insert-for-yank (current-kill arg))
4461 ;; Set the window start back where it was in the yank command,
4462 ;; if possible.
4463 (set-window-start (selected-window) yank-window-start t)
4464 (if before
4465 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4466 ;; It is cleaner to avoid activation, even though the command
4467 ;; loop would deactivate the mark because we inserted text.
4468 (goto-char (prog1 (mark t)
4469 (set-marker (mark-marker) (point) (current-buffer))))))
4470 nil)
4471
4472 (defun yank (&optional arg)
4473 "Reinsert (\"paste\") the last stretch of killed text.
4474 More precisely, reinsert the most recent kill, which is the
4475 stretch of killed text most recently killed OR yanked. Put point
4476 at the end, and set mark at the beginning without activating it.
4477 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4478 With argument N, reinsert the Nth most recent kill.
4479
4480 When this command inserts text into the buffer, it honors the
4481 `yank-handled-properties' and `yank-excluded-properties'
4482 variables, and the `yank-handler' text property. See
4483 `insert-for-yank-1' for details.
4484
4485 See also the command `yank-pop' (\\[yank-pop])."
4486 (interactive "*P")
4487 (setq yank-window-start (window-start))
4488 ;; If we don't get all the way thru, make last-command indicate that
4489 ;; for the following command.
4490 (setq this-command t)
4491 (push-mark (point))
4492 (insert-for-yank (current-kill (cond
4493 ((listp arg) 0)
4494 ((eq arg '-) -2)
4495 (t (1- arg)))))
4496 (if (consp arg)
4497 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4498 ;; It is cleaner to avoid activation, even though the command
4499 ;; loop would deactivate the mark because we inserted text.
4500 (goto-char (prog1 (mark t)
4501 (set-marker (mark-marker) (point) (current-buffer)))))
4502 ;; If we do get all the way thru, make this-command indicate that.
4503 (if (eq this-command t)
4504 (setq this-command 'yank))
4505 nil)
4506
4507 (defun rotate-yank-pointer (arg)
4508 "Rotate the yanking point in the kill ring.
4509 With ARG, rotate that many kills forward (or backward, if negative)."
4510 (interactive "p")
4511 (current-kill arg))
4512 \f
4513 ;; Some kill commands.
4514
4515 ;; Internal subroutine of delete-char
4516 (defun kill-forward-chars (arg)
4517 (if (listp arg) (setq arg (car arg)))
4518 (if (eq arg '-) (setq arg -1))
4519 (kill-region (point) (+ (point) arg)))
4520
4521 ;; Internal subroutine of backward-delete-char
4522 (defun kill-backward-chars (arg)
4523 (if (listp arg) (setq arg (car arg)))
4524 (if (eq arg '-) (setq arg -1))
4525 (kill-region (point) (- (point) arg)))
4526
4527 (defcustom backward-delete-char-untabify-method 'untabify
4528 "The method for untabifying when deleting backward.
4529 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4530 `hungry' -- delete all whitespace, both tabs and spaces;
4531 `all' -- delete all whitespace, including tabs, spaces and newlines;
4532 nil -- just delete one character."
4533 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4534 :version "20.3"
4535 :group 'killing)
4536
4537 (defun backward-delete-char-untabify (arg &optional killp)
4538 "Delete characters backward, changing tabs into spaces.
4539 The exact behavior depends on `backward-delete-char-untabify-method'.
4540 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4541 Interactively, ARG is the prefix arg (default 1)
4542 and KILLP is t if a prefix arg was specified."
4543 (interactive "*p\nP")
4544 (when (eq backward-delete-char-untabify-method 'untabify)
4545 (let ((count arg))
4546 (save-excursion
4547 (while (and (> count 0) (not (bobp)))
4548 (if (= (preceding-char) ?\t)
4549 (let ((col (current-column)))
4550 (forward-char -1)
4551 (setq col (- col (current-column)))
4552 (insert-char ?\s col)
4553 (delete-char 1)))
4554 (forward-char -1)
4555 (setq count (1- count))))))
4556 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4557 ((eq backward-delete-char-untabify-method 'all)
4558 " \t\n\r")))
4559 (n (if skip
4560 (let* ((oldpt (point))
4561 (wh (- oldpt (save-excursion
4562 (skip-chars-backward skip)
4563 (constrain-to-field nil oldpt)))))
4564 (+ arg (if (zerop wh) 0 (1- wh))))
4565 arg)))
4566 ;; Avoid warning about delete-backward-char
4567 (with-no-warnings (delete-backward-char n killp))))
4568
4569 (defun zap-to-char (arg char)
4570 "Kill up to and including ARGth occurrence of CHAR.
4571 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4572 Goes backward if ARG is negative; error if CHAR not found."
4573 (interactive (list (prefix-numeric-value current-prefix-arg)
4574 (read-char "Zap to char: " t)))
4575 ;; Avoid "obsolete" warnings for translation-table-for-input.
4576 (with-no-warnings
4577 (if (char-table-p translation-table-for-input)
4578 (setq char (or (aref translation-table-for-input char) char))))
4579 (kill-region (point) (progn
4580 (search-forward (char-to-string char) nil nil arg)
4581 (point))))
4582
4583 ;; kill-line and its subroutines.
4584
4585 (defcustom kill-whole-line nil
4586 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4587 :type 'boolean
4588 :group 'killing)
4589
4590 (defun kill-line (&optional arg)
4591 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4592 With prefix argument ARG, kill that many lines from point.
4593 Negative arguments kill lines backward.
4594 With zero argument, kills the text before point on the current line.
4595
4596 When calling from a program, nil means \"no arg\",
4597 a number counts as a prefix arg.
4598
4599 To kill a whole line, when point is not at the beginning, type \
4600 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4601
4602 If `show-trailing-whitespace' is non-nil, this command will just
4603 kill the rest of the current line, even if there are only
4604 nonblanks there.
4605
4606 If option `kill-whole-line' is non-nil, then this command kills the whole line
4607 including its terminating newline, when used at the beginning of a line
4608 with no argument. As a consequence, you can always kill a whole line
4609 by typing \\[move-beginning-of-line] \\[kill-line].
4610
4611 If you want to append the killed line to the last killed text,
4612 use \\[append-next-kill] before \\[kill-line].
4613
4614 If the buffer is read-only, Emacs will beep and refrain from deleting
4615 the line, but put the line in the kill ring anyway. This means that
4616 you can use this command to copy text from a read-only buffer.
4617 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4618 even beep.)"
4619 (interactive "P")
4620 (kill-region (point)
4621 ;; It is better to move point to the other end of the kill
4622 ;; before killing. That way, in a read-only buffer, point
4623 ;; moves across the text that is copied to the kill ring.
4624 ;; The choice has no effect on undo now that undo records
4625 ;; the value of point from before the command was run.
4626 (progn
4627 (if arg
4628 (forward-visible-line (prefix-numeric-value arg))
4629 (if (eobp)
4630 (signal 'end-of-buffer nil))
4631 (let ((end
4632 (save-excursion
4633 (end-of-visible-line) (point))))
4634 (if (or (save-excursion
4635 ;; If trailing whitespace is visible,
4636 ;; don't treat it as nothing.
4637 (unless show-trailing-whitespace
4638 (skip-chars-forward " \t" end))
4639 (= (point) end))
4640 (and kill-whole-line (bolp)))
4641 (forward-visible-line 1)
4642 (goto-char end))))
4643 (point))))
4644
4645 (defun kill-whole-line (&optional arg)
4646 "Kill current line.
4647 With prefix ARG, kill that many lines starting from the current line.
4648 If ARG is negative, kill backward. Also kill the preceding newline.
4649 \(This is meant to make \\[repeat] work well with negative arguments.)
4650 If ARG is zero, kill current line but exclude the trailing newline."
4651 (interactive "p")
4652 (or arg (setq arg 1))
4653 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4654 (signal 'end-of-buffer nil))
4655 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4656 (signal 'beginning-of-buffer nil))
4657 (unless (eq last-command 'kill-region)
4658 (kill-new "")
4659 (setq last-command 'kill-region))
4660 (cond ((zerop arg)
4661 ;; We need to kill in two steps, because the previous command
4662 ;; could have been a kill command, in which case the text
4663 ;; before point needs to be prepended to the current kill
4664 ;; ring entry and the text after point appended. Also, we
4665 ;; need to use save-excursion to avoid copying the same text
4666 ;; twice to the kill ring in read-only buffers.
4667 (save-excursion
4668 (kill-region (point) (progn (forward-visible-line 0) (point))))
4669 (kill-region (point) (progn (end-of-visible-line) (point))))
4670 ((< arg 0)
4671 (save-excursion
4672 (kill-region (point) (progn (end-of-visible-line) (point))))
4673 (kill-region (point)
4674 (progn (forward-visible-line (1+ arg))
4675 (unless (bobp) (backward-char))
4676 (point))))
4677 (t
4678 (save-excursion
4679 (kill-region (point) (progn (forward-visible-line 0) (point))))
4680 (kill-region (point)
4681 (progn (forward-visible-line arg) (point))))))
4682
4683 (defun forward-visible-line (arg)
4684 "Move forward by ARG lines, ignoring currently invisible newlines only.
4685 If ARG is negative, move backward -ARG lines.
4686 If ARG is zero, move to the beginning of the current line."
4687 (condition-case nil
4688 (if (> arg 0)
4689 (progn
4690 (while (> arg 0)
4691 (or (zerop (forward-line 1))
4692 (signal 'end-of-buffer nil))
4693 ;; If the newline we just skipped is invisible,
4694 ;; don't count it.
4695 (let ((prop
4696 (get-char-property (1- (point)) 'invisible)))
4697 (if (if (eq buffer-invisibility-spec t)
4698 prop
4699 (or (memq prop buffer-invisibility-spec)
4700 (assq prop buffer-invisibility-spec)))
4701 (setq arg (1+ arg))))
4702 (setq arg (1- arg)))
4703 ;; If invisible text follows, and it is a number of complete lines,
4704 ;; skip it.
4705 (let ((opoint (point)))
4706 (while (and (not (eobp))
4707 (let ((prop
4708 (get-char-property (point) 'invisible)))
4709 (if (eq buffer-invisibility-spec t)
4710 prop
4711 (or (memq prop buffer-invisibility-spec)
4712 (assq prop buffer-invisibility-spec)))))
4713 (goto-char
4714 (if (get-text-property (point) 'invisible)
4715 (or (next-single-property-change (point) 'invisible)
4716 (point-max))
4717 (next-overlay-change (point)))))
4718 (unless (bolp)
4719 (goto-char opoint))))
4720 (let ((first t))
4721 (while (or first (<= arg 0))
4722 (if first
4723 (beginning-of-line)
4724 (or (zerop (forward-line -1))
4725 (signal 'beginning-of-buffer nil)))
4726 ;; If the newline we just moved to is invisible,
4727 ;; don't count it.
4728 (unless (bobp)
4729 (let ((prop
4730 (get-char-property (1- (point)) 'invisible)))
4731 (unless (if (eq buffer-invisibility-spec t)
4732 prop
4733 (or (memq prop buffer-invisibility-spec)
4734 (assq prop buffer-invisibility-spec)))
4735 (setq arg (1+ arg)))))
4736 (setq first nil))
4737 ;; If invisible text follows, and it is a number of complete lines,
4738 ;; skip it.
4739 (let ((opoint (point)))
4740 (while (and (not (bobp))
4741 (let ((prop
4742 (get-char-property (1- (point)) 'invisible)))
4743 (if (eq buffer-invisibility-spec t)
4744 prop
4745 (or (memq prop buffer-invisibility-spec)
4746 (assq prop buffer-invisibility-spec)))))
4747 (goto-char
4748 (if (get-text-property (1- (point)) 'invisible)
4749 (or (previous-single-property-change (point) 'invisible)
4750 (point-min))
4751 (previous-overlay-change (point)))))
4752 (unless (bolp)
4753 (goto-char opoint)))))
4754 ((beginning-of-buffer end-of-buffer)
4755 nil)))
4756
4757 (defun end-of-visible-line ()
4758 "Move to end of current visible line."
4759 (end-of-line)
4760 ;; If the following character is currently invisible,
4761 ;; skip all characters with that same `invisible' property value,
4762 ;; then find the next newline.
4763 (while (and (not (eobp))
4764 (save-excursion
4765 (skip-chars-forward "^\n")
4766 (let ((prop
4767 (get-char-property (point) 'invisible)))
4768 (if (eq buffer-invisibility-spec t)
4769 prop
4770 (or (memq prop buffer-invisibility-spec)
4771 (assq prop buffer-invisibility-spec))))))
4772 (skip-chars-forward "^\n")
4773 (if (get-text-property (point) 'invisible)
4774 (goto-char (or (next-single-property-change (point) 'invisible)
4775 (point-max)))
4776 (goto-char (next-overlay-change (point))))
4777 (end-of-line)))
4778 \f
4779 (defun insert-buffer (buffer)
4780 "Insert after point the contents of BUFFER.
4781 Puts mark after the inserted text.
4782 BUFFER may be a buffer or a buffer name."
4783 (declare (interactive-only insert-buffer-substring))
4784 (interactive
4785 (list
4786 (progn
4787 (barf-if-buffer-read-only)
4788 (read-buffer "Insert buffer: "
4789 (if (eq (selected-window) (next-window))
4790 (other-buffer (current-buffer))
4791 (window-buffer (next-window)))
4792 t))))
4793 (push-mark
4794 (save-excursion
4795 (insert-buffer-substring (get-buffer buffer))
4796 (point)))
4797 nil)
4798
4799 (defun append-to-buffer (buffer start end)
4800 "Append to specified buffer the text of the region.
4801 It is inserted into that buffer before its point.
4802
4803 When calling from a program, give three arguments:
4804 BUFFER (or buffer name), START and END.
4805 START and END specify the portion of the current buffer to be copied."
4806 (interactive
4807 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
4808 (region-beginning) (region-end)))
4809 (let* ((oldbuf (current-buffer))
4810 (append-to (get-buffer-create buffer))
4811 (windows (get-buffer-window-list append-to t t))
4812 point)
4813 (save-excursion
4814 (with-current-buffer append-to
4815 (setq point (point))
4816 (barf-if-buffer-read-only)
4817 (insert-buffer-substring oldbuf start end)
4818 (dolist (window windows)
4819 (when (= (window-point window) point)
4820 (set-window-point window (point))))))))
4821
4822 (defun prepend-to-buffer (buffer start end)
4823 "Prepend to specified buffer the text of the region.
4824 It is inserted into that buffer after its point.
4825
4826 When calling from a program, give three arguments:
4827 BUFFER (or buffer name), START and END.
4828 START and END specify the portion of the current buffer to be copied."
4829 (interactive "BPrepend to buffer: \nr")
4830 (let ((oldbuf (current-buffer)))
4831 (with-current-buffer (get-buffer-create buffer)
4832 (barf-if-buffer-read-only)
4833 (save-excursion
4834 (insert-buffer-substring oldbuf start end)))))
4835
4836 (defun copy-to-buffer (buffer start end)
4837 "Copy to specified buffer the text of the region.
4838 It is inserted into that buffer, replacing existing text there.
4839
4840 When calling from a program, give three arguments:
4841 BUFFER (or buffer name), START and END.
4842 START and END specify the portion of the current buffer to be copied."
4843 (interactive "BCopy to buffer: \nr")
4844 (let ((oldbuf (current-buffer)))
4845 (with-current-buffer (get-buffer-create buffer)
4846 (barf-if-buffer-read-only)
4847 (erase-buffer)
4848 (save-excursion
4849 (insert-buffer-substring oldbuf start end)))))
4850 \f
4851 (define-error 'mark-inactive (purecopy "The mark is not active now"))
4852
4853 (defvar activate-mark-hook nil
4854 "Hook run when the mark becomes active.
4855 It is also run at the end of a command, if the mark is active and
4856 it is possible that the region may have changed.")
4857
4858 (defvar deactivate-mark-hook nil
4859 "Hook run when the mark becomes inactive.")
4860
4861 (defun mark (&optional force)
4862 "Return this buffer's mark value as integer, or nil if never set.
4863
4864 In Transient Mark mode, this function signals an error if
4865 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4866 or the argument FORCE is non-nil, it disregards whether the mark
4867 is active, and returns an integer or nil in the usual way.
4868
4869 If you are using this in an editing command, you are most likely making
4870 a mistake; see the documentation of `set-mark'."
4871 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
4872 (marker-position (mark-marker))
4873 (signal 'mark-inactive nil)))
4874
4875 ;; Behind display-selections-p.
4876
4877 (defun deactivate-mark (&optional force)
4878 "Deactivate the mark.
4879 If Transient Mark mode is disabled, this function normally does
4880 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4881
4882 Deactivating the mark sets `mark-active' to nil, updates the
4883 primary selection according to `select-active-regions', and runs
4884 `deactivate-mark-hook'.
4885
4886 If Transient Mark mode was temporarily enabled, reset the value
4887 of the variable `transient-mark-mode'; if this causes Transient
4888 Mark mode to be disabled, don't change `mark-active' to nil or
4889 run `deactivate-mark-hook'."
4890 (when (or (region-active-p) force)
4891 (when (and (if (eq select-active-regions 'only)
4892 (eq (car-safe transient-mark-mode) 'only)
4893 select-active-regions)
4894 (region-active-p)
4895 (display-selections-p))
4896 ;; The var `saved-region-selection', if non-nil, is the text in
4897 ;; the region prior to the last command modifying the buffer.
4898 ;; Set the selection to that, or to the current region.
4899 (cond (saved-region-selection
4900 (if (gui-backend-selection-owner-p 'PRIMARY)
4901 (gui-set-selection 'PRIMARY saved-region-selection))
4902 (setq saved-region-selection nil))
4903 ;; If another program has acquired the selection, region
4904 ;; deactivation should not clobber it (Bug#11772).
4905 ((and (/= (region-beginning) (region-end))
4906 (or (gui-backend-selection-owner-p 'PRIMARY)
4907 (null (gui-backend-selection-exists-p 'PRIMARY))))
4908 (gui-set-selection 'PRIMARY
4909 (funcall region-extract-function nil)))))
4910 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
4911 (cond
4912 ((eq (car-safe transient-mark-mode) 'only)
4913 (setq transient-mark-mode (cdr transient-mark-mode))
4914 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
4915 (kill-local-variable 'transient-mark-mode)))
4916 ((eq transient-mark-mode 'lambda)
4917 (kill-local-variable 'transient-mark-mode)))
4918 (setq mark-active nil)
4919 (run-hooks 'deactivate-mark-hook)
4920 (redisplay--update-region-highlight (selected-window))))
4921
4922 (defun activate-mark (&optional no-tmm)
4923 "Activate the mark.
4924 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
4925 (when (mark t)
4926 (unless (region-active-p)
4927 (force-mode-line-update) ;Refresh toolbar (bug#16382).
4928 (setq mark-active t)
4929 (unless (or transient-mark-mode no-tmm)
4930 (setq-local transient-mark-mode 'lambda))
4931 (run-hooks 'activate-mark-hook))))
4932
4933 (defun set-mark (pos)
4934 "Set this buffer's mark to POS. Don't use this function!
4935 That is to say, don't use this function unless you want
4936 the user to see that the mark has moved, and you want the previous
4937 mark position to be lost.
4938
4939 Normally, when a new mark is set, the old one should go on the stack.
4940 This is why most applications should use `push-mark', not `set-mark'.
4941
4942 Novice Emacs Lisp programmers often try to use the mark for the wrong
4943 purposes. The mark saves a location for the user's convenience.
4944 Most editing commands should not alter the mark.
4945 To remember a location for internal use in the Lisp program,
4946 store it in a Lisp variable. Example:
4947
4948 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4949 (if pos
4950 (progn
4951 (set-marker (mark-marker) pos (current-buffer))
4952 (activate-mark 'no-tmm))
4953 ;; Normally we never clear mark-active except in Transient Mark mode.
4954 ;; But when we actually clear out the mark value too, we must
4955 ;; clear mark-active in any mode.
4956 (deactivate-mark t)
4957 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
4958 ;; it should never be nil if the mark is nil.
4959 (setq mark-active nil)
4960 (set-marker (mark-marker) nil)))
4961
4962 (defun save-mark-and-excursion--save ()
4963 (cons
4964 (let ((mark (mark-marker)))
4965 (and (marker-position mark) (copy-marker mark)))
4966 mark-active))
4967
4968 (defun save-mark-and-excursion--restore (saved-mark-info)
4969 (let ((saved-mark (car saved-mark-info))
4970 (omark (marker-position (mark-marker)))
4971 (nmark nil)
4972 (saved-mark-active (cdr saved-mark-info)))
4973 ;; Mark marker
4974 (if (null saved-mark)
4975 (set-marker (mark-marker) nil)
4976 (setf nmark (marker-position saved-mark))
4977 (set-marker (mark-marker) nmark)
4978 (set-marker saved-mark nil))
4979 ;; Mark active
4980 (let ((cur-mark-active mark-active))
4981 (setq mark-active saved-mark-active)
4982 ;; If mark is active now, and either was not active or was at a
4983 ;; different place, run the activate hook.
4984 (if saved-mark-active
4985 (when (or (not cur-mark-active)
4986 (not (eq omark nmark)))
4987 (run-hooks 'activate-mark-hook))
4988 ;; If mark has ceased to be active, run deactivate hook.
4989 (when cur-mark-active
4990 (run-hooks 'deactivate-mark-hook))))))
4991
4992 (defmacro save-mark-and-excursion (&rest body)
4993 "Like `save-excursion', but also save and restore the mark state.
4994 This macro does what `save-excursion' did before Emacs 25.1."
4995 (let ((saved-marker-sym (make-symbol "saved-marker")))
4996 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
4997 (unwind-protect
4998 (save-excursion ,@body)
4999 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5000
5001 (defcustom use-empty-active-region nil
5002 "Whether \"region-aware\" commands should act on empty regions.
5003 If nil, region-aware commands treat empty regions as inactive.
5004 If non-nil, region-aware commands treat the region as active as
5005 long as the mark is active, even if the region is empty.
5006
5007 Region-aware commands are those that act on the region if it is
5008 active and Transient Mark mode is enabled, and on the text near
5009 point otherwise."
5010 :type 'boolean
5011 :version "23.1"
5012 :group 'editing-basics)
5013
5014 (defun use-region-p ()
5015 "Return t if the region is active and it is appropriate to act on it.
5016 This is used by commands that act specially on the region under
5017 Transient Mark mode.
5018
5019 The return value is t if Transient Mark mode is enabled and the
5020 mark is active; furthermore, if `use-empty-active-region' is nil,
5021 the region must not be empty. Otherwise, the return value is nil.
5022
5023 For some commands, it may be appropriate to ignore the value of
5024 `use-empty-active-region'; in that case, use `region-active-p'."
5025 (and (region-active-p)
5026 (or use-empty-active-region (> (region-end) (region-beginning)))))
5027
5028 (defun region-active-p ()
5029 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5030
5031 Some commands act specially on the region when Transient Mark
5032 mode is enabled. Usually, such commands should use
5033 `use-region-p' instead of this function, because `use-region-p'
5034 also checks the value of `use-empty-active-region'."
5035 (and transient-mark-mode mark-active
5036 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5037 ;; without the mark being set (e.g. bug#17324). We really should fix
5038 ;; that problem, but in the mean time, let's make sure we don't say the
5039 ;; region is active when there's no mark.
5040 (progn (cl-assert (mark)) t)))
5041
5042
5043 (defvar redisplay-unhighlight-region-function
5044 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5045
5046 (defvar redisplay-highlight-region-function
5047 (lambda (start end window rol)
5048 (if (not (overlayp rol))
5049 (let ((nrol (make-overlay start end)))
5050 (funcall redisplay-unhighlight-region-function rol)
5051 (overlay-put nrol 'window window)
5052 (overlay-put nrol 'face 'region)
5053 ;; Normal priority so that a large region doesn't hide all the
5054 ;; overlays within it, but high secondary priority so that if it
5055 ;; ends/starts in the middle of a small overlay, that small overlay
5056 ;; won't hide the region's boundaries.
5057 (overlay-put nrol 'priority '(nil . 100))
5058 nrol)
5059 (unless (and (eq (overlay-buffer rol) (current-buffer))
5060 (eq (overlay-start rol) start)
5061 (eq (overlay-end rol) end))
5062 (move-overlay rol start end (current-buffer)))
5063 rol)))
5064
5065 (defun redisplay--update-region-highlight (window)
5066 (let ((rol (window-parameter window 'internal-region-overlay)))
5067 (if (not (and (region-active-p)
5068 (or highlight-nonselected-windows
5069 (eq window (selected-window))
5070 (and (window-minibuffer-p)
5071 (eq window (minibuffer-selected-window))))))
5072 (funcall redisplay-unhighlight-region-function rol)
5073 (let* ((pt (window-point window))
5074 (mark (mark))
5075 (start (min pt mark))
5076 (end (max pt mark))
5077 (new
5078 (funcall redisplay-highlight-region-function
5079 start end window rol)))
5080 (unless (equal new rol)
5081 (set-window-parameter window 'internal-region-overlay
5082 new))))))
5083
5084 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5085 "Hook run just before redisplay.
5086 It is called in each window that is to be redisplayed. It takes one argument,
5087 which is the window that will be redisplayed. When run, the `current-buffer'
5088 is set to the buffer displayed in that window.")
5089
5090 (defun redisplay--pre-redisplay-functions (windows)
5091 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5092 (if (null windows)
5093 (with-current-buffer (window-buffer (selected-window))
5094 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5095 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5096 (with-current-buffer (window-buffer win)
5097 (run-hook-with-args 'pre-redisplay-functions win))))))
5098
5099 (add-function :before pre-redisplay-function
5100 #'redisplay--pre-redisplay-functions)
5101
5102
5103 (defvar-local mark-ring nil
5104 "The list of former marks of the current buffer, most recent first.")
5105 (put 'mark-ring 'permanent-local t)
5106
5107 (defcustom mark-ring-max 16
5108 "Maximum size of mark ring. Start discarding off end if gets this big."
5109 :type 'integer
5110 :group 'editing-basics)
5111
5112 (defvar global-mark-ring nil
5113 "The list of saved global marks, most recent first.")
5114
5115 (defcustom global-mark-ring-max 16
5116 "Maximum size of global mark ring. \
5117 Start discarding off end if gets this big."
5118 :type 'integer
5119 :group 'editing-basics)
5120
5121 (defun pop-to-mark-command ()
5122 "Jump to mark, and pop a new position for mark off the ring.
5123 \(Does not affect global mark ring)."
5124 (interactive)
5125 (if (null (mark t))
5126 (user-error "No mark set in this buffer")
5127 (if (= (point) (mark t))
5128 (message "Mark popped"))
5129 (goto-char (mark t))
5130 (pop-mark)))
5131
5132 (defun push-mark-command (arg &optional nomsg)
5133 "Set mark at where point is.
5134 If no prefix ARG and mark is already set there, just activate it.
5135 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5136 (interactive "P")
5137 (let ((mark (mark t)))
5138 (if (or arg (null mark) (/= mark (point)))
5139 (push-mark nil nomsg t)
5140 (activate-mark 'no-tmm)
5141 (unless nomsg
5142 (message "Mark activated")))))
5143
5144 (defcustom set-mark-command-repeat-pop nil
5145 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5146 That means that C-u \\[set-mark-command] \\[set-mark-command]
5147 will pop the mark twice, and
5148 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5149 will pop the mark three times.
5150
5151 A value of nil means \\[set-mark-command]'s behavior does not change
5152 after C-u \\[set-mark-command]."
5153 :type 'boolean
5154 :group 'editing-basics)
5155
5156 (defun set-mark-command (arg)
5157 "Set the mark where point is, or jump to the mark.
5158 Setting the mark also alters the region, which is the text
5159 between point and mark; this is the closest equivalent in
5160 Emacs to what some editors call the \"selection\".
5161
5162 With no prefix argument, set the mark at point, and push the
5163 old mark position on local mark ring. Also push the old mark on
5164 global mark ring, if the previous mark was set in another buffer.
5165
5166 When Transient Mark Mode is off, immediately repeating this
5167 command activates `transient-mark-mode' temporarily.
5168
5169 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5170 jump to the mark, and set the mark from
5171 position popped off the local mark ring (this does not affect the global
5172 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5173 mark ring (see `pop-global-mark').
5174
5175 If `set-mark-command-repeat-pop' is non-nil, repeating
5176 the \\[set-mark-command] command with no prefix argument pops the next position
5177 off the local (or global) mark ring and jumps there.
5178
5179 With \\[universal-argument] \\[universal-argument] as prefix
5180 argument, unconditionally set mark where point is, even if
5181 `set-mark-command-repeat-pop' is non-nil.
5182
5183 Novice Emacs Lisp programmers often try to use the mark for the wrong
5184 purposes. See the documentation of `set-mark' for more information."
5185 (interactive "P")
5186 (cond ((eq transient-mark-mode 'lambda)
5187 (kill-local-variable 'transient-mark-mode))
5188 ((eq (car-safe transient-mark-mode) 'only)
5189 (deactivate-mark)))
5190 (cond
5191 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5192 (push-mark-command nil))
5193 ((not (eq this-command 'set-mark-command))
5194 (if arg
5195 (pop-to-mark-command)
5196 (push-mark-command t)))
5197 ((and set-mark-command-repeat-pop
5198 (eq last-command 'pop-global-mark)
5199 (not arg))
5200 (setq this-command 'pop-global-mark)
5201 (pop-global-mark))
5202 ((or (and set-mark-command-repeat-pop
5203 (eq last-command 'pop-to-mark-command))
5204 arg)
5205 (setq this-command 'pop-to-mark-command)
5206 (pop-to-mark-command))
5207 ((eq last-command 'set-mark-command)
5208 (if (region-active-p)
5209 (progn
5210 (deactivate-mark)
5211 (message "Mark deactivated"))
5212 (activate-mark)
5213 (message "Mark activated")))
5214 (t
5215 (push-mark-command nil))))
5216
5217 (defun push-mark (&optional location nomsg activate)
5218 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5219 If the last global mark pushed was not in the current buffer,
5220 also push LOCATION on the global mark ring.
5221 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5222
5223 Novice Emacs Lisp programmers often try to use the mark for the wrong
5224 purposes. See the documentation of `set-mark' for more information.
5225
5226 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5227 (unless (null (mark t))
5228 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5229 (when (> (length mark-ring) mark-ring-max)
5230 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5231 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5232 (set-marker (mark-marker) (or location (point)) (current-buffer))
5233 ;; Now push the mark on the global mark ring.
5234 (if (and global-mark-ring
5235 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5236 ;; The last global mark pushed was in this same buffer.
5237 ;; Don't push another one.
5238 nil
5239 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5240 (when (> (length global-mark-ring) global-mark-ring-max)
5241 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5242 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5243 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5244 (message "Mark set"))
5245 (if (or activate (not transient-mark-mode))
5246 (set-mark (mark t)))
5247 nil)
5248
5249 (defun pop-mark ()
5250 "Pop off mark ring into the buffer's actual mark.
5251 Does not set point. Does nothing if mark ring is empty."
5252 (when mark-ring
5253 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5254 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5255 (move-marker (car mark-ring) nil)
5256 (if (null (mark t)) (ding))
5257 (setq mark-ring (cdr mark-ring)))
5258 (deactivate-mark))
5259
5260 (define-obsolete-function-alias
5261 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5262 (defun exchange-point-and-mark (&optional arg)
5263 "Put the mark where point is now, and point where the mark is now.
5264 This command works even when the mark is not active,
5265 and it reactivates the mark.
5266
5267 If Transient Mark mode is on, a prefix ARG deactivates the mark
5268 if it is active, and otherwise avoids reactivating it. If
5269 Transient Mark mode is off, a prefix ARG enables Transient Mark
5270 mode temporarily."
5271 (interactive "P")
5272 (let ((omark (mark t))
5273 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5274 (if (null omark)
5275 (user-error "No mark set in this buffer"))
5276 (set-mark (point))
5277 (goto-char omark)
5278 (cond (temp-highlight
5279 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5280 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5281 (not (or arg (region-active-p))))
5282 (deactivate-mark))
5283 (t (activate-mark)))
5284 nil))
5285
5286 (defcustom shift-select-mode t
5287 "When non-nil, shifted motion keys activate the mark momentarily.
5288
5289 While the mark is activated in this way, any shift-translated point
5290 motion key extends the region, and if Transient Mark mode was off, it
5291 is temporarily turned on. Furthermore, the mark will be deactivated
5292 by any subsequent point motion key that was not shift-translated, or
5293 by any action that normally deactivates the mark in Transient Mark mode.
5294
5295 See `this-command-keys-shift-translated' for the meaning of
5296 shift-translation."
5297 :type 'boolean
5298 :group 'editing-basics)
5299
5300 (defun handle-shift-selection ()
5301 "Activate/deactivate mark depending on invocation thru shift translation.
5302 This function is called by `call-interactively' when a command
5303 with a `^' character in its `interactive' spec is invoked, before
5304 running the command itself.
5305
5306 If `shift-select-mode' is enabled and the command was invoked
5307 through shift translation, set the mark and activate the region
5308 temporarily, unless it was already set in this way. See
5309 `this-command-keys-shift-translated' for the meaning of shift
5310 translation.
5311
5312 Otherwise, if the region has been activated temporarily,
5313 deactivate it, and restore the variable `transient-mark-mode' to
5314 its earlier value."
5315 (cond ((and shift-select-mode this-command-keys-shift-translated)
5316 (unless (and mark-active
5317 (eq (car-safe transient-mark-mode) 'only))
5318 (setq-local transient-mark-mode
5319 (cons 'only
5320 (unless (eq transient-mark-mode 'lambda)
5321 transient-mark-mode)))
5322 (push-mark nil nil t)))
5323 ((eq (car-safe transient-mark-mode) 'only)
5324 (setq transient-mark-mode (cdr transient-mark-mode))
5325 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5326 (kill-local-variable 'transient-mark-mode))
5327 (deactivate-mark))))
5328
5329 (define-minor-mode transient-mark-mode
5330 "Toggle Transient Mark mode.
5331 With a prefix argument ARG, enable Transient Mark mode if ARG is
5332 positive, and disable it otherwise. If called from Lisp, enable
5333 Transient Mark mode if ARG is omitted or nil.
5334
5335 Transient Mark mode is a global minor mode. When enabled, the
5336 region is highlighted with the `region' face whenever the mark
5337 is active. The mark is \"deactivated\" by changing the buffer,
5338 and after certain other operations that set the mark but whose
5339 main purpose is something else--for example, incremental search,
5340 \\[beginning-of-buffer], and \\[end-of-buffer].
5341
5342 You can also deactivate the mark by typing \\[keyboard-quit] or
5343 \\[keyboard-escape-quit].
5344
5345 Many commands change their behavior when Transient Mark mode is
5346 in effect and the mark is active, by acting on the region instead
5347 of their usual default part of the buffer's text. Examples of
5348 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5349 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5350 To see the documentation of commands which are sensitive to the
5351 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5352 or \"mark.*active\" at the prompt."
5353 :global t
5354 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5355 :variable (default-value 'transient-mark-mode))
5356
5357 (defvar widen-automatically t
5358 "Non-nil means it is ok for commands to call `widen' when they want to.
5359 Some commands will do this in order to go to positions outside
5360 the current accessible part of the buffer.
5361
5362 If `widen-automatically' is nil, these commands will do something else
5363 as a fallback, and won't change the buffer bounds.")
5364
5365 (defvar non-essential nil
5366 "Whether the currently executing code is performing an essential task.
5367 This variable should be non-nil only when running code which should not
5368 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5369 user for a password when we are simply scanning a set of files in the
5370 background or displaying possible completions before the user even asked
5371 for it.")
5372
5373 (defun pop-global-mark ()
5374 "Pop off global mark ring and jump to the top location."
5375 (interactive)
5376 ;; Pop entries which refer to non-existent buffers.
5377 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5378 (setq global-mark-ring (cdr global-mark-ring)))
5379 (or global-mark-ring
5380 (error "No global mark set"))
5381 (let* ((marker (car global-mark-ring))
5382 (buffer (marker-buffer marker))
5383 (position (marker-position marker)))
5384 (setq global-mark-ring (nconc (cdr global-mark-ring)
5385 (list (car global-mark-ring))))
5386 (set-buffer buffer)
5387 (or (and (>= position (point-min))
5388 (<= position (point-max)))
5389 (if widen-automatically
5390 (widen)
5391 (error "Global mark position is outside accessible part of buffer")))
5392 (goto-char position)
5393 (switch-to-buffer buffer)))
5394 \f
5395 (defcustom next-line-add-newlines nil
5396 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5397 :type 'boolean
5398 :version "21.1"
5399 :group 'editing-basics)
5400
5401 (defun next-line (&optional arg try-vscroll)
5402 "Move cursor vertically down ARG lines.
5403 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5404 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5405 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5406 function will not vscroll.
5407
5408 ARG defaults to 1.
5409
5410 If there is no character in the target line exactly under the current column,
5411 the cursor is positioned after the character in that line which spans this
5412 column, or at the end of the line if it is not long enough.
5413 If there is no line in the buffer after this one, behavior depends on the
5414 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5415 to create a line, and moves the cursor to that line. Otherwise it moves the
5416 cursor to the end of the buffer.
5417
5418 If the variable `line-move-visual' is non-nil, this command moves
5419 by display lines. Otherwise, it moves by buffer lines, without
5420 taking variable-width characters or continued lines into account.
5421
5422 The command \\[set-goal-column] can be used to create
5423 a semipermanent goal column for this command.
5424 Then instead of trying to move exactly vertically (or as close as possible),
5425 this command moves to the specified goal column (or as close as possible).
5426 The goal column is stored in the variable `goal-column', which is nil
5427 when there is no goal column. Note that setting `goal-column'
5428 overrides `line-move-visual' and causes this command to move by buffer
5429 lines rather than by display lines."
5430 (declare (interactive-only forward-line))
5431 (interactive "^p\np")
5432 (or arg (setq arg 1))
5433 (if (and next-line-add-newlines (= arg 1))
5434 (if (save-excursion (end-of-line) (eobp))
5435 ;; When adding a newline, don't expand an abbrev.
5436 (let ((abbrev-mode nil))
5437 (end-of-line)
5438 (insert (if use-hard-newlines hard-newline "\n")))
5439 (line-move arg nil nil try-vscroll))
5440 (if (called-interactively-p 'interactive)
5441 (condition-case err
5442 (line-move arg nil nil try-vscroll)
5443 ((beginning-of-buffer end-of-buffer)
5444 (signal (car err) (cdr err))))
5445 (line-move arg nil nil try-vscroll)))
5446 nil)
5447
5448 (defun previous-line (&optional arg try-vscroll)
5449 "Move cursor vertically up ARG lines.
5450 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5451 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5452 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5453 function will not vscroll.
5454
5455 ARG defaults to 1.
5456
5457 If there is no character in the target line exactly over the current column,
5458 the cursor is positioned after the character in that line which spans this
5459 column, or at the end of the line if it is not long enough.
5460
5461 If the variable `line-move-visual' is non-nil, this command moves
5462 by display lines. Otherwise, it moves by buffer lines, without
5463 taking variable-width characters or continued lines into account.
5464
5465 The command \\[set-goal-column] can be used to create
5466 a semipermanent goal column for this command.
5467 Then instead of trying to move exactly vertically (or as close as possible),
5468 this command moves to the specified goal column (or as close as possible).
5469 The goal column is stored in the variable `goal-column', which is nil
5470 when there is no goal column. Note that setting `goal-column'
5471 overrides `line-move-visual' and causes this command to move by buffer
5472 lines rather than by display lines."
5473 (declare (interactive-only
5474 "use `forward-line' with negative argument instead."))
5475 (interactive "^p\np")
5476 (or arg (setq arg 1))
5477 (if (called-interactively-p 'interactive)
5478 (condition-case err
5479 (line-move (- arg) nil nil try-vscroll)
5480 ((beginning-of-buffer end-of-buffer)
5481 (signal (car err) (cdr err))))
5482 (line-move (- arg) nil nil try-vscroll))
5483 nil)
5484
5485 (defcustom track-eol nil
5486 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5487 This means moving to the end of each line moved onto.
5488 The beginning of a blank line does not count as the end of a line.
5489 This has no effect when the variable `line-move-visual' is non-nil."
5490 :type 'boolean
5491 :group 'editing-basics)
5492
5493 (defcustom goal-column nil
5494 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5495 A non-nil setting overrides the variable `line-move-visual', which see."
5496 :type '(choice integer
5497 (const :tag "None" nil))
5498 :group 'editing-basics)
5499 (make-variable-buffer-local 'goal-column)
5500
5501 (defvar temporary-goal-column 0
5502 "Current goal column for vertical motion.
5503 It is the column where point was at the start of the current run
5504 of vertical motion commands.
5505
5506 When moving by visual lines via the function `line-move-visual', it is a cons
5507 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5508 divided by the default column width, and HSCROLL is the number of
5509 columns by which window is scrolled from left margin.
5510
5511 When the `track-eol' feature is doing its job, the value is
5512 `most-positive-fixnum'.")
5513
5514 (defcustom line-move-ignore-invisible t
5515 "Non-nil means commands that move by lines ignore invisible newlines.
5516 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5517 as if newlines that are invisible didn't exist, and count
5518 only visible newlines. Thus, moving across across 2 newlines
5519 one of which is invisible will be counted as a one-line move.
5520 Also, a non-nil value causes invisible text to be ignored when
5521 counting columns for the purposes of keeping point in the same
5522 column by \\[next-line] and \\[previous-line].
5523
5524 Outline mode sets this."
5525 :type 'boolean
5526 :group 'editing-basics)
5527
5528 (defcustom line-move-visual t
5529 "When non-nil, `line-move' moves point by visual lines.
5530 This movement is based on where the cursor is displayed on the
5531 screen, instead of relying on buffer contents alone. It takes
5532 into account variable-width characters and line continuation.
5533 If nil, `line-move' moves point by logical lines.
5534 A non-nil setting of `goal-column' overrides the value of this variable
5535 and forces movement by logical lines.
5536 A window that is horizontally scrolled also forces movement by logical
5537 lines."
5538 :type 'boolean
5539 :group 'editing-basics
5540 :version "23.1")
5541
5542 ;; Only used if display-graphic-p.
5543 (declare-function font-info "font.c" (name &optional frame))
5544
5545 (defun default-font-height ()
5546 "Return the height in pixels of the current buffer's default face font.
5547
5548 If the default font is remapped (see `face-remapping-alist'), the
5549 function returns the height of the remapped face."
5550 (let ((default-font (face-font 'default)))
5551 (cond
5552 ((and (display-multi-font-p)
5553 ;; Avoid calling font-info if the frame's default font was
5554 ;; not changed since the frame was created. That's because
5555 ;; font-info is expensive for some fonts, see bug #14838.
5556 (not (string= (frame-parameter nil 'font) default-font)))
5557 (aref (font-info default-font) 3))
5558 (t (frame-char-height)))))
5559
5560 (defun default-font-width ()
5561 "Return the width in pixels of the current buffer's default face font.
5562
5563 If the default font is remapped (see `face-remapping-alist'), the
5564 function returns the width of the remapped face."
5565 (let ((default-font (face-font 'default)))
5566 (cond
5567 ((and (display-multi-font-p)
5568 ;; Avoid calling font-info if the frame's default font was
5569 ;; not changed since the frame was created. That's because
5570 ;; font-info is expensive for some fonts, see bug #14838.
5571 (not (string= (frame-parameter nil 'font) default-font)))
5572 (let* ((info (font-info (face-font 'default)))
5573 (width (aref info 11)))
5574 (if (> width 0)
5575 width
5576 (aref info 10))))
5577 (t (frame-char-width)))))
5578
5579 (defun default-line-height ()
5580 "Return the pixel height of current buffer's default-face text line.
5581
5582 The value includes `line-spacing', if any, defined for the buffer
5583 or the frame."
5584 (let ((dfh (default-font-height))
5585 (lsp (if (display-graphic-p)
5586 (or line-spacing
5587 (default-value 'line-spacing)
5588 (frame-parameter nil 'line-spacing)
5589 0)
5590 0)))
5591 (if (floatp lsp)
5592 (setq lsp (truncate (* (frame-char-height) lsp))))
5593 (+ dfh lsp)))
5594
5595 (defun window-screen-lines ()
5596 "Return the number of screen lines in the text area of the selected window.
5597
5598 This is different from `window-text-height' in that this function counts
5599 lines in units of the height of the font used by the default face displayed
5600 in the window, not in units of the frame's default font, and also accounts
5601 for `line-spacing', if any, defined for the window's buffer or frame.
5602
5603 The value is a floating-point number."
5604 (let ((edges (window-inside-pixel-edges))
5605 (dlh (default-line-height)))
5606 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5607
5608 ;; Returns non-nil if partial move was done.
5609 (defun line-move-partial (arg noerror to-end)
5610 (if (< arg 0)
5611 ;; Move backward (up).
5612 ;; If already vscrolled, reduce vscroll
5613 (let ((vs (window-vscroll nil t))
5614 (dlh (default-line-height)))
5615 (when (> vs dlh)
5616 (set-window-vscroll nil (- vs dlh) t)))
5617
5618 ;; Move forward (down).
5619 (let* ((lh (window-line-height -1))
5620 (rowh (car lh))
5621 (vpos (nth 1 lh))
5622 (ypos (nth 2 lh))
5623 (rbot (nth 3 lh))
5624 (this-lh (window-line-height))
5625 (this-height (car this-lh))
5626 (this-ypos (nth 2 this-lh))
5627 (dlh (default-line-height))
5628 (wslines (window-screen-lines))
5629 (edges (window-inside-pixel-edges))
5630 (winh (- (nth 3 edges) (nth 1 edges) 1))
5631 py vs last-line)
5632 (if (> (mod wslines 1.0) 0.0)
5633 (setq wslines (round (+ wslines 0.5))))
5634 (when (or (null lh)
5635 (>= rbot dlh)
5636 (<= ypos (- dlh))
5637 (null this-lh)
5638 (<= this-ypos (- dlh)))
5639 (unless lh
5640 (let ((wend (pos-visible-in-window-p t nil t)))
5641 (setq rbot (nth 3 wend)
5642 rowh (nth 4 wend)
5643 vpos (nth 5 wend))))
5644 (unless this-lh
5645 (let ((wstart (pos-visible-in-window-p nil nil t)))
5646 (setq this-ypos (nth 2 wstart)
5647 this-height (nth 4 wstart))))
5648 (setq py
5649 (or (nth 1 this-lh)
5650 (let ((ppos (posn-at-point))
5651 col-row)
5652 (setq col-row (posn-actual-col-row ppos))
5653 (if col-row
5654 (- (cdr col-row) (window-vscroll))
5655 (cdr (posn-col-row ppos))))))
5656 ;; VPOS > 0 means the last line is only partially visible.
5657 ;; But if the part that is visible is at least as tall as the
5658 ;; default font, that means the line is actually fully
5659 ;; readable, and something like line-spacing is hidden. So in
5660 ;; that case we accept the last line in the window as still
5661 ;; visible, and consider the margin as starting one line
5662 ;; later.
5663 (if (and vpos (> vpos 0))
5664 (if (and rowh
5665 (>= rowh (default-font-height))
5666 (< rowh dlh))
5667 (setq last-line (min (- wslines scroll-margin) vpos))
5668 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5669 (cond
5670 ;; If last line of window is fully visible, and vscrolling
5671 ;; more would make this line invisible, move forward.
5672 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5673 (null this-height)
5674 (<= this-height dlh))
5675 (or (null rbot) (= rbot 0)))
5676 nil)
5677 ;; If cursor is not in the bottom scroll margin, and the
5678 ;; current line is is not too tall, move forward.
5679 ((and (or (null this-height) (<= this-height winh))
5680 vpos
5681 (> vpos 0)
5682 (< py last-line))
5683 nil)
5684 ;; When already vscrolled, we vscroll some more if we can,
5685 ;; or clear vscroll and move forward at end of tall image.
5686 ((> vs 0)
5687 (when (or (and rbot (> rbot 0))
5688 (and this-height (> this-height dlh)))
5689 (set-window-vscroll nil (+ vs dlh) t)))
5690 ;; If cursor just entered the bottom scroll margin, move forward,
5691 ;; but also optionally vscroll one line so redisplay won't recenter.
5692 ((and vpos
5693 (> vpos 0)
5694 (= py last-line))
5695 ;; Don't vscroll if the partially-visible line at window
5696 ;; bottom is not too tall (a.k.a. "just one more text
5697 ;; line"): in that case, we do want redisplay to behave
5698 ;; normally, i.e. recenter or whatever.
5699 ;;
5700 ;; Note: ROWH + RBOT from the value returned by
5701 ;; pos-visible-in-window-p give the total height of the
5702 ;; partially-visible glyph row at the end of the window. As
5703 ;; we are dealing with floats, we disregard sub-pixel
5704 ;; discrepancies between that and DLH.
5705 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5706 (set-window-vscroll nil dlh t))
5707 (line-move-1 arg noerror to-end)
5708 t)
5709 ;; If there are lines above the last line, scroll-up one line.
5710 ((and vpos (> vpos 0))
5711 (scroll-up 1)
5712 t)
5713 ;; Finally, start vscroll.
5714 (t
5715 (set-window-vscroll nil dlh t)))))))
5716
5717
5718 ;; This is like line-move-1 except that it also performs
5719 ;; vertical scrolling of tall images if appropriate.
5720 ;; That is not really a clean thing to do, since it mixes
5721 ;; scrolling with cursor motion. But so far we don't have
5722 ;; a cleaner solution to the problem of making C-n do something
5723 ;; useful given a tall image.
5724 (defun line-move (arg &optional noerror to-end try-vscroll)
5725 "Move forward ARG lines.
5726 If NOERROR, don't signal an error if we can't move ARG lines.
5727 TO-END is unused.
5728 TRY-VSCROLL controls whether to vscroll tall lines: if either
5729 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5730 not vscroll."
5731 (if noninteractive
5732 (line-move-1 arg noerror to-end)
5733 (unless (and auto-window-vscroll try-vscroll
5734 ;; Only vscroll for single line moves
5735 (= (abs arg) 1)
5736 ;; Under scroll-conservatively, the display engine
5737 ;; does this better.
5738 (zerop scroll-conservatively)
5739 ;; But don't vscroll in a keyboard macro.
5740 (not defining-kbd-macro)
5741 (not executing-kbd-macro)
5742 (line-move-partial arg noerror to-end))
5743 (set-window-vscroll nil 0 t)
5744 (if (and line-move-visual
5745 ;; Display-based column are incompatible with goal-column.
5746 (not goal-column)
5747 ;; When the text in the window is scrolled to the left,
5748 ;; display-based motion doesn't make sense (because each
5749 ;; logical line occupies exactly one screen line).
5750 (not (> (window-hscroll) 0))
5751 ;; Likewise when the text _was_ scrolled to the left
5752 ;; when the current run of vertical motion commands
5753 ;; started.
5754 (not (and (memq last-command
5755 `(next-line previous-line ,this-command))
5756 auto-hscroll-mode
5757 (numberp temporary-goal-column)
5758 (>= temporary-goal-column
5759 (- (window-width) hscroll-margin)))))
5760 (prog1 (line-move-visual arg noerror)
5761 ;; If we moved into a tall line, set vscroll to make
5762 ;; scrolling through tall images more smooth.
5763 (let ((lh (line-pixel-height))
5764 (edges (window-inside-pixel-edges))
5765 (dlh (default-line-height))
5766 winh)
5767 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5768 (if (and (< arg 0)
5769 (< (point) (window-start))
5770 (> lh winh))
5771 (set-window-vscroll
5772 nil
5773 (- lh dlh) t))))
5774 (line-move-1 arg noerror to-end)))))
5775
5776 ;; Display-based alternative to line-move-1.
5777 ;; Arg says how many lines to move. The value is t if we can move the
5778 ;; specified number of lines.
5779 (defun line-move-visual (arg &optional noerror)
5780 "Move ARG lines forward.
5781 If NOERROR, don't signal an error if we can't move that many lines."
5782 (let ((opoint (point))
5783 (hscroll (window-hscroll))
5784 target-hscroll)
5785 ;; Check if the previous command was a line-motion command, or if
5786 ;; we were called from some other command.
5787 (if (and (consp temporary-goal-column)
5788 (memq last-command `(next-line previous-line ,this-command)))
5789 ;; If so, there's no need to reset `temporary-goal-column',
5790 ;; but we may need to hscroll.
5791 (if (or (/= (cdr temporary-goal-column) hscroll)
5792 (> (cdr temporary-goal-column) 0))
5793 (setq target-hscroll (cdr temporary-goal-column)))
5794 ;; Otherwise, we should reset `temporary-goal-column'.
5795 (let ((posn (posn-at-point))
5796 x-pos)
5797 (cond
5798 ;; Handle the `overflow-newline-into-fringe' case:
5799 ((eq (nth 1 posn) 'right-fringe)
5800 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5801 ((car (posn-x-y posn))
5802 (setq x-pos (car (posn-x-y posn)))
5803 ;; In R2L lines, the X pixel coordinate is measured from the
5804 ;; left edge of the window, but columns are still counted
5805 ;; from the logical-order beginning of the line, i.e. from
5806 ;; the right edge in this case. We need to adjust for that.
5807 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
5808 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
5809 (setq temporary-goal-column
5810 (cons (/ (float x-pos)
5811 (frame-char-width))
5812 hscroll))))))
5813 (if target-hscroll
5814 (set-window-hscroll (selected-window) target-hscroll))
5815 ;; vertical-motion can move more than it was asked to if it moves
5816 ;; across display strings with newlines. We don't want to ring
5817 ;; the bell and announce beginning/end of buffer in that case.
5818 (or (and (or (and (>= arg 0)
5819 (>= (vertical-motion
5820 (cons (or goal-column
5821 (if (consp temporary-goal-column)
5822 (car temporary-goal-column)
5823 temporary-goal-column))
5824 arg))
5825 arg))
5826 (and (< arg 0)
5827 (<= (vertical-motion
5828 (cons (or goal-column
5829 (if (consp temporary-goal-column)
5830 (car temporary-goal-column)
5831 temporary-goal-column))
5832 arg))
5833 arg)))
5834 (or (>= arg 0)
5835 (/= (point) opoint)
5836 ;; If the goal column lies on a display string,
5837 ;; `vertical-motion' advances the cursor to the end
5838 ;; of the string. For arg < 0, this can cause the
5839 ;; cursor to get stuck. (Bug#3020).
5840 (= (vertical-motion arg) arg)))
5841 (unless noerror
5842 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
5843 nil)))))
5844
5845 ;; This is the guts of next-line and previous-line.
5846 ;; Arg says how many lines to move.
5847 ;; The value is t if we can move the specified number of lines.
5848 (defun line-move-1 (arg &optional noerror _to-end)
5849 ;; Don't run any point-motion hooks, and disregard intangibility,
5850 ;; for intermediate positions.
5851 (let ((inhibit-point-motion-hooks t)
5852 (opoint (point))
5853 (orig-arg arg))
5854 (if (consp temporary-goal-column)
5855 (setq temporary-goal-column (+ (car temporary-goal-column)
5856 (cdr temporary-goal-column))))
5857 (unwind-protect
5858 (progn
5859 (if (not (memq last-command '(next-line previous-line)))
5860 (setq temporary-goal-column
5861 (if (and track-eol (eolp)
5862 ;; Don't count beg of empty line as end of line
5863 ;; unless we just did explicit end-of-line.
5864 (or (not (bolp)) (eq last-command 'move-end-of-line)))
5865 most-positive-fixnum
5866 (current-column))))
5867
5868 (if (not (or (integerp selective-display)
5869 line-move-ignore-invisible))
5870 ;; Use just newline characters.
5871 ;; Set ARG to 0 if we move as many lines as requested.
5872 (or (if (> arg 0)
5873 (progn (if (> arg 1) (forward-line (1- arg)))
5874 ;; This way of moving forward ARG lines
5875 ;; verifies that we have a newline after the last one.
5876 ;; It doesn't get confused by intangible text.
5877 (end-of-line)
5878 (if (zerop (forward-line 1))
5879 (setq arg 0)))
5880 (and (zerop (forward-line arg))
5881 (bolp)
5882 (setq arg 0)))
5883 (unless noerror
5884 (signal (if (< arg 0)
5885 'beginning-of-buffer
5886 'end-of-buffer)
5887 nil)))
5888 ;; Move by arg lines, but ignore invisible ones.
5889 (let (done)
5890 (while (and (> arg 0) (not done))
5891 ;; If the following character is currently invisible,
5892 ;; skip all characters with that same `invisible' property value.
5893 (while (and (not (eobp)) (invisible-p (point)))
5894 (goto-char (next-char-property-change (point))))
5895 ;; Move a line.
5896 ;; We don't use `end-of-line', since we want to escape
5897 ;; from field boundaries occurring exactly at point.
5898 (goto-char (constrain-to-field
5899 (let ((inhibit-field-text-motion t))
5900 (line-end-position))
5901 (point) t t
5902 'inhibit-line-move-field-capture))
5903 ;; If there's no invisibility here, move over the newline.
5904 (cond
5905 ((eobp)
5906 (if (not noerror)
5907 (signal 'end-of-buffer nil)
5908 (setq done t)))
5909 ((and (> arg 1) ;; Use vertical-motion for last move
5910 (not (integerp selective-display))
5911 (not (invisible-p (point))))
5912 ;; We avoid vertical-motion when possible
5913 ;; because that has to fontify.
5914 (forward-line 1))
5915 ;; Otherwise move a more sophisticated way.
5916 ((zerop (vertical-motion 1))
5917 (if (not noerror)
5918 (signal 'end-of-buffer nil)
5919 (setq done t))))
5920 (unless done
5921 (setq arg (1- arg))))
5922 ;; The logic of this is the same as the loop above,
5923 ;; it just goes in the other direction.
5924 (while (and (< arg 0) (not done))
5925 ;; For completely consistency with the forward-motion
5926 ;; case, we should call beginning-of-line here.
5927 ;; However, if point is inside a field and on a
5928 ;; continued line, the call to (vertical-motion -1)
5929 ;; below won't move us back far enough; then we return
5930 ;; to the same column in line-move-finish, and point
5931 ;; gets stuck -- cyd
5932 (forward-line 0)
5933 (cond
5934 ((bobp)
5935 (if (not noerror)
5936 (signal 'beginning-of-buffer nil)
5937 (setq done t)))
5938 ((and (< arg -1) ;; Use vertical-motion for last move
5939 (not (integerp selective-display))
5940 (not (invisible-p (1- (point)))))
5941 (forward-line -1))
5942 ((zerop (vertical-motion -1))
5943 (if (not noerror)
5944 (signal 'beginning-of-buffer nil)
5945 (setq done t))))
5946 (unless done
5947 (setq arg (1+ arg))
5948 (while (and ;; Don't move over previous invis lines
5949 ;; if our target is the middle of this line.
5950 (or (zerop (or goal-column temporary-goal-column))
5951 (< arg 0))
5952 (not (bobp)) (invisible-p (1- (point))))
5953 (goto-char (previous-char-property-change (point))))))))
5954 ;; This is the value the function returns.
5955 (= arg 0))
5956
5957 (cond ((> arg 0)
5958 ;; If we did not move down as far as desired, at least go
5959 ;; to end of line. Be sure to call point-entered and
5960 ;; point-left-hooks.
5961 (let* ((npoint (prog1 (line-end-position)
5962 (goto-char opoint)))
5963 (inhibit-point-motion-hooks nil))
5964 (goto-char npoint)))
5965 ((< arg 0)
5966 ;; If we did not move up as far as desired,
5967 ;; at least go to beginning of line.
5968 (let* ((npoint (prog1 (line-beginning-position)
5969 (goto-char opoint)))
5970 (inhibit-point-motion-hooks nil))
5971 (goto-char npoint)))
5972 (t
5973 (line-move-finish (or goal-column temporary-goal-column)
5974 opoint (> orig-arg 0)))))))
5975
5976 (defun line-move-finish (column opoint forward)
5977 (let ((repeat t))
5978 (while repeat
5979 ;; Set REPEAT to t to repeat the whole thing.
5980 (setq repeat nil)
5981
5982 (let (new
5983 (old (point))
5984 (line-beg (line-beginning-position))
5985 (line-end
5986 ;; Compute the end of the line
5987 ;; ignoring effectively invisible newlines.
5988 (save-excursion
5989 ;; Like end-of-line but ignores fields.
5990 (skip-chars-forward "^\n")
5991 (while (and (not (eobp)) (invisible-p (point)))
5992 (goto-char (next-char-property-change (point)))
5993 (skip-chars-forward "^\n"))
5994 (point))))
5995
5996 ;; Move to the desired column.
5997 (line-move-to-column (truncate column))
5998
5999 ;; Corner case: suppose we start out in a field boundary in
6000 ;; the middle of a continued line. When we get to
6001 ;; line-move-finish, point is at the start of a new *screen*
6002 ;; line but the same text line; then line-move-to-column would
6003 ;; move us backwards. Test using C-n with point on the "x" in
6004 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6005 (and forward
6006 (< (point) old)
6007 (goto-char old))
6008
6009 (setq new (point))
6010
6011 ;; Process intangibility within a line.
6012 ;; With inhibit-point-motion-hooks bound to nil, a call to
6013 ;; goto-char moves point past intangible text.
6014
6015 ;; However, inhibit-point-motion-hooks controls both the
6016 ;; intangibility and the point-entered/point-left hooks. The
6017 ;; following hack avoids calling the point-* hooks
6018 ;; unnecessarily. Note that we move *forward* past intangible
6019 ;; text when the initial and final points are the same.
6020 (goto-char new)
6021 (let ((inhibit-point-motion-hooks nil))
6022 (goto-char new)
6023
6024 ;; If intangibility moves us to a different (later) place
6025 ;; in the same line, use that as the destination.
6026 (if (<= (point) line-end)
6027 (setq new (point))
6028 ;; If that position is "too late",
6029 ;; try the previous allowable position.
6030 ;; See if it is ok.
6031 (backward-char)
6032 (if (if forward
6033 ;; If going forward, don't accept the previous
6034 ;; allowable position if it is before the target line.
6035 (< line-beg (point))
6036 ;; If going backward, don't accept the previous
6037 ;; allowable position if it is still after the target line.
6038 (<= (point) line-end))
6039 (setq new (point))
6040 ;; As a last resort, use the end of the line.
6041 (setq new line-end))))
6042
6043 ;; Now move to the updated destination, processing fields
6044 ;; as well as intangibility.
6045 (goto-char opoint)
6046 (let ((inhibit-point-motion-hooks nil))
6047 (goto-char
6048 ;; Ignore field boundaries if the initial and final
6049 ;; positions have the same `field' property, even if the
6050 ;; fields are non-contiguous. This seems to be "nicer"
6051 ;; behavior in many situations.
6052 (if (eq (get-char-property new 'field)
6053 (get-char-property opoint 'field))
6054 new
6055 (constrain-to-field new opoint t t
6056 'inhibit-line-move-field-capture))))
6057
6058 ;; If all this moved us to a different line,
6059 ;; retry everything within that new line.
6060 (when (or (< (point) line-beg) (> (point) line-end))
6061 ;; Repeat the intangibility and field processing.
6062 (setq repeat t))))))
6063
6064 (defun line-move-to-column (col)
6065 "Try to find column COL, considering invisibility.
6066 This function works only in certain cases,
6067 because what we really need is for `move-to-column'
6068 and `current-column' to be able to ignore invisible text."
6069 (if (zerop col)
6070 (beginning-of-line)
6071 (move-to-column col))
6072
6073 (when (and line-move-ignore-invisible
6074 (not (bolp)) (invisible-p (1- (point))))
6075 (let ((normal-location (point))
6076 (normal-column (current-column)))
6077 ;; If the following character is currently invisible,
6078 ;; skip all characters with that same `invisible' property value.
6079 (while (and (not (eobp))
6080 (invisible-p (point)))
6081 (goto-char (next-char-property-change (point))))
6082 ;; Have we advanced to a larger column position?
6083 (if (> (current-column) normal-column)
6084 ;; We have made some progress towards the desired column.
6085 ;; See if we can make any further progress.
6086 (line-move-to-column (+ (current-column) (- col normal-column)))
6087 ;; Otherwise, go to the place we originally found
6088 ;; and move back over invisible text.
6089 ;; that will get us to the same place on the screen
6090 ;; but with a more reasonable buffer position.
6091 (goto-char normal-location)
6092 (let ((line-beg
6093 ;; We want the real line beginning, so it's consistent
6094 ;; with bolp below, otherwise we might infloop.
6095 (let ((inhibit-field-text-motion t))
6096 (line-beginning-position))))
6097 (while (and (not (bolp)) (invisible-p (1- (point))))
6098 (goto-char (previous-char-property-change (point) line-beg))))))))
6099
6100 (defun move-end-of-line (arg)
6101 "Move point to end of current line as displayed.
6102 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6103 If point reaches the beginning or end of buffer, it stops there.
6104
6105 To ignore the effects of the `intangible' text or overlay
6106 property, bind `inhibit-point-motion-hooks' to t.
6107 If there is an image in the current line, this function
6108 disregards newlines that are part of the text on which the image
6109 rests."
6110 (interactive "^p")
6111 (or arg (setq arg 1))
6112 (let (done)
6113 (while (not done)
6114 (let ((newpos
6115 (save-excursion
6116 (let ((goal-column 0)
6117 (line-move-visual nil))
6118 (and (line-move arg t)
6119 ;; With bidi reordering, we may not be at bol,
6120 ;; so make sure we are.
6121 (skip-chars-backward "^\n")
6122 (not (bobp))
6123 (progn
6124 (while (and (not (bobp)) (invisible-p (1- (point))))
6125 (goto-char (previous-single-char-property-change
6126 (point) 'invisible)))
6127 (backward-char 1)))
6128 (point)))))
6129 (goto-char newpos)
6130 (if (and (> (point) newpos)
6131 (eq (preceding-char) ?\n))
6132 (backward-char 1)
6133 (if (and (> (point) newpos) (not (eobp))
6134 (not (eq (following-char) ?\n)))
6135 ;; If we skipped something intangible and now we're not
6136 ;; really at eol, keep going.
6137 (setq arg 1)
6138 (setq done t)))))))
6139
6140 (defun move-beginning-of-line (arg)
6141 "Move point to beginning of current line as displayed.
6142 \(If there's an image in the line, this disregards newlines
6143 which are part of the text that the image rests on.)
6144
6145 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6146 If point reaches the beginning or end of buffer, it stops there.
6147 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6148 (interactive "^p")
6149 (or arg (setq arg 1))
6150
6151 (let ((orig (point))
6152 first-vis first-vis-field-value)
6153
6154 ;; Move by lines, if ARG is not 1 (the default).
6155 (if (/= arg 1)
6156 (let ((line-move-visual nil))
6157 (line-move (1- arg) t)))
6158
6159 ;; Move to beginning-of-line, ignoring fields and invisible text.
6160 (skip-chars-backward "^\n")
6161 (while (and (not (bobp)) (invisible-p (1- (point))))
6162 (goto-char (previous-char-property-change (point)))
6163 (skip-chars-backward "^\n"))
6164
6165 ;; Now find first visible char in the line.
6166 (while (and (< (point) orig) (invisible-p (point)))
6167 (goto-char (next-char-property-change (point) orig)))
6168 (setq first-vis (point))
6169
6170 ;; See if fields would stop us from reaching FIRST-VIS.
6171 (setq first-vis-field-value
6172 (constrain-to-field first-vis orig (/= arg 1) t nil))
6173
6174 (goto-char (if (/= first-vis-field-value first-vis)
6175 ;; If yes, obey them.
6176 first-vis-field-value
6177 ;; Otherwise, move to START with attention to fields.
6178 ;; (It is possible that fields never matter in this case.)
6179 (constrain-to-field (point) orig
6180 (/= arg 1) t nil)))))
6181
6182
6183 ;; Many people have said they rarely use this feature, and often type
6184 ;; it by accident. Maybe it shouldn't even be on a key.
6185 (put 'set-goal-column 'disabled t)
6186
6187 (defun set-goal-column (arg)
6188 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6189 Those commands will move to this position in the line moved to
6190 rather than trying to keep the same horizontal position.
6191 With a non-nil argument ARG, clears out the goal column
6192 so that \\[next-line] and \\[previous-line] resume vertical motion.
6193 The goal column is stored in the variable `goal-column'."
6194 (interactive "P")
6195 (if arg
6196 (progn
6197 (setq goal-column nil)
6198 (message "No goal column"))
6199 (setq goal-column (current-column))
6200 ;; The older method below can be erroneous if `set-goal-column' is bound
6201 ;; to a sequence containing %
6202 ;;(message (substitute-command-keys
6203 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6204 ;;goal-column)
6205 (message "%s"
6206 (concat
6207 (format "Goal column %d " goal-column)
6208 (substitute-command-keys
6209 "(use \\[set-goal-column] with an arg to unset it)")))
6210
6211 )
6212 nil)
6213 \f
6214 ;;; Editing based on visual lines, as opposed to logical lines.
6215
6216 (defun end-of-visual-line (&optional n)
6217 "Move point to end of current visual line.
6218 With argument N not nil or 1, move forward N - 1 visual lines first.
6219 If point reaches the beginning or end of buffer, it stops there.
6220 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6221 (interactive "^p")
6222 (or n (setq n 1))
6223 (if (/= n 1)
6224 (let ((line-move-visual t))
6225 (line-move (1- n) t)))
6226 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6227 ;; constrain to field boundaries, so we don't either.
6228 (vertical-motion (cons (window-width) 0)))
6229
6230 (defun beginning-of-visual-line (&optional n)
6231 "Move point to beginning of current visual line.
6232 With argument N not nil or 1, move forward N - 1 visual lines first.
6233 If point reaches the beginning or end of buffer, it stops there.
6234 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6235 (interactive "^p")
6236 (or n (setq n 1))
6237 (let ((opoint (point)))
6238 (if (/= n 1)
6239 (let ((line-move-visual t))
6240 (line-move (1- n) t)))
6241 (vertical-motion 0)
6242 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6243 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6244
6245 (defun kill-visual-line (&optional arg)
6246 "Kill the rest of the visual line.
6247 With prefix argument ARG, kill that many visual lines from point.
6248 If ARG is negative, kill visual lines backward.
6249 If ARG is zero, kill the text before point on the current visual
6250 line.
6251
6252 If you want to append the killed line to the last killed text,
6253 use \\[append-next-kill] before \\[kill-line].
6254
6255 If the buffer is read-only, Emacs will beep and refrain from deleting
6256 the line, but put the line in the kill ring anyway. This means that
6257 you can use this command to copy text from a read-only buffer.
6258 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6259 even beep.)"
6260 (interactive "P")
6261 ;; Like in `kill-line', it's better to move point to the other end
6262 ;; of the kill before killing.
6263 (let ((opoint (point))
6264 (kill-whole-line (and kill-whole-line (bolp))))
6265 (if arg
6266 (vertical-motion (prefix-numeric-value arg))
6267 (end-of-visual-line 1)
6268 (if (= (point) opoint)
6269 (vertical-motion 1)
6270 ;; Skip any trailing whitespace at the end of the visual line.
6271 ;; We used to do this only if `show-trailing-whitespace' is
6272 ;; nil, but that's wrong; the correct thing would be to check
6273 ;; whether the trailing whitespace is highlighted. But, it's
6274 ;; OK to just do this unconditionally.
6275 (skip-chars-forward " \t")))
6276 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6277 (1+ (point))
6278 (point)))))
6279
6280 (defun next-logical-line (&optional arg try-vscroll)
6281 "Move cursor vertically down ARG lines.
6282 This is identical to `next-line', except that it always moves
6283 by logical lines instead of visual lines, ignoring the value of
6284 the variable `line-move-visual'."
6285 (interactive "^p\np")
6286 (let ((line-move-visual nil))
6287 (with-no-warnings
6288 (next-line arg try-vscroll))))
6289
6290 (defun previous-logical-line (&optional arg try-vscroll)
6291 "Move cursor vertically up ARG lines.
6292 This is identical to `previous-line', except that it always moves
6293 by logical lines instead of visual lines, ignoring the value of
6294 the variable `line-move-visual'."
6295 (interactive "^p\np")
6296 (let ((line-move-visual nil))
6297 (with-no-warnings
6298 (previous-line arg try-vscroll))))
6299
6300 (defgroup visual-line nil
6301 "Editing based on visual lines."
6302 :group 'convenience
6303 :version "23.1")
6304
6305 (defvar visual-line-mode-map
6306 (let ((map (make-sparse-keymap)))
6307 (define-key map [remap kill-line] 'kill-visual-line)
6308 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6309 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6310 ;; These keybindings interfere with xterm function keys. Are
6311 ;; there any other suitable bindings?
6312 ;; (define-key map "\M-[" 'previous-logical-line)
6313 ;; (define-key map "\M-]" 'next-logical-line)
6314 map))
6315
6316 (defcustom visual-line-fringe-indicators '(nil nil)
6317 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6318 The value should be a list of the form (LEFT RIGHT), where LEFT
6319 and RIGHT are symbols representing the bitmaps to display, to
6320 indicate wrapped lines, in the left and right fringes respectively.
6321 See also `fringe-indicator-alist'.
6322 The default is not to display fringe indicators for wrapped lines.
6323 This variable does not affect fringe indicators displayed for
6324 other purposes."
6325 :type '(list (choice (const :tag "Hide left indicator" nil)
6326 (const :tag "Left curly arrow" left-curly-arrow)
6327 (symbol :tag "Other bitmap"))
6328 (choice (const :tag "Hide right indicator" nil)
6329 (const :tag "Right curly arrow" right-curly-arrow)
6330 (symbol :tag "Other bitmap")))
6331 :set (lambda (symbol value)
6332 (dolist (buf (buffer-list))
6333 (with-current-buffer buf
6334 (when (and (boundp 'visual-line-mode)
6335 (symbol-value 'visual-line-mode))
6336 (setq fringe-indicator-alist
6337 (cons (cons 'continuation value)
6338 (assq-delete-all
6339 'continuation
6340 (copy-tree fringe-indicator-alist)))))))
6341 (set-default symbol value)))
6342
6343 (defvar visual-line--saved-state nil)
6344
6345 (define-minor-mode visual-line-mode
6346 "Toggle visual line based editing (Visual Line mode).
6347 With a prefix argument ARG, enable Visual Line mode if ARG is
6348 positive, and disable it otherwise. If called from Lisp, enable
6349 the mode if ARG is omitted or nil.
6350
6351 When Visual Line mode is enabled, `word-wrap' is turned on in
6352 this buffer, and simple editing commands are redefined to act on
6353 visual lines, not logical lines. See Info node `Visual Line
6354 Mode' for details."
6355 :keymap visual-line-mode-map
6356 :group 'visual-line
6357 :lighter " Wrap"
6358 (if visual-line-mode
6359 (progn
6360 (set (make-local-variable 'visual-line--saved-state) nil)
6361 ;; Save the local values of some variables, to be restored if
6362 ;; visual-line-mode is turned off.
6363 (dolist (var '(line-move-visual truncate-lines
6364 truncate-partial-width-windows
6365 word-wrap fringe-indicator-alist))
6366 (if (local-variable-p var)
6367 (push (cons var (symbol-value var))
6368 visual-line--saved-state)))
6369 (set (make-local-variable 'line-move-visual) t)
6370 (set (make-local-variable 'truncate-partial-width-windows) nil)
6371 (setq truncate-lines nil
6372 word-wrap t
6373 fringe-indicator-alist
6374 (cons (cons 'continuation visual-line-fringe-indicators)
6375 fringe-indicator-alist)))
6376 (kill-local-variable 'line-move-visual)
6377 (kill-local-variable 'word-wrap)
6378 (kill-local-variable 'truncate-lines)
6379 (kill-local-variable 'truncate-partial-width-windows)
6380 (kill-local-variable 'fringe-indicator-alist)
6381 (dolist (saved visual-line--saved-state)
6382 (set (make-local-variable (car saved)) (cdr saved)))
6383 (kill-local-variable 'visual-line--saved-state)))
6384
6385 (defun turn-on-visual-line-mode ()
6386 (visual-line-mode 1))
6387
6388 (define-globalized-minor-mode global-visual-line-mode
6389 visual-line-mode turn-on-visual-line-mode)
6390
6391 \f
6392 (defun transpose-chars (arg)
6393 "Interchange characters around point, moving forward one character.
6394 With prefix arg ARG, effect is to take character before point
6395 and drag it forward past ARG other characters (backward if ARG negative).
6396 If no argument and at end of line, the previous two chars are exchanged."
6397 (interactive "*P")
6398 (when (and (null arg) (eolp) (not (bobp))
6399 (not (get-text-property (1- (point)) 'read-only)))
6400 (forward-char -1))
6401 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6402
6403 (defun transpose-words (arg)
6404 "Interchange words around point, leaving point at end of them.
6405 With prefix arg ARG, effect is to take word before or around point
6406 and drag it forward past ARG other words (backward if ARG negative).
6407 If ARG is zero, the words around or after point and around or after mark
6408 are interchanged."
6409 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6410 (interactive "*p")
6411 (transpose-subr 'forward-word arg))
6412
6413 (defun transpose-sexps (arg)
6414 "Like \\[transpose-words] but applies to sexps.
6415 Does not work on a sexp that point is in the middle of
6416 if it is a list or string."
6417 (interactive "*p")
6418 (transpose-subr
6419 (lambda (arg)
6420 ;; Here we should try to simulate the behavior of
6421 ;; (cons (progn (forward-sexp x) (point))
6422 ;; (progn (forward-sexp (- x)) (point)))
6423 ;; Except that we don't want to rely on the second forward-sexp
6424 ;; putting us back to where we want to be, since forward-sexp-function
6425 ;; might do funny things like infix-precedence.
6426 (if (if (> arg 0)
6427 (looking-at "\\sw\\|\\s_")
6428 (and (not (bobp))
6429 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6430 ;; Jumping over a symbol. We might be inside it, mind you.
6431 (progn (funcall (if (> arg 0)
6432 'skip-syntax-backward 'skip-syntax-forward)
6433 "w_")
6434 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6435 ;; Otherwise, we're between sexps. Take a step back before jumping
6436 ;; to make sure we'll obey the same precedence no matter which direction
6437 ;; we're going.
6438 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6439 (cons (save-excursion (forward-sexp arg) (point))
6440 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6441 (not (zerop (funcall (if (> arg 0)
6442 'skip-syntax-forward
6443 'skip-syntax-backward)
6444 ".")))))
6445 (point)))))
6446 arg 'special))
6447
6448 (defun transpose-lines (arg)
6449 "Exchange current line and previous line, leaving point after both.
6450 With argument ARG, takes previous line and moves it past ARG lines.
6451 With argument 0, interchanges line point is in with line mark is in."
6452 (interactive "*p")
6453 (transpose-subr (function
6454 (lambda (arg)
6455 (if (> arg 0)
6456 (progn
6457 ;; Move forward over ARG lines,
6458 ;; but create newlines if necessary.
6459 (setq arg (forward-line arg))
6460 (if (/= (preceding-char) ?\n)
6461 (setq arg (1+ arg)))
6462 (if (> arg 0)
6463 (newline arg)))
6464 (forward-line arg))))
6465 arg))
6466
6467 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6468 ;; which seems inconsistent with the ARG /= 0 case.
6469 ;; FIXME document SPECIAL.
6470 (defun transpose-subr (mover arg &optional special)
6471 "Subroutine to do the work of transposing objects.
6472 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6473 moves forward by units of the given object (e.g. forward-sentence,
6474 forward-paragraph). If ARG is zero, exchanges the current object
6475 with the one containing mark. If ARG is an integer, moves the
6476 current object past ARG following (if ARG is positive) or
6477 preceding (if ARG is negative) objects, leaving point after the
6478 current object."
6479 (let ((aux (if special mover
6480 (lambda (x)
6481 (cons (progn (funcall mover x) (point))
6482 (progn (funcall mover (- x)) (point))))))
6483 pos1 pos2)
6484 (cond
6485 ((= arg 0)
6486 (save-excursion
6487 (setq pos1 (funcall aux 1))
6488 (goto-char (or (mark) (error "No mark set in this buffer")))
6489 (setq pos2 (funcall aux 1))
6490 (transpose-subr-1 pos1 pos2))
6491 (exchange-point-and-mark))
6492 ((> arg 0)
6493 (setq pos1 (funcall aux -1))
6494 (setq pos2 (funcall aux arg))
6495 (transpose-subr-1 pos1 pos2)
6496 (goto-char (car pos2)))
6497 (t
6498 (setq pos1 (funcall aux -1))
6499 (goto-char (car pos1))
6500 (setq pos2 (funcall aux arg))
6501 (transpose-subr-1 pos1 pos2)))))
6502
6503 (defun transpose-subr-1 (pos1 pos2)
6504 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6505 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6506 (when (> (car pos1) (car pos2))
6507 (let ((swap pos1))
6508 (setq pos1 pos2 pos2 swap)))
6509 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6510 (atomic-change-group
6511 ;; This sequence of insertions attempts to preserve marker
6512 ;; positions at the start and end of the transposed objects.
6513 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6514 (len1 (- (cdr pos1) (car pos1)))
6515 (len2 (length word))
6516 (boundary (make-marker)))
6517 (set-marker boundary (car pos2))
6518 (goto-char (cdr pos1))
6519 (insert-before-markers word)
6520 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6521 (goto-char boundary)
6522 (insert word)
6523 (goto-char (+ boundary len1))
6524 (delete-region (point) (+ (point) len2))
6525 (set-marker boundary nil))))
6526 \f
6527 (defun backward-word (&optional arg)
6528 "Move backward until encountering the beginning of a word.
6529 With argument ARG, do this that many times.
6530 If ARG is omitted or nil, move point backward one word."
6531 (interactive "^p")
6532 (forward-word (- (or arg 1))))
6533
6534 (defun mark-word (&optional arg allow-extend)
6535 "Set mark ARG words away from point.
6536 The place mark goes is the same place \\[forward-word] would
6537 move to with the same argument.
6538 Interactively, if this command is repeated
6539 or (in Transient Mark mode) if the mark is active,
6540 it marks the next ARG words after the ones already marked."
6541 (interactive "P\np")
6542 (cond ((and allow-extend
6543 (or (and (eq last-command this-command) (mark t))
6544 (region-active-p)))
6545 (setq arg (if arg (prefix-numeric-value arg)
6546 (if (< (mark) (point)) -1 1)))
6547 (set-mark
6548 (save-excursion
6549 (goto-char (mark))
6550 (forward-word arg)
6551 (point))))
6552 (t
6553 (push-mark
6554 (save-excursion
6555 (forward-word (prefix-numeric-value arg))
6556 (point))
6557 nil t))))
6558
6559 (defun kill-word (arg)
6560 "Kill characters forward until encountering the end of a word.
6561 With argument ARG, do this that many times."
6562 (interactive "p")
6563 (kill-region (point) (progn (forward-word arg) (point))))
6564
6565 (defun backward-kill-word (arg)
6566 "Kill characters backward until encountering the beginning of a word.
6567 With argument ARG, do this that many times."
6568 (interactive "p")
6569 (kill-word (- arg)))
6570
6571 (defun current-word (&optional strict really-word)
6572 "Return the symbol or word that point is on (or a nearby one) as a string.
6573 The return value includes no text properties.
6574 If optional arg STRICT is non-nil, return nil unless point is within
6575 or adjacent to a symbol or word. In all cases the value can be nil
6576 if there is no word nearby.
6577 The function, belying its name, normally finds a symbol.
6578 If optional arg REALLY-WORD is non-nil, it finds just a word."
6579 (save-excursion
6580 (let* ((oldpoint (point)) (start (point)) (end (point))
6581 (syntaxes (if really-word "w" "w_"))
6582 (not-syntaxes (concat "^" syntaxes)))
6583 (skip-syntax-backward syntaxes) (setq start (point))
6584 (goto-char oldpoint)
6585 (skip-syntax-forward syntaxes) (setq end (point))
6586 (when (and (eq start oldpoint) (eq end oldpoint)
6587 ;; Point is neither within nor adjacent to a word.
6588 (not strict))
6589 ;; Look for preceding word in same line.
6590 (skip-syntax-backward not-syntaxes (line-beginning-position))
6591 (if (bolp)
6592 ;; No preceding word in same line.
6593 ;; Look for following word in same line.
6594 (progn
6595 (skip-syntax-forward not-syntaxes (line-end-position))
6596 (setq start (point))
6597 (skip-syntax-forward syntaxes)
6598 (setq end (point)))
6599 (setq end (point))
6600 (skip-syntax-backward syntaxes)
6601 (setq start (point))))
6602 ;; If we found something nonempty, return it as a string.
6603 (unless (= start end)
6604 (buffer-substring-no-properties start end)))))
6605 \f
6606 (defcustom fill-prefix nil
6607 "String for filling to insert at front of new line, or nil for none."
6608 :type '(choice (const :tag "None" nil)
6609 string)
6610 :group 'fill)
6611 (make-variable-buffer-local 'fill-prefix)
6612 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6613
6614 (defcustom auto-fill-inhibit-regexp nil
6615 "Regexp to match lines which should not be auto-filled."
6616 :type '(choice (const :tag "None" nil)
6617 regexp)
6618 :group 'fill)
6619
6620 (defun do-auto-fill ()
6621 "The default value for `normal-auto-fill-function'.
6622 This is the default auto-fill function, some major modes use a different one.
6623 Returns t if it really did any work."
6624 (let (fc justify give-up
6625 (fill-prefix fill-prefix))
6626 (if (or (not (setq justify (current-justification)))
6627 (null (setq fc (current-fill-column)))
6628 (and (eq justify 'left)
6629 (<= (current-column) fc))
6630 (and auto-fill-inhibit-regexp
6631 (save-excursion (beginning-of-line)
6632 (looking-at auto-fill-inhibit-regexp))))
6633 nil ;; Auto-filling not required
6634 (if (memq justify '(full center right))
6635 (save-excursion (unjustify-current-line)))
6636
6637 ;; Choose a fill-prefix automatically.
6638 (when (and adaptive-fill-mode
6639 (or (null fill-prefix) (string= fill-prefix "")))
6640 (let ((prefix
6641 (fill-context-prefix
6642 (save-excursion (fill-forward-paragraph -1) (point))
6643 (save-excursion (fill-forward-paragraph 1) (point)))))
6644 (and prefix (not (equal prefix ""))
6645 ;; Use auto-indentation rather than a guessed empty prefix.
6646 (not (and fill-indent-according-to-mode
6647 (string-match "\\`[ \t]*\\'" prefix)))
6648 (setq fill-prefix prefix))))
6649
6650 (while (and (not give-up) (> (current-column) fc))
6651 ;; Determine where to split the line.
6652 (let* (after-prefix
6653 (fill-point
6654 (save-excursion
6655 (beginning-of-line)
6656 (setq after-prefix (point))
6657 (and fill-prefix
6658 (looking-at (regexp-quote fill-prefix))
6659 (setq after-prefix (match-end 0)))
6660 (move-to-column (1+ fc))
6661 (fill-move-to-break-point after-prefix)
6662 (point))))
6663
6664 ;; See whether the place we found is any good.
6665 (if (save-excursion
6666 (goto-char fill-point)
6667 (or (bolp)
6668 ;; There is no use breaking at end of line.
6669 (save-excursion (skip-chars-forward " ") (eolp))
6670 ;; It is futile to split at the end of the prefix
6671 ;; since we would just insert the prefix again.
6672 (and after-prefix (<= (point) after-prefix))
6673 ;; Don't split right after a comment starter
6674 ;; since we would just make another comment starter.
6675 (and comment-start-skip
6676 (let ((limit (point)))
6677 (beginning-of-line)
6678 (and (re-search-forward comment-start-skip
6679 limit t)
6680 (eq (point) limit))))))
6681 ;; No good place to break => stop trying.
6682 (setq give-up t)
6683 ;; Ok, we have a useful place to break the line. Do it.
6684 (let ((prev-column (current-column)))
6685 ;; If point is at the fill-point, do not `save-excursion'.
6686 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6687 ;; point will end up before it rather than after it.
6688 (if (save-excursion
6689 (skip-chars-backward " \t")
6690 (= (point) fill-point))
6691 (default-indent-new-line t)
6692 (save-excursion
6693 (goto-char fill-point)
6694 (default-indent-new-line t)))
6695 ;; Now do justification, if required
6696 (if (not (eq justify 'left))
6697 (save-excursion
6698 (end-of-line 0)
6699 (justify-current-line justify nil t)))
6700 ;; If making the new line didn't reduce the hpos of
6701 ;; the end of the line, then give up now;
6702 ;; trying again will not help.
6703 (if (>= (current-column) prev-column)
6704 (setq give-up t))))))
6705 ;; Justify last line.
6706 (justify-current-line justify t t)
6707 t)))
6708
6709 (defvar comment-line-break-function 'comment-indent-new-line
6710 "Mode-specific function which line breaks and continues a comment.
6711 This function is called during auto-filling when a comment syntax
6712 is defined.
6713 The function should take a single optional argument, which is a flag
6714 indicating whether it should use soft newlines.")
6715
6716 (defun default-indent-new-line (&optional soft)
6717 "Break line at point and indent.
6718 If a comment syntax is defined, call `comment-indent-new-line'.
6719
6720 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6721 unless optional argument SOFT is non-nil."
6722 (interactive)
6723 (if comment-start
6724 (funcall comment-line-break-function soft)
6725 ;; Insert the newline before removing empty space so that markers
6726 ;; get preserved better.
6727 (if soft (insert-and-inherit ?\n) (newline 1))
6728 (save-excursion (forward-char -1) (delete-horizontal-space))
6729 (delete-horizontal-space)
6730
6731 (if (and fill-prefix (not adaptive-fill-mode))
6732 ;; Blindly trust a non-adaptive fill-prefix.
6733 (progn
6734 (indent-to-left-margin)
6735 (insert-before-markers-and-inherit fill-prefix))
6736
6737 (cond
6738 ;; If there's an adaptive prefix, use it unless we're inside
6739 ;; a comment and the prefix is not a comment starter.
6740 (fill-prefix
6741 (indent-to-left-margin)
6742 (insert-and-inherit fill-prefix))
6743 ;; If we're not inside a comment, just try to indent.
6744 (t (indent-according-to-mode))))))
6745
6746 (defvar normal-auto-fill-function 'do-auto-fill
6747 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6748 Some major modes set this.")
6749
6750 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6751 ;; `functions' and `hooks' are usually unsafe to set, but setting
6752 ;; auto-fill-function to nil in a file-local setting is safe and
6753 ;; can be useful to prevent auto-filling.
6754 (put 'auto-fill-function 'safe-local-variable 'null)
6755
6756 (define-minor-mode auto-fill-mode
6757 "Toggle automatic line breaking (Auto Fill mode).
6758 With a prefix argument ARG, enable Auto Fill mode if ARG is
6759 positive, and disable it otherwise. If called from Lisp, enable
6760 the mode if ARG is omitted or nil.
6761
6762 When Auto Fill mode is enabled, inserting a space at a column
6763 beyond `current-fill-column' automatically breaks the line at a
6764 previous space.
6765
6766 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6767 non-nil.
6768
6769 The value of `normal-auto-fill-function' specifies the function to use
6770 for `auto-fill-function' when turning Auto Fill mode on."
6771 :variable (auto-fill-function
6772 . (lambda (v) (setq auto-fill-function
6773 (if v normal-auto-fill-function)))))
6774
6775 ;; This holds a document string used to document auto-fill-mode.
6776 (defun auto-fill-function ()
6777 "Automatically break line at a previous space, in insertion of text."
6778 nil)
6779
6780 (defun turn-on-auto-fill ()
6781 "Unconditionally turn on Auto Fill mode."
6782 (auto-fill-mode 1))
6783
6784 (defun turn-off-auto-fill ()
6785 "Unconditionally turn off Auto Fill mode."
6786 (auto-fill-mode -1))
6787
6788 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6789
6790 (defun set-fill-column (arg)
6791 "Set `fill-column' to specified argument.
6792 Use \\[universal-argument] followed by a number to specify a column.
6793 Just \\[universal-argument] as argument means to use the current column."
6794 (interactive
6795 (list (or current-prefix-arg
6796 ;; We used to use current-column silently, but C-x f is too easily
6797 ;; typed as a typo for C-x C-f, so we turned it into an error and
6798 ;; now an interactive prompt.
6799 (read-number "Set fill-column to: " (current-column)))))
6800 (if (consp arg)
6801 (setq arg (current-column)))
6802 (if (not (integerp arg))
6803 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6804 (error "set-fill-column requires an explicit argument")
6805 (message "Fill column set to %d (was %d)" arg fill-column)
6806 (setq fill-column arg)))
6807 \f
6808 (defun set-selective-display (arg)
6809 "Set `selective-display' to ARG; clear it if no arg.
6810 When the value of `selective-display' is a number > 0,
6811 lines whose indentation is >= that value are not displayed.
6812 The variable `selective-display' has a separate value for each buffer."
6813 (interactive "P")
6814 (if (eq selective-display t)
6815 (error "selective-display already in use for marked lines"))
6816 (let ((current-vpos
6817 (save-restriction
6818 (narrow-to-region (point-min) (point))
6819 (goto-char (window-start))
6820 (vertical-motion (window-height)))))
6821 (setq selective-display
6822 (and arg (prefix-numeric-value arg)))
6823 (recenter current-vpos))
6824 (set-window-start (selected-window) (window-start))
6825 (princ "selective-display set to " t)
6826 (prin1 selective-display t)
6827 (princ "." t))
6828
6829 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
6830
6831 (defun toggle-truncate-lines (&optional arg)
6832 "Toggle truncating of long lines for the current buffer.
6833 When truncating is off, long lines are folded.
6834 With prefix argument ARG, truncate long lines if ARG is positive,
6835 otherwise fold them. Note that in side-by-side windows, this
6836 command has no effect if `truncate-partial-width-windows' is
6837 non-nil."
6838 (interactive "P")
6839 (setq truncate-lines
6840 (if (null arg)
6841 (not truncate-lines)
6842 (> (prefix-numeric-value arg) 0)))
6843 (force-mode-line-update)
6844 (unless truncate-lines
6845 (let ((buffer (current-buffer)))
6846 (walk-windows (lambda (window)
6847 (if (eq buffer (window-buffer window))
6848 (set-window-hscroll window 0)))
6849 nil t)))
6850 (message "Truncate long lines %s"
6851 (if truncate-lines "enabled" "disabled")))
6852
6853 (defun toggle-word-wrap (&optional arg)
6854 "Toggle whether to use word-wrapping for continuation lines.
6855 With prefix argument ARG, wrap continuation lines at word boundaries
6856 if ARG is positive, otherwise wrap them at the right screen edge.
6857 This command toggles the value of `word-wrap'. It has no effect
6858 if long lines are truncated."
6859 (interactive "P")
6860 (setq word-wrap
6861 (if (null arg)
6862 (not word-wrap)
6863 (> (prefix-numeric-value arg) 0)))
6864 (force-mode-line-update)
6865 (message "Word wrapping %s"
6866 (if word-wrap "enabled" "disabled")))
6867
6868 (defvar overwrite-mode-textual (purecopy " Ovwrt")
6869 "The string displayed in the mode line when in overwrite mode.")
6870 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
6871 "The string displayed in the mode line when in binary overwrite mode.")
6872
6873 (define-minor-mode overwrite-mode
6874 "Toggle Overwrite mode.
6875 With a prefix argument ARG, enable Overwrite mode if ARG is
6876 positive, and disable it otherwise. If called from Lisp, enable
6877 the mode if ARG is omitted or nil.
6878
6879 When Overwrite mode is enabled, printing characters typed in
6880 replace existing text on a one-for-one basis, rather than pushing
6881 it to the right. At the end of a line, such characters extend
6882 the line. Before a tab, such characters insert until the tab is
6883 filled in. \\[quoted-insert] still inserts characters in
6884 overwrite mode; this is supposed to make it easier to insert
6885 characters when necessary."
6886 :variable (overwrite-mode
6887 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
6888
6889 (define-minor-mode binary-overwrite-mode
6890 "Toggle Binary Overwrite mode.
6891 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6892 is positive, and disable it otherwise. If called from Lisp,
6893 enable the mode if ARG is omitted or nil.
6894
6895 When Binary Overwrite mode is enabled, printing characters typed
6896 in replace existing text. Newlines are not treated specially, so
6897 typing at the end of a line joins the line to the next, with the
6898 typed character between them. Typing before a tab character
6899 simply replaces the tab with the character typed.
6900 \\[quoted-insert] replaces the text at the cursor, just as
6901 ordinary typing characters do.
6902
6903 Note that Binary Overwrite mode is not its own minor mode; it is
6904 a specialization of overwrite mode, entered by setting the
6905 `overwrite-mode' variable to `overwrite-mode-binary'."
6906 :variable (overwrite-mode
6907 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
6908
6909 (define-minor-mode line-number-mode
6910 "Toggle line number display in the mode line (Line Number mode).
6911 With a prefix argument ARG, enable Line Number mode if ARG is
6912 positive, and disable it otherwise. If called from Lisp, enable
6913 the mode if ARG is omitted or nil.
6914
6915 Line numbers do not appear for very large buffers and buffers
6916 with very long lines; see variables `line-number-display-limit'
6917 and `line-number-display-limit-width'."
6918 :init-value t :global t :group 'mode-line)
6919
6920 (define-minor-mode column-number-mode
6921 "Toggle column number display in the mode line (Column Number mode).
6922 With a prefix argument ARG, enable Column Number mode if ARG is
6923 positive, and disable it otherwise.
6924
6925 If called from Lisp, enable the mode if ARG is omitted or nil."
6926 :global t :group 'mode-line)
6927
6928 (define-minor-mode size-indication-mode
6929 "Toggle buffer size display in the mode line (Size Indication mode).
6930 With a prefix argument ARG, enable Size Indication mode if ARG is
6931 positive, and disable it otherwise.
6932
6933 If called from Lisp, enable the mode if ARG is omitted or nil."
6934 :global t :group 'mode-line)
6935
6936 (define-minor-mode auto-save-mode
6937 "Toggle auto-saving in the current buffer (Auto Save mode).
6938 With a prefix argument ARG, enable Auto Save mode if ARG is
6939 positive, and disable it otherwise.
6940
6941 If called from Lisp, enable the mode if ARG is omitted or nil."
6942 :variable ((and buffer-auto-save-file-name
6943 ;; If auto-save is off because buffer has shrunk,
6944 ;; then toggling should turn it on.
6945 (>= buffer-saved-size 0))
6946 . (lambda (val)
6947 (setq buffer-auto-save-file-name
6948 (cond
6949 ((null val) nil)
6950 ((and buffer-file-name auto-save-visited-file-name
6951 (not buffer-read-only))
6952 buffer-file-name)
6953 (t (make-auto-save-file-name))))))
6954 ;; If -1 was stored here, to temporarily turn off saving,
6955 ;; turn it back on.
6956 (and (< buffer-saved-size 0)
6957 (setq buffer-saved-size 0)))
6958 \f
6959 (defgroup paren-blinking nil
6960 "Blinking matching of parens and expressions."
6961 :prefix "blink-matching-"
6962 :group 'paren-matching)
6963
6964 (defcustom blink-matching-paren t
6965 "Non-nil means show matching open-paren when close-paren is inserted.
6966 If t, highlight the paren. If `jump', briefly move cursor to its
6967 position. If `jump-offscreen', move cursor there even if the
6968 position is off screen. With any other non-nil value, the
6969 off-screen position of the opening paren will be shown in the
6970 echo area."
6971 :type '(choice
6972 (const :tag "Disable" nil)
6973 (const :tag "Highlight" t)
6974 (const :tag "Move cursor" jump)
6975 (const :tag "Move cursor, even if off screen" jump-offscreen))
6976 :group 'paren-blinking)
6977
6978 (defcustom blink-matching-paren-on-screen t
6979 "Non-nil means show matching open-paren when it is on screen.
6980 If nil, don't show it (but the open-paren can still be shown
6981 in the echo area when it is off screen).
6982
6983 This variable has no effect if `blink-matching-paren' is nil.
6984 \(In that case, the open-paren is never shown.)
6985 It is also ignored if `show-paren-mode' is enabled."
6986 :type 'boolean
6987 :group 'paren-blinking)
6988
6989 (defcustom blink-matching-paren-distance (* 100 1024)
6990 "If non-nil, maximum distance to search backwards for matching open-paren.
6991 If nil, search stops at the beginning of the accessible portion of the buffer."
6992 :version "23.2" ; 25->100k
6993 :type '(choice (const nil) integer)
6994 :group 'paren-blinking)
6995
6996 (defcustom blink-matching-delay 1
6997 "Time in seconds to delay after showing a matching paren."
6998 :type 'number
6999 :group 'paren-blinking)
7000
7001 (defcustom blink-matching-paren-dont-ignore-comments nil
7002 "If nil, `blink-matching-paren' ignores comments.
7003 More precisely, when looking for the matching parenthesis,
7004 it skips the contents of comments that end before point."
7005 :type 'boolean
7006 :group 'paren-blinking)
7007
7008 (defun blink-matching-check-mismatch (start end)
7009 "Return whether or not START...END are matching parens.
7010 END is the current point and START is the blink position.
7011 START might be nil if no matching starter was found.
7012 Returns non-nil if we find there is a mismatch."
7013 (let* ((end-syntax (syntax-after (1- end)))
7014 (matching-paren (and (consp end-syntax)
7015 (eq (syntax-class end-syntax) 5)
7016 (cdr end-syntax))))
7017 ;; For self-matched chars like " and $, we can't know when they're
7018 ;; mismatched or unmatched, so we can only do it for parens.
7019 (when matching-paren
7020 (not (and start
7021 (or
7022 (eq (char-after start) matching-paren)
7023 ;; The cdr might hold a new paren-class info rather than
7024 ;; a matching-char info, in which case the two CDRs
7025 ;; should match.
7026 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7027
7028 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7029 "Function to check parentheses mismatches.
7030 The function takes two arguments (START and END) where START is the
7031 position just before the opening token and END is the position right after.
7032 START can be nil, if it was not found.
7033 The function should return non-nil if the two tokens do not match.")
7034
7035 (defvar blink-matching--overlay
7036 (let ((ol (make-overlay (point) (point) nil t)))
7037 (overlay-put ol 'face 'show-paren-match)
7038 (delete-overlay ol)
7039 ol)
7040 "Overlay used to highlight the matching paren.")
7041
7042 (defun blink-matching-open ()
7043 "Momentarily highlight the beginning of the sexp before point."
7044 (interactive)
7045 (when (and (not (bobp))
7046 blink-matching-paren)
7047 (let* ((oldpos (point))
7048 (message-log-max nil) ; Don't log messages about paren matching.
7049 (blinkpos
7050 (save-excursion
7051 (save-restriction
7052 (if blink-matching-paren-distance
7053 (narrow-to-region
7054 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7055 (- (point) blink-matching-paren-distance))
7056 oldpos))
7057 (let ((parse-sexp-ignore-comments
7058 (and parse-sexp-ignore-comments
7059 (not blink-matching-paren-dont-ignore-comments))))
7060 (condition-case ()
7061 (progn
7062 (syntax-propertize (point))
7063 (forward-sexp -1)
7064 ;; backward-sexp skips backward over prefix chars,
7065 ;; so move back to the matching paren.
7066 (while (and (< (point) (1- oldpos))
7067 (let ((code (syntax-after (point))))
7068 (or (eq (syntax-class code) 6)
7069 (eq (logand 1048576 (car code))
7070 1048576))))
7071 (forward-char 1))
7072 (point))
7073 (error nil))))))
7074 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7075 (cond
7076 (mismatch
7077 (if blinkpos
7078 (if (minibufferp)
7079 (minibuffer-message "Mismatched parentheses")
7080 (message "Mismatched parentheses"))
7081 (if (minibufferp)
7082 (minibuffer-message "No matching parenthesis found")
7083 (message "No matching parenthesis found"))))
7084 ((not blinkpos) nil)
7085 ((or
7086 (eq blink-matching-paren 'jump-offscreen)
7087 (pos-visible-in-window-p blinkpos))
7088 ;; Matching open within window, temporarily move to or highlight
7089 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7090 ;; is non-nil.
7091 (and blink-matching-paren-on-screen
7092 (not show-paren-mode)
7093 (if (memq blink-matching-paren '(jump jump-offscreen))
7094 (save-excursion
7095 (goto-char blinkpos)
7096 (sit-for blink-matching-delay))
7097 (unwind-protect
7098 (progn
7099 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7100 (current-buffer))
7101 (sit-for blink-matching-delay))
7102 (delete-overlay blink-matching--overlay)))))
7103 (t
7104 (let ((open-paren-line-string
7105 (save-excursion
7106 (goto-char blinkpos)
7107 ;; Show what precedes the open in its line, if anything.
7108 (cond
7109 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7110 (buffer-substring (line-beginning-position)
7111 (1+ blinkpos)))
7112 ;; Show what follows the open in its line, if anything.
7113 ((save-excursion
7114 (forward-char 1)
7115 (skip-chars-forward " \t")
7116 (not (eolp)))
7117 (buffer-substring blinkpos
7118 (line-end-position)))
7119 ;; Otherwise show the previous nonblank line,
7120 ;; if there is one.
7121 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7122 (concat
7123 (buffer-substring (progn
7124 (skip-chars-backward "\n \t")
7125 (line-beginning-position))
7126 (progn (end-of-line)
7127 (skip-chars-backward " \t")
7128 (point)))
7129 ;; Replace the newline and other whitespace with `...'.
7130 "..."
7131 (buffer-substring blinkpos (1+ blinkpos))))
7132 ;; There is nothing to show except the char itself.
7133 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7134 (minibuffer-message
7135 "Matches %s"
7136 (substring-no-properties open-paren-line-string))))))))
7137
7138 (defvar blink-paren-function 'blink-matching-open
7139 "Function called, if non-nil, whenever a close parenthesis is inserted.
7140 More precisely, a char with closeparen syntax is self-inserted.")
7141
7142 (defun blink-paren-post-self-insert-function ()
7143 (when (and (eq (char-before) last-command-event) ; Sanity check.
7144 (memq (char-syntax last-command-event) '(?\) ?\$))
7145 blink-paren-function
7146 (not executing-kbd-macro)
7147 (not noninteractive)
7148 ;; Verify an even number of quoting characters precede the close.
7149 ;; FIXME: Also check if this parenthesis closes a comment as
7150 ;; can happen in Pascal and SML.
7151 (= 1 (logand 1 (- (point)
7152 (save-excursion
7153 (forward-char -1)
7154 (skip-syntax-backward "/\\")
7155 (point))))))
7156 (funcall blink-paren-function)))
7157
7158 (put 'blink-paren-post-self-insert-function 'priority 100)
7159
7160 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7161 ;; Most likely, this hook is nil, so this arg doesn't matter,
7162 ;; but I use it as a reminder that this function usually
7163 ;; likes to be run after others since it does
7164 ;; `sit-for'. That's also the reason it get a `priority' prop
7165 ;; of 100.
7166 'append)
7167 \f
7168 ;; This executes C-g typed while Emacs is waiting for a command.
7169 ;; Quitting out of a program does not go through here;
7170 ;; that happens in the QUIT macro at the C code level.
7171 (defun keyboard-quit ()
7172 "Signal a `quit' condition.
7173 During execution of Lisp code, this character causes a quit directly.
7174 At top-level, as an editor command, this simply beeps."
7175 (interactive)
7176 ;; Avoid adding the region to the window selection.
7177 (setq saved-region-selection nil)
7178 (let (select-active-regions)
7179 (deactivate-mark))
7180 (if (fboundp 'kmacro-keyboard-quit)
7181 (kmacro-keyboard-quit))
7182 (when completion-in-region-mode
7183 (completion-in-region-mode -1))
7184 ;; Force the next redisplay cycle to remove the "Def" indicator from
7185 ;; all the mode lines.
7186 (if defining-kbd-macro
7187 (force-mode-line-update t))
7188 (setq defining-kbd-macro nil)
7189 (let ((debug-on-quit nil))
7190 (signal 'quit nil)))
7191
7192 (defvar buffer-quit-function nil
7193 "Function to call to \"quit\" the current buffer, or nil if none.
7194 \\[keyboard-escape-quit] calls this function when its more local actions
7195 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7196
7197 (defun keyboard-escape-quit ()
7198 "Exit the current \"mode\" (in a generalized sense of the word).
7199 This command can exit an interactive command such as `query-replace',
7200 can clear out a prefix argument or a region,
7201 can get out of the minibuffer or other recursive edit,
7202 cancel the use of the current buffer (for special-purpose buffers),
7203 or go back to just one window (by deleting all but the selected window)."
7204 (interactive)
7205 (cond ((eq last-command 'mode-exited) nil)
7206 ((region-active-p)
7207 (deactivate-mark))
7208 ((> (minibuffer-depth) 0)
7209 (abort-recursive-edit))
7210 (current-prefix-arg
7211 nil)
7212 ((> (recursion-depth) 0)
7213 (exit-recursive-edit))
7214 (buffer-quit-function
7215 (funcall buffer-quit-function))
7216 ((not (one-window-p t))
7217 (delete-other-windows))
7218 ((string-match "^ \\*" (buffer-name (current-buffer)))
7219 (bury-buffer))))
7220
7221 (defun play-sound-file (file &optional volume device)
7222 "Play sound stored in FILE.
7223 VOLUME and DEVICE correspond to the keywords of the sound
7224 specification for `play-sound'."
7225 (interactive "fPlay sound file: ")
7226 (let ((sound (list :file file)))
7227 (if volume
7228 (plist-put sound :volume volume))
7229 (if device
7230 (plist-put sound :device device))
7231 (push 'sound sound)
7232 (play-sound sound)))
7233
7234 \f
7235 (defcustom read-mail-command 'rmail
7236 "Your preference for a mail reading package.
7237 This is used by some keybindings which support reading mail.
7238 See also `mail-user-agent' concerning sending mail."
7239 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7240 (function-item :tag "Gnus" :format "%t\n" gnus)
7241 (function-item :tag "Emacs interface to MH"
7242 :format "%t\n" mh-rmail)
7243 (function :tag "Other"))
7244 :version "21.1"
7245 :group 'mail)
7246
7247 (defcustom mail-user-agent 'message-user-agent
7248 "Your preference for a mail composition package.
7249 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7250 outgoing email message. This variable lets you specify which
7251 mail-sending package you prefer.
7252
7253 Valid values include:
7254
7255 `message-user-agent' -- use the Message package.
7256 See Info node `(message)'.
7257 `sendmail-user-agent' -- use the Mail package.
7258 See Info node `(emacs)Sending Mail'.
7259 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7260 See Info node `(mh-e)'.
7261 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7262 paraphernalia if Gnus is running, particularly
7263 the Gcc: header for archiving.
7264
7265 Additional valid symbols may be available; check with the author of
7266 your package for details. The function should return non-nil if it
7267 succeeds.
7268
7269 See also `read-mail-command' concerning reading mail."
7270 :type '(radio (function-item :tag "Message package"
7271 :format "%t\n"
7272 message-user-agent)
7273 (function-item :tag "Mail package"
7274 :format "%t\n"
7275 sendmail-user-agent)
7276 (function-item :tag "Emacs interface to MH"
7277 :format "%t\n"
7278 mh-e-user-agent)
7279 (function-item :tag "Message with full Gnus features"
7280 :format "%t\n"
7281 gnus-user-agent)
7282 (function :tag "Other"))
7283 :version "23.2" ; sendmail->message
7284 :group 'mail)
7285
7286 (defcustom compose-mail-user-agent-warnings t
7287 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7288 If the value of `mail-user-agent' is the default, and the user
7289 appears to have customizations applying to the old default,
7290 `compose-mail' issues a warning."
7291 :type 'boolean
7292 :version "23.2"
7293 :group 'mail)
7294
7295 (defun rfc822-goto-eoh ()
7296 "If the buffer starts with a mail header, move point to the header's end.
7297 Otherwise, moves to `point-min'.
7298 The end of the header is the start of the next line, if there is one,
7299 else the end of the last line. This function obeys RFC822."
7300 (goto-char (point-min))
7301 (when (re-search-forward
7302 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7303 (goto-char (match-beginning 0))))
7304
7305 ;; Used by Rmail (e.g., rmail-forward).
7306 (defvar mail-encode-mml nil
7307 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7308 the outgoing message before sending it.")
7309
7310 (defun compose-mail (&optional to subject other-headers continue
7311 switch-function yank-action send-actions
7312 return-action)
7313 "Start composing a mail message to send.
7314 This uses the user's chosen mail composition package
7315 as selected with the variable `mail-user-agent'.
7316 The optional arguments TO and SUBJECT specify recipients
7317 and the initial Subject field, respectively.
7318
7319 OTHER-HEADERS is an alist specifying additional
7320 header fields. Elements look like (HEADER . VALUE) where both
7321 HEADER and VALUE are strings.
7322
7323 CONTINUE, if non-nil, says to continue editing a message already
7324 being composed. Interactively, CONTINUE is the prefix argument.
7325
7326 SWITCH-FUNCTION, if non-nil, is a function to use to
7327 switch to and display the buffer used for mail composition.
7328
7329 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7330 to insert the raw text of the message being replied to.
7331 It has the form (FUNCTION . ARGS). The user agent will apply
7332 FUNCTION to ARGS, to insert the raw text of the original message.
7333 \(The user agent will also run `mail-citation-hook', *after* the
7334 original text has been inserted in this way.)
7335
7336 SEND-ACTIONS is a list of actions to call when the message is sent.
7337 Each action has the form (FUNCTION . ARGS).
7338
7339 RETURN-ACTION, if non-nil, is an action for returning to the
7340 caller. It has the form (FUNCTION . ARGS). The function is
7341 called after the mail has been sent or put aside, and the mail
7342 buffer buried."
7343 (interactive
7344 (list nil nil nil current-prefix-arg))
7345
7346 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7347 ;; from sendmail-user-agent to message-user-agent. Some users may
7348 ;; encounter incompatibilities. This hack tries to detect problems
7349 ;; and warn about them.
7350 (and compose-mail-user-agent-warnings
7351 (eq mail-user-agent 'message-user-agent)
7352 (let (warn-vars)
7353 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7354 mail-yank-hooks mail-archive-file-name
7355 mail-default-reply-to mail-mailing-lists
7356 mail-self-blind))
7357 (and (boundp var)
7358 (symbol-value var)
7359 (push var warn-vars)))
7360 (when warn-vars
7361 (display-warning 'mail
7362 (format-message "\
7363 The default mail mode is now Message mode.
7364 You have the following Mail mode variable%s customized:
7365 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7366 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7367 (if (> (length warn-vars) 1) "s" "")
7368 (mapconcat 'symbol-name
7369 warn-vars " "))))))
7370
7371 (let ((function (get mail-user-agent 'composefunc)))
7372 (funcall function to subject other-headers continue switch-function
7373 yank-action send-actions return-action)))
7374
7375 (defun compose-mail-other-window (&optional to subject other-headers continue
7376 yank-action send-actions
7377 return-action)
7378 "Like \\[compose-mail], but edit the outgoing message in another window."
7379 (interactive (list nil nil nil current-prefix-arg))
7380 (compose-mail to subject other-headers continue
7381 'switch-to-buffer-other-window yank-action send-actions
7382 return-action))
7383
7384 (defun compose-mail-other-frame (&optional to subject other-headers continue
7385 yank-action send-actions
7386 return-action)
7387 "Like \\[compose-mail], but edit the outgoing message in another frame."
7388 (interactive (list nil nil nil current-prefix-arg))
7389 (compose-mail to subject other-headers continue
7390 'switch-to-buffer-other-frame yank-action send-actions
7391 return-action))
7392
7393 \f
7394 (defvar set-variable-value-history nil
7395 "History of values entered with `set-variable'.
7396
7397 Maximum length of the history list is determined by the value
7398 of `history-length', which see.")
7399
7400 (defun set-variable (variable value &optional make-local)
7401 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7402 VARIABLE should be a user option variable name, a Lisp variable
7403 meant to be customized by users. You should enter VALUE in Lisp syntax,
7404 so if you want VALUE to be a string, you must surround it with doublequotes.
7405 VALUE is used literally, not evaluated.
7406
7407 If VARIABLE has a `variable-interactive' property, that is used as if
7408 it were the arg to `interactive' (which see) to interactively read VALUE.
7409
7410 If VARIABLE has been defined with `defcustom', then the type information
7411 in the definition is used to check that VALUE is valid.
7412
7413 Note that this function is at heart equivalent to the basic `set' function.
7414 For a variable defined with `defcustom', it does not pay attention to
7415 any :set property that the variable might have (if you want that, use
7416 \\[customize-set-variable] instead).
7417
7418 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7419 (interactive
7420 (let* ((default-var (variable-at-point))
7421 (var (if (custom-variable-p default-var)
7422 (read-variable (format "Set variable (default %s): " default-var)
7423 default-var)
7424 (read-variable "Set variable: ")))
7425 (minibuffer-help-form '(describe-variable var))
7426 (prop (get var 'variable-interactive))
7427 (obsolete (car (get var 'byte-obsolete-variable)))
7428 (prompt (format "Set %s %s to value: " var
7429 (cond ((local-variable-p var)
7430 "(buffer-local)")
7431 ((or current-prefix-arg
7432 (local-variable-if-set-p var))
7433 "buffer-locally")
7434 (t "globally"))))
7435 (val (progn
7436 (when obsolete
7437 (message (concat "`%S' is obsolete; "
7438 (if (symbolp obsolete) "use `%S' instead" "%s"))
7439 var obsolete)
7440 (sit-for 3))
7441 (if prop
7442 ;; Use VAR's `variable-interactive' property
7443 ;; as an interactive spec for prompting.
7444 (call-interactively `(lambda (arg)
7445 (interactive ,prop)
7446 arg))
7447 (read-from-minibuffer prompt nil
7448 read-expression-map t
7449 'set-variable-value-history
7450 (format "%S" (symbol-value var)))))))
7451 (list var val current-prefix-arg)))
7452
7453 (and (custom-variable-p variable)
7454 (not (get variable 'custom-type))
7455 (custom-load-symbol variable))
7456 (let ((type (get variable 'custom-type)))
7457 (when type
7458 ;; Match with custom type.
7459 (require 'cus-edit)
7460 (setq type (widget-convert type))
7461 (unless (widget-apply type :match value)
7462 (user-error "Value `%S' does not match type %S of %S"
7463 value (car type) variable))))
7464
7465 (if make-local
7466 (make-local-variable variable))
7467
7468 (set variable value)
7469
7470 ;; Force a thorough redisplay for the case that the variable
7471 ;; has an effect on the display, like `tab-width' has.
7472 (force-mode-line-update))
7473 \f
7474 ;; Define the major mode for lists of completions.
7475
7476 (defvar completion-list-mode-map
7477 (let ((map (make-sparse-keymap)))
7478 (define-key map [mouse-2] 'choose-completion)
7479 (define-key map [follow-link] 'mouse-face)
7480 (define-key map [down-mouse-2] nil)
7481 (define-key map "\C-m" 'choose-completion)
7482 (define-key map "\e\e\e" 'delete-completion-window)
7483 (define-key map [left] 'previous-completion)
7484 (define-key map [right] 'next-completion)
7485 (define-key map [?\t] 'next-completion)
7486 (define-key map [backtab] 'previous-completion)
7487 (define-key map "q" 'quit-window)
7488 (define-key map "z" 'kill-this-buffer)
7489 map)
7490 "Local map for completion list buffers.")
7491
7492 ;; Completion mode is suitable only for specially formatted data.
7493 (put 'completion-list-mode 'mode-class 'special)
7494
7495 (defvar completion-reference-buffer nil
7496 "Record the buffer that was current when the completion list was requested.
7497 This is a local variable in the completion list buffer.
7498 Initial value is nil to avoid some compiler warnings.")
7499
7500 (defvar completion-no-auto-exit nil
7501 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7502 This also applies to other functions such as `choose-completion'.")
7503
7504 (defvar completion-base-position nil
7505 "Position of the base of the text corresponding to the shown completions.
7506 This variable is used in the *Completions* buffers.
7507 Its value is a list of the form (START END) where START is the place
7508 where the completion should be inserted and END (if non-nil) is the end
7509 of the text to replace. If END is nil, point is used instead.")
7510
7511 (defvar completion-list-insert-choice-function #'completion--replace
7512 "Function to use to insert the text chosen in *Completions*.
7513 Called with three arguments (BEG END TEXT), it should replace the text
7514 between BEG and END with TEXT. Expected to be set buffer-locally
7515 in the *Completions* buffer.")
7516
7517 (defvar completion-base-size nil
7518 "Number of chars before point not involved in completion.
7519 This is a local variable in the completion list buffer.
7520 It refers to the chars in the minibuffer if completing in the
7521 minibuffer, or in `completion-reference-buffer' otherwise.
7522 Only characters in the field at point are included.
7523
7524 If nil, Emacs determines which part of the tail end of the
7525 buffer's text is involved in completion by comparing the text
7526 directly.")
7527 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7528
7529 (defun delete-completion-window ()
7530 "Delete the completion list window.
7531 Go to the window from which completion was requested."
7532 (interactive)
7533 (let ((buf completion-reference-buffer))
7534 (if (one-window-p t)
7535 (if (window-dedicated-p) (delete-frame))
7536 (delete-window (selected-window))
7537 (if (get-buffer-window buf)
7538 (select-window (get-buffer-window buf))))))
7539
7540 (defun previous-completion (n)
7541 "Move to the previous item in the completion list."
7542 (interactive "p")
7543 (next-completion (- n)))
7544
7545 (defun next-completion (n)
7546 "Move to the next item in the completion list.
7547 With prefix argument N, move N items (negative N means move backward)."
7548 (interactive "p")
7549 (let ((beg (point-min)) (end (point-max)))
7550 (while (and (> n 0) (not (eobp)))
7551 ;; If in a completion, move to the end of it.
7552 (when (get-text-property (point) 'mouse-face)
7553 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7554 ;; Move to start of next one.
7555 (unless (get-text-property (point) 'mouse-face)
7556 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7557 (setq n (1- n)))
7558 (while (and (< n 0) (not (bobp)))
7559 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7560 ;; If in a completion, move to the start of it.
7561 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7562 (goto-char (previous-single-property-change
7563 (point) 'mouse-face nil beg)))
7564 ;; Move to end of the previous completion.
7565 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7566 (goto-char (previous-single-property-change
7567 (point) 'mouse-face nil beg)))
7568 ;; Move to the start of that one.
7569 (goto-char (previous-single-property-change
7570 (point) 'mouse-face nil beg))
7571 (setq n (1+ n))))))
7572
7573 (defun choose-completion (&optional event)
7574 "Choose the completion at point.
7575 If EVENT, use EVENT's position to determine the starting position."
7576 (interactive (list last-nonmenu-event))
7577 ;; In case this is run via the mouse, give temporary modes such as
7578 ;; isearch a chance to turn off.
7579 (run-hooks 'mouse-leave-buffer-hook)
7580 (with-current-buffer (window-buffer (posn-window (event-start event)))
7581 (let ((buffer completion-reference-buffer)
7582 (base-size completion-base-size)
7583 (base-position completion-base-position)
7584 (insert-function completion-list-insert-choice-function)
7585 (choice
7586 (save-excursion
7587 (goto-char (posn-point (event-start event)))
7588 (let (beg end)
7589 (cond
7590 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7591 (setq end (point) beg (1+ (point))))
7592 ((and (not (bobp))
7593 (get-text-property (1- (point)) 'mouse-face))
7594 (setq end (1- (point)) beg (point)))
7595 (t (error "No completion here")))
7596 (setq beg (previous-single-property-change beg 'mouse-face))
7597 (setq end (or (next-single-property-change end 'mouse-face)
7598 (point-max)))
7599 (buffer-substring-no-properties beg end)))))
7600
7601 (unless (buffer-live-p buffer)
7602 (error "Destination buffer is dead"))
7603 (quit-window nil (posn-window (event-start event)))
7604
7605 (with-current-buffer buffer
7606 (choose-completion-string
7607 choice buffer
7608 (or base-position
7609 (when base-size
7610 ;; Someone's using old completion code that doesn't know
7611 ;; about base-position yet.
7612 (list (+ base-size (field-beginning))))
7613 ;; If all else fails, just guess.
7614 (list (choose-completion-guess-base-position choice)))
7615 insert-function)))))
7616
7617 ;; Delete the longest partial match for STRING
7618 ;; that can be found before POINT.
7619 (defun choose-completion-guess-base-position (string)
7620 (save-excursion
7621 (let ((opoint (point))
7622 len)
7623 ;; Try moving back by the length of the string.
7624 (goto-char (max (- (point) (length string))
7625 (minibuffer-prompt-end)))
7626 ;; See how far back we were actually able to move. That is the
7627 ;; upper bound on how much we can match and delete.
7628 (setq len (- opoint (point)))
7629 (if completion-ignore-case
7630 (setq string (downcase string)))
7631 (while (and (> len 0)
7632 (let ((tail (buffer-substring (point) opoint)))
7633 (if completion-ignore-case
7634 (setq tail (downcase tail)))
7635 (not (string= tail (substring string 0 len)))))
7636 (setq len (1- len))
7637 (forward-char 1))
7638 (point))))
7639
7640 (defun choose-completion-delete-max-match (string)
7641 (declare (obsolete choose-completion-guess-base-position "23.2"))
7642 (delete-region (choose-completion-guess-base-position string) (point)))
7643
7644 (defvar choose-completion-string-functions nil
7645 "Functions that may override the normal insertion of a completion choice.
7646 These functions are called in order with three arguments:
7647 CHOICE - the string to insert in the buffer,
7648 BUFFER - the buffer in which the choice should be inserted,
7649 BASE-POSITION - where to insert the completion.
7650
7651 If a function in the list returns non-nil, that function is supposed
7652 to have inserted the CHOICE in the BUFFER, and possibly exited
7653 the minibuffer; no further functions will be called.
7654
7655 If all functions in the list return nil, that means to use
7656 the default method of inserting the completion in BUFFER.")
7657
7658 (defun choose-completion-string (choice &optional
7659 buffer base-position insert-function)
7660 "Switch to BUFFER and insert the completion choice CHOICE.
7661 BASE-POSITION says where to insert the completion.
7662 INSERT-FUNCTION says how to insert the completion and falls
7663 back on `completion-list-insert-choice-function' when nil."
7664
7665 ;; If BUFFER is the minibuffer, exit the minibuffer
7666 ;; unless it is reading a file name and CHOICE is a directory,
7667 ;; or completion-no-auto-exit is non-nil.
7668
7669 ;; Some older code may call us passing `base-size' instead of
7670 ;; `base-position'. It's difficult to make any use of `base-size',
7671 ;; so we just ignore it.
7672 (unless (consp base-position)
7673 (message "Obsolete `base-size' passed to choose-completion-string")
7674 (setq base-position nil))
7675
7676 (let* ((buffer (or buffer completion-reference-buffer))
7677 (mini-p (minibufferp buffer)))
7678 ;; If BUFFER is a minibuffer, barf unless it's the currently
7679 ;; active minibuffer.
7680 (if (and mini-p
7681 (not (and (active-minibuffer-window)
7682 (equal buffer
7683 (window-buffer (active-minibuffer-window))))))
7684 (error "Minibuffer is not active for completion")
7685 ;; Set buffer so buffer-local choose-completion-string-functions works.
7686 (set-buffer buffer)
7687 (unless (run-hook-with-args-until-success
7688 'choose-completion-string-functions
7689 ;; The fourth arg used to be `mini-p' but was useless
7690 ;; (since minibufferp can be used on the `buffer' arg)
7691 ;; and indeed unused. The last used to be `base-size', so we
7692 ;; keep it to try and avoid breaking old code.
7693 choice buffer base-position nil)
7694 ;; This remove-text-properties should be unnecessary since `choice'
7695 ;; comes from buffer-substring-no-properties.
7696 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7697 ;; Insert the completion into the buffer where it was requested.
7698 (funcall (or insert-function completion-list-insert-choice-function)
7699 (or (car base-position) (point))
7700 (or (cadr base-position) (point))
7701 choice)
7702 ;; Update point in the window that BUFFER is showing in.
7703 (let ((window (get-buffer-window buffer t)))
7704 (set-window-point window (point)))
7705 ;; If completing for the minibuffer, exit it with this choice.
7706 (and (not completion-no-auto-exit)
7707 (minibufferp buffer)
7708 minibuffer-completion-table
7709 ;; If this is reading a file name, and the file name chosen
7710 ;; is a directory, don't exit the minibuffer.
7711 (let* ((result (buffer-substring (field-beginning) (point)))
7712 (bounds
7713 (completion-boundaries result minibuffer-completion-table
7714 minibuffer-completion-predicate
7715 "")))
7716 (if (eq (car bounds) (length result))
7717 ;; The completion chosen leads to a new set of completions
7718 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7719 (let ((mini (active-minibuffer-window)))
7720 (select-window mini)
7721 (when minibuffer-auto-raise
7722 (raise-frame (window-frame mini))))
7723 (exit-minibuffer))))))))
7724
7725 (define-derived-mode completion-list-mode nil "Completion List"
7726 "Major mode for buffers showing lists of possible completions.
7727 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7728 to select the completion near point.
7729 Or click to select one with the mouse.
7730
7731 \\{completion-list-mode-map}"
7732 (set (make-local-variable 'completion-base-size) nil))
7733
7734 (defun completion-list-mode-finish ()
7735 "Finish setup of the completions buffer.
7736 Called from `temp-buffer-show-hook'."
7737 (when (eq major-mode 'completion-list-mode)
7738 (setq buffer-read-only t)))
7739
7740 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7741
7742
7743 ;; Variables and faces used in `completion-setup-function'.
7744
7745 (defcustom completion-show-help t
7746 "Non-nil means show help message in *Completions* buffer."
7747 :type 'boolean
7748 :version "22.1"
7749 :group 'completion)
7750
7751 ;; This function goes in completion-setup-hook, so that it is called
7752 ;; after the text of the completion list buffer is written.
7753 (defun completion-setup-function ()
7754 (let* ((mainbuf (current-buffer))
7755 (base-dir
7756 ;; FIXME: This is a bad hack. We try to set the default-directory
7757 ;; in the *Completions* buffer so that the relative file names
7758 ;; displayed there can be treated as valid file names, independently
7759 ;; from the completion context. But this suffers from many problems:
7760 ;; - It's not clear when the completions are file names. With some
7761 ;; completion tables (e.g. bzr revision specs), the listed
7762 ;; completions can mix file names and other things.
7763 ;; - It doesn't pay attention to possible quoting.
7764 ;; - With fancy completion styles, the code below will not always
7765 ;; find the right base directory.
7766 (if minibuffer-completing-file-name
7767 (file-name-as-directory
7768 (expand-file-name
7769 (buffer-substring (minibuffer-prompt-end)
7770 (- (point) (or completion-base-size 0))))))))
7771 (with-current-buffer standard-output
7772 (let ((base-size completion-base-size) ;Read before killing localvars.
7773 (base-position completion-base-position)
7774 (insert-fun completion-list-insert-choice-function))
7775 (completion-list-mode)
7776 (set (make-local-variable 'completion-base-size) base-size)
7777 (set (make-local-variable 'completion-base-position) base-position)
7778 (set (make-local-variable 'completion-list-insert-choice-function)
7779 insert-fun))
7780 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7781 (if base-dir (setq default-directory base-dir))
7782 ;; Maybe insert help string.
7783 (when completion-show-help
7784 (goto-char (point-min))
7785 (if (display-mouse-p)
7786 (insert "Click on a completion to select it.\n"))
7787 (insert (substitute-command-keys
7788 "In this buffer, type \\[choose-completion] to \
7789 select the completion near point.\n\n"))))))
7790
7791 (add-hook 'completion-setup-hook 'completion-setup-function)
7792
7793 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7794 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7795
7796 (defun switch-to-completions ()
7797 "Select the completion list window."
7798 (interactive)
7799 (let ((window (or (get-buffer-window "*Completions*" 0)
7800 ;; Make sure we have a completions window.
7801 (progn (minibuffer-completion-help)
7802 (get-buffer-window "*Completions*" 0)))))
7803 (when window
7804 (select-window window)
7805 ;; In the new buffer, go to the first completion.
7806 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7807 (when (bobp)
7808 (next-completion 1)))))
7809 \f
7810 ;;; Support keyboard commands to turn on various modifiers.
7811
7812 ;; These functions -- which are not commands -- each add one modifier
7813 ;; to the following event.
7814
7815 (defun event-apply-alt-modifier (_ignore-prompt)
7816 "\\<function-key-map>Add the Alt modifier to the following event.
7817 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7818 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7819 (defun event-apply-super-modifier (_ignore-prompt)
7820 "\\<function-key-map>Add the Super modifier to the following event.
7821 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7822 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7823 (defun event-apply-hyper-modifier (_ignore-prompt)
7824 "\\<function-key-map>Add the Hyper modifier to the following event.
7825 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7826 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7827 (defun event-apply-shift-modifier (_ignore-prompt)
7828 "\\<function-key-map>Add the Shift modifier to the following event.
7829 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7830 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7831 (defun event-apply-control-modifier (_ignore-prompt)
7832 "\\<function-key-map>Add the Ctrl modifier to the following event.
7833 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7834 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7835 (defun event-apply-meta-modifier (_ignore-prompt)
7836 "\\<function-key-map>Add the Meta modifier to the following event.
7837 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7838 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7839
7840 (defun event-apply-modifier (event symbol lshiftby prefix)
7841 "Apply a modifier flag to event EVENT.
7842 SYMBOL is the name of this modifier, as a symbol.
7843 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7844 PREFIX is the string that represents this modifier in an event type symbol."
7845 (if (numberp event)
7846 (cond ((eq symbol 'control)
7847 (if (and (<= (downcase event) ?z)
7848 (>= (downcase event) ?a))
7849 (- (downcase event) ?a -1)
7850 (if (and (<= (downcase event) ?Z)
7851 (>= (downcase event) ?A))
7852 (- (downcase event) ?A -1)
7853 (logior (lsh 1 lshiftby) event))))
7854 ((eq symbol 'shift)
7855 (if (and (<= (downcase event) ?z)
7856 (>= (downcase event) ?a))
7857 (upcase event)
7858 (logior (lsh 1 lshiftby) event)))
7859 (t
7860 (logior (lsh 1 lshiftby) event)))
7861 (if (memq symbol (event-modifiers event))
7862 event
7863 (let ((event-type (if (symbolp event) event (car event))))
7864 (setq event-type (intern (concat prefix (symbol-name event-type))))
7865 (if (symbolp event)
7866 event-type
7867 (cons event-type (cdr event)))))))
7868
7869 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7870 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7871 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7872 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7873 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7874 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7875 \f
7876 ;;;; Keypad support.
7877
7878 ;; Make the keypad keys act like ordinary typing keys. If people add
7879 ;; bindings for the function key symbols, then those bindings will
7880 ;; override these, so this shouldn't interfere with any existing
7881 ;; bindings.
7882
7883 ;; Also tell read-char how to handle these keys.
7884 (mapc
7885 (lambda (keypad-normal)
7886 (let ((keypad (nth 0 keypad-normal))
7887 (normal (nth 1 keypad-normal)))
7888 (put keypad 'ascii-character normal)
7889 (define-key function-key-map (vector keypad) (vector normal))))
7890 ;; See also kp-keys bound in bindings.el.
7891 '((kp-space ?\s)
7892 (kp-tab ?\t)
7893 (kp-enter ?\r)
7894 (kp-separator ?,)
7895 (kp-equal ?=)
7896 ;; Do the same for various keys that are represented as symbols under
7897 ;; GUIs but naturally correspond to characters.
7898 (backspace 127)
7899 (delete 127)
7900 (tab ?\t)
7901 (linefeed ?\n)
7902 (clear ?\C-l)
7903 (return ?\C-m)
7904 (escape ?\e)
7905 ))
7906 \f
7907 ;;;;
7908 ;;;; forking a twin copy of a buffer.
7909 ;;;;
7910
7911 (defvar clone-buffer-hook nil
7912 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7913
7914 (defvar clone-indirect-buffer-hook nil
7915 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7916
7917 (defun clone-process (process &optional newname)
7918 "Create a twin copy of PROCESS.
7919 If NEWNAME is nil, it defaults to PROCESS' name;
7920 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7921 If PROCESS is associated with a buffer, the new process will be associated
7922 with the current buffer instead.
7923 Returns nil if PROCESS has already terminated."
7924 (setq newname (or newname (process-name process)))
7925 (if (string-match "<[0-9]+>\\'" newname)
7926 (setq newname (substring newname 0 (match-beginning 0))))
7927 (when (memq (process-status process) '(run stop open))
7928 (let* ((process-connection-type (process-tty-name process))
7929 (new-process
7930 (if (memq (process-status process) '(open))
7931 (let ((args (process-contact process t)))
7932 (setq args (plist-put args :name newname))
7933 (setq args (plist-put args :buffer
7934 (if (process-buffer process)
7935 (current-buffer))))
7936 (apply 'make-network-process args))
7937 (apply 'start-process newname
7938 (if (process-buffer process) (current-buffer))
7939 (process-command process)))))
7940 (set-process-query-on-exit-flag
7941 new-process (process-query-on-exit-flag process))
7942 (set-process-inherit-coding-system-flag
7943 new-process (process-inherit-coding-system-flag process))
7944 (set-process-filter new-process (process-filter process))
7945 (set-process-sentinel new-process (process-sentinel process))
7946 (set-process-plist new-process (copy-sequence (process-plist process)))
7947 new-process)))
7948
7949 ;; things to maybe add (currently partly covered by `funcall mode'):
7950 ;; - syntax-table
7951 ;; - overlays
7952 (defun clone-buffer (&optional newname display-flag)
7953 "Create and return a twin copy of the current buffer.
7954 Unlike an indirect buffer, the new buffer can be edited
7955 independently of the old one (if it is not read-only).
7956 NEWNAME is the name of the new buffer. It may be modified by
7957 adding or incrementing <N> at the end as necessary to create a
7958 unique buffer name. If nil, it defaults to the name of the
7959 current buffer, with the proper suffix. If DISPLAY-FLAG is
7960 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7961 clone a file-visiting buffer, or a buffer whose major mode symbol
7962 has a non-nil `no-clone' property, results in an error.
7963
7964 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7965 current buffer with appropriate suffix. However, if a prefix
7966 argument is given, then the command prompts for NEWNAME in the
7967 minibuffer.
7968
7969 This runs the normal hook `clone-buffer-hook' in the new buffer
7970 after it has been set up properly in other respects."
7971 (interactive
7972 (progn
7973 (if buffer-file-name
7974 (error "Cannot clone a file-visiting buffer"))
7975 (if (get major-mode 'no-clone)
7976 (error "Cannot clone a buffer in %s mode" mode-name))
7977 (list (if current-prefix-arg
7978 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7979 t)))
7980 (if buffer-file-name
7981 (error "Cannot clone a file-visiting buffer"))
7982 (if (get major-mode 'no-clone)
7983 (error "Cannot clone a buffer in %s mode" mode-name))
7984 (setq newname (or newname (buffer-name)))
7985 (if (string-match "<[0-9]+>\\'" newname)
7986 (setq newname (substring newname 0 (match-beginning 0))))
7987 (let ((buf (current-buffer))
7988 (ptmin (point-min))
7989 (ptmax (point-max))
7990 (pt (point))
7991 (mk (if mark-active (mark t)))
7992 (modified (buffer-modified-p))
7993 (mode major-mode)
7994 (lvars (buffer-local-variables))
7995 (process (get-buffer-process (current-buffer)))
7996 (new (generate-new-buffer (or newname (buffer-name)))))
7997 (save-restriction
7998 (widen)
7999 (with-current-buffer new
8000 (insert-buffer-substring buf)))
8001 (with-current-buffer new
8002 (narrow-to-region ptmin ptmax)
8003 (goto-char pt)
8004 (if mk (set-mark mk))
8005 (set-buffer-modified-p modified)
8006
8007 ;; Clone the old buffer's process, if any.
8008 (when process (clone-process process))
8009
8010 ;; Now set up the major mode.
8011 (funcall mode)
8012
8013 ;; Set up other local variables.
8014 (mapc (lambda (v)
8015 (condition-case () ;in case var is read-only
8016 (if (symbolp v)
8017 (makunbound v)
8018 (set (make-local-variable (car v)) (cdr v)))
8019 (error nil)))
8020 lvars)
8021
8022 ;; Run any hooks (typically set up by the major mode
8023 ;; for cloning to work properly).
8024 (run-hooks 'clone-buffer-hook))
8025 (if display-flag
8026 ;; Presumably the current buffer is shown in the selected frame, so
8027 ;; we want to display the clone elsewhere.
8028 (let ((same-window-regexps nil)
8029 (same-window-buffer-names))
8030 (pop-to-buffer new)))
8031 new))
8032
8033
8034 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8035 "Create an indirect buffer that is a twin copy of the current buffer.
8036
8037 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8038 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8039 or if not called with a prefix arg, NEWNAME defaults to the current
8040 buffer's name. The name is modified by adding a `<N>' suffix to it
8041 or by incrementing the N in an existing suffix. Trying to clone a
8042 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8043 property results in an error.
8044
8045 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8046 This is always done when called interactively.
8047
8048 Optional third arg NORECORD non-nil means do not put this buffer at the
8049 front of the list of recently selected ones.
8050
8051 Returns the newly created indirect buffer."
8052 (interactive
8053 (progn
8054 (if (get major-mode 'no-clone-indirect)
8055 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8056 (list (if current-prefix-arg
8057 (read-buffer "Name of indirect buffer: " (current-buffer)))
8058 t)))
8059 (if (get major-mode 'no-clone-indirect)
8060 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8061 (setq newname (or newname (buffer-name)))
8062 (if (string-match "<[0-9]+>\\'" newname)
8063 (setq newname (substring newname 0 (match-beginning 0))))
8064 (let* ((name (generate-new-buffer-name newname))
8065 (buffer (make-indirect-buffer (current-buffer) name t)))
8066 (with-current-buffer buffer
8067 (run-hooks 'clone-indirect-buffer-hook))
8068 (when display-flag
8069 (pop-to-buffer buffer norecord))
8070 buffer))
8071
8072
8073 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8074 "Like `clone-indirect-buffer' but display in another window."
8075 (interactive
8076 (progn
8077 (if (get major-mode 'no-clone-indirect)
8078 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8079 (list (if current-prefix-arg
8080 (read-buffer "Name of indirect buffer: " (current-buffer)))
8081 t)))
8082 (let ((pop-up-windows t))
8083 (clone-indirect-buffer newname display-flag norecord)))
8084
8085 \f
8086 ;;; Handling of Backspace and Delete keys.
8087
8088 (defcustom normal-erase-is-backspace 'maybe
8089 "Set the default behavior of the Delete and Backspace keys.
8090
8091 If set to t, Delete key deletes forward and Backspace key deletes
8092 backward.
8093
8094 If set to nil, both Delete and Backspace keys delete backward.
8095
8096 If set to 'maybe (which is the default), Emacs automatically
8097 selects a behavior. On window systems, the behavior depends on
8098 the keyboard used. If the keyboard has both a Backspace key and
8099 a Delete key, and both are mapped to their usual meanings, the
8100 option's default value is set to t, so that Backspace can be used
8101 to delete backward, and Delete can be used to delete forward.
8102
8103 If not running under a window system, customizing this option
8104 accomplishes a similar effect by mapping C-h, which is usually
8105 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8106 via `keyboard-translate'. The former functionality of C-h is
8107 available on the F1 key. You should probably not use this
8108 setting if you don't have both Backspace, Delete and F1 keys.
8109
8110 Setting this variable with setq doesn't take effect. Programmatically,
8111 call `normal-erase-is-backspace-mode' (which see) instead."
8112 :type '(choice (const :tag "Off" nil)
8113 (const :tag "Maybe" maybe)
8114 (other :tag "On" t))
8115 :group 'editing-basics
8116 :version "21.1"
8117 :set (lambda (symbol value)
8118 ;; The fboundp is because of a problem with :set when
8119 ;; dumping Emacs. It doesn't really matter.
8120 (if (fboundp 'normal-erase-is-backspace-mode)
8121 (normal-erase-is-backspace-mode (or value 0))
8122 (set-default symbol value))))
8123
8124 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8125 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8126 (unless frame (setq frame (selected-frame)))
8127 (with-selected-frame frame
8128 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8129 (normal-erase-is-backspace-mode
8130 (if (if (eq normal-erase-is-backspace 'maybe)
8131 (and (not noninteractive)
8132 (or (memq system-type '(ms-dos windows-nt))
8133 (memq window-system '(w32 ns))
8134 (and (memq window-system '(x))
8135 (fboundp 'x-backspace-delete-keys-p)
8136 (x-backspace-delete-keys-p))
8137 ;; If the terminal Emacs is running on has erase char
8138 ;; set to ^H, use the Backspace key for deleting
8139 ;; backward, and the Delete key for deleting forward.
8140 (and (null window-system)
8141 (eq tty-erase-char ?\^H))))
8142 normal-erase-is-backspace)
8143 1 0)))))
8144
8145 (define-minor-mode normal-erase-is-backspace-mode
8146 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8147 With a prefix argument ARG, enable this feature if ARG is
8148 positive, and disable it otherwise. If called from Lisp, enable
8149 the mode if ARG is omitted or nil.
8150
8151 On window systems, when this mode is on, Delete is mapped to C-d
8152 and Backspace is mapped to DEL; when this mode is off, both
8153 Delete and Backspace are mapped to DEL. (The remapping goes via
8154 `local-function-key-map', so binding Delete or Backspace in the
8155 global or local keymap will override that.)
8156
8157 In addition, on window systems, the bindings of C-Delete, M-Delete,
8158 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8159 the global keymap in accordance with the functionality of Delete and
8160 Backspace. For example, if Delete is remapped to C-d, which deletes
8161 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8162 to DEL, which deletes backward, C-Delete is bound to
8163 `backward-kill-word'.
8164
8165 If not running on a window system, a similar effect is accomplished by
8166 remapping C-h (normally produced by the Backspace key) and DEL via
8167 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8168 to C-d; if it's off, the keys are not remapped.
8169
8170 When not running on a window system, and this mode is turned on, the
8171 former functionality of C-h is available on the F1 key. You should
8172 probably not turn on this mode on a text-only terminal if you don't
8173 have both Backspace, Delete and F1 keys.
8174
8175 See also `normal-erase-is-backspace'."
8176 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8177 . (lambda (v)
8178 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8179 (if v 1 0))))
8180 (let ((enabled (eq 1 (terminal-parameter
8181 nil 'normal-erase-is-backspace))))
8182
8183 (cond ((or (memq window-system '(x w32 ns pc))
8184 (memq system-type '(ms-dos windows-nt)))
8185 (let ((bindings
8186 `(([M-delete] [M-backspace])
8187 ([C-M-delete] [C-M-backspace])
8188 ([?\e C-delete] [?\e C-backspace]))))
8189
8190 (if enabled
8191 (progn
8192 (define-key local-function-key-map [delete] [deletechar])
8193 (define-key local-function-key-map [kp-delete] [deletechar])
8194 (define-key local-function-key-map [backspace] [?\C-?])
8195 (dolist (b bindings)
8196 ;; Not sure if input-decode-map is really right, but
8197 ;; keyboard-translate-table (used below) only works
8198 ;; for integer events, and key-translation-table is
8199 ;; global (like the global-map, used earlier).
8200 (define-key input-decode-map (car b) nil)
8201 (define-key input-decode-map (cadr b) nil)))
8202 (define-key local-function-key-map [delete] [?\C-?])
8203 (define-key local-function-key-map [kp-delete] [?\C-?])
8204 (define-key local-function-key-map [backspace] [?\C-?])
8205 (dolist (b bindings)
8206 (define-key input-decode-map (car b) (cadr b))
8207 (define-key input-decode-map (cadr b) (car b))))))
8208 (t
8209 (if enabled
8210 (progn
8211 (keyboard-translate ?\C-h ?\C-?)
8212 (keyboard-translate ?\C-? ?\C-d))
8213 (keyboard-translate ?\C-h ?\C-h)
8214 (keyboard-translate ?\C-? ?\C-?))))
8215
8216 (if (called-interactively-p 'interactive)
8217 (message "Delete key deletes %s"
8218 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8219 "forward" "backward")))))
8220 \f
8221 (defvar vis-mode-saved-buffer-invisibility-spec nil
8222 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8223
8224 (define-minor-mode read-only-mode
8225 "Change whether the current buffer is read-only.
8226 With prefix argument ARG, make the buffer read-only if ARG is
8227 positive, otherwise make it writable. If buffer is read-only
8228 and `view-read-only' is non-nil, enter view mode.
8229
8230 Do not call this from a Lisp program unless you really intend to
8231 do the same thing as the \\[read-only-mode] command, including
8232 possibly enabling or disabling View mode. Also, note that this
8233 command works by setting the variable `buffer-read-only', which
8234 does not affect read-only regions caused by text properties. To
8235 ignore read-only status in a Lisp program (whether due to text
8236 properties or buffer state), bind `inhibit-read-only' temporarily
8237 to a non-nil value."
8238 :variable buffer-read-only
8239 (cond
8240 ((and (not buffer-read-only) view-mode)
8241 (View-exit-and-edit)
8242 (make-local-variable 'view-read-only)
8243 (setq view-read-only t)) ; Must leave view mode.
8244 ((and buffer-read-only view-read-only
8245 ;; If view-mode is already active, `view-mode-enter' is a nop.
8246 (not view-mode)
8247 (not (eq (get major-mode 'mode-class) 'special)))
8248 (view-mode-enter))))
8249
8250 (define-minor-mode visible-mode
8251 "Toggle making all invisible text temporarily visible (Visible mode).
8252 With a prefix argument ARG, enable Visible mode if ARG is
8253 positive, and disable it otherwise. If called from Lisp, enable
8254 the mode if ARG is omitted or nil.
8255
8256 This mode works by saving the value of `buffer-invisibility-spec'
8257 and setting it to nil."
8258 :lighter " Vis"
8259 :group 'editing-basics
8260 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8261 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8262 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8263 (when visible-mode
8264 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8265 buffer-invisibility-spec)
8266 (setq buffer-invisibility-spec nil)))
8267 \f
8268 (defvar messages-buffer-mode-map
8269 (let ((map (make-sparse-keymap)))
8270 (set-keymap-parent map special-mode-map)
8271 (define-key map "g" nil) ; nothing to revert
8272 map))
8273
8274 (define-derived-mode messages-buffer-mode special-mode "Messages"
8275 "Major mode used in the \"*Messages*\" buffer.")
8276
8277 (defun messages-buffer ()
8278 "Return the \"*Messages*\" buffer.
8279 If it does not exist, create and it switch it to `messages-buffer-mode'."
8280 (or (get-buffer "*Messages*")
8281 (with-current-buffer (get-buffer-create "*Messages*")
8282 (messages-buffer-mode)
8283 (current-buffer))))
8284
8285 \f
8286 ;; Minibuffer prompt stuff.
8287
8288 ;;(defun minibuffer-prompt-modification (start end)
8289 ;; (error "You cannot modify the prompt"))
8290 ;;
8291 ;;
8292 ;;(defun minibuffer-prompt-insertion (start end)
8293 ;; (let ((inhibit-modification-hooks t))
8294 ;; (delete-region start end)
8295 ;; ;; Discard undo information for the text insertion itself
8296 ;; ;; and for the text deletion.above.
8297 ;; (when (consp buffer-undo-list)
8298 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8299 ;; (message "You cannot modify the prompt")))
8300 ;;
8301 ;;
8302 ;;(setq minibuffer-prompt-properties
8303 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8304 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8305
8306 \f
8307 ;;;; Problematic external packages.
8308
8309 ;; rms says this should be done by specifying symbols that define
8310 ;; versions together with bad values. This is therefore not as
8311 ;; flexible as it could be. See the thread:
8312 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8313 (defconst bad-packages-alist
8314 ;; Not sure exactly which semantic versions have problems.
8315 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8316 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8317 "The version of `semantic' loaded does not work in Emacs 22.
8318 It can cause constant high CPU load.
8319 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8320 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8321 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8322 ;; provided the `CUA-mode' feature. Since this is no longer true,
8323 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8324 (CUA-mode t nil
8325 "CUA-mode is now part of the standard GNU Emacs distribution,
8326 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8327
8328 You have loaded an older version of CUA-mode which does not work
8329 correctly with this version of Emacs. You should remove the old
8330 version and use the one distributed with Emacs."))
8331 "Alist of packages known to cause problems in this version of Emacs.
8332 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8333 PACKAGE is either a regular expression to match file names, or a
8334 symbol (a feature name), like for `with-eval-after-load'.
8335 SYMBOL is either the name of a string variable, or t. Upon
8336 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8337 warning using STRING as the message.")
8338
8339 (defun bad-package-check (package)
8340 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8341 (condition-case nil
8342 (let* ((list (assoc package bad-packages-alist))
8343 (symbol (nth 1 list)))
8344 (and list
8345 (boundp symbol)
8346 (or (eq symbol t)
8347 (and (stringp (setq symbol (eval symbol)))
8348 (string-match-p (nth 2 list) symbol)))
8349 (display-warning package (nth 3 list) :warning)))
8350 (error nil)))
8351
8352 (dolist (elem bad-packages-alist)
8353 (let ((pkg (car elem)))
8354 (with-eval-after-load pkg
8355 (bad-package-check pkg))))
8356
8357 \f
8358 ;;; Generic dispatcher commands
8359
8360 ;; Macro `define-alternatives' is used to create generic commands.
8361 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8362 ;; that can have different alternative implementations where choosing
8363 ;; among them is exclusively a matter of user preference.
8364
8365 ;; (define-alternatives COMMAND) creates a new interactive command
8366 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8367 ;; Typically, the user will not need to customize this variable; packages
8368 ;; wanting to add alternative implementations should use
8369 ;;
8370 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8371
8372 (defmacro define-alternatives (command &rest customizations)
8373 "Define the new command `COMMAND'.
8374
8375 The argument `COMMAND' should be a symbol.
8376
8377 Running `M-x COMMAND RET' for the first time prompts for which
8378 alternative to use and records the selected command as a custom
8379 variable.
8380
8381 Running `C-u M-x COMMAND RET' prompts again for an alternative
8382 and overwrites the previous choice.
8383
8384 The variable `COMMAND-alternatives' contains an alist with
8385 alternative implementations of COMMAND. `define-alternatives'
8386 does not have any effect until this variable is set.
8387
8388 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8389 `defcustom' keywords and values to add to the declaration of
8390 `COMMAND-alternatives' (typically :group and :version)."
8391 (let* ((command-name (symbol-name command))
8392 (varalt-name (concat command-name "-alternatives"))
8393 (varalt-sym (intern varalt-name))
8394 (varimp-sym (intern (concat command-name "--implementation"))))
8395 `(progn
8396
8397 (defcustom ,varalt-sym nil
8398 ,(format "Alist of alternative implementations for the `%s' command.
8399
8400 Each entry must be a pair (ALTNAME . ALTFUN), where:
8401 ALTNAME - The name shown at user to describe the alternative implementation.
8402 ALTFUN - The function called to implement this alternative."
8403 command-name)
8404 :type '(alist :key-type string :value-type function)
8405 ,@customizations)
8406
8407 (put ',varalt-sym 'definition-name ',command)
8408 (defvar ,varimp-sym nil "Internal use only.")
8409
8410 (defun ,command (&optional arg)
8411 ,(format "Run generic command `%s'.
8412 If used for the first time, or with interactive ARG, ask the user which
8413 implementation to use for `%s'. The variable `%s'
8414 contains the list of implementations currently supported for this command."
8415 command-name command-name varalt-name)
8416 (interactive "P")
8417 (when (or arg (null ,varimp-sym))
8418 (let ((val (completing-read
8419 ,(format-message
8420 "Select implementation for command `%s': "
8421 command-name)
8422 ,varalt-sym nil t)))
8423 (unless (string-equal val "")
8424 (when (null ,varimp-sym)
8425 (message
8426 "Use C-u M-x %s RET`to select another implementation"
8427 ,command-name)
8428 (sit-for 3))
8429 (customize-save-variable ',varimp-sym
8430 (cdr (assoc-string val ,varalt-sym))))))
8431 (if ,varimp-sym
8432 (call-interactively ,varimp-sym)
8433 (message "%s" ,(format-message
8434 "No implementation selected for command `%s'"
8435 command-name)))))))
8436
8437 \f
8438 ;;; Functions for changing capitalization that Do What I Mean
8439 (defun upcase-dwim (arg)
8440 "Upcase words in the region, if active; if not, upcase word at point.
8441 If the region is active, this function calls `upcase-region'.
8442 Otherwise, it calls `upcase-word', with prefix argument passed to it
8443 to upcase ARG words."
8444 (interactive "*p")
8445 (if (use-region-p)
8446 (upcase-region (region-beginning) (region-end))
8447 (upcase-word arg)))
8448
8449 (defun downcase-dwim (arg)
8450 "Downcase words in the region, if active; if not, downcase word at point.
8451 If the region is active, this function calls `downcase-region'.
8452 Otherwise, it calls `downcase-word', with prefix argument passed to it
8453 to downcase ARG words."
8454 (interactive "*p")
8455 (if (use-region-p)
8456 (downcase-region (region-beginning) (region-end))
8457 (downcase-word arg)))
8458
8459 (defun capitalize-dwim (arg)
8460 "Capitalize words in the region, if active; if not, capitalize word at point.
8461 If the region is active, this function calls `capitalize-region'.
8462 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8463 to capitalize ARG words."
8464 (interactive "*p")
8465 (if (use-region-p)
8466 (capitalize-region (region-beginning) (region-end))
8467 (capitalize-word arg)))
8468
8469 \f
8470
8471 (provide 'simple)
8472
8473 ;;; simple.el ends here