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