Skip to content
Permalink
emacs-26.3
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
9015 lines (8171 sloc) 363 KB
;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
;; Copyright (C) 1985-1987, 1993-2019 Free Software Foundation, Inc.
;; Maintainer: emacs-devel@gnu.org
;; Keywords: internal
;; Package: emacs
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; A grab-bag of basic Emacs commands not specifically related to some
;; major mode or to file-handling.
;;; Code:
(eval-when-compile (require 'cl-lib))
(declare-function widget-convert "wid-edit" (type &rest args))
(declare-function shell-mode "shell" ())
;;; From compile.el
(defvar compilation-current-error)
(defvar compilation-context-lines)
(defcustom shell-command-dont-erase-buffer nil
"If non-nil, output buffer is not erased between shell commands.
Also, a non-nil value sets the point in the output buffer
once the command completes.
The value `beg-last-out' sets point at the beginning of the output,
`end-last-out' sets point at the end of the buffer, `save-point'
restores the buffer position before the command."
:type '(choice
(const :tag "Erase buffer" nil)
(const :tag "Set point to beginning of last output" beg-last-out)
(const :tag "Set point to end of last output" end-last-out)
(const :tag "Save point" save-point))
:group 'shell
:version "26.1")
(defvar shell-command-saved-pos nil
"Record of point positions in output buffers after command completion.
The value is an alist whose elements are of the form (BUFFER . POS),
where BUFFER is the output buffer, and POS is the point position
in BUFFER once the command finishes.
This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
(defcustom idle-update-delay 0.5
"Idle time delay before updating various things on the screen.
Various Emacs features that update auxiliary information when point moves
wait this many seconds after Emacs becomes idle before doing an update."
:type 'number
:group 'display
:version "22.1")
(defgroup killing nil
"Killing and yanking commands."
:group 'editing)
(defgroup paren-matching nil
"Highlight (un)matching of parens and expressions."
:group 'matching)
;;; next-error support framework
(defgroup next-error nil
"`next-error' support framework."
:group 'compilation
:version "22.1")
(defface next-error
'((t (:inherit region)))
"Face used to highlight next error locus."
:group 'next-error
:version "22.1")
(defcustom next-error-highlight 0.5
"Highlighting of locations in selected source buffers.
If a number, highlight the locus in `next-error' face for the given time
in seconds, or until the next command is executed.
If t, highlight the locus until the next command is executed, or until
some other locus replaces it.
If nil, don't highlight the locus in the source buffer.
If `fringe-arrow', indicate the locus by the fringe arrow
indefinitely until some other locus replaces it."
:type '(choice (number :tag "Highlight for specified time")
(const :tag "Semipermanent highlighting" t)
(const :tag "No highlighting" nil)
(const :tag "Fringe arrow" fringe-arrow))
:group 'next-error
:version "22.1")
(defcustom next-error-highlight-no-select 0.5
"Highlighting of locations in `next-error-no-select'.
If number, highlight the locus in `next-error' face for given time in seconds.
If t, highlight the locus indefinitely until some other locus replaces it.
If nil, don't highlight the locus in the source buffer.
If `fringe-arrow', indicate the locus by the fringe arrow
indefinitely until some other locus replaces it."
:type '(choice (number :tag "Highlight for specified time")
(const :tag "Semipermanent highlighting" t)
(const :tag "No highlighting" nil)
(const :tag "Fringe arrow" fringe-arrow))
:group 'next-error
:version "22.1")
(defcustom next-error-recenter nil
"Display the line in the visited source file recentered as specified.
If non-nil, the value is passed directly to `recenter'."
:type '(choice (integer :tag "Line to recenter to")
(const :tag "Center of window" (4))
(const :tag "No recentering" nil))
:group 'next-error
:version "23.1")
(defcustom next-error-hook nil
"List of hook functions run by `next-error' after visiting source file."
:type 'hook
:group 'next-error)
(defvar next-error-highlight-timer nil)
(defvar next-error-overlay-arrow-position nil)
(put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
(add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
(defvar next-error-last-buffer nil
"The most recent `next-error' buffer.
A buffer becomes most recent when its compilation, grep, or
similar mode is started, or when it is used with \\[next-error]
or \\[compile-goto-error].")
(defvar next-error-function nil
"Function to use to find the next error in the current buffer.
The function is called with 2 parameters:
ARG is an integer specifying by how many errors to move.
RESET is a boolean which, if non-nil, says to go back to the beginning
of the errors before moving.
Major modes providing compile-like functionality should set this variable
to indicate to `next-error' that this is a candidate buffer and how
to navigate in it.")
(make-variable-buffer-local 'next-error-function)
(defvar next-error-move-function nil
"Function to use to move to an error locus.
It takes two arguments, a buffer position in the error buffer
and a buffer position in the error locus buffer.
The buffer for the error locus should already be current.
nil means use goto-char using the second argument position.")
(make-variable-buffer-local 'next-error-move-function)
(defsubst next-error-buffer-p (buffer
&optional avoid-current
extra-test-inclusive
extra-test-exclusive)
"Return non-nil if BUFFER is a `next-error' capable buffer.
If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
return nil.
The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
BUFFER would not normally qualify. If it returns non-nil, BUFFER
is considered `next-error' capable, anyway, and the function
returns non-nil.
The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
buffer would normally qualify. If it returns nil, BUFFER is
rejected, and the function returns nil."
(and (buffer-name buffer) ;First make sure it's live.
(not (and avoid-current (eq buffer (current-buffer))))
(with-current-buffer buffer
(if next-error-function ; This is the normal test.
;; Optionally reject some buffers.
(if extra-test-exclusive
(funcall extra-test-exclusive)
t)
;; Optionally accept some other buffers.
(and extra-test-inclusive
(funcall extra-test-inclusive))))))
(defun next-error-find-buffer (&optional avoid-current
extra-test-inclusive
extra-test-exclusive)
"Return a `next-error' capable buffer.
If AVOID-CURRENT is non-nil, treat the current buffer
as an absolute last resort only.
The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
that normally would not qualify. If it returns t, the buffer
in question is treated as usable.
The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
that would normally be considered usable. If it returns nil,
that buffer is rejected."
(or
;; 1. If one window on the selected frame displays such buffer, return it.
(let ((window-buffers
(delete-dups
(delq nil (mapcar (lambda (w)
(if (next-error-buffer-p
(window-buffer w)
avoid-current
extra-test-inclusive extra-test-exclusive)
(window-buffer w)))
(window-list))))))
(if (eq (length window-buffers) 1)
(car window-buffers)))
;; 2. If next-error-last-buffer is an acceptable buffer, use that.
(if (and next-error-last-buffer
(next-error-buffer-p next-error-last-buffer avoid-current
extra-test-inclusive extra-test-exclusive))
next-error-last-buffer)
;; 3. If the current buffer is acceptable, choose it.
(if (next-error-buffer-p (current-buffer) avoid-current
extra-test-inclusive extra-test-exclusive)
(current-buffer))
;; 4. Look for any acceptable buffer.
(let ((buffers (buffer-list)))
(while (and buffers
(not (next-error-buffer-p
(car buffers) avoid-current
extra-test-inclusive extra-test-exclusive)))
(setq buffers (cdr buffers)))
(car buffers))
;; 5. Use the current buffer as a last resort if it qualifies,
;; even despite AVOID-CURRENT.
(and avoid-current
(next-error-buffer-p (current-buffer) nil
extra-test-inclusive extra-test-exclusive)
(progn
(message "This is the only buffer with error message locations")
(current-buffer)))
;; 6. Give up.
(error "No buffers contain error message locations")))
(defun next-error (&optional arg reset)
"Visit next `next-error' message and corresponding source code.
If all the error messages parsed so far have been processed already,
the message buffer is checked for new ones.
A prefix ARG specifies how many error messages to move;
negative means move back to previous error messages.
Just \\[universal-argument] as a prefix means reparse the error message buffer
and start at the first error.
The RESET argument specifies that we should restart from the beginning.
\\[next-error] normally uses the most recently started
compilation, grep, or occur buffer. It can also operate on any
buffer with output from the \\[compile], \\[grep] commands, or,
more generally, on any buffer in Compilation mode or with
Compilation Minor mode enabled, or any buffer in which
`next-error-function' is bound to an appropriate function.
To specify use of a particular buffer for error messages, type
\\[next-error] in that buffer when it is the only one displayed
in the current frame.
Once \\[next-error] has chosen the buffer for error messages, it
runs `next-error-hook' with `run-hooks', and stays with that buffer
until you use it in some other buffer which uses Compilation mode
or Compilation Minor mode.
To control which errors are matched, customize the variable
`compilation-error-regexp-alist'."
(interactive "P")
(if (consp arg) (setq reset t arg nil))
(when (setq next-error-last-buffer (next-error-find-buffer))
;; we know here that next-error-function is a valid symbol we can funcall
(with-current-buffer next-error-last-buffer
(funcall next-error-function (prefix-numeric-value arg) reset)
(when next-error-recenter
(recenter next-error-recenter))
(run-hooks 'next-error-hook))))
(defun next-error-internal ()
"Visit the source code corresponding to the `next-error' message at point."
(setq next-error-last-buffer (current-buffer))
;; we know here that next-error-function is a valid symbol we can funcall
(with-current-buffer next-error-last-buffer
(funcall next-error-function 0 nil)
(when next-error-recenter
(recenter next-error-recenter))
(run-hooks 'next-error-hook)))
(defalias 'goto-next-locus 'next-error)
(defalias 'next-match 'next-error)
(defun previous-error (&optional n)
"Visit previous `next-error' message and corresponding source code.
Prefix arg N says how many error messages to move backwards (or
forwards, if negative).
This operates on the output from the \\[compile] and \\[grep] commands."
(interactive "p")
(next-error (- (or n 1))))
(defun first-error (&optional n)
"Restart at the first error.
Visit corresponding source code.
With prefix arg N, visit the source code of the Nth error.
This operates on the output from the \\[compile] command, for instance."
(interactive "p")
(next-error n t))
(defun next-error-no-select (&optional n)
"Move point to the next error in the `next-error' buffer and highlight match.
Prefix arg N says how many error messages to move forwards (or
backwards, if negative).
Finds and highlights the source line like \\[next-error], but does not
select the source buffer."
(interactive "p")
(let ((next-error-highlight next-error-highlight-no-select))
(next-error n))
(pop-to-buffer next-error-last-buffer))
(defun previous-error-no-select (&optional n)
"Move point to the previous error in the `next-error' buffer and highlight match.
Prefix arg N says how many error messages to move backwards (or
forwards, if negative).
Finds and highlights the source line like \\[previous-error], but does not
select the source buffer."
(interactive "p")
(next-error-no-select (- (or n 1))))
;; Internal variable for `next-error-follow-mode-post-command-hook'.
(defvar next-error-follow-last-line nil)
(define-minor-mode next-error-follow-minor-mode
"Minor mode for compilation, occur and diff modes.
With a prefix argument ARG, enable mode if ARG is positive, and
disable it otherwise. If called from Lisp, enable mode if ARG is
omitted or nil.
When turned on, cursor motion in the compilation, grep, occur or diff
buffer causes automatic display of the corresponding source code location."
:group 'next-error :init-value nil :lighter " Fol"
(if (not next-error-follow-minor-mode)
(remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
(add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
(make-local-variable 'next-error-follow-last-line)))
;; Used as a `post-command-hook' by `next-error-follow-mode'
;; for the *Compilation* *grep* and *Occur* buffers.
(defun next-error-follow-mode-post-command-hook ()
(unless (equal next-error-follow-last-line (line-number-at-pos))
(setq next-error-follow-last-line (line-number-at-pos))
(condition-case nil
(let ((compilation-context-lines nil))
(setq compilation-current-error (point))
(next-error-no-select 0))
(error t))))
;;;
(defun fundamental-mode ()
"Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one."
(interactive)
(kill-all-local-variables)
(run-mode-hooks))
;; Special major modes to view specially formatted data rather than files.
(defvar special-mode-map
(let ((map (make-sparse-keymap)))
(suppress-keymap map)
(define-key map "q" 'quit-window)
(define-key map " " 'scroll-up-command)
(define-key map [?\S-\ ] 'scroll-down-command)
(define-key map "\C-?" 'scroll-down-command)
(define-key map "?" 'describe-mode)
(define-key map "h" 'describe-mode)
(define-key map ">" 'end-of-buffer)
(define-key map "<" 'beginning-of-buffer)
(define-key map "g" 'revert-buffer)
map))
(put 'special-mode 'mode-class 'special)
(define-derived-mode special-mode nil "Special"
"Parent major mode from which special major modes should inherit."
(setq buffer-read-only t))
;; Making and deleting lines.
(defvar self-insert-uses-region-functions nil
"Special hook to tell if `self-insert-command' will use the region.
It must be called via `run-hook-with-args-until-success' with no arguments.
If any function on this hook returns a non-nil value, `delete-selection-mode'
will act on that value (see `delete-selection-helper'), and will
usually delete the region. If all the functions on this hook return
nil, it is an indiction that `self-insert-command' needs the region
untouched by `delete-selection-mode', and will itself do whatever is
appropriate with the region.
Any function on `post-self-insert-hook' which act on the region should
add a function to this hook so that `delete-selection-mode' could
refrain from deleting the region before `post-self-insert-hook'
functions are called.
This hook is run by `delete-selection-uses-region-p', which see.")
(defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
"Propertized string representing a hard newline character.")
(defun newline (&optional arg interactive)
"Insert a newline, and move to left margin of the new line if it's blank.
If option `use-hard-newlines' is non-nil, the newline is marked with the
text-property `hard'.
With ARG, insert that many newlines.
If `electric-indent-mode' is enabled, this indents the final new line
that it adds, and reindents the preceding line. To just insert
a newline, use \\[electric-indent-just-newline].
Calls `auto-fill-function' if the current column number is greater
than the value of `fill-column' and ARG is nil.
A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
(interactive "*P\np")
(barf-if-buffer-read-only)
;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
;; Set last-command-event to tell self-insert what to insert.
(let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
(beforepos (point))
(last-command-event ?\n)
;; Don't auto-fill if we have a numeric argument.
(auto-fill-function (if arg nil auto-fill-function))
(arg (prefix-numeric-value arg))
(postproc
;; Do the rest in post-self-insert-hook, because we want to do it
;; *before* other functions on that hook.
(lambda ()
;; Mark the newline(s) `hard'.
(if use-hard-newlines
(set-hard-newline-properties
(- (point) arg) (point)))
;; If the newline leaves the previous line blank, and we
;; have a left margin, delete that from the blank line.
(save-excursion
(goto-char beforepos)
(beginning-of-line)
(and (looking-at "[ \t]$")
(> (current-left-margin) 0)
(delete-region (point)
(line-end-position))))
;; Indent the line after the newline, except in one case:
;; when we added the newline at the beginning of a line which
;; starts a page.
(or was-page-start
(move-to-left-margin nil t)))))
(if (not interactive)
;; FIXME: For non-interactive uses, many calls actually
;; just want (insert "\n"), so maybe we should do just
;; that, so as to avoid the risk of filling or running
;; abbrevs unexpectedly.
(let ((post-self-insert-hook (list postproc)))
(self-insert-command arg))
(unwind-protect
(progn
(add-hook 'post-self-insert-hook postproc nil t)
(self-insert-command arg))
;; We first used let-binding to protect the hook, but that
;; was naive since add-hook affects the symbol-default
;; value of the variable, whereas the let-binding might
;; only protect the buffer-local value.
(remove-hook 'post-self-insert-hook postproc t))))
nil)
(defun set-hard-newline-properties (from to)
(let ((sticky (get-text-property from 'rear-nonsticky)))
(put-text-property from to 'hard 't)
;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
(if (and (listp sticky) (not (memq 'hard sticky)))
(put-text-property from (point) 'rear-nonsticky
(cons 'hard sticky)))))
(defun open-line (n)
"Insert a newline and leave point before it.
If there is a fill prefix and/or a `left-margin', insert them on
the new line if the line would have been blank.
With arg N, insert N newlines."
(interactive "*p")
(let* ((do-fill-prefix (and fill-prefix (bolp)))
(do-left-margin (and (bolp) (> (current-left-margin) 0)))
(loc (point-marker))
;; Don't expand an abbrev before point.
(abbrev-mode nil))
(newline n)
(goto-char loc)
(while (> n 0)
(cond ((bolp)
(if do-left-margin (indent-to (current-left-margin)))
(if do-fill-prefix (insert-and-inherit fill-prefix))))
(forward-line 1)
(setq n (1- n)))
(goto-char loc)
;; Necessary in case a margin or prefix was inserted.
(end-of-line)))
(defun split-line (&optional arg)
"Split current line, moving portion beyond point vertically down.
If the current line starts with `fill-prefix', insert it on the new
line as well. With prefix ARG, don't insert `fill-prefix' on new line.
When called from Lisp code, ARG may be a prefix string to copy."
(interactive "*P")
(skip-chars-forward " \t")
(let* ((col (current-column))
(pos (point))
;; What prefix should we check for (nil means don't).
(prefix (cond ((stringp arg) arg)
(arg nil)
(t fill-prefix)))
;; Does this line start with it?
(have-prfx (and prefix
(save-excursion
(beginning-of-line)
(looking-at (regexp-quote prefix))))))
(newline 1)
(if have-prfx (insert-and-inherit prefix))
(indent-to col 0)
(goto-char pos)))
(defun delete-indentation (&optional arg)
"Join this line to previous and fix up whitespace at join.
If there is a fill prefix, delete it from the beginning of this line.
With argument, join this line to following line."
(interactive "*P")
(beginning-of-line)
(if arg (forward-line 1))
(if (eq (preceding-char) ?\n)
(progn
(delete-region (point) (1- (point)))
;; If the second line started with the fill prefix,
;; delete the prefix.
(if (and fill-prefix
(<= (+ (point) (length fill-prefix)) (point-max))
(string= fill-prefix
(buffer-substring (point)
(+ (point) (length fill-prefix)))))
(delete-region (point) (+ (point) (length fill-prefix))))
(fixup-whitespace))))
(defalias 'join-line #'delete-indentation) ; easier to find
(defun delete-blank-lines ()
"On blank line, delete all surrounding blank lines, leaving just one.
On isolated blank line, delete that one.
On nonblank line, delete any immediately following blank lines."
(interactive "*")
(let (thisblank singleblank)
(save-excursion
(beginning-of-line)
(setq thisblank (looking-at "[ \t]*$"))
;; Set singleblank if there is just one blank line here.
(setq singleblank
(and thisblank
(not (looking-at "[ \t]*\n[ \t]*$"))
(or (bobp)
(progn (forward-line -1)
(not (looking-at "[ \t]*$")))))))
;; Delete preceding blank lines, and this one too if it's the only one.
(if thisblank
(progn
(beginning-of-line)
(if singleblank (forward-line 1))
(delete-region (point)
(if (re-search-backward "[^ \t\n]" nil t)
(progn (forward-line 1) (point))
(point-min)))))
;; Delete following blank lines, unless the current line is blank
;; and there are no following blank lines.
(if (not (and thisblank singleblank))
(save-excursion
(end-of-line)
(forward-line 1)
(delete-region (point)
(if (re-search-forward "[^ \t\n]" nil t)
(progn (beginning-of-line) (point))
(point-max)))))
;; Handle the special case where point is followed by newline and eob.
;; Delete the line, leaving point at eob.
(if (looking-at "^[ \t]*\n\\'")
(delete-region (point) (point-max)))))
(defcustom delete-trailing-lines t
"If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
Trailing lines are deleted only if `delete-trailing-whitespace'
is called on the entire buffer (rather than an active region)."
:type 'boolean
:group 'editing
:version "24.3")
(defun region-modifiable-p (start end)
"Return non-nil if the region contains no read-only text."
(and (not (get-text-property start 'read-only))
(eq end (next-single-property-change start 'read-only nil end))))
(defun delete-trailing-whitespace (&optional start end)
"Delete trailing whitespace between START and END.
If called interactively, START and END are the start/end of the
region if the mark is active, or of the buffer's accessible
portion if the mark is inactive.
This command deletes whitespace characters after the last
non-whitespace character in each line between START and END. It
does not consider formfeed characters to be whitespace.
If this command acts on the entire buffer (i.e. if called
interactively with the mark inactive, or called from Lisp with
END nil), it also deletes all trailing lines at the end of the
buffer if the variable `delete-trailing-lines' is non-nil."
(interactive (progn
(barf-if-buffer-read-only)
(if (use-region-p)
(list (region-beginning) (region-end))
(list nil nil))))
(save-match-data
(save-excursion
(let ((end-marker (and end (copy-marker end))))
(goto-char (or start (point-min)))
(with-syntax-table (make-syntax-table (syntax-table))
;; Don't delete formfeeds, even if they are considered whitespace.
(modify-syntax-entry ?\f "_")
(while (re-search-forward "\\s-$" end-marker t)
(skip-syntax-backward "-" (line-beginning-position))
(let ((b (point)) (e (match-end 0)))
(if (region-modifiable-p b e)
(delete-region b e)
(goto-char e)))))
(if end
(set-marker end-marker nil)
;; Delete trailing empty lines.
(and delete-trailing-lines
;; Really the end of buffer.
(= (goto-char (point-max)) (1+ (buffer-size)))
(<= (skip-chars-backward "\n") -2)
(region-modifiable-p (1+ (point)) (point-max))
(delete-region (1+ (point)) (point-max)))))))
;; Return nil for the benefit of `write-file-functions'.
nil)
(defun newline-and-indent ()
"Insert a newline, then indent according to major mode.
Indentation is done using the value of `indent-line-function'.
In programming language modes, this is the same as TAB.
In some text modes, where TAB inserts a tab, this command indents to the
column specified by the function `current-left-margin'."
(interactive "*")
(delete-horizontal-space t)
(newline nil t)
(indent-according-to-mode))
(defun reindent-then-newline-and-indent ()
"Reindent current line, insert newline, then indent the new line.
Indentation of both lines is done according to the current major mode,
which means calling the current value of `indent-line-function'.
In programming language modes, this is the same as TAB.
In some text modes, where TAB inserts a tab, this indents to the
column specified by the function `current-left-margin'."
(interactive "*")
(let ((pos (point)))
;; Be careful to insert the newline before indenting the line.
;; Otherwise, the indentation might be wrong.
(newline)
(save-excursion
(goto-char pos)
;; We are at EOL before the call to indent-according-to-mode, and
;; after it we usually are as well, but not always. We tried to
;; address it with `save-excursion' but that uses a normal marker
;; whereas we need `move after insertion', so we do the save/restore
;; by hand.
(setq pos (copy-marker pos t))
(indent-according-to-mode)
(goto-char pos)
;; Remove the trailing white-space after indentation because
;; indentation may introduce the whitespace.
(delete-horizontal-space t))
(indent-according-to-mode)))
(defcustom read-quoted-char-radix 8
"Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
Legitimate radix values are 8, 10 and 16."
:type '(choice (const 8) (const 10) (const 16))
:group 'editing-basics)
(defun read-quoted-char (&optional prompt)
"Like `read-char', but do not allow quitting.
Also, if the first character read is an octal digit,
we read any number of octal digits and return the
specified character code. Any nondigit terminates the sequence.
If the terminator is RET, it is discarded;
any other terminator is used itself as input.
The optional argument PROMPT specifies a string to use to prompt the user.
The variable `read-quoted-char-radix' controls which radix to use
for numeric input."
(let ((message-log-max nil)
(help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
help-event-list)))
done (first t) (code 0) char translated)
(while (not done)
(let ((inhibit-quit first)
;; Don't let C-h or other help chars get the help
;; message--only help function keys. See bug#16617.
(help-char nil)
(help-event-list help-events)
(help-form
"Type the special character you want to use,
or the octal character code.
RET terminates the character code and is discarded;
any other non-digit terminates the character code and is then used as input."))
(setq char (read-event (and prompt (format "%s-" prompt)) t))
(if inhibit-quit (setq quit-flag nil)))
;; Translate TAB key into control-I ASCII character, and so on.
;; Note: `read-char' does it using the `ascii-character' property.
;; We tried using read-key instead, but that disables the keystroke
;; echo produced by 'C-q', see bug#24635.
(let ((translation (lookup-key local-function-key-map (vector char))))
(setq translated (if (arrayp translation)
(aref translation 0)
char)))
(if (integerp translated)
(setq translated (char-resolve-modifiers translated)))
(cond ((null translated))
((not (integerp translated))
(setq unread-command-events (list char)
done t))
((/= (logand translated ?\M-\^@) 0)
;; Turn a meta-character into a character with the 0200 bit set.
(setq code (logior (logand translated (lognot ?\M-\^@)) 128)
done t))
((and (<= ?0 translated)
(< translated (+ ?0 (min 10 read-quoted-char-radix))))
(setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
(and prompt (setq prompt (message "%s %c" prompt translated))))
((and (<= ?a (downcase translated))
(< (downcase translated)
(+ ?a -10 (min 36 read-quoted-char-radix))))
(setq code (+ (* code read-quoted-char-radix)
(+ 10 (- (downcase translated) ?a))))
(and prompt (setq prompt (message "%s %c" prompt translated))))
((and (not first) (eq translated ?\C-m))
(setq done t))
((not first)
(setq unread-command-events (list char)
done t))
(t (setq code translated
done t)))
(setq first nil))
code))
(defun quoted-insert (arg)
"Read next input character and insert it.
This is useful for inserting control characters.
With argument, insert ARG copies of the character.
If the first character you type after this command is an octal digit,
you should type a sequence of octal digits which specify a character code.
Any nondigit terminates the sequence. If the terminator is a RET,
it is discarded; any other terminator is used itself as input.
The variable `read-quoted-char-radix' specifies the radix for this feature;
set it to 10 or 16 to use decimal or hex instead of octal.
In overwrite mode, this function inserts the character anyway, and
does not handle octal digits specially. This means that if you use
overwrite as your normal editing mode, you can use this function to
insert characters when necessary.
In binary overwrite mode, this function does overwrite, and octal
digits are interpreted as a character code. This is intended to be
useful for editing binary files."
(interactive "*p")
(let* ((char
;; Avoid "obsolete" warnings for translation-table-for-input.
(with-no-warnings
(let (translation-table-for-input input-method-function)
(if (or (not overwrite-mode)
(eq overwrite-mode 'overwrite-mode-binary))
(read-quoted-char)
(read-char))))))
;; This used to assume character codes 0240 - 0377 stand for
;; characters in some single-byte character set, and converted them
;; to Emacs characters. But in 23.1 this feature is deprecated
;; in favor of inserting the corresponding Unicode characters.
;; (if (and enable-multibyte-characters
;; (>= char ?\240)
;; (<= char ?\377))
;; (setq char (unibyte-char-to-multibyte char)))
(unless (characterp char)
(user-error "%s is not a valid character"
(key-description (vector char))))
(if (> arg 0)
(if (eq overwrite-mode 'overwrite-mode-binary)
(delete-char arg)))
(while (> arg 0)
(insert-and-inherit char)
(setq arg (1- arg)))))
(defun forward-to-indentation (&optional arg)
"Move forward ARG lines and position at first nonblank character."
(interactive "^p")
(forward-line (or arg 1))
(skip-chars-forward " \t"))
(defun backward-to-indentation (&optional arg)
"Move backward ARG lines and position at first nonblank character."
(interactive "^p")
(forward-line (- (or arg 1)))
(skip-chars-forward " \t"))
(defun back-to-indentation ()
"Move point to the first non-whitespace character on this line."
(interactive "^")
(beginning-of-line 1)
(skip-syntax-forward " " (line-end-position))
;; Move back over chars that have whitespace syntax but have the p flag.
(backward-prefix-chars))
(defun fixup-whitespace ()
"Fixup white space between objects around point.
Leave one space or none, according to the context."
(interactive "*")
(save-excursion
(delete-horizontal-space)
(if (or (looking-at "^\\|$\\|\\s)")
(save-excursion (forward-char -1)
(looking-at "$\\|\\s(\\|\\s'")))
nil
(insert ?\s))))
(defun delete-horizontal-space (&optional backward-only)
"Delete all spaces and tabs around point.
If BACKWARD-ONLY is non-nil, only delete them before point."
(interactive "*P")
(let ((orig-pos (point)))
(delete-region
(if backward-only
orig-pos
(progn
(skip-chars-forward " \t")
(constrain-to-field nil orig-pos t)))
(progn
(skip-chars-backward " \t")
(constrain-to-field nil orig-pos)))))
(defun just-one-space (&optional n)
"Delete all spaces and tabs around point, leaving one space (or N spaces).
If N is negative, delete newlines as well, leaving -N spaces.
See also `cycle-spacing'."
(interactive "*p")
(cycle-spacing n nil 'single-shot))
(defvar cycle-spacing--context nil
"Store context used in consecutive calls to `cycle-spacing' command.
The first time `cycle-spacing' runs, it saves in this variable:
its N argument, the original point position, and the original spacing
around point.")
(defun cycle-spacing (&optional n preserve-nl-back mode)
"Manipulate whitespace around point in a smart way.
In interactive use, this function behaves differently in successive
consecutive calls.
The first call in a sequence acts like `just-one-space'.
It deletes all spaces and tabs around point, leaving one space
\(or N spaces). N is the prefix argument. If N is negative,
it deletes newlines as well, leaving -N spaces.
\(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
The second call in a sequence deletes all spaces.
The third call in a sequence restores the original whitespace (and point).
If MODE is `single-shot', it only performs the first step in the sequence.
If MODE is `fast' and the first step would not result in any change
\(i.e., there are exactly (abs N) spaces around point),
the function goes straight to the second step.
Repeatedly calling the function with different values of N starts a
new sequence each time."
(interactive "*p")
(let ((orig-pos (point))
(skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
(num (abs (or n 1))))
(skip-chars-backward (if preserve-nl-back " \t" skip-characters))
(constrain-to-field nil orig-pos)
(cond
;; Command run for the first time, single-shot mode or different argument
((or (eq 'single-shot mode)
(not (equal last-command this-command))
(not cycle-spacing--context)
(not (eq (car cycle-spacing--context) n)))
(let* ((start (point))
(num (- num (skip-chars-forward " " (+ num (point)))))
(mid (point))
(end (progn
(skip-chars-forward skip-characters)
(constrain-to-field nil orig-pos t))))
(setq cycle-spacing--context ;; Save for later.
;; Special handling for case where there was no space at all.
(unless (= start end)
(cons n (cons orig-pos (buffer-substring start (point))))))
;; If this run causes no change in buffer content, delete all spaces,
;; otherwise delete all excess spaces.
(delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
start mid) end)
(insert (make-string num ?\s))))
;; Command run for the second time.
((not (equal orig-pos (point)))
(delete-region (point) orig-pos))
;; Command run for the third time.
(t
(insert (cddr cycle-spacing--context))
(goto-char (cadr cycle-spacing--context))
(setq cycle-spacing--context nil)))))
(defun beginning-of-buffer (&optional arg)
"Move point to the beginning of the buffer.
With numeric arg N, put point N/10 of the way from the beginning.
If the buffer is narrowed, this command uses the beginning of the
accessible part of the buffer.
Push mark at previous position, unless either a \\[universal-argument] prefix
is supplied, or Transient Mark mode is enabled and the mark is active."
(declare (interactive-only "use `(goto-char (point-min))' instead."))
(interactive "^P")
(or (consp arg)
(region-active-p)
(push-mark))
(let ((size (- (point-max) (point-min))))
(goto-char (if (and arg (not (consp arg)))
(+ (point-min)
(if (> size 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg)
(/ size 10))
(/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
(point-min))))
(if (and arg (not (consp arg))) (forward-line 1)))
(defun end-of-buffer (&optional arg)
"Move point to the end of the buffer.
With numeric arg N, put point N/10 of the way from the end.
If the buffer is narrowed, this command uses the end of the
accessible part of the buffer.
Push mark at previous position, unless either a \\[universal-argument] prefix
is supplied, or Transient Mark mode is enabled and the mark is active."
(declare (interactive-only "use `(goto-char (point-max))' instead."))
(interactive "^P")
(or (consp arg) (region-active-p) (push-mark))
(let ((size (- (point-max) (point-min))))
(goto-char (if (and arg (not (consp arg)))
(- (point-max)
(if (> size 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg)
(/ size 10))
(/ (* size (prefix-numeric-value arg)) 10)))
(point-max))))
;; If we went to a place in the middle of the buffer,
;; adjust it to the beginning of a line.
(cond ((and arg (not (consp arg))) (forward-line 1))
((and (eq (current-buffer) (window-buffer))
(> (point) (window-end nil t)))
;; If the end of the buffer is not already on the screen,
;; then scroll specially to put it near, but not at, the bottom.
(overlay-recenter (point))
(recenter -3))))
(defcustom delete-active-region t
"Whether single-char deletion commands delete an active region.
This has an effect only if Transient Mark mode is enabled, and
affects `delete-forward-char' and `delete-backward-char', though
not `delete-char'.
If the value is the symbol `kill', the active region is killed
instead of deleted."
:type '(choice (const :tag "Delete active region" t)
(const :tag "Kill active region" kill)
(const :tag "Do ordinary deletion" nil))
:group 'killing
:version "24.1")
(defvar region-extract-function
(lambda (method)
(when (region-beginning)
(cond
((eq method 'bounds)
(list (cons (region-beginning) (region-end))))
((eq method 'delete-only)
(delete-region (region-beginning) (region-end)))
(t
(filter-buffer-substring (region-beginning) (region-end) method)))))
"Function to get the region's content.
Called with one argument METHOD which can be:
- nil: return the content as a string (list of strings for
non-contiguous regions).
- `delete-only': delete the region; the return value is undefined.
- `bounds': return the boundaries of the region as a list of one
or more cons cells of the form (START . END).
- anything else: delete the region and return its content
as a string (or list of strings for non-contiguous regions),
after filtering it with `filter-buffer-substring', which
is called, for each contiguous sub-region, with METHOD as its
3rd argument.")
(defvar region-insert-function
(lambda (lines)
(let ((first t))
(while lines
(or first
(insert ?\n))
(insert-for-yank (car lines))
(setq lines (cdr lines)
first nil))))
"Function to insert the region's content.
Called with one argument LINES.
Insert the region as a list of lines.")
(defun delete-backward-char (n &optional killflag)
"Delete the previous N characters (following if N is negative).
If Transient Mark mode is enabled, the mark is active, and N is 1,
delete the text in the region and deactivate the mark instead.
To disable this, set option `delete-active-region' to nil.
Optional second arg KILLFLAG, if non-nil, means to kill (save in
kill ring) instead of delete. Interactively, N is the prefix
arg, and KILLFLAG is set if N is explicitly specified.
When killing, the killed text is filtered by
`filter-buffer-substring' before it is saved in the kill ring, so
the actual saved text might be different from what was killed.
In Overwrite mode, single character backward deletion may replace
tabs with spaces so as to back over columns, unless point is at
the end of the line."
(declare (interactive-only delete-char))
(interactive "p\nP")
(unless (integerp n)
(signal 'wrong-type-argument (list 'integerp n)))
(cond ((and (use-region-p)
delete-active-region
(= n 1))
;; If a region is active, kill or delete it.
(if (eq delete-active-region 'kill)
(kill-region (region-beginning) (region-end) 'region)
(funcall region-extract-function 'delete-only)))
;; In Overwrite mode, maybe untabify while deleting
((null (or (null overwrite-mode)
(<= n 0)
(memq (char-before) '(?\t ?\n))
(eobp)
(eq (char-after) ?\n)))
(let ((ocol (current-column)))
(delete-char (- n) killflag)
(save-excursion
(insert-char ?\s (- ocol (current-column)) nil))))
;; Otherwise, do simple deletion.
(t (delete-char (- n) killflag))))
(defun delete-forward-char (n &optional killflag)
"Delete the following N characters (previous if N is negative).
If Transient Mark mode is enabled, the mark is active, and N is 1,
delete the text in the region and deactivate the mark instead.
To disable this, set variable `delete-active-region' to nil.
Optional second arg KILLFLAG non-nil means to kill (save in kill
ring) instead of delete. Interactively, N is the prefix arg, and
KILLFLAG is set if N was explicitly specified.
When killing, the killed text is filtered by
`filter-buffer-substring' before it is saved in the kill ring, so
the actual saved text might be different from what was killed."
(declare (interactive-only delete-char))
(interactive "p\nP")
(unless (integerp n)
(signal 'wrong-type-argument (list 'integerp n)))
(cond ((and (use-region-p)
delete-active-region
(= n 1))
;; If a region is active, kill or delete it.
(if (eq delete-active-region 'kill)
(kill-region (region-beginning) (region-end) 'region)
(funcall region-extract-function 'delete-only)))
;; Otherwise, do simple deletion.
(t (delete-char n killflag))))
(defun mark-whole-buffer ()
"Put point at beginning and mark at end of buffer.
If narrowing is in effect, only uses the accessible part of the buffer.
You probably should not use this function in Lisp programs;
it is usually a mistake for a Lisp function to use any subroutine
that uses or sets the mark."
(declare (interactive-only t))
(interactive)
(push-mark)
(push-mark (point-max) nil t)
;; This is really `point-min' in most cases, but if we're in the
;; minibuffer, this is at the end of the prompt.
(goto-char (minibuffer-prompt-end)))
;; Counting lines, one way or another.
(defun goto-line (line &optional buffer)
"Go to LINE, counting from line 1 at beginning of buffer.
If called interactively, a numeric prefix argument specifies
LINE; without a numeric prefix argument, read LINE from the
minibuffer.
If optional argument BUFFER is non-nil, switch to that buffer and
move to line LINE there. If called interactively with \\[universal-argument]
as argument, BUFFER is the most recently selected other buffer.
Prior to moving point, this function sets the mark (without
activating it), unless Transient Mark mode is enabled and the
mark is already active.
This function is usually the wrong thing to use in a Lisp program.
What you probably want instead is something like:
(goto-char (point-min))
(forward-line (1- N))
If at all possible, an even better solution is to use char counts
rather than line counts."
(declare (interactive-only forward-line))
(interactive
(if (and current-prefix-arg (not (consp current-prefix-arg)))
(list (prefix-numeric-value current-prefix-arg))
;; Look for a default, a number in the buffer at point.
(let* ((default
(save-excursion
(skip-chars-backward "0-9")
(if (looking-at "[0-9]")
(string-to-number
(buffer-substring-no-properties
(point)
(progn (skip-chars-forward "0-9")
(point)))))))
;; Decide if we're switching buffers.
(buffer
(if (consp current-prefix-arg)
(other-buffer (current-buffer) t)))
(buffer-prompt
(if buffer
(concat " in " (buffer-name buffer))
"")))
;; Read the argument, offering that number (if any) as default.
(list (read-number (format "Goto line%s: " buffer-prompt)
(list default (line-number-at-pos)))
buffer))))
;; Switch to the desired buffer, one way or another.
(if buffer
(let ((window (get-buffer-window buffer)))
(if window (select-window window)
(switch-to-buffer-other-window buffer))))
;; Leave mark at previous position
(or (region-active-p) (push-mark))
;; Move to the specified line number in that buffer.
(save-restriction
(widen)
(goto-char (point-min))
(if (eq selective-display t)
(re-search-forward "[\n\C-m]" nil 'end (1- line))
(forward-line (1- line)))))
(defun count-words-region (start end &optional arg)
"Count the number of words in the region.
If called interactively, print a message reporting the number of
lines, words, and characters in the region (whether or not the
region is active); with prefix ARG, report for the entire buffer
rather than the region.
If called from Lisp, return the number of words between positions
START and END."
(interactive (if current-prefix-arg
(list nil nil current-prefix-arg)
(list (region-beginning) (region-end) nil)))
(cond ((not (called-interactively-p 'any))
(count-words start end))
(arg
(count-words--buffer-message))
(t
(count-words--message "Region" start end))))
(defun count-words (start end)
"Count words between START and END.
If called interactively, START and END are normally the start and
end of the buffer; but if the region is active, START and END are
the start and end of the region. Print a message reporting the
number of lines, words, and chars.
If called from Lisp, return the number of words between START and
END, without printing any message."
(interactive (list nil nil))
(cond ((not (called-interactively-p 'any))
(let ((words 0))
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(while (forward-word-strictly 1)
(setq words (1+ words)))))
words))
((use-region-p)
(call-interactively 'count-words-region))
(t
(count-words--buffer-message))))
(defun count-words--buffer-message ()
(count-words--message
(if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
(point-min) (point-max)))
(defun count-words--message (str start end)
(let ((lines (count-lines start end))
(words (count-words start end))
(chars (- end start)))
(message "%s has %d line%s, %d word%s, and %d character%s."
str
lines (if (= lines 1) "" "s")
words (if (= words 1) "" "s")
chars (if (= chars 1) "" "s"))))
(define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
(defun what-line ()
"Print the current buffer line number and narrowed line number of point."
(interactive)
(let ((start (point-min))
(n (line-number-at-pos)))
(if (= start 1)
(message "Line %d" n)
(save-excursion
(save-restriction
(widen)
(message "line %d (narrowed line %d)"
(+ n (line-number-at-pos start) -1) n))))))
(defun count-lines (start end)
"Return number of lines between START and END.
This is usually the number of newlines between them,
but can be one more if START is not equal to END
and the greater of them is not at the start of a line."
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(if (eq selective-display t)
(save-match-data
(let ((done 0))
(while (re-search-forward "[\n\C-m]" nil t 40)
(setq done (+ 40 done)))
(while (re-search-forward "[\n\C-m]" nil t 1)
(setq done (+ 1 done)))
(goto-char (point-max))
(if (and (/= start end)
(not (bolp)))
(1+ done)
done)))
(- (buffer-size) (forward-line (buffer-size)))))))
(defun line-number-at-pos (&optional pos absolute)
"Return buffer line number at position POS.
If POS is nil, use current buffer location.
If ABSOLUTE is nil, the default, counting starts
at (point-min), so the value refers to the contents of the
accessible portion of the (potentially narrowed) buffer. If
ABSOLUTE is non-nil, ignore any narrowing and return the
absolute line number."
(save-restriction
(when absolute
(widen))
(let ((opoint (or pos (point))) start)
(save-excursion
(goto-char (point-min))
(setq start (point))
(goto-char opoint)
(forward-line 0)
(1+ (count-lines start (point)))))))
(defun what-cursor-position (&optional detail)
"Print info on cursor position (on screen and within buffer).
Also describe the character after point, and give its character code
in octal, decimal and hex.
For a non-ASCII multibyte character, also give its encoding in the
buffer's selected coding system if the coding system encodes the
character safely. If the character is encoded into one byte, that
code is shown in hex. If the character is encoded into more than one
byte, just \"...\" is shown.
In addition, with prefix argument, show details about that character
in *Help* buffer. See also the command `describe-char'."
(interactive "P")
(let* ((char (following-char))
(bidi-fixer
;; If the character is one of LRE, LRO, RLE, RLO, it will
;; start a directional embedding, which could completely
;; disrupt the rest of the line (e.g., RLO will display the
;; rest of the line right-to-left). So we put an invisible
;; PDF character after these characters, to end the
;; embedding, which eliminates any effects on the rest of
;; the line. For RLE and RLO we also append an invisible
;; LRM, to avoid reordering the following numerical
;; characters. For LRI/RLI/FSI we append a PDI.
(cond ((memq char '(?\x202a ?\x202d))
(propertize (string ?\x202c) 'invisible t))
((memq char '(?\x202b ?\x202e))
(propertize (string ?\x202c ?\x200e) 'invisible t))
((memq char '(?\x2066 ?\x2067 ?\x2068))
(propertize (string ?\x2069) 'invisible t))
;; Strong right-to-left characters cause reordering of
;; the following numerical characters which show the
;; codepoint, so append LRM to countermand that.
((memq (get-char-code-property char 'bidi-class) '(R AL))
(propertize (string ?\x200e) 'invisible t))
(t
"")))
(beg (point-min))
(end (point-max))
(pos (point))
(total (buffer-size))
(percent (round (* 100.0 (1- pos)) (max 1 total)))
(hscroll (if (= (window-hscroll) 0)
""
(format " Hscroll=%d" (window-hscroll))))
(col (current-column)))
(if (= pos end)
(if (or (/= beg 1) (/= end (1+ total)))
(message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
pos total percent beg end col hscroll)
(message "point=%d of %d (EOB) column=%d%s"
pos total col hscroll))
(let ((coding buffer-file-coding-system)
encoded encoding-msg display-prop under-display)
(if (or (not coding)
(eq (coding-system-type coding) t))
(setq coding (default-value 'buffer-file-coding-system)))
(if (and (>= char #x3fff80) (<= char #x3fffff))
(setq encoding-msg
(format "(%d, #o%o, #x%x, raw-byte)" char char char))
;; Check if the character is displayed with some `display'
;; text property. In that case, set under-display to the
;; buffer substring covered by that property.
(setq display-prop (get-char-property pos 'display))
(if display-prop
(let ((to (or (next-single-char-property-change pos 'display)
(point-max))))
(if (< to (+ pos 4))
(setq under-display "")
(setq under-display "..."
to (+ pos 4)))
(setq under-display
(concat (buffer-substring-no-properties pos to)
under-display)))
(setq encoded (and (>= char 128) (encode-coding-char char coding))))
(setq encoding-msg
(if display-prop
(if (not (stringp display-prop))
(format "(%d, #o%o, #x%x, part of display \"%s\")"
char char char under-display)
(format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
char char char under-display display-prop))
(if encoded
(format "(%d, #o%o, #x%x, file %s)"
char char char
(if (> (length encoded) 1)
"..."
(encoded-string-description encoded coding)))
(format "(%d, #o%o, #x%x)" char char char)))))
(if detail
;; We show the detailed information about CHAR.
(describe-char (point)))
(if (or (/= beg 1) (/= end (1+ total)))
(message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
(if (< char 256)
(single-key-description char)
(buffer-substring-no-properties (point) (1+ (point))))
bidi-fixer
encoding-msg pos total percent beg end col hscroll)
(message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
(if enable-multibyte-characters
(if (< char 128)
(single-key-description char)
(buffer-substring-no-properties (point) (1+ (point))))
(single-key-description char))
bidi-fixer encoding-msg pos total percent col hscroll))))))
;; Initialize read-expression-map. It is defined at C level.
(defvar read-expression-map
(let ((m (make-sparse-keymap)))
(define-key m "\M-\t" 'completion-at-point)
;; Might as well bind TAB to completion, since inserting a TAB char is
;; much too rarely useful.
(define-key m "\t" 'completion-at-point)
(set-keymap-parent m minibuffer-local-map)
m))
(defun read-minibuffer (prompt &optional initial-contents)
"Return a Lisp object read using the minibuffer, unevaluated.
Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
is a string to insert in the minibuffer before reading.
\(INITIAL-CONTENTS can also be a cons of a string and an integer.
Such arguments are used as in `read-from-minibuffer'.)"
;; Used for interactive spec `x'.
(read-from-minibuffer prompt initial-contents minibuffer-local-map
t 'minibuffer-history))
(defun eval-minibuffer (prompt &optional initial-contents)
"Return value of Lisp expression read using the minibuffer.
Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
is a string to insert in the minibuffer before reading.
\(INITIAL-CONTENTS can also be a cons of a string and an integer.
Such arguments are used as in `read-from-minibuffer'.)"
;; Used for interactive spec `X'.
(eval (read--expression prompt initial-contents)))
(defvar minibuffer-completing-symbol nil
"Non-nil means completing a Lisp symbol in the minibuffer.")
(make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
(defvar minibuffer-default nil
"The current default value or list of default values in the minibuffer.
The functions `read-from-minibuffer' and `completing-read' bind
this variable locally.")
(defcustom eval-expression-print-level 4
"Value for `print-level' while printing value in `eval-expression'.
A value of nil means no limit."
:group 'lisp
:type '(choice (const :tag "No Limit" nil) integer)
:version "21.1")
(defcustom eval-expression-print-length 12
"Value for `print-length' while printing value in `eval-expression'.
A value of nil means no limit."
:group 'lisp
:type '(choice (const :tag "No Limit" nil) integer)
:version "21.1")
(defcustom eval-expression-debug-on-error t
"If non-nil set `debug-on-error' to t in `eval-expression'.
If nil, don't change the value of `debug-on-error'."
:group 'lisp
:type 'boolean
:version "21.1")
(defcustom eval-expression-print-maximum-character 127
"The largest integer that will be displayed as a character.
This affects printing by `eval-expression' (via
`eval-expression-print-format')."
:group 'lisp
:type 'integer
:version "26.1")
(defun eval-expression-print-format (value)
"If VALUE is an integer, return a specially formatted string.
This string will typically look like \" (#o1, #x1, ?\\C-a)\".
If VALUE is not an integer, return nil.
This function is used by commands like `eval-expression' that
display the result of expression evaluation."
(when (integerp value)
(let ((char-string
(and (characterp value)
(<= value eval-expression-print-maximum-character)
(char-displayable-p value)
(prin1-char value))))
(if char-string
(format " (#o%o, #x%x, %s)" value value char-string)
(format " (#o%o, #x%x)" value value)))))
(defvar eval-expression-minibuffer-setup-hook nil
"Hook run by `eval-expression' when entering the minibuffer.")
(defun read--expression (prompt &optional initial-contents)
(let ((minibuffer-completing-symbol t))
(minibuffer-with-setup-hook
(lambda ()
;; FIXME: call emacs-lisp-mode?
(add-function :before-until (local 'eldoc-documentation-function)
#'elisp-eldoc-documentation-function)
(eldoc-mode 1)
(add-hook 'completion-at-point-functions
#'elisp-completion-at-point nil t)
(run-hooks 'eval-expression-minibuffer-setup-hook))
(read-from-minibuffer prompt initial-contents
read-expression-map t
'read-expression-history))))
(defun eval-expression-get-print-arguments (prefix-argument)
"Get arguments for commands that print an expression result.
Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
based on PREFIX-ARG. This function determines the interpretation
of the prefix argument for `eval-expression' and
`eval-last-sexp'."
(let ((num (prefix-numeric-value prefix-argument)))
(list (not (memq prefix-argument '(- nil)))
(= num 0)
(cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
((= num -1) most-positive-fixnum)
(t eval-expression-print-maximum-character)))))
;; We define this, rather than making `eval' interactive,
;; for the sake of completion of names like eval-region, eval-buffer.
(defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
"Evaluate EXP and print value in the echo area.
When called interactively, read an Emacs Lisp expression and
evaluate it. Value is also consed on to front of the variable
`values'. Optional argument INSERT-VALUE non-nil (interactively,
with a non `-' prefix argument) means insert the result into the
current buffer instead of printing it in the echo area.
Normally, this function truncates long output according to the
value of the variables `eval-expression-print-length' and
`eval-expression-print-level'. When NO-TRUNCATE is
non-nil (interactively, with a prefix argument of zero), however,
there is no such truncation.
If the resulting value is an integer, and CHAR-PRINT-LIMIT is
non-nil (interactively, unless given a non-zero prefix argument)
it will be printed in several additional formats (octal,
hexadecimal, and character). The character format is only used
if the value is below CHAR-PRINT-LIMIT (interactively, if the
prefix argument is -1 or the value doesn't exceed
`eval-expression-print-maximum-character').
Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
minibuffer.
If `eval-expression-debug-on-error' is non-nil, which is the default,
this command arranges for all errors to enter the debugger."
(interactive
(cons (read--expression "Eval: ")
(eval-expression-get-print-arguments current-prefix-arg)))
(if (null eval-expression-debug-on-error)
(push (eval exp lexical-binding) values)
(let ((old-value (make-symbol "t")) new-value)
;; Bind debug-on-error to something unique so that we can
;; detect when evalled code changes it.
(let ((debug-on-error old-value))
(push (eval (macroexpand-all exp) lexical-binding) values)
(setq new-value debug-on-error))
;; If evalled code has changed the value of debug-on-error,
;; propagate that change to the global binding.
(unless (eq old-value new-value)
(setq debug-on-error new-value))))
(let ((print-length (unless no-truncate eval-expression-print-length))
(print-level (unless no-truncate eval-expression-print-level))
(eval-expression-print-maximum-character char-print-limit)
(deactivate-mark))
(let ((out (if insert-value (current-buffer) t)))
(prog1
(prin1 (car values) out)
(let ((str (and char-print-limit
(eval-expression-print-format (car values)))))
(when str (princ str out)))))))
(defun edit-and-eval-command (prompt command)
"Prompting with PROMPT, let user edit COMMAND and eval result.
COMMAND is a Lisp expression. Let user edit that expression in
the minibuffer, then read and evaluate the result."
(let ((command
(let ((print-level nil)
(minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
(unwind-protect
(read-from-minibuffer prompt
(prin1-to-string command)
read-expression-map t
'command-history)
;; If command was added to command-history as a string,
;; get rid of that. We want only evaluable expressions there.
(if (stringp (car command-history))
(setq command-history (cdr command-history)))))))
;; If command to be redone does not match front of history,
;; add it to the history.
(or (equal command (car command-history))
(setq command-history (cons command command-history)))
(eval command)))
(defun repeat-complex-command (arg)
"Edit and re-evaluate last complex command, or ARGth from last.
A complex command is one which used the minibuffer.
The command is placed in the minibuffer as a Lisp form for editing.
The result is executed, repeating the command as changed.
If the command has been changed or is not the most recent previous
command it is added to the front of the command history.
You can use the minibuffer history commands \
\\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
to get different commands to edit and resubmit."
(interactive "p")
(let ((elt (nth (1- arg) command-history))
newcmd)
(if elt
(progn
(setq newcmd
(let ((print-level nil)
(minibuffer-history-position arg)
(minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
(unwind-protect
(read-from-minibuffer
"Redo: " (prin1-to-string elt) read-expression-map t
(cons 'command-history arg))
;; If command was added to command-history as a
;; string, get rid of that. We want only
;; evaluable expressions there.
(if (stringp (car command-history))
(setq command-history (cdr command-history))))))
;; If command to be redone does not match front of history,
;; add it to the history.
(or (equal newcmd (car command-history))
(setq command-history (cons newcmd command-history)))
(apply #'funcall-interactively
(car newcmd)
(mapcar (lambda (e) (eval e t)) (cdr newcmd))))
(if command-history
(error "Argument %d is beyond length of command history" arg)
(error "There are no previous complex commands to repeat")))))
(defvar extended-command-history nil)
(defvar execute-extended-command--last-typed nil)
(defun read-extended-command ()
"Read command name to invoke in `execute-extended-command'."
(minibuffer-with-setup-hook
(lambda ()
(add-hook 'post-self-insert-hook
(lambda ()
(setq execute-extended-command--last-typed
(minibuffer-contents)))
nil 'local)
(set (make-local-variable 'minibuffer-default-add-function)
(lambda ()
;; Get a command name at point in the original buffer
;; to propose it after M-n.
(with-current-buffer (window-buffer (minibuffer-selected-window))
(and (commandp (function-called-at-point))
(format "%S" (function-called-at-point)))))))
;; Read a string, completing from and restricting to the set of
;; all defined commands. Don't provide any initial input.
;; Save the command read on the extended-command history list.
(completing-read
(concat (cond
((eq current-prefix-arg '-) "- ")
((and (consp current-prefix-arg)
(eq (car current-prefix-arg) 4)) "C-u ")
((and (consp current-prefix-arg)
(integerp (car current-prefix-arg)))
(format "%d " (car current-prefix-arg)))
((integerp current-prefix-arg)
(format "%d " current-prefix-arg)))
;; This isn't strictly correct if `execute-extended-command'
;; is bound to anything else (e.g. [menu]).
;; It could use (key-description (this-single-command-keys)),
;; but actually a prompt other than "M-x" would be confusing,
;; because "M-x" is a well-known prompt to read a command
;; and it serves as a shorthand for "Extended command: ".
"M-x ")
(lambda (string pred action)
(let ((pred
(if (memq action '(nil t))
;; Exclude obsolete commands from completions.
(lambda (sym)
(and (funcall pred sym)
(or (equal string (symbol-name sym))
(not (get sym 'byte-obsolete-info)))))
pred)))
(complete-with-action action obarray string pred)))
#'commandp t nil 'extended-command-history)))
(defcustom suggest-key-bindings t
"Non-nil means show the equivalent key-binding when M-x command has one.
The value can be a length of time to show the message for.
If the value is non-nil and not a number, we wait 2 seconds."
:group 'keyboard
:type '(choice (const :tag "off" nil)
(integer :tag "time" 2)
(other :tag "on")))
(defcustom extended-command-suggest-shorter t
"If non-nil, show a shorter M-x invocation when there is one."
:group 'keyboard
:type 'boolean
:version "26.1")
(defun execute-extended-command--shorter-1 (name length)
(cond
((zerop length) (list ""))
((equal name "") nil)
(t
(nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
(execute-extended-command--shorter-1
(substring name 1) (1- length)))
(when (string-match "\\`\\(-\\)?[^-]*" name)
(execute-extended-command--shorter-1
(substring name (match-end 0)) length))))))
(defun execute-extended-command--shorter (name typed)
(let ((candidates '())
(max (length typed))
(len 1)
binding)
(while (and (not binding)
(progn
(unless candidates
(setq len (1+ len))
(setq candidates (execute-extended-command--shorter-1
name len)))
;; Don't show the help message if the binding isn't
;; significantly shorter than the M-x command the user typed.
(< len (- max 5))))
(input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
(let ((candidate (pop candidates)))
(when (equal name
(car-safe (completion-try-completion
candidate obarray 'commandp len)))
(setq binding candidate))))
binding))
(defun execute-extended-command (prefixarg &optional command-name typed)
;; Based on Fexecute_extended_command in keyboard.c of Emacs.
;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
"Read a command name, then read the arguments and call the command.
To pass a prefix argument to the command you are
invoking, give a prefix argument to `execute-extended-command'."
(declare (interactive-only command-execute))
;; FIXME: Remember the actual text typed by the user before completion,
;; so that we don't later on suggest the same shortening.
(interactive
(let ((execute-extended-command--last-typed nil))
(list current-prefix-arg
(read-extended-command)
execute-extended-command--last-typed)))
;; Emacs<24 calling-convention was with a single `prefixarg' argument.
(unless command-name
(let ((current-prefix-arg prefixarg) ; for prompt
(execute-extended-command--last-typed nil))
(setq command-name (read-extended-command))
(setq typed execute-extended-command--last-typed)))
(let* ((function (and (stringp command-name) (intern-soft command-name)))
(binding (and suggest-key-bindings
(not executing-kbd-macro)
(where-is-internal function overriding-local-map t))))
(unless (commandp function)
(error "`%s' is not a valid command name" command-name))
;; Some features, such as novice.el, rely on this-command-keys
;; including M-x COMMAND-NAME RET.
(set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
(setq this-command function)
;; Normally `real-this-command' should never be changed, but here we really
;; want to pretend that M-x <cmd> RET is nothing more than a "key
;; binding" for <cmd>, so the command the user really wanted to run is
;; `function' and not `execute-extended-command'. The difference is
;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
(setq real-this-command function)
(let ((prefix-arg prefixarg))
(command-execute function 'record))
;; If enabled, show which key runs this command.
;; But first wait, and skip the message if there is input.
(let* ((waited
;; If this command displayed something in the echo area;
;; wait a few seconds, then display our suggestion message.
;; FIXME: Wait *after* running post-command-hook!
;; FIXME: Don't wait if execute-extended-command--shorter won't
;; find a better answer anyway!
(when suggest-key-bindings
(sit-for (cond
((zerop (length (current-message))) 0)
((numberp suggest-key-bindings) suggest-key-bindings)
(t 2))))))
(when (and waited (not (consp unread-command-events)))
(unless (or (not extended-command-suggest-shorter)
binding executing-kbd-macro (not (symbolp function))
(<= (length (symbol-name function)) 2))
;; There's no binding for CMD. Let's try and find the shortest
;; string to use in M-x.
;; FIXME: Can be slow. Cache it maybe?
(while-no-input
(setq binding (execute-extended-command--shorter
(symbol-name function) typed))))
(when binding
(with-temp-message
(format-message "You can run the command `%s' with %s"
function
(if (stringp binding)
(concat "M-x " binding " RET")
(key-description binding)))
(sit-for (if (numberp suggest-key-bindings)
suggest-key-bindings
2))))))))
(defun command-execute (cmd &optional record-flag keys special)
;; BEWARE: Called directly from the C code.
"Execute CMD as an editor command.
CMD must be a symbol that satisfies the `commandp' predicate.
Optional second arg RECORD-FLAG non-nil
means unconditionally put this command in the variable `command-history'.
Otherwise, that is done only if an arg is read using the minibuffer.
The argument KEYS specifies the value to use instead of (this-command-keys)
when reading the arguments; if it is nil, (this-command-keys) is used.
The argument SPECIAL, if non-nil, means that this command is executing
a special event, so ignore the prefix argument and don't clear it."
(setq debug-on-next-call nil)
(let ((prefixarg (unless special
;; FIXME: This should probably be done around
;; pre-command-hook rather than here!
(prog1 prefix-arg
(setq current-prefix-arg prefix-arg)
(setq prefix-arg nil)
(when current-prefix-arg
(prefix-command-update))))))
(if (and (symbolp cmd)
(get cmd 'disabled)
disabled-command-function)
;; FIXME: Weird calling convention!
(run-hooks 'disabled-command-function)
(let ((final cmd))
(while
(progn
(setq final (indirect-function final))
(if (autoloadp final)
(setq final (autoload-do-load final cmd)))))
(cond
((arrayp final)
;; If requested, place the macro in the command history. For
;; other sorts of commands, call-interactively takes care of this.
(when record-flag
(push `(execute-kbd-macro ,final ,prefixarg) command-history)
;; Don't keep command history around forever.
(when (and (numberp history-length) (> history-length 0))
(let ((cell (nthcdr history-length command-history)))
(if (consp cell) (setcdr cell nil)))))
(execute-kbd-macro final prefixarg))
(t
;; Pass `cmd' rather than `final', for the backtrace's sake.
(prog1 (call-interactively cmd record-flag keys)
(when (and (symbolp cmd)
(get cmd 'byte-obsolete-info)
(not (get cmd 'command-execute-obsolete-warned)))
(put cmd 'command-execute-obsolete-warned t)
(message "%s" (macroexp--obsolete-warning
cmd (get cmd 'byte-obsolete-info) "command"))))))))))
(defvar minibuffer-history nil
"Default minibuffer history list.
This is used for all minibuffer input
except when an alternate history list is specified.
Maximum length of the history list is determined by the value
of `history-length', which see.")
(defvar minibuffer-history-sexp-flag nil
"Control whether history list elements are expressions or strings.
If the value of this variable equals current minibuffer depth,
they are expressions; otherwise they are strings.
\(That convention is designed to do the right thing for
recursive uses of the minibuffer.)")
(setq minibuffer-history-variable 'minibuffer-history)
(setq minibuffer-history-position nil) ;; Defvar is in C code.
(defvar minibuffer-history-search-history nil)
(defvar minibuffer-text-before-history nil
"Text that was in this minibuffer before any history commands.
This is nil if there have not yet been any history commands
in this use of the minibuffer.")
(add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
(defun minibuffer-history-initialize ()
(setq minibuffer-text-before-history nil))
(defun minibuffer-avoid-prompt (_new _old)
"A point-motion hook for the minibuffer, that moves point out of the prompt."
(declare (obsolete cursor-intangible-mode "25.1"))
(constrain-to-field nil (point-max)))
(defcustom minibuffer-history-case-insensitive-variables nil
"Minibuffer history variables for which matching should ignore case.
If a history variable is a member of this list, then the
\\[previous-matching-history-element] and \\[next-matching-history-element]\
commands ignore case when searching it, regardless of `case-fold-search'."
:type '(repeat variable)
:group 'minibuffer)
(defun previous-matching-history-element (regexp n)
"Find the previous history element that matches REGEXP.
\(Previous history elements refer to earlier actions.)
With prefix argument N, search for Nth previous match.
If N is negative, find the next or Nth next match.
Normally, history elements are matched case-insensitively if
`case-fold-search' is non-nil, but an uppercase letter in REGEXP
makes the search case-sensitive.
See also `minibuffer-history-case-insensitive-variables'."
(interactive
(let* ((enable-recursive-minibuffers t)
(regexp (read-from-minibuffer "Previous element matching (regexp): "
nil
minibuffer-local-map
nil
'minibuffer-history-search-history
(car minibuffer-history-search-history))))
;; Use the last regexp specified, by default, if input is empty.
(list (if (string= regexp "")
(if minibuffer-history-search-history
(car minibuffer-history-search-history)
(user-error "No previous history search regexp"))
regexp)
(prefix-numeric-value current-prefix-arg))))
(unless (zerop n)
(if (and (zerop minibuffer-history-position)
(null minibuffer-text-before-history))
(setq minibuffer-text-before-history
(minibuffer-contents-no-properties)))
(let ((history (symbol-value minibuffer-history-variable))
(case-fold-search
(if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
;; On some systems, ignore case for file names.
(if (memq minibuffer-history-variable
minibuffer-history-case-insensitive-variables)
t
;; Respect the user's setting for case-fold-search:
case-fold-search)
nil))
prevpos
match-string
match-offset
(pos minibuffer-history-position))
(while (/= n 0)
(setq prevpos pos)
(setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
(when (= pos prevpos)
(user-error (if (= pos 1)
"No later matching history item"
"No earlier matching history item")))
(setq match-string
(if (eq minibuffer-history-sexp-flag (minibuffer-depth))
(let ((print-level nil))
(prin1-to-string (nth (1- pos) history)))
(nth (1- pos) history)))
(setq match-offset
(if (< n 0)
(and (string-match regexp match-string)
(match-end 0))
(and (string-match (concat ".*\\(" regexp "\\)") match-string)
(match-beginning 1))))
(when match-offset
(setq n (+ n (if (< n 0) 1 -1)))))
(setq minibuffer-history-position pos)
(goto-char (point-max))
(delete-minibuffer-contents)
(insert match-string)
(goto-char (+ (minibuffer-prompt-end) match-offset))))
(if (memq (car (car command-history)) '(previous-matching-history-element
next-matching-history-element))
(setq command-history (cdr command-history))))
(defun next-matching-history-element (regexp n)
"Find the next history element that matches REGEXP.
\(The next history element refers to a more recent action.)
With prefix argument N, search for Nth next match.
If N is negative, find the previous or Nth previous match.
Normally, history elements are matched case-insensitively if
`case-fold-search' is non-nil, but an uppercase letter in REGEXP
makes the search case-sensitive."
(interactive
(let* ((enable-recursive-minibuffers t)
(regexp (read-from-minibuffer "Next element matching (regexp): "
nil
minibuffer-local-map
nil
'minibuffer-history-search-history
(car minibuffer-history-search-history))))
;; Use the last regexp specified, by default, if input is empty.
(list (if (string= regexp "")
(if minibuffer-history-search-history
(car minibuffer-history-search-history)
(user-error "No previous history search regexp"))
regexp)
(prefix-numeric-value current-prefix-arg))))
(previous-matching-history-element regexp (- n)))
(defvar minibuffer-temporary-goal-position nil)
(defvar minibuffer-default-add-function 'minibuffer-default-add-completions
"Function run by `goto-history-element' before consuming default values.
This is useful to dynamically add more elements to the list of default values
when `goto-history-element' reaches the end of this list.
Before calling this function `goto-history-element' sets the variable
`minibuffer-default-add-done' to t, so it will call this function only
once. In special cases, when this function needs to be called more
than once, it can set `minibuffer-default-add-done' to nil explicitly,
overriding the setting of this variable to t in `goto-history-element'.")
(defvar minibuffer-default-add-done nil
"When nil, add more elements to the end of the list of default values.
The value nil causes `goto-history-element' to add more elements to
the list of defaults when it reaches the end of this list. It does
this by calling a function defined by `minibuffer-default-add-function'.")
(make-variable-buffer-local 'minibuffer-default-add-done)
(defun minibuffer-default-add-completions ()
"Return a list of all completions without the default value.
This function is used to add all elements of the completion table to
the end of the list of defaults just after the default value."
(let ((def minibuffer-default)
(all (all-completions ""
minibuffer-completion-table
minibuffer-completion-predicate)))
(if (listp def)
(append def all)
(cons def (delete def all)))))
(defun goto-history-element (nabs)
"Puts element of the minibuffer history in the minibuffer.
The argument NABS specifies the absolute history position."
(interactive "p")
(when (and (not minibuffer-default-add-done)
(functionp minibuffer-default-add-function)
(< nabs (- (if (listp minibuffer-default)
(length minibuffer-default)
1))))
(setq minibuffer-default-add-done t
minibuffer-default (funcall minibuffer-default-add-function)))
(let ((minimum (if minibuffer-default
(- (if (listp minibuffer-default)
(length minibuffer-default)
1))
0))
elt minibuffer-returned-to-present)
(if (and (zerop minibuffer-history-position)
(null minibuffer-text-before-history))
(setq minibuffer-text-before-history
(minibuffer-contents-no-properties)))
(if (< nabs minimum)
(user-error (if minibuffer-default
"End of defaults; no next item"
"End of history; no default available")))
(if (> nabs (if (listp (symbol-value minibuffer-history-variable))
(length (symbol-value minibuffer-history-variable))
0))
(user-error "Beginning of history; no preceding item"))
(unless (memq last-command '(next-history-element
previous-history-element))
(let ((prompt-end (minibuffer-prompt-end)))
(set (make-local-variable 'minibuffer-temporary-goal-position)
(cond ((<= (point) prompt-end) prompt-end)
((eobp) nil)
(t (point))))))
(goto-char (point-max))
(delete-minibuffer-contents)
(setq minibuffer-history-position nabs)
(cond ((< nabs 0)
(setq elt (if (listp minibuffer-default)
(nth (1- (abs nabs)) minibuffer-default)
minibuffer-default)))
((= nabs 0)
(setq elt (or minibuffer-text-before-history ""))
(setq minibuffer-returned-to-present t)
(setq minibuffer-text-before-history nil))
(t (setq elt (nth (1- minibuffer-history-position)
(symbol-value minibuffer-history-variable)))))
(insert
(if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
(not minibuffer-returned-to-present))
(let ((print-level nil))
(prin1-to-string elt))
elt))
(goto-char (or minibuffer-temporary-goal-position (point-max)))))
(defun next-history-element (n)
"Puts next element of the minibuffer history in the minibuffer.
With argument N, it uses the Nth following element."
(interactive "p")
(or (zerop n)
(goto-history-element (- minibuffer-history-position n))))
(defun previous-history-element (n)
"Puts previous element of the minibuffer history in the minibuffer.
With argument N, it uses the Nth previous element."
(interactive "p")
(or (zerop n)
(goto-history-element (+ minibuffer-history-position n))))
(defun next-line-or-history-element (&optional arg)
"Move cursor vertically down ARG lines, or to the next history element.
When point moves over the bottom line of multi-line minibuffer, puts ARGth
next element of the minibuffer history in the minibuffer."
(interactive "^p")
(or arg (setq arg 1))
(let* ((old-point (point))
;; Don't add newlines if they have the mode enabled globally.
(next-line-add-newlines nil)
;; Remember the original goal column of possibly multi-line input
;; excluding the length of the prompt on the first line.
(prompt-end (minibuffer-prompt-end))
(old-column (unless (and (eolp) (> (point) prompt-end))
(if (= (line-number-at-pos) 1)
(max (- (current-column)
(save-excursion
(goto-char (1- prompt-end))
(current-column)))
0)
(current-column)))))
(condition-case nil
(with-no-warnings
(next-line arg))
(end-of-buffer
;; Restore old position since `line-move-visual' moves point to
;; the end of the line when it fails to go to the next line.
(goto-char old-point)
(next-history-element arg)
;; Reset `temporary-goal-column' because a correct value is not
;; calculated when `next-line' above fails by bumping against
;; the bottom of the minibuffer (bug#22544).
(setq temporary-goal-column 0)
;; Restore the original goal column on the last line
;; of possibly multi-line input.
(goto-char (point-max))
(when old-column
(if (= (line-number-at-pos) 1)
(move-to-column (+ old-column
(save-excursion
(goto-char (1- (minibuffer-prompt-end)))
(current-column))))
(move-to-column old-column)))))))
(defun previous-line-or-history-element (&optional arg)
"Move cursor vertically up ARG lines, or to the previous history element.
When point moves over the top line of multi-line minibuffer, puts ARGth
previous element of the minibuffer history in the minibuffer."
(interactive "^p")
(or arg (setq arg 1))
(let* ((old-point (point))
;; Remember the original goal column of possibly multi-line input
;; excluding the length of the prompt on the first line.
(prompt-end (minibuffer-prompt-end))
(old-column (unless (and (eolp) (> (point) prompt-end))
(if (= (line-number-at-pos) 1)
(max (- (current-column)
(save-excursion
(goto-char (1- prompt-end))
(current-column)))
0)
(current-column)))))
(condition-case nil
(with-no-warnings
(previous-line arg))
(beginning-of-buffer
;; Restore old position since `line-move-visual' moves point to
;; the beginning of the line when it fails to go to the previous line.
(goto-char old-point)
(previous-history-element arg)
;; Reset `temporary-goal-column' because a correct value is not
;; calculated when `previous-line' above fails by bumping against
;; the top of the minibuffer (bug#22544).
(setq temporary-goal-column 0)
;; Restore the original goal column on the first line
;; of possibly multi-line input.
(goto-char (minibuffer-prompt-end))
(if old-column
(if (= (line-number-at-pos) 1)
(move-to-column (+ old-column
(save-excursion
(goto-char (1- (minibuffer-prompt-end)))
(current-column))))
(move-to-column old-column))
;; Put the cursor at the end of the visual line instead of the
;; logical line, so the next `previous-line-or-history-element'
;; would move to the previous history element, not to a possible upper
;; visual line from the end of logical line in `line-move-visual' mode.
(end-of-visual-line)
;; Since `end-of-visual-line' puts the cursor at the beginning
;; of the next visual line, move it one char back to the end
;; of the first visual line (bug#22544).
(unless (eolp) (backward-char 1)))))))
(defun next-complete-history-element (n)
"Get next history element which completes the minibuffer before the point.
The contents of the minibuffer after the point are deleted, and replaced
by the new completion."
(interactive "p")
(let ((point-at-start (point)))
(next-matching-history-element
(concat
"^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
n)
;; next-matching-history-element always puts us at (point-min).
;; Move to the position we were at before changing the buffer contents.
;; This is still sensible, because the text before point has not changed.
(goto-char point-at-start)))
(defun previous-complete-history-element (n)
"\
Get previous history element which completes the minibuffer before the point.
The contents of the minibuffer after the point are deleted, and replaced
by the new completion."
(interactive "p")
(next-complete-history-element (- n)))
;; For compatibility with the old subr of the same name.
(defun minibuffer-prompt-width ()
"Return the display width of the minibuffer prompt.
Return 0 if current buffer is not a minibuffer."
;; Return the width of everything before the field at the end of
;; the buffer; this should be 0 for normal buffers.
(1- (minibuffer-prompt-end)))
;; isearch minibuffer history
(add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
(defvar minibuffer-history-isearch-message-overlay)
(make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
(defun minibuffer-history-isearch-setup ()
"Set up a minibuffer for using isearch to search the minibuffer history.
Intended to be added to `minibuffer-setup-hook'."
(set (make-local-variable 'isearch-search-fun-function)
'minibuffer-history-isearch-search)
(set (make-local-variable 'isearch-message-function)
'minibuffer-history-isearch-message)
(set (make-local-variable 'isearch-wrap-function)
'minibuffer-history-isearch-wrap)
(set (make-local-variable 'isearch-push-state-function)
'minibuffer-history-isearch-push-state)
(add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
(defun minibuffer-history-isearch-end ()
"Clean up the minibuffer after terminating isearch in the minibuffer."
(if minibuffer-history-isearch-message-overlay
(delete-overlay minibuffer-history-isearch-message-overlay)))
(defun minibuffer-history-isearch-search ()
"Return the proper search function, for isearch in minibuffer history."
(lambda (string bound noerror)
(let ((search-fun
;; Use standard functions to search within minibuffer text
(isearch-search-fun-default))
found)
;; Avoid lazy-highlighting matches in the minibuffer prompt when
;; searching forward. Lazy-highlight calls this lambda with the
;; bound arg, so skip the minibuffer prompt.
(if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
(goto-char (minibuffer-prompt-end)))
(or
;; 1. First try searching in the initial minibuffer text
(funcall search-fun string
(if isearch-forward bound (minibuffer-prompt-end))
noerror)
;; 2. If the above search fails, start putting next/prev history
;; elements in the minibuffer successively, and search the string
;; in them. Do this only when bound is nil (i.e. not while
;; lazy-highlighting search strings in the current minibuffer text).
(unless bound
(condition-case nil
(progn
(while (not found)
(cond (isearch-forward
(next-history-element 1)
(goto-char (minibuffer-prompt-end)))
(t
(previous-history-element 1)
(goto-char (point-max))))
(setq isearch-barrier (point) isearch-opoint (point))
;; After putting the next/prev history element, search
;; the string in them again, until next-history-element
;; or previous-history-element raises an error at the
;; beginning/end of history.
(setq found (funcall search-fun string
(unless isearch-forward
;; For backward search, don't search
;; in the minibuffer prompt
(minibuffer-prompt-end))
noerror)))
;; Return point of the new search result
(point))
;; Return nil when next(prev)-history-element fails
(error nil)))))))
(defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
"Display the minibuffer history search prompt.
If there are no search errors, this function displays an overlay with
the isearch prompt which replaces the original minibuffer prompt.
Otherwise, it displays the standard isearch message returned from
the function `isearch-message'."
(if (not (and (minibufferp) isearch-success (not isearch-error)))
;; Use standard function `isearch-message' when not in the minibuffer,
;; or search fails, or has an error (like incomplete regexp).
;; This function overwrites minibuffer text with isearch message,
;; so it's possible to see what is wrong in the search string.
(isearch-message c-q-hack ellipsis)
;; Otherwise, put the overlay with the standard isearch prompt over
;; the initial minibuffer prompt.
(if (overlayp minibuffer-history-isearch-message-overlay)
(move-overlay minibuffer-history-isearch-message-overlay
(point-min) (minibuffer-prompt-end))
(setq minibuffer-history-isearch-message-overlay
(make-overlay (point-min) (minibuffer-prompt-end)))
(overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
(overlay-put minibuffer-history-isearch-message-overlay
'display (isearch-message-prefix c-q-hack ellipsis))
;; And clear any previous isearch message.
(message "")))
(defun minibuffer-history-isearch-wrap ()
"Wrap the minibuffer history search when search fails.
Move point to the first history element for a forward search,
or to the last history element for a backward search."
;; When `minibuffer-history-isearch-search' fails on reaching the
;; beginning/end of the history, wrap the search to the first/last
;; minibuffer history element.
(if isearch-forward
(goto-history-element (length (symbol-value minibuffer-history-variable)))
(goto-history-element 0))
(setq isearch-success t)
(goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
(defun minibuffer-history-isearch-push-state ()
"Save a function restoring the state of minibuffer history search.
Save `minibuffer-history-position' to the additional state parameter
in the search status stack."
(let ((pos minibuffer-history-position))
(lambda (cmd)
(minibuffer-history-isearch-pop-state cmd pos))))
(defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
"Restore the minibuffer history search state.
Go to the history element by the absolute history position HIST-POS."
(goto-history-element hist-pos))
;Put this on C-x u, so we can force that rather than C-_ into startup msg
(define-obsolete-function-alias 'advertised-undo 'undo "23.2")
(defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
"Table mapping redo records to the corresponding undo one.
A redo record for undo-in-region maps to t.
A redo record for ordinary undo maps to the following (earlier) undo.")
(defvar undo-in-region nil
"Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
(defvar undo-no-redo nil
"If t, `undo' doesn't go through redo entries.")
(defvar pending-undo-list nil
"Within a run of consecutive undo commands, list remaining to be undone.
If t, we undid all the way to the end of it.")
(defun undo (&optional arg)
"Undo some previous changes.
Repeat this command to undo more changes.
A numeric ARG serves as a repeat count.
In Transient Mark mode when the mark is active, only undo changes within
the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
as an argument limits undo to changes within the current region."
(interactive "*P")
;; Make last-command indicate for the next command that this was an undo.
;; That way, another undo will undo more.
;; If we get to the end of the undo history and get an error,
;; another undo command will find the undo history empty
;; and will get another error. To begin undoing the undos,
;; you must type some other command.
(let* ((modified (buffer-modified-p))
;; For an indirect buffer, look in the base buffer for the
;; auto-save data.
(base-buffer (or (buffer-base-buffer) (current-buffer)))
(recent-save (with-current-buffer base-buffer
(recent-auto-save-p)))
message)
;; If we get an error in undo-start,
;; the next command should not be a "consecutive undo".
;; So set `this-command' to something other than `undo'.
(setq this-command 'undo-start)
(unless (and (eq last-command 'undo)
(or (eq pending-undo-list t)
;; If something (a timer or filter?) changed the buffer
;; since the previous command, don't continue the undo seq.
(let ((list buffer-undo-list))
(while (eq (car list) nil)
(setq list (cdr list)))
;; If the last undo record made was made by undo
;; it shows nothing else happened in between.
(gethash list undo-equiv-table))))
(setq undo-in-region
(or (region-active-p) (and arg (not (numberp arg)))))
(if undo-in-region
(undo-start (region-beginning) (region-end))
(undo-start))
;; get rid of initial undo boundary
(undo-more 1))
;; If we got this far, the next command should be a consecutive undo.
(setq this-command 'undo)
;; Check to see whether we're hitting a redo record, and if
;; so, ask the user whether she wants to skip the redo/undo pair.
(let ((equiv (gethash pending-undo-list undo-equiv-table)))
(or (eq (selected-window) (minibuffer-window))
(setq message (format "%s%s!"
(if (or undo-no-redo (not equiv))
"Undo" "Redo")
(if undo-in-region " in region" ""))))
(when (and (consp equiv) undo-no-redo)
;; The equiv entry might point to another redo record if we have done
;; undo-redo-undo-redo-... so skip to the very last equiv.
(while (let ((next (gethash equiv undo-equiv-table)))
(if next (setq equiv next))))
(setq pending-undo-list equiv)))
(undo-more
(if (numberp arg)
(prefix-numeric-value arg)
1))
;; Record the fact that the just-generated undo records come from an
;; undo operation--that is, they are redo records.
;; In the ordinary case (not within a region), map the redo
;; record to the following undos.
;; I don't know how to do that in the undo-in-region case.
(let ((list buffer-undo-list))
;; Strip any leading undo boundaries there might be, like we do
;; above when checking.
(while (eq (car list) nil)
(setq list (cdr list)))
(puthash list
;; Prevent identity mapping. This can happen if
;; consecutive nils are erroneously in undo list.
(if (or undo-in-region (eq list pending-undo-list))
t
pending-undo-list)
undo-equiv-table))
;; Don't specify a position in the undo record for the undo command.
;; Instead, undoing this should move point to where the change is.
(let ((tail buffer-undo-list)
(prev nil))
(while (car tail)
(when (integerp (car tail))
(let ((pos (car tail)))
(if prev
(setcdr prev (cdr tail))
(setq buffer-undo-list (cdr tail)))
(setq tail (cdr tail))
(while (car tail)
(if (eq pos (car tail))
(if prev
(setcdr prev (cdr tail))
(setq buffer-undo-list (cdr tail)))
(setq prev tail))
(setq tail (cdr tail)))
(setq tail nil)))
(setq prev tail tail (cdr tail))))
;; Record what the current undo list says,
;; so the next command can tell if the buffer was modified in between.
(and modified (not (buffer-modified-p))
(with-current-buffer base-buffer
(delete-auto-save-file-if-necessary recent-save)))
;; Display a message announcing success.
(if message
(message "%s" message))))
(defun buffer-disable-undo (&optional buffer)
"Make BUFFER stop keeping undo information.
No argument or nil as argument means do this for the current buffer."
(interactive)
(with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
(setq buffer-undo-list t)))
(defun undo-only (&optional arg)
"Undo some previous changes.
Repeat this command to undo more changes.
A numeric ARG serves as a repeat count.
Contrary to `undo', this will not redo a previous undo."
(interactive "*p")
(let ((undo-no-redo t)) (undo arg)))
(defvar undo-in-progress nil
"Non-nil while performing an undo.
Some change-hooks test this variable to do something different.")
(defun undo-more (n)
"Undo back N undo-boundaries beyond what was already undone recently.
Call `undo-start' to get ready to undo recent changes,
then call `undo-more' one or more times to undo them."
(or (listp pending-undo-list)
(user-error (concat "No further undo information"
(and undo-in-region " for region"))))
(let ((undo-in-progress t))
;; Note: The following, while pulling elements off
;; `pending-undo-list' will call primitive change functions which
;; will push more elements onto `buffer-undo-list'.
(setq pending-undo-list (primitive-undo n pending-undo-list))
(if (null pending-undo-list)
(setq pending-undo-list t))))
(defun primitive-undo (n list)
"Undo N records from the front of the list LIST.
Return what remains of the list."
;; This is a good feature, but would make undo-start
;; unable to do what is expected.
;;(when (null (car (list)))
;; ;; If the head of the list is a boundary, it is the boundary
;; ;; preceding this command. Get rid of it and don't count it.
;; (setq list (cdr list))))
(let ((arg n)
;; In a writable buffer, enable undoing read-only text that is
;; so because of text properties.
(inhibit-read-only t)
;; Don't let `intangible' properties interfere with undo.
(inhibit-point-motion-hooks t)
;; We use oldlist only to check for EQ. ++kfs
(oldlist buffer-undo-list)
(did-apply nil)
(next nil))
(while (> arg 0)
(while (setq next (pop list)) ;Exit inner loop at undo boundary.
;; Handle an integer by setting point to that value.
(pcase next
((pred integerp) (goto-char next))
;; Element (t . TIME) records previous modtime.
;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
;; UNKNOWN_MODTIME_NSECS.
(`(t . ,time)
;; If this records an obsolete save
;; (not matching the actual disk file)
;; then don't mark unmodified.
(when (or (equal time (visited-file-modtime))
(and (consp time)
(equal (list (car time) (cdr time))
(visited-file-modtime))))
(when (fboundp 'unlock-buffer)
(unlock-buffer))
(set-buffer-modified-p nil)))
;; Element (nil PROP VAL BEG . END) is property change.
(`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
(when (or (> (point-min) beg) (< (point-max) end))
(error "Changes to be undone are outside visible portion of buffer"))
(put-text-property beg end prop val))
;; Element (BEG . END) means range was inserted.
(`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
(when (or (> (point-min) beg) (< (point-max) end))
(error "Changes to be undone are outside visible portion of buffer"))
;; Set point first thing, so that undoing this undo
;; does not send point back to where it is now.
(goto-char beg)
(delete-region beg end))
;; Element (apply FUN . ARGS) means call FUN to undo.
(`(apply . ,fun-args)
(let ((currbuff (current-buffer)))
(if (integerp (car fun-args))
;; Long format: (apply DELTA START END FUN . ARGS).
(pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
(start-mark (copy-marker start nil))
(end-mark (copy-marker end t)))
(when (or (> (point-min) start) (< (point-max) end))
(error "Changes to be undone are outside visible portion of buffer"))
(apply fun args) ;; Use `save-current-buffer'?
;; Check that the function did what the entry
;; said it would do.
(unless (and (= start start-mark)
(= (+ delta end) end-mark))
(error "Changes to be undone by function different than announced"))
(set-marker start-mark nil)
(set-marker end-mark nil))
(apply fun-args))
(unless (eq currbuff (current-buffer))
(error "Undo function switched buffer"))
(setq did-apply t)))
;; Element (STRING . POS) means STRING was deleted.
(`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
(let ((valid-marker-adjustments nil)
(apos (abs pos)))
(when (or (< apos (point-min)) (> apos (point-max)))
(error "Changes to be undone are outside visible portion of buffer"))
;; Check that marker adjustments which were recorded
;; with the (STRING . POS) record are still valid, ie
;; the markers haven't moved. We check their validity
;; before reinserting the string so as we don't need to
;; mind marker insertion-type.
(while (and (markerp (car-safe (car list)))
(integerp (cdr-safe (car list))))
(let* ((marker-adj (pop list))
(m (car marker-adj)))
(and (eq (marker-buffer m) (current-buffer))
(= apos m)
(push marker-adj valid-marker-adjustments))))
;; Insert string and adjust point
(if (< pos 0)
(progn
(goto-char (- pos))
(insert string))
(goto-char pos)
(insert string)
(goto-char pos))
;; Adjust the valid marker adjustments
(dolist (adj valid-marker-adjustments)
;; Insert might have invalidated some of the markers
;; via modification hooks. Update only the currently
;; valid ones (bug#25599).
(if (marker-buffer (car adj))
(set-marker (car adj)
(- (car adj) (cdr adj)))))))
;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
(`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
(warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
next)
;; Even though these elements are not expected in the undo
;; list, adjust them to be conservative for the 24.4
;; release. (Bug#16818)
(when (marker-buffer marker)
(set-marker marker
(- marker offset)
(marker-buffer marker))))
(_ (error "Unrecognized entry in undo list %S" next))))
(setq arg (1- arg)))
;; Make sure an apply entry produces at least one undo entry,
;; so the test in `undo' for continuing an undo series
;; will work right.
(if (and did-apply
(eq oldlist buffer-undo-list))
(setq buffer-undo-list
(cons (list 'apply 'cdr nil) buffer-undo-list))))
list)
;; Deep copy of a list
(defun undo-copy-list (list)
"Make a copy of undo list LIST."
(mapcar 'undo-copy-list-1 list))
(defun undo-copy-list-1 (elt)
(if (consp elt)
(cons (car elt) (undo-copy-list-1 (cdr elt)))
elt))
(defun undo-start (&optional beg end)
"Set `pending-undo-list' to the front of the undo list.
The next call to `undo-more' will undo the most recently made change.
If BEG and END are specified, then only undo elements
that apply to text between BEG and END are used; other undo elements
are ignored. If BEG and END are nil, all undo elements are used."
(if (eq buffer-undo-list t)
(user-error "No undo information in this buffer"))
(setq pending-undo-list
(if (and beg end (not (= beg end)))
(undo-make-selective-list (min beg end) (max beg end))
buffer-undo-list)))
;; The positions given in elements of the undo list are the positions
;; as of the time that element was recorded to undo history. In
;; general, subsequent buffer edits render those positions invalid in
;; the current buffer, unless adjusted according to the intervening
;; undo elements.
;;
;; Undo in region is a use case that requires adjustments to undo
;; elements. It must adjust positions of elements in the region based
;; on newer elements not in the region so as they may be correctly
;; applied in the current buffer. undo-make-selective-list
;; accomplishes this with its undo-deltas list of adjustments. An
;; example undo history from oldest to newest:
;;
;; buf pos:
;; 123456789 buffer-undo-list undo-deltas
;; --------- ---------------- -----------
;; aaa (1 . 4) (1 . -3)
;; aaba (3 . 4) N/A (in region)
;; ccaaba (1 . 3) (1 . -2)
;; ccaabaddd (7 . 10) (7 . -3)
;; ccaabdd ("ad" . 6) (6 . 2)
;; ccaabaddd (6 . 8) (6 . -2)
;; | |<-- region: "caab", from 2 to 6
;;
;; When the user starts a run of undos in region,
;; undo-make-selective-list is called to create the full list of in
;; region elements. Each element is adjusted forward chronologically
;; through undo-deltas to determine if it is in the region.
;;
;; In the above example, the insertion of "b" is (3 . 4) in the
;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
;; . 6) is assessed as in the region and placed in the selective list.
;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
;; due to the selected element. The "b" insertion is the only element
;; fully in the region, so in this example undo-make-selective-list
;; returns (nil (5 . 6)).
;;
;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
;; . 10) adjusts to (6 . 8) due to the first undo delta.
;;
;; More interesting is how to adjust the "ddd" insertion due to the
;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
;; If the reinsertion was a manual retyping of "ad", then the total
;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
;; the reinsertion was due to undo, one might expect the first "d"
;; character would again be a part of the "ddd" text, meaning its
;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
;;
;; undo-make-selective-list assumes in this situation that "ad" was a
;; new edit, even if it was inserted because of an undo.
;; Consequently, if the user undos in region "8 to 10" of the
;; "ccaabaddd" buffer, they could be surprised that it becomes
;; "ccaabad", as though the first "d" became detached from the
;; original "ddd" insertion. This quirk is a FIXME.
(defun undo-make-selective-list (start end)
"Return a list of undo elements for the region START to END.
The elements come from `buffer-undo-list', but we keep only the
elements inside this region, and discard those outside this
region. The elements' positions are adjusted so as the returned
list can be applied to the current buffer."
(let ((ulist buffer-undo-list)
;; A list of position adjusted undo elements in the region.
(selective-list (list nil))
;; A list of undo-deltas for out of region undo elements.
undo-deltas
undo-elt)
(while ulist
(when undo-no-redo
(while (gethash ulist undo-equiv-table)
(setq ulist (gethash ulist undo-equiv-table))))
(setq undo-elt (car ulist))
(cond
((null undo-elt)
;; Don't put two nils together in the list
(when (car selective-list)
(push nil selective-list)))
((and (consp undo-elt) (eq (car undo-elt) t))
;; This is a "was unmodified" element. Keep it
;; if we have kept everything thus far.
(when (not undo-deltas)
(push undo-elt selective-list)))
;; Skip over marker adjustments, instead relying
;; on finding them after (TEXT . POS) elements
((markerp (car-safe undo-elt))
nil)
(t
(let ((adjusted-undo-elt (undo-adjust-elt undo-elt
undo-deltas)))
(if (undo-elt-in-region adjusted-undo-elt start end)
(progn
(setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
(push adjusted-undo-elt selective-list)
;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
;; kept. primitive-undo may discard them later.
(when (and (stringp (car-safe adjusted-undo-elt))
(integerp (cdr-safe adjusted-undo-elt)))
(let ((list-i (cdr ulist)))
(while (markerp (car-safe (car list-i)))
(push (pop list-i) selective-list)))))
(let ((delta (undo-delta undo-elt)))
(when (/= 0 (cdr delta))
(push delta undo-deltas)))))))
(pop ulist))
(nreverse selective-list)))
(defun undo-elt-in-region (undo-elt start end)
"Determine whether UNDO-ELT falls inside the region START ... END.
If it crosses the edge, we return nil.
Generally this function is not useful for determining
whether (MARKER . ADJUSTMENT) undo elements are in the region,
because markers can be arbitrarily relocated. Instead, pass the
marker adjustment's corresponding (TEXT . POS) element."
(cond ((integerp undo-elt)
(and (>= undo-elt start)
(<= undo-elt end)))
((eq undo-elt nil)
t)
((atom undo-elt)
nil)
((stringp (car undo-elt))
;; (TEXT . POSITION)
(and (>= (abs (cdr undo-elt)) start)
(<= (abs (cdr undo-elt)) end)))
((and (consp undo-elt) (markerp (car undo-elt)))
;; (MARKER . ADJUSTMENT)
(<= start (car undo-elt) end))
((null (car undo-elt))
;; (nil PROPERTY VALUE BEG . END)
(let ((tail (nthcdr 3 undo-elt)))
(and (>= (car tail) start)
(<= (cdr tail) end))))
((integerp (car undo-elt))
;; (BEGIN . END)
(and (>= (car undo-elt) start)
(<= (cdr undo-elt) end)))))
(defun undo-elt-crosses-region (undo-elt start end)
"Test whether UNDO-ELT crosses one edge of that region START ... END.
This assumes we have already decided that UNDO-ELT
is not *inside* the region START...END."
(declare (obsolete nil "25.1"))
(cond ((atom undo-elt) nil)
((null (car undo-elt))
;; (nil PROPERTY VALUE BEG . END)
(let ((tail (nthcdr 3 undo-elt)))
(and (< (car tail) end)
(> (cdr tail) start))))
((integerp (car undo-elt))
;; (BEGIN . END)
(and (< (car undo-elt) end)
(> (cdr undo-elt) start)))))
(defun undo-adjust-elt (elt deltas)
"Return adjustment of undo element ELT by the undo DELTAS
list."
(pcase elt
;; POSITION
((pred integerp)
(undo-adjust-pos elt deltas))
;; (BEG . END)
(`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
(undo-adjust-beg-end beg end deltas))
;; (TEXT . POSITION)
(`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
(cons text (* (if (< pos 0) -1 1)
(undo-adjust-pos (abs pos) deltas))))
;; (nil PROPERTY VALUE BEG . END)
(`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
`(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
;; (apply DELTA START END FUN . ARGS)
;; FIXME
;; All others return same elt
(_ elt)))
;; (BEG . END) can adjust to the same positions, commonly when an
;; insertion was undone and they are out of region, for example:
;;
;; buf pos:
;; 123456789 buffer-undo-list undo-deltas
;; --------- ---------------- -----------
;; [...]
;; abbaa (2 . 4) (2 . -2)
;; aaa ("bb" . 2) (2 . 2)
;; [...]