PageRenderTime 105ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 2ms

/lisp/simple.el

https://bitbucket.org/danchr/emacs
Emacs Lisp | 6632 lines | 5243 code | 614 blank | 775 comment | 236 complexity | dca99fe45a688a3e45c5067e64e818ec MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.0, AGPL-3.0
  1. ;;; simple.el --- basic editing commands for Emacs
  2. ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
  3. ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
  4. ;; Free Software Foundation, Inc.
  5. ;; Maintainer: FSF
  6. ;; Keywords: internal
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; A grab-bag of basic Emacs commands not specifically related to some
  20. ;; major mode or to file-handling.
  21. ;;; Code:
  22. ;; This is for lexical-let in apply-partially.
  23. (eval-when-compile (require 'cl))
  24. (declare-function widget-convert "wid-edit" (type &rest args))
  25. (declare-function shell-mode "shell" ())
  26. (defvar compilation-current-error)
  27. (defcustom idle-update-delay 0.5
  28. "Idle time delay before updating various things on the screen.
  29. Various Emacs features that update auxiliary information when point moves
  30. wait this many seconds after Emacs becomes idle before doing an update."
  31. :type 'number
  32. :group 'display
  33. :version "22.1")
  34. (defgroup killing nil
  35. "Killing and yanking commands."
  36. :group 'editing)
  37. (defgroup paren-matching nil
  38. "Highlight (un)matching of parens and expressions."
  39. :group 'matching)
  40. (defun get-next-valid-buffer (list &optional buffer visible-ok frame)
  41. "Search LIST for a valid buffer to display in FRAME.
  42. Return nil when all buffers in LIST are undesirable for display,
  43. otherwise return the first suitable buffer in LIST.
  44. Buffers not visible in windows are preferred to visible buffers,
  45. unless VISIBLE-OK is non-nil.
  46. If the optional argument FRAME is nil, it defaults to the selected frame.
  47. If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
  48. ;; This logic is more or less copied from other-buffer.
  49. (setq frame (or frame (selected-frame)))
  50. (let ((pred (frame-parameter frame 'buffer-predicate))
  51. found buf)
  52. (while (and (not found) list)
  53. (setq buf (car list))
  54. (if (and (not (eq buffer buf))
  55. (buffer-live-p buf)
  56. (or (null pred) (funcall pred buf))
  57. (not (eq (aref (buffer-name buf) 0) ?\s))
  58. (or visible-ok (null (get-buffer-window buf 'visible))))
  59. (setq found buf)
  60. (setq list (cdr list))))
  61. (car list)))
  62. (defun last-buffer (&optional buffer visible-ok frame)
  63. "Return the last buffer in FRAME's buffer list.
  64. If BUFFER is the last buffer, return the preceding buffer instead.
  65. Buffers not visible in windows are preferred to visible buffers,
  66. unless optional argument VISIBLE-OK is non-nil.
  67. Optional third argument FRAME nil or omitted means use the
  68. selected frame's buffer list.
  69. If no such buffer exists, return the buffer `*scratch*', creating
  70. it if necessary."
  71. (setq frame (or frame (selected-frame)))
  72. (or (get-next-valid-buffer (nreverse (buffer-list frame))
  73. buffer visible-ok frame)
  74. (get-buffer "*scratch*")
  75. (let ((scratch (get-buffer-create "*scratch*")))
  76. (set-buffer-major-mode scratch)
  77. scratch)))
  78. (defun next-buffer ()
  79. "Switch to the next buffer in cyclic order."
  80. (interactive)
  81. (let ((buffer (current-buffer)))
  82. (switch-to-buffer (other-buffer buffer t))
  83. (bury-buffer buffer)))
  84. (defun previous-buffer ()
  85. "Switch to the previous buffer in cyclic order."
  86. (interactive)
  87. (switch-to-buffer (last-buffer (current-buffer) t)))
  88. ;;; next-error support framework
  89. (defgroup next-error nil
  90. "`next-error' support framework."
  91. :group 'compilation
  92. :version "22.1")
  93. (defface next-error
  94. '((t (:inherit region)))
  95. "Face used to highlight next error locus."
  96. :group 'next-error
  97. :version "22.1")
  98. (defcustom next-error-highlight 0.5
  99. "Highlighting of locations in selected source buffers.
  100. If a number, highlight the locus in `next-error' face for the given time
  101. in seconds, or until the next command is executed.
  102. If t, highlight the locus until the next command is executed, or until
  103. some other locus replaces it.
  104. If nil, don't highlight the locus in the source buffer.
  105. If `fringe-arrow', indicate the locus by the fringe arrow."
  106. :type '(choice (number :tag "Highlight for specified time")
  107. (const :tag "Semipermanent highlighting" t)
  108. (const :tag "No highlighting" nil)
  109. (const :tag "Fringe arrow" fringe-arrow))
  110. :group 'next-error
  111. :version "22.1")
  112. (defcustom next-error-highlight-no-select 0.5
  113. "Highlighting of locations in `next-error-no-select'.
  114. If number, highlight the locus in `next-error' face for given time in seconds.
  115. If t, highlight the locus indefinitely until some other locus replaces it.
  116. If nil, don't highlight the locus in the source buffer.
  117. If `fringe-arrow', indicate the locus by the fringe arrow."
  118. :type '(choice (number :tag "Highlight for specified time")
  119. (const :tag "Semipermanent highlighting" t)
  120. (const :tag "No highlighting" nil)
  121. (const :tag "Fringe arrow" fringe-arrow))
  122. :group 'next-error
  123. :version "22.1")
  124. (defcustom next-error-recenter nil
  125. "Display the line in the visited source file recentered as specified.
  126. If non-nil, the value is passed directly to `recenter'."
  127. :type '(choice (integer :tag "Line to recenter to")
  128. (const :tag "Center of window" (4))
  129. (const :tag "No recentering" nil))
  130. :group 'next-error
  131. :version "23.1")
  132. (defcustom next-error-hook nil
  133. "List of hook functions run by `next-error' after visiting source file."
  134. :type 'hook
  135. :group 'next-error)
  136. (defvar next-error-highlight-timer nil)
  137. (defvar next-error-overlay-arrow-position nil)
  138. (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
  139. (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
  140. (defvar next-error-last-buffer nil
  141. "The most recent `next-error' buffer.
  142. A buffer becomes most recent when its compilation, grep, or
  143. similar mode is started, or when it is used with \\[next-error]
  144. or \\[compile-goto-error].")
  145. (defvar next-error-function nil
  146. "Function to use to find the next error in the current buffer.
  147. The function is called with 2 parameters:
  148. ARG is an integer specifying by how many errors to move.
  149. RESET is a boolean which, if non-nil, says to go back to the beginning
  150. of the errors before moving.
  151. Major modes providing compile-like functionality should set this variable
  152. to indicate to `next-error' that this is a candidate buffer and how
  153. to navigate in it.")
  154. (make-variable-buffer-local 'next-error-function)
  155. (defvar next-error-move-function nil
  156. "Function to use to move to an error locus.
  157. It takes two arguments, a buffer position in the error buffer
  158. and a buffer position in the error locus buffer.
  159. The buffer for the error locus should already be current.
  160. nil means use goto-char using the second argument position.")
  161. (make-variable-buffer-local 'next-error-move-function)
  162. (defsubst next-error-buffer-p (buffer
  163. &optional avoid-current
  164. extra-test-inclusive
  165. extra-test-exclusive)
  166. "Test if BUFFER is a `next-error' capable buffer.
  167. If AVOID-CURRENT is non-nil, treat the current buffer
  168. as an absolute last resort only.
  169. The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
  170. that normally would not qualify. If it returns t, the buffer
  171. in question is treated as usable.
  172. The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
  173. that would normally be considered usable. If it returns nil,
  174. that buffer is rejected."
  175. (and (buffer-name buffer) ;First make sure it's live.
  176. (not (and avoid-current (eq buffer (current-buffer))))
  177. (with-current-buffer buffer
  178. (if next-error-function ; This is the normal test.
  179. ;; Optionally reject some buffers.
  180. (if extra-test-exclusive
  181. (funcall extra-test-exclusive)
  182. t)
  183. ;; Optionally accept some other buffers.
  184. (and extra-test-inclusive
  185. (funcall extra-test-inclusive))))))
  186. (defun next-error-find-buffer (&optional avoid-current
  187. extra-test-inclusive
  188. extra-test-exclusive)
  189. "Return a `next-error' capable buffer.
  190. If AVOID-CURRENT is non-nil, treat the current buffer
  191. as an absolute last resort only.
  192. The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
  193. that normally would not qualify. If it returns t, the buffer
  194. in question is treated as usable.
  195. The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
  196. that would normally be considered usable. If it returns nil,
  197. that buffer is rejected."
  198. (or
  199. ;; 1. If one window on the selected frame displays such buffer, return it.
  200. (let ((window-buffers
  201. (delete-dups
  202. (delq nil (mapcar (lambda (w)
  203. (if (next-error-buffer-p
  204. (window-buffer w)
  205. avoid-current
  206. extra-test-inclusive extra-test-exclusive)
  207. (window-buffer w)))
  208. (window-list))))))
  209. (if (eq (length window-buffers) 1)
  210. (car window-buffers)))
  211. ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
  212. (if (and next-error-last-buffer
  213. (next-error-buffer-p next-error-last-buffer avoid-current
  214. extra-test-inclusive extra-test-exclusive))
  215. next-error-last-buffer)
  216. ;; 3. If the current buffer is acceptable, choose it.
  217. (if (next-error-buffer-p (current-buffer) avoid-current
  218. extra-test-inclusive extra-test-exclusive)
  219. (current-buffer))
  220. ;; 4. Look for any acceptable buffer.
  221. (let ((buffers (buffer-list)))
  222. (while (and buffers
  223. (not (next-error-buffer-p
  224. (car buffers) avoid-current
  225. extra-test-inclusive extra-test-exclusive)))
  226. (setq buffers (cdr buffers)))
  227. (car buffers))
  228. ;; 5. Use the current buffer as a last resort if it qualifies,
  229. ;; even despite AVOID-CURRENT.
  230. (and avoid-current
  231. (next-error-buffer-p (current-buffer) nil
  232. extra-test-inclusive extra-test-exclusive)
  233. (progn
  234. (message "This is the only buffer with error message locations")
  235. (current-buffer)))
  236. ;; 6. Give up.
  237. (error "No buffers contain error message locations")))
  238. (defun next-error (&optional arg reset)
  239. "Visit next `next-error' message and corresponding source code.
  240. If all the error messages parsed so far have been processed already,
  241. the message buffer is checked for new ones.
  242. A prefix ARG specifies how many error messages to move;
  243. negative means move back to previous error messages.
  244. Just \\[universal-argument] as a prefix means reparse the error message buffer
  245. and start at the first error.
  246. The RESET argument specifies that we should restart from the beginning.
  247. \\[next-error] normally uses the most recently started
  248. compilation, grep, or occur buffer. It can also operate on any
  249. buffer with output from the \\[compile], \\[grep] commands, or,
  250. more generally, on any buffer in Compilation mode or with
  251. Compilation Minor mode enabled, or any buffer in which
  252. `next-error-function' is bound to an appropriate function.
  253. To specify use of a particular buffer for error messages, type
  254. \\[next-error] in that buffer when it is the only one displayed
  255. in the current frame.
  256. Once \\[next-error] has chosen the buffer for error messages, it
  257. runs `next-error-hook' with `run-hooks', and stays with that buffer
  258. until you use it in some other buffer which uses Compilation mode
  259. or Compilation Minor mode.
  260. See variables `compilation-parse-errors-function' and
  261. \`compilation-error-regexp-alist' for customization ideas."
  262. (interactive "P")
  263. (if (consp arg) (setq reset t arg nil))
  264. (when (setq next-error-last-buffer (next-error-find-buffer))
  265. ;; we know here that next-error-function is a valid symbol we can funcall
  266. (with-current-buffer next-error-last-buffer
  267. (funcall next-error-function (prefix-numeric-value arg) reset)
  268. (when next-error-recenter
  269. (recenter next-error-recenter))
  270. (run-hooks 'next-error-hook))))
  271. (defun next-error-internal ()
  272. "Visit the source code corresponding to the `next-error' message at point."
  273. (setq next-error-last-buffer (current-buffer))
  274. ;; we know here that next-error-function is a valid symbol we can funcall
  275. (with-current-buffer next-error-last-buffer
  276. (funcall next-error-function 0 nil)
  277. (when next-error-recenter
  278. (recenter next-error-recenter))
  279. (run-hooks 'next-error-hook)))
  280. (defalias 'goto-next-locus 'next-error)
  281. (defalias 'next-match 'next-error)
  282. (defun previous-error (&optional n)
  283. "Visit previous `next-error' message and corresponding source code.
  284. Prefix arg N says how many error messages to move backwards (or
  285. forwards, if negative).
  286. This operates on the output from the \\[compile] and \\[grep] commands."
  287. (interactive "p")
  288. (next-error (- (or n 1))))
  289. (defun first-error (&optional n)
  290. "Restart at the first error.
  291. Visit corresponding source code.
  292. With prefix arg N, visit the source code of the Nth error.
  293. This operates on the output from the \\[compile] command, for instance."
  294. (interactive "p")
  295. (next-error n t))
  296. (defun next-error-no-select (&optional n)
  297. "Move point to the next error in the `next-error' buffer and highlight match.
  298. Prefix arg N says how many error messages to move forwards (or
  299. backwards, if negative).
  300. Finds and highlights the source line like \\[next-error], but does not
  301. select the source buffer."
  302. (interactive "p")
  303. (let ((next-error-highlight next-error-highlight-no-select))
  304. (next-error n))
  305. (pop-to-buffer next-error-last-buffer))
  306. (defun previous-error-no-select (&optional n)
  307. "Move point to the previous error in the `next-error' buffer and highlight match.
  308. Prefix arg N says how many error messages to move backwards (or
  309. forwards, if negative).
  310. Finds and highlights the source line like \\[previous-error], but does not
  311. select the source buffer."
  312. (interactive "p")
  313. (next-error-no-select (- (or n 1))))
  314. ;; Internal variable for `next-error-follow-mode-post-command-hook'.
  315. (defvar next-error-follow-last-line nil)
  316. (define-minor-mode next-error-follow-minor-mode
  317. "Minor mode for compilation, occur and diff modes.
  318. When turned on, cursor motion in the compilation, grep, occur or diff
  319. buffer causes automatic display of the corresponding source code
  320. location."
  321. :group 'next-error :init-value nil :lighter " Fol"
  322. (if (not next-error-follow-minor-mode)
  323. (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
  324. (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
  325. (make-local-variable 'next-error-follow-last-line)))
  326. ;; Used as a `post-command-hook' by `next-error-follow-mode'
  327. ;; for the *Compilation* *grep* and *Occur* buffers.
  328. (defun next-error-follow-mode-post-command-hook ()
  329. (unless (equal next-error-follow-last-line (line-number-at-pos))
  330. (setq next-error-follow-last-line (line-number-at-pos))
  331. (condition-case nil
  332. (let ((compilation-context-lines nil))
  333. (setq compilation-current-error (point))
  334. (next-error-no-select 0))
  335. (error t))))
  336. ;;;
  337. (defun fundamental-mode ()
  338. "Major mode not specialized for anything in particular.
  339. Other major modes are defined by comparison with this one."
  340. (interactive)
  341. (kill-all-local-variables)
  342. (unless delay-mode-hooks
  343. (run-hooks 'after-change-major-mode-hook)))
  344. ;; Special major modes to view specially formatted data rather than files.
  345. (defvar special-mode-map
  346. (let ((map (make-sparse-keymap)))
  347. (suppress-keymap map)
  348. (define-key map "q" 'quit-window)
  349. (define-key map " " 'scroll-up)
  350. (define-key map "\C-?" 'scroll-down)
  351. (define-key map "?" 'describe-mode)
  352. (define-key map ">" 'end-of-buffer)
  353. (define-key map "<" 'beginning-of-buffer)
  354. (define-key map "g" 'revert-buffer)
  355. map))
  356. (put 'special-mode 'mode-class 'special)
  357. (define-derived-mode special-mode nil "Special"
  358. "Parent major mode from which special major modes should inherit."
  359. (setq buffer-read-only t))
  360. ;; Making and deleting lines.
  361. (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
  362. "Propertized string representing a hard newline character.")
  363. (defun newline (&optional arg)
  364. "Insert a newline, and move to left margin of the new line if it's blank.
  365. If `use-hard-newlines' is non-nil, the newline is marked with the
  366. text-property `hard'.
  367. With ARG, insert that many newlines.
  368. Call `auto-fill-function' if the current column number is greater
  369. than the value of `fill-column' and ARG is nil."
  370. (interactive "*P")
  371. (barf-if-buffer-read-only)
  372. ;; Inserting a newline at the end of a line produces better redisplay in
  373. ;; try_window_id than inserting at the beginning of a line, and the textual
  374. ;; result is the same. So, if we're at beginning of line, pretend to be at
  375. ;; the end of the previous line.
  376. (let ((flag (and (not (bobp))
  377. (bolp)
  378. ;; Make sure no functions want to be told about
  379. ;; the range of the changes.
  380. (not after-change-functions)
  381. (not before-change-functions)
  382. ;; Make sure there are no markers here.
  383. (not (buffer-has-markers-at (1- (point))))
  384. (not (buffer-has-markers-at (point)))
  385. ;; Make sure no text properties want to know
  386. ;; where the change was.
  387. (not (get-char-property (1- (point)) 'modification-hooks))
  388. (not (get-char-property (1- (point)) 'insert-behind-hooks))
  389. (or (eobp)
  390. (not (get-char-property (point) 'insert-in-front-hooks)))
  391. ;; Make sure the newline before point isn't intangible.
  392. (not (get-char-property (1- (point)) 'intangible))
  393. ;; Make sure the newline before point isn't read-only.
  394. (not (get-char-property (1- (point)) 'read-only))
  395. ;; Make sure the newline before point isn't invisible.
  396. (not (get-char-property (1- (point)) 'invisible))
  397. ;; Make sure the newline before point has the same
  398. ;; properties as the char before it (if any).
  399. (< (or (previous-property-change (point)) -2)
  400. (- (point) 2))))
  401. (was-page-start (and (bolp)
  402. (looking-at page-delimiter)))
  403. (beforepos (point)))
  404. (if flag (backward-char 1))
  405. ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
  406. ;; Set last-command-event to tell self-insert what to insert.
  407. (let ((last-command-event ?\n)
  408. ;; Don't auto-fill if we have a numeric argument.
  409. ;; Also not if flag is true (it would fill wrong line);
  410. ;; there is no need to since we're at BOL.
  411. (auto-fill-function (if (or arg flag) nil auto-fill-function)))
  412. (unwind-protect
  413. (self-insert-command (prefix-numeric-value arg))
  414. ;; If we get an error in self-insert-command, put point at right place.
  415. (if flag (forward-char 1))))
  416. ;; Even if we did *not* get an error, keep that forward-char;
  417. ;; all further processing should apply to the newline that the user
  418. ;; thinks he inserted.
  419. ;; Mark the newline(s) `hard'.
  420. (if use-hard-newlines
  421. (set-hard-newline-properties
  422. (- (point) (prefix-numeric-value arg)) (point)))
  423. ;; If the newline leaves the previous line blank,
  424. ;; and we have a left margin, delete that from the blank line.
  425. (or flag
  426. (save-excursion
  427. (goto-char beforepos)
  428. (beginning-of-line)
  429. (and (looking-at "[ \t]$")
  430. (> (current-left-margin) 0)
  431. (delete-region (point) (progn (end-of-line) (point))))))
  432. ;; Indent the line after the newline, except in one case:
  433. ;; when we added the newline at the beginning of a line
  434. ;; which starts a page.
  435. (or was-page-start
  436. (move-to-left-margin nil t)))
  437. nil)
  438. (defun set-hard-newline-properties (from to)
  439. (let ((sticky (get-text-property from 'rear-nonsticky)))
  440. (put-text-property from to 'hard 't)
  441. ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
  442. (if (and (listp sticky) (not (memq 'hard sticky)))
  443. (put-text-property from (point) 'rear-nonsticky
  444. (cons 'hard sticky)))))
  445. (defun open-line (n)
  446. "Insert a newline and leave point before it.
  447. If there is a fill prefix and/or a `left-margin', insert them
  448. on the new line if the line would have been blank.
  449. With arg N, insert N newlines."
  450. (interactive "*p")
  451. (let* ((do-fill-prefix (and fill-prefix (bolp)))
  452. (do-left-margin (and (bolp) (> (current-left-margin) 0)))
  453. (loc (point))
  454. ;; Don't expand an abbrev before point.
  455. (abbrev-mode nil))
  456. (newline n)
  457. (goto-char loc)
  458. (while (> n 0)
  459. (cond ((bolp)
  460. (if do-left-margin (indent-to (current-left-margin)))
  461. (if do-fill-prefix (insert-and-inherit fill-prefix))))
  462. (forward-line 1)
  463. (setq n (1- n)))
  464. (goto-char loc)
  465. (end-of-line)))
  466. (defun split-line (&optional arg)
  467. "Split current line, moving portion beyond point vertically down.
  468. If the current line starts with `fill-prefix', insert it on the new
  469. line as well. With prefix ARG, don't insert `fill-prefix' on new line.
  470. When called from Lisp code, ARG may be a prefix string to copy."
  471. (interactive "*P")
  472. (skip-chars-forward " \t")
  473. (let* ((col (current-column))
  474. (pos (point))
  475. ;; What prefix should we check for (nil means don't).
  476. (prefix (cond ((stringp arg) arg)
  477. (arg nil)
  478. (t fill-prefix)))
  479. ;; Does this line start with it?
  480. (have-prfx (and prefix
  481. (save-excursion
  482. (beginning-of-line)
  483. (looking-at (regexp-quote prefix))))))
  484. (newline 1)
  485. (if have-prfx (insert-and-inherit prefix))
  486. (indent-to col 0)
  487. (goto-char pos)))
  488. (defun delete-indentation (&optional arg)
  489. "Join this line to previous and fix up whitespace at join.
  490. If there is a fill prefix, delete it from the beginning of this line.
  491. With argument, join this line to following line."
  492. (interactive "*P")
  493. (beginning-of-line)
  494. (if arg (forward-line 1))
  495. (if (eq (preceding-char) ?\n)
  496. (progn
  497. (delete-region (point) (1- (point)))
  498. ;; If the second line started with the fill prefix,
  499. ;; delete the prefix.
  500. (if (and fill-prefix
  501. (<= (+ (point) (length fill-prefix)) (point-max))
  502. (string= fill-prefix
  503. (buffer-substring (point)
  504. (+ (point) (length fill-prefix)))))
  505. (delete-region (point) (+ (point) (length fill-prefix))))
  506. (fixup-whitespace))))
  507. (defalias 'join-line #'delete-indentation) ; easier to find
  508. (defun delete-blank-lines ()
  509. "On blank line, delete all surrounding blank lines, leaving just one.
  510. On isolated blank line, delete that one.
  511. On nonblank line, delete any immediately following blank lines."
  512. (interactive "*")
  513. (let (thisblank singleblank)
  514. (save-excursion
  515. (beginning-of-line)
  516. (setq thisblank (looking-at "[ \t]*$"))
  517. ;; Set singleblank if there is just one blank line here.
  518. (setq singleblank
  519. (and thisblank
  520. (not (looking-at "[ \t]*\n[ \t]*$"))
  521. (or (bobp)
  522. (progn (forward-line -1)
  523. (not (looking-at "[ \t]*$")))))))
  524. ;; Delete preceding blank lines, and this one too if it's the only one.
  525. (if thisblank
  526. (progn
  527. (beginning-of-line)
  528. (if singleblank (forward-line 1))
  529. (delete-region (point)
  530. (if (re-search-backward "[^ \t\n]" nil t)
  531. (progn (forward-line 1) (point))
  532. (point-min)))))
  533. ;; Delete following blank lines, unless the current line is blank
  534. ;; and there are no following blank lines.
  535. (if (not (and thisblank singleblank))
  536. (save-excursion
  537. (end-of-line)
  538. (forward-line 1)
  539. (delete-region (point)
  540. (if (re-search-forward "[^ \t\n]" nil t)
  541. (progn (beginning-of-line) (point))
  542. (point-max)))))
  543. ;; Handle the special case where point is followed by newline and eob.
  544. ;; Delete the line, leaving point at eob.
  545. (if (looking-at "^[ \t]*\n\\'")
  546. (delete-region (point) (point-max)))))
  547. (defun delete-trailing-whitespace ()
  548. "Delete all the trailing whitespace across the current buffer.
  549. All whitespace after the last non-whitespace character in a line is deleted.
  550. This respects narrowing, created by \\[narrow-to-region] and friends.
  551. A formfeed is not considered whitespace by this function."
  552. (interactive "*")
  553. (save-match-data
  554. (save-excursion
  555. (goto-char (point-min))
  556. (while (re-search-forward "\\s-$" nil t)
  557. (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
  558. ;; Don't delete formfeeds, even if they are considered whitespace.
  559. (save-match-data
  560. (if (looking-at ".*\f")
  561. (goto-char (match-end 0))))
  562. (delete-region (point) (match-end 0))))))
  563. (defun newline-and-indent ()
  564. "Insert a newline, then indent according to major mode.
  565. Indentation is done using the value of `indent-line-function'.
  566. In programming language modes, this is the same as TAB.
  567. In some text modes, where TAB inserts a tab, this command indents to the
  568. column specified by the function `current-left-margin'."
  569. (interactive "*")
  570. (delete-horizontal-space t)
  571. (newline)
  572. (indent-according-to-mode))
  573. (defun reindent-then-newline-and-indent ()
  574. "Reindent current line, insert newline, then indent the new line.
  575. Indentation of both lines is done according to the current major mode,
  576. which means calling the current value of `indent-line-function'.
  577. In programming language modes, this is the same as TAB.
  578. In some text modes, where TAB inserts a tab, this indents to the
  579. column specified by the function `current-left-margin'."
  580. (interactive "*")
  581. (let ((pos (point)))
  582. ;; Be careful to insert the newline before indenting the line.
  583. ;; Otherwise, the indentation might be wrong.
  584. (newline)
  585. (save-excursion
  586. (goto-char pos)
  587. ;; We are at EOL before the call to indent-according-to-mode, and
  588. ;; after it we usually are as well, but not always. We tried to
  589. ;; address it with `save-excursion' but that uses a normal marker
  590. ;; whereas we need `move after insertion', so we do the save/restore
  591. ;; by hand.
  592. (setq pos (copy-marker pos t))
  593. (indent-according-to-mode)
  594. (goto-char pos)
  595. ;; Remove the trailing white-space after indentation because
  596. ;; indentation may introduce the whitespace.
  597. (delete-horizontal-space t))
  598. (indent-according-to-mode)))
  599. (defun quoted-insert (arg)
  600. "Read next input character and insert it.
  601. This is useful for inserting control characters.
  602. With argument, insert ARG copies of the character.
  603. If the first character you type after this command is an octal digit,
  604. you should type a sequence of octal digits which specify a character code.
  605. Any nondigit terminates the sequence. If the terminator is a RET,
  606. it is discarded; any other terminator is used itself as input.
  607. The variable `read-quoted-char-radix' specifies the radix for this feature;
  608. set it to 10 or 16 to use decimal or hex instead of octal.
  609. In overwrite mode, this function inserts the character anyway, and
  610. does not handle octal digits specially. This means that if you use
  611. overwrite as your normal editing mode, you can use this function to
  612. insert characters when necessary.
  613. In binary overwrite mode, this function does overwrite, and octal
  614. digits are interpreted as a character code. This is intended to be
  615. useful for editing binary files."
  616. (interactive "*p")
  617. (let* ((char
  618. ;; Avoid "obsolete" warnings for translation-table-for-input.
  619. (with-no-warnings
  620. (let (translation-table-for-input input-method-function)
  621. (if (or (not overwrite-mode)
  622. (eq overwrite-mode 'overwrite-mode-binary))
  623. (read-quoted-char)
  624. (read-char))))))
  625. ;; This used to assume character codes 0240 - 0377 stand for
  626. ;; characters in some single-byte character set, and converted them
  627. ;; to Emacs characters. But in 23.1 this feature is deprecated
  628. ;; in favor of inserting the corresponding Unicode characters.
  629. ;; (if (and enable-multibyte-characters
  630. ;; (>= char ?\240)
  631. ;; (<= char ?\377))
  632. ;; (setq char (unibyte-char-to-multibyte char)))
  633. (if (> arg 0)
  634. (if (eq overwrite-mode 'overwrite-mode-binary)
  635. (delete-char arg)))
  636. (while (> arg 0)
  637. (insert-and-inherit char)
  638. (setq arg (1- arg)))))
  639. (defun forward-to-indentation (&optional arg)
  640. "Move forward ARG lines and position at first nonblank character."
  641. (interactive "^p")
  642. (forward-line (or arg 1))
  643. (skip-chars-forward " \t"))
  644. (defun backward-to-indentation (&optional arg)
  645. "Move backward ARG lines and position at first nonblank character."
  646. (interactive "^p")
  647. (forward-line (- (or arg 1)))
  648. (skip-chars-forward " \t"))
  649. (defun back-to-indentation ()
  650. "Move point to the first non-whitespace character on this line."
  651. (interactive "^")
  652. (beginning-of-line 1)
  653. (skip-syntax-forward " " (line-end-position))
  654. ;; Move back over chars that have whitespace syntax but have the p flag.
  655. (backward-prefix-chars))
  656. (defun fixup-whitespace ()
  657. "Fixup white space between objects around point.
  658. Leave one space or none, according to the context."
  659. (interactive "*")
  660. (save-excursion
  661. (delete-horizontal-space)
  662. (if (or (looking-at "^\\|\\s)")
  663. (save-excursion (forward-char -1)
  664. (looking-at "$\\|\\s(\\|\\s'")))
  665. nil
  666. (insert ?\s))))
  667. (defun delete-horizontal-space (&optional backward-only)
  668. "Delete all spaces and tabs around point.
  669. If BACKWARD-ONLY is non-nil, only delete them before point."
  670. (interactive "*P")
  671. (let ((orig-pos (point)))
  672. (delete-region
  673. (if backward-only
  674. orig-pos
  675. (progn
  676. (skip-chars-forward " \t")
  677. (constrain-to-field nil orig-pos t)))
  678. (progn
  679. (skip-chars-backward " \t")
  680. (constrain-to-field nil orig-pos)))))
  681. (defun just-one-space (&optional n)
  682. "Delete all spaces and tabs around point, leaving one space (or N spaces)."
  683. (interactive "*p")
  684. (let ((orig-pos (point)))
  685. (skip-chars-backward " \t")
  686. (constrain-to-field nil orig-pos)
  687. (dotimes (i (or n 1))
  688. (if (= (following-char) ?\s)
  689. (forward-char 1)
  690. (insert ?\s)))
  691. (delete-region
  692. (point)
  693. (progn
  694. (skip-chars-forward " \t")
  695. (constrain-to-field nil orig-pos t)))))
  696. (defun beginning-of-buffer (&optional arg)
  697. "Move point to the beginning of the buffer; leave mark at previous position.
  698. With \\[universal-argument] prefix, do not set mark at previous position.
  699. With numeric arg N, put point N/10 of the way from the beginning.
  700. If the buffer is narrowed, this command uses the beginning and size
  701. of the accessible part of the buffer.
  702. Don't use this command in Lisp programs!
  703. \(goto-char (point-min)) is faster and avoids clobbering the mark."
  704. (interactive "^P")
  705. (or (consp arg)
  706. (region-active-p)
  707. (push-mark))
  708. (let ((size (- (point-max) (point-min))))
  709. (goto-char (if (and arg (not (consp arg)))
  710. (+ (point-min)
  711. (if (> size 10000)
  712. ;; Avoid overflow for large buffer sizes!
  713. (* (prefix-numeric-value arg)
  714. (/ size 10))
  715. (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
  716. (point-min))))
  717. (if (and arg (not (consp arg))) (forward-line 1)))
  718. (defun end-of-buffer (&optional arg)
  719. "Move point to the end of the buffer; leave mark at previous position.
  720. With \\[universal-argument] prefix, do not set mark at previous position.
  721. With numeric arg N, put point N/10 of the way from the end.
  722. If the buffer is narrowed, this command uses the beginning and size
  723. of the accessible part of the buffer.
  724. Don't use this command in Lisp programs!
  725. \(goto-char (point-max)) is faster and avoids clobbering the mark."
  726. (interactive "^P")
  727. (or (consp arg) (region-active-p) (push-mark))
  728. (let ((size (- (point-max) (point-min))))
  729. (goto-char (if (and arg (not (consp arg)))
  730. (- (point-max)
  731. (if (> size 10000)
  732. ;; Avoid overflow for large buffer sizes!
  733. (* (prefix-numeric-value arg)
  734. (/ size 10))
  735. (/ (* size (prefix-numeric-value arg)) 10)))
  736. (point-max))))
  737. ;; If we went to a place in the middle of the buffer,
  738. ;; adjust it to the beginning of a line.
  739. (cond ((and arg (not (consp arg))) (forward-line 1))
  740. ((> (point) (window-end nil t))
  741. ;; If the end of the buffer is not already on the screen,
  742. ;; then scroll specially to put it near, but not at, the bottom.
  743. (overlay-recenter (point))
  744. (recenter -3))))
  745. (defun mark-whole-buffer ()
  746. "Put point at beginning and mark at end of buffer.
  747. You probably should not use this function in Lisp programs;
  748. it is usually a mistake for a Lisp function to use any subroutine
  749. that uses or sets the mark."
  750. (interactive)
  751. (push-mark (point))
  752. (push-mark (point-max) nil t)
  753. (goto-char (point-min)))
  754. ;; Counting lines, one way or another.
  755. (defun goto-line (line &optional buffer)
  756. "Goto LINE, counting from line 1 at beginning of buffer.
  757. Normally, move point in the current buffer, and leave mark at the
  758. previous position. With just \\[universal-argument] as argument,
  759. move point in the most recently selected other buffer, and switch to it.
  760. If there's a number in the buffer at point, it is the default for LINE.
  761. This function is usually the wrong thing to use in a Lisp program.
  762. What you probably want instead is something like:
  763. (goto-char (point-min)) (forward-line (1- N))
  764. If at all possible, an even better solution is to use char counts
  765. rather than line counts."
  766. (interactive
  767. (if (and current-prefix-arg (not (consp current-prefix-arg)))
  768. (list (prefix-numeric-value current-prefix-arg))
  769. ;; Look for a default, a number in the buffer at point.
  770. (let* ((default
  771. (save-excursion
  772. (skip-chars-backward "0-9")
  773. (if (looking-at "[0-9]")
  774. (buffer-substring-no-properties
  775. (point)
  776. (progn (skip-chars-forward "0-9")
  777. (point))))))
  778. ;; Decide if we're switching buffers.
  779. (buffer
  780. (if (consp current-prefix-arg)
  781. (other-buffer (current-buffer) t)))
  782. (buffer-prompt
  783. (if buffer
  784. (concat " in " (buffer-name buffer))
  785. "")))
  786. ;; Read the argument, offering that number (if any) as default.
  787. (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
  788. "Goto line%s: ")
  789. buffer-prompt
  790. default)
  791. nil nil t
  792. 'minibuffer-history
  793. default)
  794. buffer))))
  795. ;; Switch to the desired buffer, one way or another.
  796. (if buffer
  797. (let ((window (get-buffer-window buffer)))
  798. (if window (select-window window)
  799. (switch-to-buffer-other-window buffer))))
  800. ;; Leave mark at previous position
  801. (or (region-active-p) (push-mark))
  802. ;; Move to the specified line number in that buffer.
  803. (save-restriction
  804. (widen)
  805. (goto-char (point-min))
  806. (if (eq selective-display t)
  807. (re-search-forward "[\n\C-m]" nil 'end (1- line))
  808. (forward-line (1- line)))))
  809. (defun count-lines-region (start end)
  810. "Print number of lines and characters in the region."
  811. (interactive "r")
  812. (message "Region has %d lines, %d characters"
  813. (count-lines start end) (- end start)))
  814. (defun what-line ()
  815. "Print the current buffer line number and narrowed line number of point."
  816. (interactive)
  817. (let ((start (point-min))
  818. (n (line-number-at-pos)))
  819. (if (= start 1)
  820. (message "Line %d" n)
  821. (save-excursion
  822. (save-restriction
  823. (widen)
  824. (message "line %d (narrowed line %d)"
  825. (+ n (line-number-at-pos start) -1) n))))))
  826. (defun count-lines (start end)
  827. "Return number of lines between START and END.
  828. This is usually the number of newlines between them,
  829. but can be one more if START is not equal to END
  830. and the greater of them is not at the start of a line."
  831. (save-excursion
  832. (save-restriction
  833. (narrow-to-region start end)
  834. (goto-char (point-min))
  835. (if (eq selective-display t)
  836. (save-match-data
  837. (let ((done 0))
  838. (while (re-search-forward "[\n\C-m]" nil t 40)
  839. (setq done (+ 40 done)))
  840. (while (re-search-forward "[\n\C-m]" nil t 1)
  841. (setq done (+ 1 done)))
  842. (goto-char (point-max))
  843. (if (and (/= start end)
  844. (not (bolp)))
  845. (1+ done)
  846. done)))
  847. (- (buffer-size) (forward-line (buffer-size)))))))
  848. (defun line-number-at-pos (&optional pos)
  849. "Return (narrowed) buffer line number at position POS.
  850. If POS is nil, use current buffer location.
  851. Counting starts at (point-min), so the value refers
  852. to the contents of the accessible portion of the buffer."
  853. (let ((opoint (or pos (point))) start)
  854. (save-excursion
  855. (goto-char (point-min))
  856. (setq start (point))
  857. (goto-char opoint)
  858. (forward-line 0)
  859. (1+ (count-lines start (point))))))
  860. (defun what-cursor-position (&optional detail)
  861. "Print info on cursor position (on screen and within buffer).
  862. Also describe the character after point, and give its character code
  863. in octal, decimal and hex.
  864. For a non-ASCII multibyte character, also give its encoding in the
  865. buffer's selected coding system if the coding system encodes the
  866. character safely. If the character is encoded into one byte, that
  867. code is shown in hex. If the character is encoded into more than one
  868. byte, just \"...\" is shown.
  869. In addition, with prefix argument, show details about that character
  870. in *Help* buffer. See also the command `describe-char'."
  871. (interactive "P")
  872. (let* ((char (following-char))
  873. (beg (point-min))
  874. (end (point-max))
  875. (pos (point))
  876. (total (buffer-size))
  877. (percent (if (> total 50000)
  878. ;; Avoid overflow from multiplying by 100!
  879. (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
  880. (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
  881. (hscroll (if (= (window-hscroll) 0)
  882. ""
  883. (format " Hscroll=%d" (window-hscroll))))
  884. (col (current-column)))
  885. (if (= pos end)
  886. (if (or (/= beg 1) (/= end (1+ total)))
  887. (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
  888. pos total percent beg end col hscroll)
  889. (message "point=%d of %d (EOB) column=%d%s"
  890. pos total col hscroll))
  891. (let ((coding buffer-file-coding-system)
  892. encoded encoding-msg display-prop under-display)
  893. (if (or (not coding)
  894. (eq (coding-system-type coding) t))
  895. (setq coding (default-value 'buffer-file-coding-system)))
  896. (if (eq (char-charset char) 'eight-bit)
  897. (setq encoding-msg
  898. (format "(%d, #o%o, #x%x, raw-byte)" char char char))
  899. ;; Check if the character is displayed with some `display'
  900. ;; text property. In that case, set under-display to the
  901. ;; buffer substring covered by that property.
  902. (setq display-prop (get-text-property pos 'display))
  903. (if display-prop
  904. (let ((to (or (next-single-property-change pos 'display)
  905. (point-max))))
  906. (if (< to (+ pos 4))
  907. (setq under-display "")
  908. (setq under-display "..."
  909. to (+ pos 4)))
  910. (setq under-display
  911. (concat (buffer-substring-no-properties pos to)
  912. under-display)))
  913. (setq encoded (and (>= char 128) (encode-coding-char char coding))))
  914. (setq encoding-msg
  915. (if display-prop
  916. (if (not (stringp display-prop))
  917. (format "(%d, #o%o, #x%x, part of display \"%s\")"
  918. char char char under-display)
  919. (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
  920. char char char under-display display-prop))
  921. (if encoded
  922. (format "(%d, #o%o, #x%x, file %s)"
  923. char char char
  924. (if (> (length encoded) 1)
  925. "..."
  926. (encoded-string-description encoded coding)))
  927. (format "(%d, #o%o, #x%x)" char char char)))))
  928. (if detail
  929. ;; We show the detailed information about CHAR.
  930. (describe-char (point)))
  931. (if (or (/= beg 1) (/= end (1+ total)))
  932. (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
  933. (if (< char 256)
  934. (single-key-description char)
  935. (buffer-substring-no-properties (point) (1+ (point))))
  936. encoding-msg pos total percent beg end col hscroll)
  937. (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
  938. (if enable-multibyte-characters
  939. (if (< char 128)
  940. (single-key-description char)
  941. (buffer-substring-no-properties (point) (1+ (point))))
  942. (single-key-description char))
  943. encoding-msg pos total percent col hscroll))))))
  944. ;; Initialize read-expression-map. It is defined at C level.
  945. (let ((m (make-sparse-keymap)))
  946. (define-key m "\M-\t" 'lisp-complete-symbol)
  947. (set-keymap-parent m minibuffer-local-map)
  948. (setq read-expression-map m))
  949. (defvar read-expression-history nil)
  950. (defvar minibuffer-completing-symbol nil
  951. "Non-nil means completing a Lisp symbol in the minibuffer.")
  952. (defvar minibuffer-default nil
  953. "The current default value or list of default values in the minibuffer.
  954. The functions `read-from-minibuffer' and `completing-read' bind
  955. this variable locally.")
  956. (defcustom eval-expression-print-level 4
  957. "Value for `print-level' while printing value in `eval-expression'.
  958. A value of nil means no limit."
  959. :group 'lisp
  960. :type '(choice (const :tag "No Limit" nil) integer)
  961. :version "21.1")
  962. (defcustom eval-expression-print-length 12
  963. "Value for `print-length' while printing value in `eval-expression'.
  964. A value of nil means no limit."
  965. :group 'lisp
  966. :type '(choice (const :tag "No Limit" nil) integer)
  967. :version "21.1")
  968. (defcustom eval-expression-debug-on-error t
  969. "If non-nil set `debug-on-error' to t in `eval-expression'.
  970. If nil, don't change the value of `debug-on-error'."
  971. :group 'lisp
  972. :type 'boolean
  973. :version "21.1")
  974. (defun eval-expression-print-format (value)
  975. "Format VALUE as a result of evaluated expression.
  976. Return a formatted string which is displayed in the echo area
  977. in addition to the value printed by prin1 in functions which
  978. display the result of expression evaluation."
  979. (if (and (integerp value)
  980. (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
  981. (eq this-command last-command)
  982. (if (boundp 'edebug-active) edebug-active)))
  983. (let ((char-string
  984. (if (or (if (boundp 'edebug-active) edebug-active)
  985. (memq this-command '(eval-last-sexp eval-print-last-sexp)))
  986. (prin1-char value))))
  987. (if char-string
  988. (format " (#o%o, #x%x, %s)" value value char-string)
  989. (format " (#o%o, #x%x)" value value)))))
  990. ;; We define this, rather than making `eval' interactive,
  991. ;; for the sake of completion of names like eval-region, eval-buffer.
  992. (defun eval-expression (eval-expression-arg
  993. &optional eval-expression-insert-value)
  994. "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
  995. Value is also consed on to front of the variable `values'.
  996. Optional argument EVAL-EXPRESSION-INSERT-VALUE non-nil (interactively,
  997. with prefix argument) means insert the result into the current buffer
  998. instead of printing it in the echo area. Truncates long output
  999. according to the value of the variables `eval-expression-print-length'
  1000. and `eval-expression-print-level'.
  1001. If `eval-expression-debug-on-error' is non-nil, which is the default,
  1002. this command arranges for all errors to enter the debugger."
  1003. (interactive
  1004. (list (let ((minibuffer-completing-symbol t))
  1005. (read-from-minibuffer "Eval: "
  1006. nil read-expression-map t
  1007. 'read-expression-history))
  1008. current-prefix-arg))
  1009. (if (null eval-expression-debug-on-error)
  1010. (setq values (cons (eval eval-expression-arg) values))
  1011. (let ((old-value (make-symbol "t")) new-value)
  1012. ;; Bind debug-on-error to something unique so that we can
  1013. ;; detect when evaled code changes it.
  1014. (let ((debug-on-error old-value))
  1015. (setq values (cons (eval eval-expression-arg) values))
  1016. (setq new-value debug-on-error))
  1017. ;; If evaled code has changed the value of debug-on-error,
  1018. ;; propagate that change to the global binding.
  1019. (unless (eq old-value new-value)
  1020. (setq debug-on-error new-value))))
  1021. (let ((print-length eval-expression-print-length)
  1022. (print-level eval-expression-print-level))
  1023. (if eval-expression-insert-value
  1024. (with-no-warnings
  1025. (let ((standard-output (current-buffer)))
  1026. (prin1 (car values))))
  1027. (prog1
  1028. (prin1 (car values) t)
  1029. (let ((str (eval-expression-print-format (car values))))
  1030. (if str (princ str t)))))))
  1031. (defun edit-and-eval-command (prompt command)
  1032. "Prompting with PROMPT, let user edit COMMAND and eval result.
  1033. COMMAND is a Lisp expression. Let user edit that expression in
  1034. the minibuffer, then read and evaluate the result."
  1035. (let ((command
  1036. (let ((print-level nil)
  1037. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1038. (unwind-protect
  1039. (read-from-minibuffer prompt
  1040. (prin1-to-string command)
  1041. read-expression-map t
  1042. 'command-history)
  1043. ;; If command was added to command-history as a string,
  1044. ;; get rid of that. We want only evaluable expressions there.
  1045. (if (stringp (car command-history))
  1046. (setq command-history (cdr command-history)))))))
  1047. ;; If command to be redone does not match front of history,
  1048. ;; add it to the history.
  1049. (or (equal command (car command-history))
  1050. (setq command-history (cons command command-history)))
  1051. (eval command)))
  1052. (defun repeat-complex-command (arg)
  1053. "Edit and re-evaluate last complex command, or ARGth from last.
  1054. A complex command is one which used the minibuffer.
  1055. The command is placed in the minibuffer as a Lisp form for editing.
  1056. The result is executed, repeating the command as changed.
  1057. If the command has been changed or is not the most recent previous
  1058. command it is added to the front of the command history.
  1059. You can use the minibuffer history commands \
  1060. \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
  1061. to get different commands to edit and resubmit."
  1062. (interactive "p")
  1063. (let ((elt (nth (1- arg) command-history))
  1064. newcmd)
  1065. (if elt
  1066. (progn
  1067. (setq newcmd
  1068. (let ((print-level nil)
  1069. (minibuffer-history-position arg)
  1070. (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
  1071. (unwind-protect
  1072. (read-from-minibuffer
  1073. "Redo: " (prin1-to-string elt) read-expression-map t
  1074. (cons 'command-history arg))
  1075. ;; If command was added to command-history as a
  1076. ;; string, get rid of that. We want only
  1077. ;; evaluable expressions there.
  1078. (if (stringp (car command-history))
  1079. (setq command-history (cdr command-history))))))
  1080. ;; If command to be redone does not match front of history,
  1081. ;; add it to the history.
  1082. (or (equal newcmd (car command-history))
  1083. (setq command-history (cons newcmd command-history)))
  1084. (eval newcmd))
  1085. (if command-history
  1086. (error "Argument %d is beyond length of command history" arg)
  1087. (error "There are no previous complex commands to repeat")))))
  1088. (defvar minibuffer-history nil
  1089. "Default minibuffer history list.
  1090. This is used for all minibuffer input
  1091. except when an alternate history list is specified.
  1092. Maximum length of the history list is determined by the value
  1093. of `history-length', which see.")
  1094. (defvar minibuffer-history-sexp-flag nil
  1095. "Control whether history list elements are expressions or strings.
  1096. If the value of this variable equals current minibuffer depth,
  1097. they are expressions; otherwise they are strings.
  1098. \(That convention is designed to do the right thing for
  1099. recursive uses of the minibuffer.)")
  1100. (setq minibuffer-history-variable 'minibuffer-history)
  1101. (setq minibuffer-history-position nil) ;; Defvar is in C code.
  1102. (defvar minibuffer-history-search-history nil)
  1103. (defvar minibuffer-text-before-history nil
  1104. "Text that was in this minibuffer before any history commands.
  1105. This is nil if there have not yet been any history commands
  1106. in this use of the minibuffer.")
  1107. (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
  1108. (defun minibuffer-history-initialize ()
  1109. (setq minibuffer-text-before-history nil))
  1110. (defun minibuffer-avoid-prompt (new old)
  1111. "A point-motion hook for the minibuffer, that moves point out of the prompt."
  1112. (constrain-to-field nil (point-max)))
  1113. (defcustom minibuffer-history-case-insensitive-variables nil
  1114. "Minibuffer history variables for which matching should ignore case.
  1115. If a history variable is a member of this list, then the
  1116. \\[previous-matching-history-element] and \\[next-matching-history-element]\
  1117. commands ignore case when searching it, regardless of `case-fold-search'."
  1118. :type '(repeat variable)
  1119. :group 'minibuffer)
  1120. (defun previous-matching-history-element (regexp n)
  1121. "Find the previous history element that matches REGEXP.
  1122. \(Previous history elements refer to earlier actions.)
  1123. With prefix argument N, search for Nth previous match.
  1124. If N is negative, find the next or Nth next match.
  1125. Normally, history elements are matched case-insensitively if
  1126. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1127. makes the search case-sensitive.
  1128. See also `minibuffer-history-case-insensitive-variables'."
  1129. (interactive
  1130. (let* ((enable-recursive-minibuffers t)
  1131. (regexp (read-from-minibuffer "Previous element matching (regexp): "
  1132. nil
  1133. minibuffer-local-map
  1134. nil
  1135. 'minibuffer-history-search-history
  1136. (car minibuffer-history-search-history))))
  1137. ;; Use the last regexp specified, by default, if input is empty.
  1138. (list (if (string= regexp "")
  1139. (if minibuffer-history-search-history
  1140. (car minibuffer-history-search-history)
  1141. (error "No previous history search regexp"))
  1142. regexp)
  1143. (prefix-numeric-value current-prefix-arg))))
  1144. (unless (zerop n)
  1145. (if (and (zerop minibuffer-history-position)
  1146. (null minibuffer-text-before-history))
  1147. (setq minibuffer-text-before-history
  1148. (minibuffer-contents-no-properties)))
  1149. (let ((history (symbol-value minibuffer-history-variable))
  1150. (case-fold-search
  1151. (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
  1152. ;; On some systems, ignore case for file names.
  1153. (if (memq minibuffer-history-variable
  1154. minibuffer-history-case-insensitive-variables)
  1155. t
  1156. ;; Respect the user's setting for case-fold-search:
  1157. case-fold-search)
  1158. nil))
  1159. prevpos
  1160. match-string
  1161. match-offset
  1162. (pos minibuffer-history-position))
  1163. (while (/= n 0)
  1164. (setq prevpos pos)
  1165. (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
  1166. (when (= pos prevpos)
  1167. (error (if (= pos 1)
  1168. "No later matching history item"
  1169. "No earlier matching history item")))
  1170. (setq match-string
  1171. (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1172. (let ((print-level nil))
  1173. (prin1-to-string (nth (1- pos) history)))
  1174. (nth (1- pos) history)))
  1175. (setq match-offset
  1176. (if (< n 0)
  1177. (and (string-match regexp match-string)
  1178. (match-end 0))
  1179. (and (string-match (concat ".*\\(" regexp "\\)") match-string)
  1180. (match-beginning 1))))
  1181. (when match-offset
  1182. (setq n (+ n (if (< n 0) 1 -1)))))
  1183. (setq minibuffer-history-position pos)
  1184. (goto-char (point-max))
  1185. (delete-minibuffer-contents)
  1186. (insert match-string)
  1187. (goto-char (+ (minibuffer-prompt-end) match-offset))))
  1188. (if (memq (car (car command-history)) '(previous-matching-history-element
  1189. next-matching-history-element))
  1190. (setq command-history (cdr command-history))))
  1191. (defun next-matching-history-element (regexp n)
  1192. "Find the next history element that matches REGEXP.
  1193. \(The next history element refers to a more recent action.)
  1194. With prefix argument N, search for Nth next match.
  1195. If N is negative, find the previous or Nth previous match.
  1196. Normally, history elements are matched case-insensitively if
  1197. `case-fold-search' is non-nil, but an uppercase letter in REGEXP
  1198. makes the search case-sensitive."
  1199. (interactive
  1200. (let* ((enable-recursive-minibuffers t)
  1201. (regexp (read-from-minibuffer "Next element matching (regexp): "
  1202. nil
  1203. minibuffer-local-map
  1204. nil
  1205. 'minibuffer-history-search-history
  1206. (car minibuffer-history-search-history))))
  1207. ;; Use the last regexp specified, by default, if input is empty.
  1208. (list (if (string= regexp "")
  1209. (if minibuffer-history-search-history
  1210. (car minibuffer-history-search-history)
  1211. (error "No previous history search regexp"))
  1212. regexp)
  1213. (prefix-numeric-value current-prefix-arg))))
  1214. (previous-matching-history-element regexp (- n)))
  1215. (defvar minibuffer-temporary-goal-position nil)
  1216. (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
  1217. "Function run by `goto-history-element' before consuming default values.
  1218. This is useful to dynamically add more elements to the list of default values
  1219. when `goto-history-element' reaches the end of this list.
  1220. Before calling this function `goto-history-element' sets the variable
  1221. `minibuffer-default-add-done' to t, so it will call this function only
  1222. once. In special cases, when this function needs to be called more
  1223. than once, it can set `minibuffer-default-add-done' to nil explicitly,
  1224. overriding the setting of this variable to t in `goto-history-element'.")
  1225. (defvar minibuffer-default-add-done nil
  1226. "When nil, add more elements to the end of the list of default values.
  1227. The value nil causes `goto-history-element' to add more elements to
  1228. the list of defaults when it reaches the end of this list. It does
  1229. this by calling a function defined by `minibuffer-default-add-function'.")
  1230. (make-variable-buffer-local 'minibuffer-default-add-done)
  1231. (defun minibuffer-default-add-completions ()
  1232. "Return a list of all completions without the default value.
  1233. This function is used to add all elements of the completion table to
  1234. the end of the list of defaults just after the default value."
  1235. (let ((def minibuffer-default)
  1236. (all (all-completions ""
  1237. minibuffer-completion-table
  1238. minibuffer-completion-predicate)))
  1239. (if (listp def)
  1240. (append def all)
  1241. (cons def (delete def all)))))
  1242. (defun goto-history-element (nabs)
  1243. "Puts element of the minibuffer history in the minibuffer.
  1244. The argument NABS specifies the absolute history position."
  1245. (interactive "p")
  1246. (when (and (not minibuffer-default-add-done)
  1247. (functionp minibuffer-default-add-function)
  1248. (< nabs (- (if (listp minibuffer-default)
  1249. (length minibuffer-default)
  1250. 1))))
  1251. (setq minibuffer-default-add-done t
  1252. minibuffer-default (funcall minibuffer-default-add-function)))
  1253. (let ((minimum (if minibuffer-default
  1254. (- (if (listp minibuffer-default)
  1255. (length minibuffer-default)
  1256. 1))
  1257. 0))
  1258. elt minibuffer-returned-to-present)
  1259. (if (and (zerop minibuffer-history-position)
  1260. (null minibuffer-text-before-history))
  1261. (setq minibuffer-text-before-history
  1262. (minibuffer-contents-no-properties)))
  1263. (if (< nabs minimum)
  1264. (if minibuffer-default
  1265. (error "End of defaults; no next item")
  1266. (error "End of history; no default available")))
  1267. (if (> nabs (length (symbol-value minibuffer-history-variable)))
  1268. (error "Beginning of history; no preceding item"))
  1269. (unless (memq last-command '(next-history-element
  1270. previous-history-element))
  1271. (let ((prompt-end (minibuffer-prompt-end)))
  1272. (set (make-local-variable 'minibuffer-temporary-goal-position)
  1273. (cond ((<= (point) prompt-end) prompt-end)
  1274. ((eobp) nil)
  1275. (t (point))))))
  1276. (goto-char (point-max))
  1277. (delete-minibuffer-contents)
  1278. (setq minibuffer-history-position nabs)
  1279. (cond ((< nabs 0)
  1280. (setq elt (if (listp minibuffer-default)
  1281. (nth (1- (abs nabs)) minibuffer-default)
  1282. minibuffer-default)))
  1283. ((= nabs 0)
  1284. (setq elt (or minibuffer-text-before-history ""))
  1285. (setq minibuffer-returned-to-present t)
  1286. (setq minibuffer-text-before-history nil))
  1287. (t (setq elt (nth (1- minibuffer-history-position)
  1288. (symbol-value minibuffer-history-variable)))))
  1289. (insert
  1290. (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
  1291. (not minibuffer-returned-to-present))
  1292. (let ((print-level nil))
  1293. (prin1-to-string elt))
  1294. elt))
  1295. (goto-char (or minibuffer-temporary-goal-position (point-max)))))
  1296. (defun next-history-element (n)
  1297. "Puts next element of the minibuffer history in the minibuffer.
  1298. With argument N, it uses the Nth following element."
  1299. (interactive "p")
  1300. (or (zerop n)
  1301. (goto-history-element (- minibuffer-history-position n))))
  1302. (defun previous-history-element (n)
  1303. "Puts previous element of the minibuffer history in the minibuffer.
  1304. With argument N, it uses the Nth previous element."
  1305. (interactive "p")
  1306. (or (zerop n)
  1307. (goto-history-element (+ minibuffer-history-position n))))
  1308. (defun next-complete-history-element (n)
  1309. "Get next history element which completes the minibuffer before the point.
  1310. The contents of the minibuffer after the point are deleted, and replaced
  1311. by the new completion."
  1312. (interactive "p")
  1313. (let ((point-at-start (point)))
  1314. (next-matching-history-element
  1315. (concat
  1316. "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
  1317. n)
  1318. ;; next-matching-history-element always puts us at (point-min).
  1319. ;; Move to the position we were at before changing the buffer contents.
  1320. ;; This is still sensical, because the text before point has not changed.
  1321. (goto-char point-at-start)))
  1322. (defun previous-complete-history-element (n)
  1323. "\
  1324. Get previous history element which completes the minibuffer before the point.
  1325. The contents of the minibuffer after the point are deleted, and replaced
  1326. by the new completion."
  1327. (interactive "p")
  1328. (next-complete-history-element (- n)))
  1329. ;; For compatibility with the old subr of the same name.
  1330. (defun minibuffer-prompt-width ()
  1331. "Return the display width of the minibuffer prompt.
  1332. Return 0 if current buffer is not a minibuffer."
  1333. ;; Return the width of everything before the field at the end of
  1334. ;; the buffer; this should be 0 for normal buffers.
  1335. (1- (minibuffer-prompt-end)))
  1336. ;; isearch minibuffer history
  1337. (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
  1338. (defvar minibuffer-history-isearch-message-overlay)
  1339. (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
  1340. (defun minibuffer-history-isearch-setup ()
  1341. "Set up a minibuffer for using isearch to search the minibuffer history.
  1342. Intended to be added to `minibuffer-setup-hook'."
  1343. (set (make-local-variable 'isearch-search-fun-function)
  1344. 'minibuffer-history-isearch-search)
  1345. (set (make-local-variable 'isearch-message-function)
  1346. 'minibuffer-history-isearch-message)
  1347. (set (make-local-variable 'isearch-wrap-function)
  1348. 'minibuffer-history-isearch-wrap)
  1349. (set (make-local-variable 'isearch-push-state-function)
  1350. 'minibuffer-history-isearch-push-state)
  1351. (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
  1352. (defun minibuffer-history-isearch-end ()
  1353. "Clean up the minibuffer after terminating isearch in the minibuffer."
  1354. (if minibuffer-history-isearch-message-overlay
  1355. (delete-overlay minibuffer-history-isearch-message-overlay)))
  1356. (defun minibuffer-history-isearch-search ()
  1357. "Return the proper search function, for isearch in minibuffer history."
  1358. (cond
  1359. (isearch-word
  1360. (if isearch-forward 'word-search-forward 'word-search-backward))
  1361. (t
  1362. (lambda (string bound noerror)
  1363. (let ((search-fun
  1364. ;; Use standard functions to search within minibuffer text
  1365. (cond
  1366. (isearch-regexp
  1367. (if isearch-forward 're-search-forward 're-search-backward))
  1368. (t
  1369. (if isearch-forward 'search-forward 'search-backward))))
  1370. found)
  1371. ;; Avoid lazy-highlighting matches in the minibuffer prompt when
  1372. ;; searching forward. Lazy-highlight calls this lambda with the
  1373. ;; bound arg, so skip the minibuffer prompt.
  1374. (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
  1375. (goto-char (minibuffer-prompt-end)))
  1376. (or
  1377. ;; 1. First try searching in the initial minibuffer text
  1378. (funcall search-fun string
  1379. (if isearch-forward bound (minibuffer-prompt-end))
  1380. noerror)
  1381. ;; 2. If the above search fails, start putting next/prev history
  1382. ;; elements in the minibuffer successively, and search the string
  1383. ;; in them. Do this only when bound is nil (i.e. not while
  1384. ;; lazy-highlighting search strings in the current minibuffer text).
  1385. (unless bound
  1386. (condition-case nil
  1387. (progn
  1388. (while (not found)
  1389. (cond (isearch-forward
  1390. (next-history-element 1)
  1391. (goto-char (minibuffer-prompt-end)))
  1392. (t
  1393. (previous-history-element 1)
  1394. (goto-char (point-max))))
  1395. (setq isearch-barrier (point) isearch-opoint (point))
  1396. ;; After putting the next/prev history element, search
  1397. ;; the string in them again, until next-history-element
  1398. ;; or previous-history-element raises an error at the
  1399. ;; beginning/end of history.
  1400. (setq found (funcall search-fun string
  1401. (unless isearch-forward
  1402. ;; For backward search, don't search
  1403. ;; in the minibuffer prompt
  1404. (minibuffer-prompt-end))
  1405. noerror)))
  1406. ;; Return point of the new search result
  1407. (point))
  1408. ;; Return nil when next(prev)-history-element fails
  1409. (error nil)))))))))
  1410. (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
  1411. "Display the minibuffer history search prompt.
  1412. If there are no search errors, this function displays an overlay with
  1413. the isearch prompt which replaces the original minibuffer prompt.
  1414. Otherwise, it displays the standard isearch message returned from
  1415. `isearch-message'."
  1416. (if (not (and (minibufferp) isearch-success (not isearch-error)))
  1417. ;; Use standard function `isearch-message' when not in the minibuffer,
  1418. ;; or search fails, or has an error (like incomplete regexp).
  1419. ;; This function overwrites minibuffer text with isearch message,
  1420. ;; so it's possible to see what is wrong in the search string.
  1421. (isearch-message c-q-hack ellipsis)
  1422. ;; Otherwise, put the overlay with the standard isearch prompt over
  1423. ;; the initial minibuffer prompt.
  1424. (if (overlayp minibuffer-history-isearch-message-overlay)
  1425. (move-overlay minibuffer-history-isearch-message-overlay
  1426. (point-min) (minibuffer-prompt-end))
  1427. (setq minibuffer-history-isearch-message-overlay
  1428. (make-overlay (point-min) (minibuffer-prompt-end)))
  1429. (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
  1430. (overlay-put minibuffer-history-isearch-message-overlay
  1431. 'display (isearch-message-prefix c-q-hack ellipsis))
  1432. ;; And clear any previous isearch message.
  1433. (message "")))
  1434. (defun minibuffer-history-isearch-wrap ()
  1435. "Wrap the minibuffer history search when search fails.
  1436. Move point to the first history element for a forward search,
  1437. or to the last history element for a backward search."
  1438. (unless isearch-word
  1439. ;; When `minibuffer-history-isearch-search' fails on reaching the
  1440. ;; beginning/end of the history, wrap the search to the first/last
  1441. ;; minibuffer history element.
  1442. (if isearch-forward
  1443. (goto-history-element (length (symbol-value minibuffer-history-variable)))
  1444. (goto-history-element 0))
  1445. (setq isearch-success t))
  1446. (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
  1447. (defun minibuffer-history-isearch-push-state ()
  1448. "Save a function restoring the state of minibuffer history search.
  1449. Save `minibuffer-history-position' to the additional state parameter
  1450. in the search status stack."
  1451. `(lambda (cmd)
  1452. (minibuffer-history-isearch-pop-state cmd ,minibuffer-history-position)))
  1453. (defun minibuffer-history-isearch-pop-state (cmd hist-pos)
  1454. "Restore the minibuffer history search state.
  1455. Go to the history element by the absolute history position HIST-POS."
  1456. (goto-history-element hist-pos))
  1457. ;Put this on C-x u, so we can force that rather than C-_ into startup msg
  1458. (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
  1459. (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
  1460. "Table mapping redo records to the corresponding undo one.
  1461. A redo record for undo-in-region maps to t.
  1462. A redo record for ordinary undo maps to the following (earlier) undo.")
  1463. (defvar undo-in-region nil
  1464. "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
  1465. (defvar undo-no-redo nil
  1466. "If t, `undo' doesn't go through redo entries.")
  1467. (defvar pending-undo-list nil
  1468. "Within a run of consecutive undo commands, list remaining to be undone.
  1469. If t, we undid all the way to the end of it.")
  1470. (defun undo (&optional arg)
  1471. "Undo some previous changes.
  1472. Repeat this command to undo more changes.
  1473. A numeric ARG serves as a repeat count.
  1474. In Transient Mark mode when the mark is active, only undo changes within
  1475. the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
  1476. as an argument limits undo to changes within the current region."
  1477. (interactive "*P")
  1478. ;; Make last-command indicate for the next command that this was an undo.
  1479. ;; That way, another undo will undo more.
  1480. ;; If we get to the end of the undo history and get an error,
  1481. ;; another undo command will find the undo history empty
  1482. ;; and will get another error. To begin undoing the undos,
  1483. ;; you must type some other command.
  1484. (let ((modified (buffer-modified-p))
  1485. (recent-save (recent-auto-save-p))
  1486. message)
  1487. ;; If we get an error in undo-start,
  1488. ;; the next command should not be a "consecutive undo".
  1489. ;; So set `this-command' to something other than `undo'.
  1490. (setq this-command 'undo-start)
  1491. (unless (and (eq last-command 'undo)
  1492. (or (eq pending-undo-list t)
  1493. ;; If something (a timer or filter?) changed the buffer
  1494. ;; since the previous command, don't continue the undo seq.
  1495. (let ((list buffer-undo-list))
  1496. (while (eq (car list) nil)
  1497. (setq list (cdr list)))
  1498. ;; If the last undo record made was made by undo
  1499. ;; it shows nothing else happened in between.
  1500. (gethash list undo-equiv-table))))
  1501. (setq undo-in-region
  1502. (or (region-active-p) (and arg (not (numberp arg)))))
  1503. (if undo-in-region
  1504. (undo-start (region-beginning) (region-end))
  1505. (undo-start))
  1506. ;; get rid of initial undo boundary
  1507. (undo-more 1))
  1508. ;; If we got this far, the next command should be a consecutive undo.
  1509. (setq this-command 'undo)
  1510. ;; Check to see whether we're hitting a redo record, and if
  1511. ;; so, ask the user whether she wants to skip the redo/undo pair.
  1512. (let ((equiv (gethash pending-undo-list undo-equiv-table)))
  1513. (or (eq (selected-window) (minibuffer-window))
  1514. (setq message (if undo-in-region
  1515. (if equiv "Redo in region!" "Undo in region!")
  1516. (if equiv "Redo!" "Undo!"))))
  1517. (when (and (consp equiv) undo-no-redo)
  1518. ;; The equiv entry might point to another redo record if we have done
  1519. ;; undo-redo-undo-redo-... so skip to the very last equiv.
  1520. (while (let ((next (gethash equiv undo-equiv-table)))
  1521. (if next (setq equiv next))))
  1522. (setq pending-undo-list equiv)))
  1523. (undo-more
  1524. (if (numberp arg)
  1525. (prefix-numeric-value arg)
  1526. 1))
  1527. ;; Record the fact that the just-generated undo records come from an
  1528. ;; undo operation--that is, they are redo records.
  1529. ;; In the ordinary case (not within a region), map the redo
  1530. ;; record to the following undos.
  1531. ;; I don't know how to do that in the undo-in-region case.
  1532. (let ((list buffer-undo-list))
  1533. ;; Strip any leading undo boundaries there might be, like we do
  1534. ;; above when checking.
  1535. (while (eq (car list) nil)
  1536. (setq list (cdr list)))
  1537. (puthash list (if undo-in-region t pending-undo-list)
  1538. undo-equiv-table))
  1539. ;; Don't specify a position in the undo record for the undo command.
  1540. ;; Instead, undoing this should move point to where the change is.
  1541. (let ((tail buffer-undo-list)
  1542. (prev nil))
  1543. (while (car tail)
  1544. (when (integerp (car tail))
  1545. (let ((pos (car tail)))
  1546. (if prev
  1547. (setcdr prev (cdr tail))
  1548. (setq buffer-undo-list (cdr tail)))
  1549. (setq tail (cdr tail))
  1550. (while (car tail)
  1551. (if (eq pos (car tail))
  1552. (if prev
  1553. (setcdr prev (cdr tail))
  1554. (setq buffer-undo-list (cdr tail)))
  1555. (setq prev tail))
  1556. (setq tail (cdr tail)))
  1557. (setq tail nil)))
  1558. (setq prev tail tail (cdr tail))))
  1559. ;; Record what the current undo list says,
  1560. ;; so the next command can tell if the buffer was modified in between.
  1561. (and modified (not (buffer-modified-p))
  1562. (delete-auto-save-file-if-necessary recent-save))
  1563. ;; Display a message announcing success.
  1564. (if message
  1565. (message "%s" message))))
  1566. (defun buffer-disable-undo (&optional buffer)
  1567. "Make BUFFER stop keeping undo information.
  1568. No argument or nil as argument means do this for the current buffer."
  1569. (interactive)
  1570. (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
  1571. (setq buffer-undo-list t)))
  1572. (defun undo-only (&optional arg)
  1573. "Undo some previous changes.
  1574. Repeat this command to undo more changes.
  1575. A numeric ARG serves as a repeat count.
  1576. Contrary to `undo', this will not redo a previous undo."
  1577. (interactive "*p")
  1578. (let ((undo-no-redo t)) (undo arg)))
  1579. (defvar undo-in-progress nil
  1580. "Non-nil while performing an undo.
  1581. Some change-hooks test this variable to do something different.")
  1582. (defun undo-more (n)
  1583. "Undo back N undo-boundaries beyond what was already undone recently.
  1584. Call `undo-start' to get ready to undo recent changes,
  1585. then call `undo-more' one or more times to undo them."
  1586. (or (listp pending-undo-list)
  1587. (error (concat "No further undo information"
  1588. (and undo-in-region " for region"))))
  1589. (let ((undo-in-progress t))
  1590. ;; Note: The following, while pulling elements off
  1591. ;; `pending-undo-list' will call primitive change functions which
  1592. ;; will push more elements onto `buffer-undo-list'.
  1593. (setq pending-undo-list (primitive-undo n pending-undo-list))
  1594. (if (null pending-undo-list)
  1595. (setq pending-undo-list t))))
  1596. ;; Deep copy of a list
  1597. (defun undo-copy-list (list)
  1598. "Make a copy of undo list LIST."
  1599. (mapcar 'undo-copy-list-1 list))
  1600. (defun undo-copy-list-1 (elt)
  1601. (if (consp elt)
  1602. (cons (car elt) (undo-copy-list-1 (cdr elt)))
  1603. elt))
  1604. (defun undo-start (&optional beg end)
  1605. "Set `pending-undo-list' to the front of the undo list.
  1606. The next call to `undo-more' will undo the most recently made change.
  1607. If BEG and END are specified, then only undo elements
  1608. that apply to text between BEG and END are used; other undo elements
  1609. are ignored. If BEG and END are nil, all undo elements are used."
  1610. (if (eq buffer-undo-list t)
  1611. (error "No undo information in this buffer"))
  1612. (setq pending-undo-list
  1613. (if (and beg end (not (= beg end)))
  1614. (undo-make-selective-list (min beg end) (max beg end))
  1615. buffer-undo-list)))
  1616. (defvar undo-adjusted-markers)
  1617. (defun undo-make-selective-list (start end)
  1618. "Return a list of undo elements for the region START to END.
  1619. The elements come from `buffer-undo-list', but we keep only
  1620. the elements inside this region, and discard those outside this region.
  1621. If we find an element that crosses an edge of this region,
  1622. we stop and ignore all further elements."
  1623. (let ((undo-list-copy (undo-copy-list buffer-undo-list))
  1624. (undo-list (list nil))
  1625. undo-adjusted-markers
  1626. some-rejected
  1627. undo-elt undo-elt temp-undo-list delta)
  1628. (while undo-list-copy
  1629. (setq undo-elt (car undo-list-copy))
  1630. (let ((keep-this
  1631. (cond ((and (consp undo-elt) (eq (car undo-elt) t))
  1632. ;; This is a "was unmodified" element.
  1633. ;; Keep it if we have kept everything thus far.
  1634. (not some-rejected))
  1635. (t
  1636. (undo-elt-in-region undo-elt start end)))))
  1637. (if keep-this
  1638. (progn
  1639. (setq end (+ end (cdr (undo-delta undo-elt))))
  1640. ;; Don't put two nils together in the list
  1641. (if (not (and (eq (car undo-list) nil)
  1642. (eq undo-elt nil)))
  1643. (setq undo-list (cons undo-elt undo-list))))
  1644. (if (undo-elt-crosses-region undo-elt start end)
  1645. (setq undo-list-copy nil)
  1646. (setq some-rejected t)
  1647. (setq temp-undo-list (cdr undo-list-copy))
  1648. (setq delta (undo-delta undo-elt))
  1649. (when (/= (cdr delta) 0)
  1650. (let ((position (car delta))
  1651. (offset (cdr delta)))
  1652. ;; Loop down the earlier events adjusting their buffer
  1653. ;; positions to reflect the fact that a change to the buffer
  1654. ;; isn't being undone. We only need to process those element
  1655. ;; types which undo-elt-in-region will return as being in
  1656. ;; the region since only those types can ever get into the
  1657. ;; output
  1658. (while temp-undo-list
  1659. (setq undo-elt (car temp-undo-list))
  1660. (cond ((integerp undo-elt)
  1661. (if (>= undo-elt position)
  1662. (setcar temp-undo-list (- undo-elt offset))))
  1663. ((atom undo-elt) nil)
  1664. ((stringp (car undo-elt))
  1665. ;; (TEXT . POSITION)
  1666. (let ((text-pos (abs (cdr undo-elt)))
  1667. (point-at-end (< (cdr undo-elt) 0 )))
  1668. (if (>= text-pos position)
  1669. (setcdr undo-elt (* (if point-at-end -1 1)
  1670. (- text-pos offset))))))
  1671. ((integerp (car undo-elt))
  1672. ;; (BEGIN . END)
  1673. (when (>= (car undo-elt) position)
  1674. (setcar undo-elt (- (car undo-elt) offset))
  1675. (setcdr undo-elt (- (cdr undo-elt) offset))))
  1676. ((null (car undo-elt))
  1677. ;; (nil PROPERTY VALUE BEG . END)
  1678. (let ((tail (nthcdr 3 undo-elt)))
  1679. (when (>= (car tail) position)
  1680. (setcar tail (- (car tail) offset))
  1681. (setcdr tail (- (cdr tail) offset))))))
  1682. (setq temp-undo-list (cdr temp-undo-list))))))))
  1683. (setq undo-list-copy (cdr undo-list-copy)))
  1684. (nreverse undo-list)))
  1685. (defun undo-elt-in-region (undo-elt start end)
  1686. "Determine whether UNDO-ELT falls inside the region START ... END.
  1687. If it crosses the edge, we return nil."
  1688. (cond ((integerp undo-elt)
  1689. (and (>= undo-elt start)
  1690. (<= undo-elt end)))
  1691. ((eq undo-elt nil)
  1692. t)
  1693. ((atom undo-elt)
  1694. nil)
  1695. ((stringp (car undo-elt))
  1696. ;; (TEXT . POSITION)
  1697. (and (>= (abs (cdr undo-elt)) start)
  1698. (< (abs (cdr undo-elt)) end)))
  1699. ((and (consp undo-elt) (markerp (car undo-elt)))
  1700. ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
  1701. ;; See if MARKER is inside the region.
  1702. (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
  1703. (unless alist-elt
  1704. (setq alist-elt (cons (car undo-elt)
  1705. (marker-position (car undo-elt))))
  1706. (setq undo-adjusted-markers
  1707. (cons alist-elt undo-adjusted-markers)))
  1708. (and (cdr alist-elt)
  1709. (>= (cdr alist-elt) start)
  1710. (<= (cdr alist-elt) end))))
  1711. ((null (car undo-elt))
  1712. ;; (nil PROPERTY VALUE BEG . END)
  1713. (let ((tail (nthcdr 3 undo-elt)))
  1714. (and (>= (car tail) start)
  1715. (<= (cdr tail) end))))
  1716. ((integerp (car undo-elt))
  1717. ;; (BEGIN . END)
  1718. (and (>= (car undo-elt) start)
  1719. (<= (cdr undo-elt) end)))))
  1720. (defun undo-elt-crosses-region (undo-elt start end)
  1721. "Test whether UNDO-ELT crosses one edge of that region START ... END.
  1722. This assumes we have already decided that UNDO-ELT
  1723. is not *inside* the region START...END."
  1724. (cond ((atom undo-elt) nil)
  1725. ((null (car undo-elt))
  1726. ;; (nil PROPERTY VALUE BEG . END)
  1727. (let ((tail (nthcdr 3 undo-elt)))
  1728. (and (< (car tail) end)
  1729. (> (cdr tail) start))))
  1730. ((integerp (car undo-elt))
  1731. ;; (BEGIN . END)
  1732. (and (< (car undo-elt) end)
  1733. (> (cdr undo-elt) start)))))
  1734. ;; Return the first affected buffer position and the delta for an undo element
  1735. ;; delta is defined as the change in subsequent buffer positions if we *did*
  1736. ;; the undo.
  1737. (defun undo-delta (undo-elt)
  1738. (if (consp undo-elt)
  1739. (cond ((stringp (car undo-elt))
  1740. ;; (TEXT . POSITION)
  1741. (cons (abs (cdr undo-elt)) (length (car undo-elt))))
  1742. ((integerp (car undo-elt))
  1743. ;; (BEGIN . END)
  1744. (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
  1745. (t
  1746. '(0 . 0)))
  1747. '(0 . 0)))
  1748. (defcustom undo-ask-before-discard nil
  1749. "If non-nil ask about discarding undo info for the current command.
  1750. Normally, Emacs discards the undo info for the current command if
  1751. it exceeds `undo-outer-limit'. But if you set this option
  1752. non-nil, it asks in the echo area whether to discard the info.
  1753. If you answer no, there is a slight risk that Emacs might crash, so
  1754. only do it if you really want to undo the command.
  1755. This option is mainly intended for debugging. You have to be
  1756. careful if you use it for other purposes. Garbage collection is
  1757. inhibited while the question is asked, meaning that Emacs might
  1758. leak memory. So you should make sure that you do not wait
  1759. excessively long before answering the question."
  1760. :type 'boolean
  1761. :group 'undo
  1762. :version "22.1")
  1763. (defvar undo-extra-outer-limit nil
  1764. "If non-nil, an extra level of size that's ok in an undo item.
  1765. We don't ask the user about truncating the undo list until the
  1766. current item gets bigger than this amount.
  1767. This variable only matters if `undo-ask-before-discard' is non-nil.")
  1768. (make-variable-buffer-local 'undo-extra-outer-limit)
  1769. ;; When the first undo batch in an undo list is longer than
  1770. ;; undo-outer-limit, this function gets called to warn the user that
  1771. ;; the undo info for the current command was discarded. Garbage
  1772. ;; collection is inhibited around the call, so it had better not do a
  1773. ;; lot of consing.
  1774. (setq undo-outer-limit-function 'undo-outer-limit-truncate)
  1775. (defun undo-outer-limit-truncate (size)
  1776. (if undo-ask-before-discard
  1777. (when (or (null undo-extra-outer-limit)
  1778. (> size undo-extra-outer-limit))
  1779. ;; Don't ask the question again unless it gets even bigger.
  1780. ;; This applies, in particular, if the user quits from the question.
  1781. ;; Such a quit quits out of GC, but something else will call GC
  1782. ;; again momentarily. It will call this function again,
  1783. ;; but we don't want to ask the question again.
  1784. (setq undo-extra-outer-limit (+ size 50000))
  1785. (if (let (use-dialog-box track-mouse executing-kbd-macro )
  1786. (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
  1787. (buffer-name) size)))
  1788. (progn (setq buffer-undo-list nil)
  1789. (setq undo-extra-outer-limit nil)
  1790. t)
  1791. nil))
  1792. (display-warning '(undo discard-info)
  1793. (concat
  1794. (format "Buffer `%s' undo info was %d bytes long.\n"
  1795. (buffer-name) size)
  1796. "The undo info was discarded because it exceeded \
  1797. `undo-outer-limit'.
  1798. This is normal if you executed a command that made a huge change
  1799. to the buffer. In that case, to prevent similar problems in the
  1800. future, set `undo-outer-limit' to a value that is large enough to
  1801. cover the maximum size of normal changes you expect a single
  1802. command to make, but not so large that it might exceed the
  1803. maximum memory allotted to Emacs.
  1804. If you did not execute any such command, the situation is
  1805. probably due to a bug and you should report it.
  1806. You can disable the popping up of this buffer by adding the entry
  1807. \(undo discard-info) to the user option `warning-suppress-types',
  1808. which is defined in the `warnings' library.\n")
  1809. :warning)
  1810. (setq buffer-undo-list nil)
  1811. t))
  1812. (defvar shell-command-history nil
  1813. "History list for some commands that read shell commands.
  1814. Maximum length of the history list is determined by the value
  1815. of `history-length', which see.")
  1816. (defvar shell-command-switch (purecopy "-c")
  1817. "Switch used to have the shell execute its command line argument.")
  1818. (defvar shell-command-default-error-buffer nil
  1819. "*Buffer name for `shell-command' and `shell-command-on-region' error output.
  1820. This buffer is used when `shell-command' or `shell-command-on-region'
  1821. is run interactively. A value of nil means that output to stderr and
  1822. stdout will be intermixed in the output stream.")
  1823. (declare-function mailcap-file-default-commands "mailcap" (files))
  1824. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  1825. (defun minibuffer-default-add-shell-commands ()
  1826. "Return a list of all commands associated with the current file.
  1827. This function is used to add all related commands retrieved by `mailcap'
  1828. to the end of the list of defaults just after the default value."
  1829. (interactive)
  1830. (let* ((filename (if (listp minibuffer-default)
  1831. (car minibuffer-default)
  1832. minibuffer-default))
  1833. (commands (and filename (require 'mailcap nil t)
  1834. (mailcap-file-default-commands (list filename)))))
  1835. (setq commands (mapcar (lambda (command)
  1836. (concat command " " filename))
  1837. commands))
  1838. (if (listp minibuffer-default)
  1839. (append minibuffer-default commands)
  1840. (cons minibuffer-default commands))))
  1841. (defvar shell-delimiter-argument-list)
  1842. (defvar shell-file-name-chars)
  1843. (defvar shell-file-name-quote-list)
  1844. (defun minibuffer-complete-shell-command ()
  1845. "Dynamically complete shell command at point."
  1846. (interactive)
  1847. (require 'shell)
  1848. (let ((comint-delimiter-argument-list shell-delimiter-argument-list)
  1849. (comint-file-name-chars shell-file-name-chars)
  1850. (comint-file-name-quote-list shell-file-name-quote-list))
  1851. (run-hook-with-args-until-success 'shell-dynamic-complete-functions)))
  1852. (defvar minibuffer-local-shell-command-map
  1853. (let ((map (make-sparse-keymap)))
  1854. (set-keymap-parent map minibuffer-local-map)
  1855. (define-key map "\t" 'minibuffer-complete-shell-command)
  1856. map)
  1857. "Keymap used for completing shell commands in minibuffer.")
  1858. (defun read-shell-command (prompt &optional initial-contents hist &rest args)
  1859. "Read a shell command from the minibuffer.
  1860. The arguments are the same as the ones of `read-from-minibuffer',
  1861. except READ and KEYMAP are missing and HIST defaults
  1862. to `shell-command-history'."
  1863. (minibuffer-with-setup-hook
  1864. (lambda ()
  1865. (set (make-local-variable 'minibuffer-default-add-function)
  1866. 'minibuffer-default-add-shell-commands))
  1867. (apply 'read-from-minibuffer prompt initial-contents
  1868. minibuffer-local-shell-command-map
  1869. nil
  1870. (or hist 'shell-command-history)
  1871. args)))
  1872. (defun async-shell-command (command &optional output-buffer error-buffer)
  1873. "Execute string COMMAND asynchronously in background.
  1874. Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
  1875. surrounded by whitespace and executes the command asynchronously.
  1876. The output appears in the buffer `*Async Shell Command*'."
  1877. (interactive
  1878. (list
  1879. (read-shell-command "Async shell command: " nil nil
  1880. (and buffer-file-name
  1881. (file-relative-name buffer-file-name)))
  1882. current-prefix-arg
  1883. shell-command-default-error-buffer))
  1884. (unless (string-match "&[ \t]*\\'" command)
  1885. (setq command (concat command " &")))
  1886. (shell-command command output-buffer error-buffer))
  1887. (defun shell-command (command &optional output-buffer error-buffer)
  1888. "Execute string COMMAND in inferior shell; display output, if any.
  1889. With prefix argument, insert the COMMAND's output at point.
  1890. If COMMAND ends in ampersand, execute it asynchronously.
  1891. The output appears in the buffer `*Async Shell Command*'.
  1892. That buffer is in shell mode.
  1893. Otherwise, COMMAND is executed synchronously. The output appears in
  1894. the buffer `*Shell Command Output*'. If the output is short enough to
  1895. display in the echo area (which is determined by the variables
  1896. `resize-mini-windows' and `max-mini-window-height'), it is shown
  1897. there, but it is nonetheless available in buffer `*Shell Command
  1898. Output*' even though that buffer is not automatically displayed.
  1899. To specify a coding system for converting non-ASCII characters
  1900. in the shell command output, use \\[universal-coding-system-argument] \
  1901. before this command.
  1902. Noninteractive callers can specify coding systems by binding
  1903. `coding-system-for-read' and `coding-system-for-write'.
  1904. The optional second argument OUTPUT-BUFFER, if non-nil,
  1905. says to put the output in some other buffer.
  1906. If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
  1907. If OUTPUT-BUFFER is not a buffer and not nil,
  1908. insert output in current buffer. (This cannot be done asynchronously.)
  1909. In either case, the buffer is first erased, and the output is
  1910. inserted after point (leaving mark after it).
  1911. If the command terminates without error, but generates output,
  1912. and you did not specify \"insert it in the current buffer\",
  1913. the output can be displayed in the echo area or in its buffer.
  1914. If the output is short enough to display in the echo area
  1915. \(determined by the variable `max-mini-window-height' if
  1916. `resize-mini-windows' is non-nil), it is shown there.
  1917. Otherwise,the buffer containing the output is displayed.
  1918. If there is output and an error, and you did not specify \"insert it
  1919. in the current buffer\", a message about the error goes at the end
  1920. of the output.
  1921. If there is no output, or if output is inserted in the current buffer,
  1922. then `*Shell Command Output*' is deleted.
  1923. If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
  1924. or buffer name to which to direct the command's standard error output.
  1925. If it is nil, error output is mingled with regular output.
  1926. In an interactive call, the variable `shell-command-default-error-buffer'
  1927. specifies the value of ERROR-BUFFER."
  1928. (interactive
  1929. (list
  1930. (read-shell-command "Shell command: " nil nil
  1931. (let ((filename
  1932. (cond
  1933. (buffer-file-name)
  1934. ((eq major-mode 'dired-mode)
  1935. (dired-get-filename nil t)))))
  1936. (and filename (file-relative-name filename))))
  1937. current-prefix-arg
  1938. shell-command-default-error-buffer))
  1939. ;; Look for a handler in case default-directory is a remote file name.
  1940. (let ((handler
  1941. (find-file-name-handler (directory-file-name default-directory)
  1942. 'shell-command)))
  1943. (if handler
  1944. (funcall handler 'shell-command command output-buffer error-buffer)
  1945. (if (and output-buffer
  1946. (not (or (bufferp output-buffer) (stringp output-buffer))))
  1947. ;; Output goes in current buffer.
  1948. (let ((error-file
  1949. (if error-buffer
  1950. (make-temp-file
  1951. (expand-file-name "scor"
  1952. (or small-temporary-file-directory
  1953. temporary-file-directory)))
  1954. nil)))
  1955. (barf-if-buffer-read-only)
  1956. (push-mark nil t)
  1957. ;; We do not use -f for csh; we will not support broken use of
  1958. ;; .cshrcs. Even the BSD csh manual says to use
  1959. ;; "if ($?prompt) exit" before things which are not useful
  1960. ;; non-interactively. Besides, if someone wants their other
  1961. ;; aliases for shell commands then they can still have them.
  1962. (call-process shell-file-name nil
  1963. (if error-file
  1964. (list t error-file)
  1965. t)
  1966. nil shell-command-switch command)
  1967. (when (and error-file (file-exists-p error-file))
  1968. (if (< 0 (nth 7 (file-attributes error-file)))
  1969. (with-current-buffer (get-buffer-create error-buffer)
  1970. (let ((pos-from-end (- (point-max) (point))))
  1971. (or (bobp)
  1972. (insert "\f\n"))
  1973. ;; Do no formatting while reading error file,
  1974. ;; because that can run a shell command, and we
  1975. ;; don't want that to cause an infinite recursion.
  1976. (format-insert-file error-file nil)
  1977. ;; Put point after the inserted errors.
  1978. (goto-char (- (point-max) pos-from-end)))
  1979. (display-buffer (current-buffer))))
  1980. (delete-file error-file))
  1981. ;; This is like exchange-point-and-mark, but doesn't
  1982. ;; activate the mark. It is cleaner to avoid activation,
  1983. ;; even though the command loop would deactivate the mark
  1984. ;; because we inserted text.
  1985. (goto-char (prog1 (mark t)
  1986. (set-marker (mark-marker) (point)
  1987. (current-buffer)))))
  1988. ;; Output goes in a separate buffer.
  1989. ;; Preserve the match data in case called from a program.
  1990. (save-match-data
  1991. (if (string-match "[ \t]*&[ \t]*\\'" command)
  1992. ;; Command ending with ampersand means asynchronous.
  1993. (let ((buffer (get-buffer-create
  1994. (or output-buffer "*Async Shell Command*")))
  1995. (directory default-directory)
  1996. proc)
  1997. ;; Remove the ampersand.
  1998. (setq command (substring command 0 (match-beginning 0)))
  1999. ;; If will kill a process, query first.
  2000. (setq proc (get-buffer-process buffer))
  2001. (if proc
  2002. (if (yes-or-no-p "A command is running. Kill it? ")
  2003. (kill-process proc)
  2004. (error "Shell command in progress")))
  2005. (with-current-buffer buffer
  2006. (setq buffer-read-only nil)
  2007. (erase-buffer)
  2008. (display-buffer buffer)
  2009. (setq default-directory directory)
  2010. (setq proc (start-process "Shell" buffer shell-file-name
  2011. shell-command-switch command))
  2012. (setq mode-line-process '(":%s"))
  2013. (require 'shell) (shell-mode)
  2014. (set-process-sentinel proc 'shell-command-sentinel)
  2015. ;; Use the comint filter for proper handling of carriage motion
  2016. ;; (see `comint-inhibit-carriage-motion'),.
  2017. (set-process-filter proc 'comint-output-filter)
  2018. ))
  2019. ;; Otherwise, command is executed synchronously.
  2020. (shell-command-on-region (point) (point) command
  2021. output-buffer nil error-buffer)))))))
  2022. (defun display-message-or-buffer (message
  2023. &optional buffer-name not-this-window frame)
  2024. "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
  2025. MESSAGE may be either a string or a buffer.
  2026. A buffer is displayed using `display-buffer' if MESSAGE is too long for
  2027. the maximum height of the echo area, as defined by `max-mini-window-height'
  2028. if `resize-mini-windows' is non-nil.
  2029. Returns either the string shown in the echo area, or when a pop-up
  2030. buffer is used, the window used to display it.
  2031. If MESSAGE is a string, then the optional argument BUFFER-NAME is the
  2032. name of the buffer used to display it in the case where a pop-up buffer
  2033. is used, defaulting to `*Message*'. In the case where MESSAGE is a
  2034. string and it is displayed in the echo area, it is not specified whether
  2035. the contents are inserted into the buffer anyway.
  2036. Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
  2037. and only used if a buffer is displayed."
  2038. (cond ((and (stringp message) (not (string-match "\n" message)))
  2039. ;; Trivial case where we can use the echo area
  2040. (message "%s" message))
  2041. ((and (stringp message)
  2042. (= (string-match "\n" message) (1- (length message))))
  2043. ;; Trivial case where we can just remove single trailing newline
  2044. (message "%s" (substring message 0 (1- (length message)))))
  2045. (t
  2046. ;; General case
  2047. (with-current-buffer
  2048. (if (bufferp message)
  2049. message
  2050. (get-buffer-create (or buffer-name "*Message*")))
  2051. (unless (bufferp message)
  2052. (erase-buffer)
  2053. (insert message))
  2054. (let ((lines
  2055. (if (= (buffer-size) 0)
  2056. 0
  2057. (count-screen-lines nil nil nil (minibuffer-window)))))
  2058. (cond ((= lines 0))
  2059. ((and (or (<= lines 1)
  2060. (<= lines
  2061. (if resize-mini-windows
  2062. (cond ((floatp max-mini-window-height)
  2063. (* (frame-height)
  2064. max-mini-window-height))
  2065. ((integerp max-mini-window-height)
  2066. max-mini-window-height)
  2067. (t
  2068. 1))
  2069. 1)))
  2070. ;; Don't use the echo area if the output buffer is
  2071. ;; already dispayed in the selected frame.
  2072. (not (get-buffer-window (current-buffer))))
  2073. ;; Echo area
  2074. (goto-char (point-max))
  2075. (when (bolp)
  2076. (backward-char 1))
  2077. (message "%s" (buffer-substring (point-min) (point))))
  2078. (t
  2079. ;; Buffer
  2080. (goto-char (point-min))
  2081. (display-buffer (current-buffer)
  2082. not-this-window frame))))))))
  2083. ;; We have a sentinel to prevent insertion of a termination message
  2084. ;; in the buffer itself.
  2085. (defun shell-command-sentinel (process signal)
  2086. (if (memq (process-status process) '(exit signal))
  2087. (message "%s: %s."
  2088. (car (cdr (cdr (process-command process))))
  2089. (substring signal 0 -1))))
  2090. (defun shell-command-on-region (start end command
  2091. &optional output-buffer replace
  2092. error-buffer display-error-buffer)
  2093. "Execute string COMMAND in inferior shell with region as input.
  2094. Normally display output (if any) in temp buffer `*Shell Command Output*';
  2095. Prefix arg means replace the region with it. Return the exit code of
  2096. COMMAND.
  2097. To specify a coding system for converting non-ASCII characters
  2098. in the input and output to the shell command, use \\[universal-coding-system-argument]
  2099. before this command. By default, the input (from the current buffer)
  2100. is encoded in the same coding system that will be used to save the file,
  2101. `buffer-file-coding-system'. If the output is going to replace the region,
  2102. then it is decoded from that same coding system.
  2103. The noninteractive arguments are START, END, COMMAND,
  2104. OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
  2105. Noninteractive callers can specify coding systems by binding
  2106. `coding-system-for-read' and `coding-system-for-write'.
  2107. If the command generates output, the output may be displayed
  2108. in the echo area or in a buffer.
  2109. If the output is short enough to display in the echo area
  2110. \(determined by the variable `max-mini-window-height' if
  2111. `resize-mini-windows' is non-nil), it is shown there. Otherwise
  2112. it is displayed in the buffer `*Shell Command Output*'. The output
  2113. is available in that buffer in both cases.
  2114. If there is output and an error, a message about the error
  2115. appears at the end of the output.
  2116. If there is no output, or if output is inserted in the current buffer,
  2117. then `*Shell Command Output*' is deleted.
  2118. If the optional fourth argument OUTPUT-BUFFER is non-nil,
  2119. that says to put the output in some other buffer.
  2120. If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
  2121. If OUTPUT-BUFFER is not a buffer and not nil,
  2122. insert output in the current buffer.
  2123. In either case, the output is inserted after point (leaving mark after it).
  2124. If REPLACE, the optional fifth argument, is non-nil, that means insert
  2125. the output in place of text from START to END, putting point and mark
  2126. around it.
  2127. If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
  2128. or buffer name to which to direct the command's standard error output.
  2129. If it is nil, error output is mingled with regular output.
  2130. If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
  2131. were any errors. (This is always t, interactively.)
  2132. In an interactive call, the variable `shell-command-default-error-buffer'
  2133. specifies the value of ERROR-BUFFER."
  2134. (interactive (let (string)
  2135. (unless (mark)
  2136. (error "The mark is not set now, so there is no region"))
  2137. ;; Do this before calling region-beginning
  2138. ;; and region-end, in case subprocess output
  2139. ;; relocates them while we are in the minibuffer.
  2140. (setq string (read-shell-command "Shell command on region: "))
  2141. ;; call-interactively recognizes region-beginning and
  2142. ;; region-end specially, leaving them in the history.
  2143. (list (region-beginning) (region-end)
  2144. string
  2145. current-prefix-arg
  2146. current-prefix-arg
  2147. shell-command-default-error-buffer
  2148. t)))
  2149. (let ((error-file
  2150. (if error-buffer
  2151. (make-temp-file
  2152. (expand-file-name "scor"
  2153. (or small-temporary-file-directory
  2154. temporary-file-directory)))
  2155. nil))
  2156. exit-status)
  2157. (if (or replace
  2158. (and output-buffer
  2159. (not (or (bufferp output-buffer) (stringp output-buffer)))))
  2160. ;; Replace specified region with output from command.
  2161. (let ((swap (and replace (< start end))))
  2162. ;; Don't muck with mark unless REPLACE says we should.
  2163. (goto-char start)
  2164. (and replace (push-mark (point) 'nomsg))
  2165. (setq exit-status
  2166. (call-process-region start end shell-file-name t
  2167. (if error-file
  2168. (list t error-file)
  2169. t)
  2170. nil shell-command-switch command))
  2171. ;; It is rude to delete a buffer which the command is not using.
  2172. ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
  2173. ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
  2174. ;; (kill-buffer shell-buffer)))
  2175. ;; Don't muck with mark unless REPLACE says we should.
  2176. (and replace swap (exchange-point-and-mark)))
  2177. ;; No prefix argument: put the output in a temp buffer,
  2178. ;; replacing its entire contents.
  2179. (let ((buffer (get-buffer-create
  2180. (or output-buffer "*Shell Command Output*"))))
  2181. (unwind-protect
  2182. (if (eq buffer (current-buffer))
  2183. ;; If the input is the same buffer as the output,
  2184. ;; delete everything but the specified region,
  2185. ;; then replace that region with the output.
  2186. (progn (setq buffer-read-only nil)
  2187. (delete-region (max start end) (point-max))
  2188. (delete-region (point-min) (min start end))
  2189. (setq exit-status
  2190. (call-process-region (point-min) (point-max)
  2191. shell-file-name t
  2192. (if error-file
  2193. (list t error-file)
  2194. t)
  2195. nil shell-command-switch
  2196. command)))
  2197. ;; Clear the output buffer, then run the command with
  2198. ;; output there.
  2199. (let ((directory default-directory))
  2200. (with-current-buffer buffer
  2201. (setq buffer-read-only nil)
  2202. (if (not output-buffer)
  2203. (setq default-directory directory))
  2204. (erase-buffer)))
  2205. (setq exit-status
  2206. (call-process-region start end shell-file-name nil
  2207. (if error-file
  2208. (list buffer error-file)
  2209. buffer)
  2210. nil shell-command-switch command)))
  2211. ;; Report the output.
  2212. (with-current-buffer buffer
  2213. (setq mode-line-process
  2214. (cond ((null exit-status)
  2215. " - Error")
  2216. ((stringp exit-status)
  2217. (format " - Signal [%s]" exit-status))
  2218. ((not (equal 0 exit-status))
  2219. (format " - Exit [%d]" exit-status)))))
  2220. (if (with-current-buffer buffer (> (point-max) (point-min)))
  2221. ;; There's some output, display it
  2222. (display-message-or-buffer buffer)
  2223. ;; No output; error?
  2224. (let ((output
  2225. (if (and error-file
  2226. (< 0 (nth 7 (file-attributes error-file))))
  2227. "some error output"
  2228. "no output")))
  2229. (cond ((null exit-status)
  2230. (message "(Shell command failed with error)"))
  2231. ((equal 0 exit-status)
  2232. (message "(Shell command succeeded with %s)"
  2233. output))
  2234. ((stringp exit-status)
  2235. (message "(Shell command killed by signal %s)"
  2236. exit-status))
  2237. (t
  2238. (message "(Shell command failed with code %d and %s)"
  2239. exit-status output))))
  2240. ;; Don't kill: there might be useful info in the undo-log.
  2241. ;; (kill-buffer buffer)
  2242. ))))
  2243. (when (and error-file (file-exists-p error-file))
  2244. (if (< 0 (nth 7 (file-attributes error-file)))
  2245. (with-current-buffer (get-buffer-create error-buffer)
  2246. (let ((pos-from-end (- (point-max) (point))))
  2247. (or (bobp)
  2248. (insert "\f\n"))
  2249. ;; Do no formatting while reading error file,
  2250. ;; because that can run a shell command, and we
  2251. ;; don't want that to cause an infinite recursion.
  2252. (format-insert-file error-file nil)
  2253. ;; Put point after the inserted errors.
  2254. (goto-char (- (point-max) pos-from-end)))
  2255. (and display-error-buffer
  2256. (display-buffer (current-buffer)))))
  2257. (delete-file error-file))
  2258. exit-status))
  2259. (defun shell-command-to-string (command)
  2260. "Execute shell command COMMAND and return its output as a string."
  2261. (with-output-to-string
  2262. (with-current-buffer
  2263. standard-output
  2264. (call-process shell-file-name nil t nil shell-command-switch command))))
  2265. (defun process-file (program &optional infile buffer display &rest args)
  2266. "Process files synchronously in a separate process.
  2267. Similar to `call-process', but may invoke a file handler based on
  2268. `default-directory'. The current working directory of the
  2269. subprocess is `default-directory'.
  2270. File names in INFILE and BUFFER are handled normally, but file
  2271. names in ARGS should be relative to `default-directory', as they
  2272. are passed to the process verbatim. \(This is a difference to
  2273. `call-process' which does not support file handlers for INFILE
  2274. and BUFFER.\)
  2275. Some file handlers might not support all variants, for example
  2276. they might behave as if DISPLAY was nil, regardless of the actual
  2277. value passed."
  2278. (let ((fh (find-file-name-handler default-directory 'process-file))
  2279. lc stderr-file)
  2280. (unwind-protect
  2281. (if fh (apply fh 'process-file program infile buffer display args)
  2282. (when infile (setq lc (file-local-copy infile)))
  2283. (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
  2284. (make-temp-file "emacs")))
  2285. (prog1
  2286. (apply 'call-process program
  2287. (or lc infile)
  2288. (if stderr-file (list (car buffer) stderr-file) buffer)
  2289. display args)
  2290. (when stderr-file (copy-file stderr-file (cadr buffer)))))
  2291. (when stderr-file (delete-file stderr-file))
  2292. (when lc (delete-file lc)))))
  2293. (defvar process-file-side-effects t
  2294. "Whether a call of `process-file' changes remote files.
  2295. Per default, this variable is always set to `t', meaning that a
  2296. call of `process-file' could potentially change any file on a
  2297. remote host. When set to `nil', a file handler could optimize
  2298. its behaviour with respect to remote file attributes caching.
  2299. This variable should never be changed by `setq'. Instead of, it
  2300. shall be set only by let-binding.")
  2301. (defun start-file-process (name buffer program &rest program-args)
  2302. "Start a program in a subprocess. Return the process object for it.
  2303. Similar to `start-process', but may invoke a file handler based on
  2304. `default-directory'. See Info node `(elisp)Magic File Names'.
  2305. This handler ought to run PROGRAM, perhaps on the local host,
  2306. perhaps on a remote host that corresponds to `default-directory'.
  2307. In the latter case, the local part of `default-directory' becomes
  2308. the working directory of the process.
  2309. PROGRAM and PROGRAM-ARGS might be file names. They are not
  2310. objects of file handler invocation. File handlers might not
  2311. support pty association, if PROGRAM is nil."
  2312. (let ((fh (find-file-name-handler default-directory 'start-file-process)))
  2313. (if fh (apply fh 'start-file-process name buffer program program-args)
  2314. (apply 'start-process name buffer program program-args))))
  2315. (defvar universal-argument-map
  2316. (let ((map (make-sparse-keymap)))
  2317. (define-key map [t] 'universal-argument-other-key)
  2318. (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
  2319. (define-key map [switch-frame] nil)
  2320. (define-key map [?\C-u] 'universal-argument-more)
  2321. (define-key map [?-] 'universal-argument-minus)
  2322. (define-key map [?0] 'digit-argument)
  2323. (define-key map [?1] 'digit-argument)
  2324. (define-key map [?2] 'digit-argument)
  2325. (define-key map [?3] 'digit-argument)
  2326. (define-key map [?4] 'digit-argument)
  2327. (define-key map [?5] 'digit-argument)
  2328. (define-key map [?6] 'digit-argument)
  2329. (define-key map [?7] 'digit-argument)
  2330. (define-key map [?8] 'digit-argument)
  2331. (define-key map [?9] 'digit-argument)
  2332. (define-key map [kp-0] 'digit-argument)
  2333. (define-key map [kp-1] 'digit-argument)
  2334. (define-key map [kp-2] 'digit-argument)
  2335. (define-key map [kp-3] 'digit-argument)
  2336. (define-key map [kp-4] 'digit-argument)
  2337. (define-key map [kp-5] 'digit-argument)
  2338. (define-key map [kp-6] 'digit-argument)
  2339. (define-key map [kp-7] 'digit-argument)
  2340. (define-key map [kp-8] 'digit-argument)
  2341. (define-key map [kp-9] 'digit-argument)
  2342. (define-key map [kp-subtract] 'universal-argument-minus)
  2343. map)
  2344. "Keymap used while processing \\[universal-argument].")
  2345. (defvar universal-argument-num-events nil
  2346. "Number of argument-specifying events read by `universal-argument'.
  2347. `universal-argument-other-key' uses this to discard those events
  2348. from (this-command-keys), and reread only the final command.")
  2349. (defvar overriding-map-is-bound nil
  2350. "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
  2351. (defvar saved-overriding-map nil
  2352. "The saved value of `overriding-terminal-local-map'.
  2353. That variable gets restored to this value on exiting \"universal
  2354. argument mode\".")
  2355. (defun ensure-overriding-map-is-bound ()
  2356. "Check `overriding-terminal-local-map' is `universal-argument-map'."
  2357. (unless overriding-map-is-bound
  2358. (setq saved-overriding-map overriding-terminal-local-map)
  2359. (setq overriding-terminal-local-map universal-argument-map)
  2360. (setq overriding-map-is-bound t)))
  2361. (defun restore-overriding-map ()
  2362. "Restore `overriding-terminal-local-map' to its saved value."
  2363. (setq overriding-terminal-local-map saved-overriding-map)
  2364. (setq overriding-map-is-bound nil))
  2365. (defun universal-argument ()
  2366. "Begin a numeric argument for the following command.
  2367. Digits or minus sign following \\[universal-argument] make up the numeric argument.
  2368. \\[universal-argument] following the digits or minus sign ends the argument.
  2369. \\[universal-argument] without digits or minus sign provides 4 as argument.
  2370. Repeating \\[universal-argument] without digits or minus sign
  2371. multiplies the argument by 4 each time.
  2372. For some commands, just \\[universal-argument] by itself serves as a flag
  2373. which is different in effect from any particular numeric argument.
  2374. These commands include \\[set-mark-command] and \\[start-kbd-macro]."
  2375. (interactive)
  2376. (setq prefix-arg (list 4))
  2377. (setq universal-argument-num-events (length (this-command-keys)))
  2378. (ensure-overriding-map-is-bound))
  2379. ;; A subsequent C-u means to multiply the factor by 4 if we've typed
  2380. ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
  2381. (defun universal-argument-more (arg)
  2382. (interactive "P")
  2383. (if (consp arg)
  2384. (setq prefix-arg (list (* 4 (car arg))))
  2385. (if (eq arg '-)
  2386. (setq prefix-arg (list -4))
  2387. (setq prefix-arg arg)
  2388. (restore-overriding-map)))
  2389. (setq universal-argument-num-events (length (this-command-keys))))
  2390. (defun negative-argument (arg)
  2391. "Begin a negative numeric argument for the next command.
  2392. \\[universal-argument] following digits or minus sign ends the argument."
  2393. (interactive "P")
  2394. (cond ((integerp arg)
  2395. (setq prefix-arg (- arg)))
  2396. ((eq arg '-)
  2397. (setq prefix-arg nil))
  2398. (t
  2399. (setq prefix-arg '-)))
  2400. (setq universal-argument-num-events (length (this-command-keys)))
  2401. (ensure-overriding-map-is-bound))
  2402. (defun digit-argument (arg)
  2403. "Part of the numeric argument for the next command.
  2404. \\[universal-argument] following digits or minus sign ends the argument."
  2405. (interactive "P")
  2406. (let* ((char (if (integerp last-command-event)
  2407. last-command-event
  2408. (get last-command-event 'ascii-character)))
  2409. (digit (- (logand char ?\177) ?0)))
  2410. (cond ((integerp arg)
  2411. (setq prefix-arg (+ (* arg 10)
  2412. (if (< arg 0) (- digit) digit))))
  2413. ((eq arg '-)
  2414. ;; Treat -0 as just -, so that -01 will work.
  2415. (setq prefix-arg (if (zerop digit) '- (- digit))))
  2416. (t
  2417. (setq prefix-arg digit))))
  2418. (setq universal-argument-num-events (length (this-command-keys)))
  2419. (ensure-overriding-map-is-bound))
  2420. ;; For backward compatibility, minus with no modifiers is an ordinary
  2421. ;; command if digits have already been entered.
  2422. (defun universal-argument-minus (arg)
  2423. (interactive "P")
  2424. (if (integerp arg)
  2425. (universal-argument-other-key arg)
  2426. (negative-argument arg)))
  2427. ;; Anything else terminates the argument and is left in the queue to be
  2428. ;; executed as a command.
  2429. (defun universal-argument-other-key (arg)
  2430. (interactive "P")
  2431. (setq prefix-arg arg)
  2432. (let* ((key (this-command-keys))
  2433. (keylist (listify-key-sequence key)))
  2434. (setq unread-command-events
  2435. (append (nthcdr universal-argument-num-events keylist)
  2436. unread-command-events)))
  2437. (reset-this-command-lengths)
  2438. (restore-overriding-map))
  2439. (defvar buffer-substring-filters nil
  2440. "List of filter functions for `filter-buffer-substring'.
  2441. Each function must accept a single argument, a string, and return
  2442. a string. The buffer substring is passed to the first function
  2443. in the list, and the return value of each function is passed to
  2444. the next. The return value of the last function is used as the
  2445. return value of `filter-buffer-substring'.
  2446. If this variable is nil, no filtering is performed.")
  2447. (defun filter-buffer-substring (beg end &optional delete noprops)
  2448. "Return the buffer substring between BEG and END, after filtering.
  2449. The buffer substring is passed through each of the filter
  2450. functions in `buffer-substring-filters', and the value from the
  2451. last filter function is returned. If `buffer-substring-filters'
  2452. is nil, the buffer substring is returned unaltered.
  2453. If DELETE is non-nil, the text between BEG and END is deleted
  2454. from the buffer.
  2455. If NOPROPS is non-nil, final string returned does not include
  2456. text properties, while the string passed to the filters still
  2457. includes text properties from the buffer text.
  2458. Point is temporarily set to BEG before calling
  2459. `buffer-substring-filters', in case the functions need to know
  2460. where the text came from.
  2461. This function should be used instead of `buffer-substring',
  2462. `buffer-substring-no-properties', or `delete-and-extract-region'
  2463. when you want to allow filtering to take place. For example,
  2464. major or minor modes can use `buffer-substring-filters' to
  2465. extract characters that are special to a buffer, and should not
  2466. be copied into other buffers."
  2467. (cond
  2468. ((or delete buffer-substring-filters)
  2469. (save-excursion
  2470. (goto-char beg)
  2471. (let ((string (if delete (delete-and-extract-region beg end)
  2472. (buffer-substring beg end))))
  2473. (dolist (filter buffer-substring-filters)
  2474. (setq string (funcall filter string)))
  2475. (if noprops
  2476. (set-text-properties 0 (length string) nil string))
  2477. string)))
  2478. (noprops
  2479. (buffer-substring-no-properties beg end))
  2480. (t
  2481. (buffer-substring beg end))))
  2482. ;;;; Window system cut and paste hooks.
  2483. (defvar interprogram-cut-function nil
  2484. "Function to call to make a killed region available to other programs.
  2485. Most window systems provide some sort of facility for cutting and
  2486. pasting text between the windows of different programs.
  2487. This variable holds a function that Emacs calls whenever text
  2488. is put in the kill ring, to make the new kill available to other
  2489. programs.
  2490. The function takes one or two arguments.
  2491. The first argument, TEXT, is a string containing
  2492. the text which should be made available.
  2493. The second, optional, argument PUSH, has the same meaning as the
  2494. similar argument to `x-set-cut-buffer', which see.")
  2495. (defvar interprogram-paste-function nil
  2496. "Function to call to get text cut from other programs.
  2497. Most window systems provide some sort of facility for cutting and
  2498. pasting text between the windows of different programs.
  2499. This variable holds a function that Emacs calls to obtain
  2500. text that other programs have provided for pasting.
  2501. The function should be called with no arguments. If the function
  2502. returns nil, then no other program has provided such text, and the top
  2503. of the Emacs kill ring should be used. If the function returns a
  2504. string, then the caller of the function \(usually `current-kill')
  2505. should put this string in the kill ring as the latest kill.
  2506. This function may also return a list of strings if the window
  2507. system supports multiple selections. The first string will be
  2508. used as the pasted text, but the other will be placed in the
  2509. kill ring for easy access via `yank-pop'.
  2510. Note that the function should return a string only if a program other
  2511. than Emacs has provided a string for pasting; if Emacs provided the
  2512. most recent string, the function should return nil. If it is
  2513. difficult to tell whether Emacs or some other program provided the
  2514. current string, it is probably good enough to return nil if the string
  2515. is equal (according to `string=') to the last text Emacs provided.")
  2516. ;;;; The kill ring data structure.
  2517. (defvar kill-ring nil
  2518. "List of killed text sequences.
  2519. Since the kill ring is supposed to interact nicely with cut-and-paste
  2520. facilities offered by window systems, use of this variable should
  2521. interact nicely with `interprogram-cut-function' and
  2522. `interprogram-paste-function'. The functions `kill-new',
  2523. `kill-append', and `current-kill' are supposed to implement this
  2524. interaction; you may want to use them instead of manipulating the kill
  2525. ring directly.")
  2526. (defcustom kill-ring-max 60
  2527. "Maximum length of kill ring before oldest elements are thrown away."
  2528. :type 'integer
  2529. :group 'killing)
  2530. (defvar kill-ring-yank-pointer nil
  2531. "The tail of the kill ring whose car is the last thing yanked.")
  2532. (defcustom save-interprogram-paste-before-kill nil
  2533. "Save clipboard strings into kill ring before replacing them.
  2534. When one selects something in another program to paste it into Emacs,
  2535. but kills something in Emacs before actually pasting it,
  2536. this selection is gone unless this variable is non-nil,
  2537. in which case the other program's selection is saved in the `kill-ring'
  2538. before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
  2539. :type 'boolean
  2540. :group 'killing
  2541. :version "23.2")
  2542. (defcustom kill-do-not-save-duplicates nil
  2543. "Do not add a new string to `kill-ring' when it is the same as the last one."
  2544. :type 'boolean
  2545. :group 'killing
  2546. :version "23.2")
  2547. (defun kill-new (string &optional replace yank-handler)
  2548. "Make STRING the latest kill in the kill ring.
  2549. Set `kill-ring-yank-pointer' to point to it.
  2550. If `interprogram-cut-function' is non-nil, apply it to STRING.
  2551. Optional second argument REPLACE non-nil means that STRING will replace
  2552. the front of the kill ring, rather than being added to the list.
  2553. Optional third arguments YANK-HANDLER controls how the STRING is later
  2554. inserted into a buffer; see `insert-for-yank' for details.
  2555. When a yank handler is specified, STRING must be non-empty (the yank
  2556. handler, if non-nil, is stored as a `yank-handler' text property on STRING).
  2557. When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
  2558. are non-nil, saves the interprogram paste string(s) into `kill-ring' before
  2559. STRING.
  2560. When the yank handler has a non-nil PARAM element, the original STRING
  2561. argument is not used by `insert-for-yank'. However, since Lisp code
  2562. may access and use elements from the kill ring directly, the STRING
  2563. argument should still be a \"useful\" string for such uses."
  2564. (if (> (length string) 0)
  2565. (if yank-handler
  2566. (put-text-property 0 (length string)
  2567. 'yank-handler yank-handler string))
  2568. (if yank-handler
  2569. (signal 'args-out-of-range
  2570. (list string "yank-handler specified for empty string"))))
  2571. (when (and kill-do-not-save-duplicates
  2572. (equal string (car kill-ring)))
  2573. (setq replace t))
  2574. (if (fboundp 'menu-bar-update-yank-menu)
  2575. (menu-bar-update-yank-menu string (and replace (car kill-ring))))
  2576. (when save-interprogram-paste-before-kill
  2577. (let ((interprogram-paste (and interprogram-paste-function
  2578. (funcall interprogram-paste-function))))
  2579. (when interprogram-paste
  2580. (if (listp interprogram-paste)
  2581. (dolist (s (nreverse interprogram-paste))
  2582. (push s kill-ring))
  2583. (push interprogram-paste kill-ring)))))
  2584. (if (and replace kill-ring)
  2585. (setcar kill-ring string)
  2586. (push string kill-ring)
  2587. (if (> (length kill-ring) kill-ring-max)
  2588. (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
  2589. (setq kill-ring-yank-pointer kill-ring)
  2590. (if interprogram-cut-function
  2591. (funcall interprogram-cut-function string (not replace))))
  2592. (defun kill-append (string before-p &optional yank-handler)
  2593. "Append STRING to the end of the latest kill in the kill ring.
  2594. If BEFORE-P is non-nil, prepend STRING to the kill.
  2595. Optional third argument YANK-HANDLER, if non-nil, specifies the
  2596. yank-handler text property to be set on the combined kill ring
  2597. string. If the specified yank-handler arg differs from the
  2598. yank-handler property of the latest kill string, this function
  2599. adds the combined string to the kill ring as a new element,
  2600. instead of replacing the last kill with it.
  2601. If `interprogram-cut-function' is set, pass the resulting kill to it."
  2602. (let* ((cur (car kill-ring)))
  2603. (kill-new (if before-p (concat string cur) (concat cur string))
  2604. (or (= (length cur) 0)
  2605. (equal yank-handler (get-text-property 0 'yank-handler cur)))
  2606. yank-handler)))
  2607. (defcustom yank-pop-change-selection nil
  2608. "If non-nil, rotating the kill ring changes the window system selection."
  2609. :type 'boolean
  2610. :group 'killing
  2611. :version "23.1")
  2612. (defun current-kill (n &optional do-not-move)
  2613. "Rotate the yanking point by N places, and then return that kill.
  2614. If N is zero, `interprogram-paste-function' is set, and calling
  2615. it returns a string or list of strings, then that string (or
  2616. list) is added to the front of the kill ring and the string (or
  2617. first string in the list) is returned as the latest kill.
  2618. If N is not zero, and if `yank-pop-change-selection' is
  2619. non-nil, use `interprogram-cut-function' to transfer the
  2620. kill at the new yank point into the window system selection.
  2621. If optional arg DO-NOT-MOVE is non-nil, then don't actually
  2622. move the yanking point; just return the Nth kill forward."
  2623. (let ((interprogram-paste (and (= n 0)
  2624. interprogram-paste-function
  2625. (funcall interprogram-paste-function))))
  2626. (if interprogram-paste
  2627. (progn
  2628. ;; Disable the interprogram cut function when we add the new
  2629. ;; text to the kill ring, so Emacs doesn't try to own the
  2630. ;; selection, with identical text.
  2631. (let ((interprogram-cut-function nil))
  2632. (if (listp interprogram-paste)
  2633. (mapc 'kill-new (nreverse interprogram-paste))
  2634. (kill-new interprogram-paste)))
  2635. (car kill-ring))
  2636. (or kill-ring (error "Kill ring is empty"))
  2637. (let ((ARGth-kill-element
  2638. (nthcdr (mod (- n (length kill-ring-yank-pointer))
  2639. (length kill-ring))
  2640. kill-ring)))
  2641. (unless do-not-move
  2642. (setq kill-ring-yank-pointer ARGth-kill-element)
  2643. (when (and yank-pop-change-selection
  2644. (> n 0)
  2645. interprogram-cut-function)
  2646. (funcall interprogram-cut-function (car ARGth-kill-element))))
  2647. (car ARGth-kill-element)))))
  2648. ;;;; Commands for manipulating the kill ring.
  2649. (defcustom kill-read-only-ok nil
  2650. "Non-nil means don't signal an error for killing read-only text."
  2651. :type 'boolean
  2652. :group 'killing)
  2653. (put 'text-read-only 'error-conditions
  2654. '(text-read-only buffer-read-only error))
  2655. (put 'text-read-only 'error-message (purecopy "Text is read-only"))
  2656. (defun kill-region (beg end &optional yank-handler)
  2657. "Kill (\"cut\") text between point and mark.
  2658. This deletes the text from the buffer and saves it in the kill ring.
  2659. The command \\[yank] can retrieve it from there.
  2660. \(If you want to save the region without killing it, use \\[kill-ring-save].)
  2661. If you want to append the killed region to the last killed text,
  2662. use \\[append-next-kill] before \\[kill-region].
  2663. If the buffer is read-only, Emacs will beep and refrain from deleting
  2664. the text, but put the text in the kill ring anyway. This means that
  2665. you can use the killing commands to copy text from a read-only buffer.
  2666. This is the primitive for programs to kill text (as opposed to deleting it).
  2667. Supply two arguments, character positions indicating the stretch of text
  2668. to be killed.
  2669. Any command that calls this function is a \"kill command\".
  2670. If the previous command was also a kill command,
  2671. the text killed this time appends to the text killed last time
  2672. to make one entry in the kill ring.
  2673. In Lisp code, optional third arg YANK-HANDLER, if non-nil,
  2674. specifies the yank-handler text property to be set on the killed
  2675. text. See `insert-for-yank'."
  2676. ;; Pass point first, then mark, because the order matters
  2677. ;; when calling kill-append.
  2678. (interactive (list (point) (mark)))
  2679. (unless (and beg end)
  2680. (error "The mark is not set now, so there is no region"))
  2681. (condition-case nil
  2682. (let ((string (filter-buffer-substring beg end t)))
  2683. (when string ;STRING is nil if BEG = END
  2684. ;; Add that string to the kill ring, one way or another.
  2685. (if (eq last-command 'kill-region)
  2686. (kill-append string (< end beg) yank-handler)
  2687. (kill-new string nil yank-handler)))
  2688. (when (or string (eq last-command 'kill-region))
  2689. (setq this-command 'kill-region))
  2690. nil)
  2691. ((buffer-read-only text-read-only)
  2692. ;; The code above failed because the buffer, or some of the characters
  2693. ;; in the region, are read-only.
  2694. ;; We should beep, in case the user just isn't aware of this.
  2695. ;; However, there's no harm in putting
  2696. ;; the region's text in the kill ring, anyway.
  2697. (copy-region-as-kill beg end)
  2698. ;; Set this-command now, so it will be set even if we get an error.
  2699. (setq this-command 'kill-region)
  2700. ;; This should barf, if appropriate, and give us the correct error.
  2701. (if kill-read-only-ok
  2702. (progn (message "Read only text copied to kill ring") nil)
  2703. ;; Signal an error if the buffer is read-only.
  2704. (barf-if-buffer-read-only)
  2705. ;; If the buffer isn't read-only, the text is.
  2706. (signal 'text-read-only (list (current-buffer)))))))
  2707. ;; copy-region-as-kill no longer sets this-command, because it's confusing
  2708. ;; to get two copies of the text when the user accidentally types M-w and
  2709. ;; then corrects it with the intended C-w.
  2710. (defun copy-region-as-kill (beg end)
  2711. "Save the region as if killed, but don't kill it.
  2712. In Transient Mark mode, deactivate the mark.
  2713. If `interprogram-cut-function' is non-nil, also save the text for a window
  2714. system cut and paste.
  2715. This command's old key binding has been given to `kill-ring-save'."
  2716. (interactive "r")
  2717. (if (eq last-command 'kill-region)
  2718. (kill-append (filter-buffer-substring beg end) (< end beg))
  2719. (kill-new (filter-buffer-substring beg end)))
  2720. (setq deactivate-mark t)
  2721. nil)
  2722. (defun kill-ring-save (beg end)
  2723. "Save the region as if killed, but don't kill it.
  2724. In Transient Mark mode, deactivate the mark.
  2725. If `interprogram-cut-function' is non-nil, also save the text for a window
  2726. system cut and paste.
  2727. If you want to append the killed line to the last killed text,
  2728. use \\[append-next-kill] before \\[kill-ring-save].
  2729. This command is similar to `copy-region-as-kill', except that it gives
  2730. visual feedback indicating the extent of the region being copied."
  2731. (interactive "r")
  2732. (copy-region-as-kill beg end)
  2733. ;; This use of called-interactively-p is correct
  2734. ;; because the code it controls just gives the user visual feedback.
  2735. (if (called-interactively-p 'interactive)
  2736. (let ((other-end (if (= (point) beg) end beg))
  2737. (opoint (point))
  2738. ;; Inhibit quitting so we can make a quit here
  2739. ;; look like a C-g typed as a command.
  2740. (inhibit-quit t))
  2741. (if (pos-visible-in-window-p other-end (selected-window))
  2742. ;; Swap point-and-mark quickly so as to show the region that
  2743. ;; was selected. Don't do it if the region is highlighted.
  2744. (unless (and (region-active-p)
  2745. (face-background 'region))
  2746. ;; Swap point and mark.
  2747. (set-marker (mark-marker) (point) (current-buffer))
  2748. (goto-char other-end)
  2749. (sit-for blink-matching-delay)
  2750. ;; Swap back.
  2751. (set-marker (mark-marker) other-end (current-buffer))
  2752. (goto-char opoint)
  2753. ;; If user quit, deactivate the mark
  2754. ;; as C-g would as a command.
  2755. (and quit-flag mark-active
  2756. (deactivate-mark)))
  2757. (let* ((killed-text (current-kill 0))
  2758. (message-len (min (length killed-text) 40)))
  2759. (if (= (point) beg)
  2760. ;; Don't say "killed"; that is misleading.
  2761. (message "Saved text until \"%s\""
  2762. (substring killed-text (- message-len)))
  2763. (message "Saved text from \"%s\""
  2764. (substring killed-text 0 message-len))))))))
  2765. (defun append-next-kill (&optional interactive)
  2766. "Cause following command, if it kills, to append to previous kill.
  2767. The argument is used for internal purposes; do not supply one."
  2768. (interactive "p")
  2769. ;; We don't use (interactive-p), since that breaks kbd macros.
  2770. (if interactive
  2771. (progn
  2772. (setq this-command 'kill-region)
  2773. (message "If the next command is a kill, it will append"))
  2774. (setq last-command 'kill-region)))
  2775. ;; Yanking.
  2776. ;; This is actually used in subr.el but defcustom does not work there.
  2777. (defcustom yank-excluded-properties
  2778. '(read-only invisible intangible field mouse-face help-echo local-map keymap
  2779. yank-handler follow-link fontified)
  2780. "Text properties to discard when yanking.
  2781. The value should be a list of text properties to discard or t,
  2782. which means to discard all text properties."
  2783. :type '(choice (const :tag "All" t) (repeat symbol))
  2784. :group 'killing
  2785. :version "22.1")
  2786. (defvar yank-window-start nil)
  2787. (defvar yank-undo-function nil
  2788. "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
  2789. Function is called with two parameters, START and END corresponding to
  2790. the value of the mark and point; it is guaranteed that START <= END.
  2791. Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
  2792. (defun yank-pop (&optional arg)
  2793. "Replace just-yanked stretch of killed text with a different stretch.
  2794. This command is allowed only immediately after a `yank' or a `yank-pop'.
  2795. At such a time, the region contains a stretch of reinserted
  2796. previously-killed text. `yank-pop' deletes that text and inserts in its
  2797. place a different stretch of killed text.
  2798. With no argument, the previous kill is inserted.
  2799. With argument N, insert the Nth previous kill.
  2800. If N is negative, this is a more recent kill.
  2801. The sequence of kills wraps around, so that after the oldest one
  2802. comes the newest one.
  2803. When this command inserts killed text into the buffer, it honors
  2804. `yank-excluded-properties' and `yank-handler' as described in the
  2805. doc string for `insert-for-yank-1', which see."
  2806. (interactive "*p")
  2807. (if (not (eq last-command 'yank))
  2808. (error "Previous command was not a yank"))
  2809. (setq this-command 'yank)
  2810. (unless arg (setq arg 1))
  2811. (let ((inhibit-read-only t)
  2812. (before (< (point) (mark t))))
  2813. (if before
  2814. (funcall (or yank-undo-function 'delete-region) (point) (mark t))
  2815. (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
  2816. (setq yank-undo-function nil)
  2817. (set-marker (mark-marker) (point) (current-buffer))
  2818. (insert-for-yank (current-kill arg))
  2819. ;; Set the window start back where it was in the yank command,
  2820. ;; if possible.
  2821. (set-window-start (selected-window) yank-window-start t)
  2822. (if before
  2823. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  2824. ;; It is cleaner to avoid activation, even though the command
  2825. ;; loop would deactivate the mark because we inserted text.
  2826. (goto-char (prog1 (mark t)
  2827. (set-marker (mark-marker) (point) (current-buffer))))))
  2828. nil)
  2829. (defun yank (&optional arg)
  2830. "Reinsert (\"paste\") the last stretch of killed text.
  2831. More precisely, reinsert the stretch of killed text most recently
  2832. killed OR yanked. Put point at end, and set mark at beginning.
  2833. With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
  2834. With argument N, reinsert the Nth most recently killed stretch of killed
  2835. text.
  2836. When this command inserts killed text into the buffer, it honors
  2837. `yank-excluded-properties' and `yank-handler' as described in the
  2838. doc string for `insert-for-yank-1', which see.
  2839. See also the command `yank-pop' (\\[yank-pop])."
  2840. (interactive "*P")
  2841. (setq yank-window-start (window-start))
  2842. ;; If we don't get all the way thru, make last-command indicate that
  2843. ;; for the following command.
  2844. (setq this-command t)
  2845. (push-mark (point))
  2846. (insert-for-yank (current-kill (cond
  2847. ((listp arg) 0)
  2848. ((eq arg '-) -2)
  2849. (t (1- arg)))))
  2850. (if (consp arg)
  2851. ;; This is like exchange-point-and-mark, but doesn't activate the mark.
  2852. ;; It is cleaner to avoid activation, even though the command
  2853. ;; loop would deactivate the mark because we inserted text.
  2854. (goto-char (prog1 (mark t)
  2855. (set-marker (mark-marker) (point) (current-buffer)))))
  2856. ;; If we do get all the way thru, make this-command indicate that.
  2857. (if (eq this-command t)
  2858. (setq this-command 'yank))
  2859. nil)
  2860. (defun rotate-yank-pointer (arg)
  2861. "Rotate the yanking point in the kill ring.
  2862. With ARG, rotate that many kills forward (or backward, if negative)."
  2863. (interactive "p")
  2864. (current-kill arg))
  2865. ;; Some kill commands.
  2866. ;; Internal subroutine of delete-char
  2867. (defun kill-forward-chars (arg)
  2868. (if (listp arg) (setq arg (car arg)))
  2869. (if (eq arg '-) (setq arg -1))
  2870. (kill-region (point) (+ (point) arg)))
  2871. ;; Internal subroutine of backward-delete-char
  2872. (defun kill-backward-chars (arg)
  2873. (if (listp arg) (setq arg (car arg)))
  2874. (if (eq arg '-) (setq arg -1))
  2875. (kill-region (point) (- (point) arg)))
  2876. (defcustom backward-delete-char-untabify-method 'untabify
  2877. "The method for untabifying when deleting backward.
  2878. Can be `untabify' -- turn a tab to many spaces, then delete one space;
  2879. `hungry' -- delete all whitespace, both tabs and spaces;
  2880. `all' -- delete all whitespace, including tabs, spaces and newlines;
  2881. nil -- just delete one character."
  2882. :type '(choice (const untabify) (const hungry) (const all) (const nil))
  2883. :version "20.3"
  2884. :group 'killing)
  2885. (defun backward-delete-char-untabify (arg &optional killp)
  2886. "Delete characters backward, changing tabs into spaces.
  2887. The exact behavior depends on `backward-delete-char-untabify-method'.
  2888. Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
  2889. Interactively, ARG is the prefix arg (default 1)
  2890. and KILLP is t if a prefix arg was specified."
  2891. (interactive "*p\nP")
  2892. (when (eq backward-delete-char-untabify-method 'untabify)
  2893. (let ((count arg))
  2894. (save-excursion
  2895. (while (and (> count 0) (not (bobp)))
  2896. (if (= (preceding-char) ?\t)
  2897. (let ((col (current-column)))
  2898. (forward-char -1)
  2899. (setq col (- col (current-column)))
  2900. (insert-char ?\s col)
  2901. (delete-char 1)))
  2902. (forward-char -1)
  2903. (setq count (1- count))))))
  2904. (delete-backward-char
  2905. (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
  2906. ((eq backward-delete-char-untabify-method 'all)
  2907. " \t\n\r"))))
  2908. (if skip
  2909. (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
  2910. (point)))))
  2911. (+ arg (if (zerop wh) 0 (1- wh))))
  2912. arg))
  2913. killp))
  2914. (defun zap-to-char (arg char)
  2915. "Kill up to and including ARGth occurrence of CHAR.
  2916. Case is ignored if `case-fold-search' is non-nil in the current buffer.
  2917. Goes backward if ARG is negative; error if CHAR not found."
  2918. (interactive "p\ncZap to char: ")
  2919. ;; Avoid "obsolete" warnings for translation-table-for-input.
  2920. (with-no-warnings
  2921. (if (char-table-p translation-table-for-input)
  2922. (setq char (or (aref translation-table-for-input char) char))))
  2923. (kill-region (point) (progn
  2924. (search-forward (char-to-string char) nil nil arg)
  2925. ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
  2926. (point))))
  2927. ;; kill-line and its subroutines.
  2928. (defcustom kill-whole-line nil
  2929. "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
  2930. :type 'boolean
  2931. :group 'killing)
  2932. (defun kill-line (&optional arg)
  2933. "Kill the rest of the current line; if no nonblanks there, kill thru newline.
  2934. With prefix argument ARG, kill that many lines from point.
  2935. Negative arguments kill lines backward.
  2936. With zero argument, kills the text before point on the current line.
  2937. When calling from a program, nil means \"no arg\",
  2938. a number counts as a prefix arg.
  2939. To kill a whole line, when point is not at the beginning, type \
  2940. \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
  2941. If `kill-whole-line' is non-nil, then this command kills the whole line
  2942. including its terminating newline, when used at the beginning of a line
  2943. with no argument. As a consequence, you can always kill a whole line
  2944. by typing \\[move-beginning-of-line] \\[kill-line].
  2945. If you want to append the killed line to the last killed text,
  2946. use \\[append-next-kill] before \\[kill-line].
  2947. If the buffer is read-only, Emacs will beep and refrain from deleting
  2948. the line, but put the line in the kill ring anyway. This means that
  2949. you can use this command to copy text from a read-only buffer.
  2950. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  2951. even beep.)"
  2952. (interactive "P")
  2953. (kill-region (point)
  2954. ;; It is better to move point to the other end of the kill
  2955. ;; before killing. That way, in a read-only buffer, point
  2956. ;; moves across the text that is copied to the kill ring.
  2957. ;; The choice has no effect on undo now that undo records
  2958. ;; the value of point from before the command was run.
  2959. (progn
  2960. (if arg
  2961. (forward-visible-line (prefix-numeric-value arg))
  2962. (if (eobp)
  2963. (signal 'end-of-buffer nil))
  2964. (let ((end
  2965. (save-excursion
  2966. (end-of-visible-line) (point))))
  2967. (if (or (save-excursion
  2968. ;; If trailing whitespace is visible,
  2969. ;; don't treat it as nothing.
  2970. (unless show-trailing-whitespace
  2971. (skip-chars-forward " \t" end))
  2972. (= (point) end))
  2973. (and kill-whole-line (bolp)))
  2974. (forward-visible-line 1)
  2975. (goto-char end))))
  2976. (point))))
  2977. (defun kill-whole-line (&optional arg)
  2978. "Kill current line.
  2979. With prefix ARG, kill that many lines starting from the current line.
  2980. If ARG is negative, kill backward. Also kill the preceding newline.
  2981. \(This is meant to make \\[repeat] work well with negative arguments.\)
  2982. If ARG is zero, kill current line but exclude the trailing newline."
  2983. (interactive "p")
  2984. (or arg (setq arg 1))
  2985. (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
  2986. (signal 'end-of-buffer nil))
  2987. (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
  2988. (signal 'beginning-of-buffer nil))
  2989. (unless (eq last-command 'kill-region)
  2990. (kill-new "")
  2991. (setq last-command 'kill-region))
  2992. (cond ((zerop arg)
  2993. ;; We need to kill in two steps, because the previous command
  2994. ;; could have been a kill command, in which case the text
  2995. ;; before point needs to be prepended to the current kill
  2996. ;; ring entry and the text after point appended. Also, we
  2997. ;; need to use save-excursion to avoid copying the same text
  2998. ;; twice to the kill ring in read-only buffers.
  2999. (save-excursion
  3000. (kill-region (point) (progn (forward-visible-line 0) (point))))
  3001. (kill-region (point) (progn (end-of-visible-line) (point))))
  3002. ((< arg 0)
  3003. (save-excursion
  3004. (kill-region (point) (progn (end-of-visible-line) (point))))
  3005. (kill-region (point)
  3006. (progn (forward-visible-line (1+ arg))
  3007. (unless (bobp) (backward-char))
  3008. (point))))
  3009. (t
  3010. (save-excursion
  3011. (kill-region (point) (progn (forward-visible-line 0) (point))))
  3012. (kill-region (point)
  3013. (progn (forward-visible-line arg) (point))))))
  3014. (defun forward-visible-line (arg)
  3015. "Move forward by ARG lines, ignoring currently invisible newlines only.
  3016. If ARG is negative, move backward -ARG lines.
  3017. If ARG is zero, move to the beginning of the current line."
  3018. (condition-case nil
  3019. (if (> arg 0)
  3020. (progn
  3021. (while (> arg 0)
  3022. (or (zerop (forward-line 1))
  3023. (signal 'end-of-buffer nil))
  3024. ;; If the newline we just skipped is invisible,
  3025. ;; don't count it.
  3026. (let ((prop
  3027. (get-char-property (1- (point)) 'invisible)))
  3028. (if (if (eq buffer-invisibility-spec t)
  3029. prop
  3030. (or (memq prop buffer-invisibility-spec)
  3031. (assq prop buffer-invisibility-spec)))
  3032. (setq arg (1+ arg))))
  3033. (setq arg (1- arg)))
  3034. ;; If invisible text follows, and it is a number of complete lines,
  3035. ;; skip it.
  3036. (let ((opoint (point)))
  3037. (while (and (not (eobp))
  3038. (let ((prop
  3039. (get-char-property (point) 'invisible)))
  3040. (if (eq buffer-invisibility-spec t)
  3041. prop
  3042. (or (memq prop buffer-invisibility-spec)
  3043. (assq prop buffer-invisibility-spec)))))
  3044. (goto-char
  3045. (if (get-text-property (point) 'invisible)
  3046. (or (next-single-property-change (point) 'invisible)
  3047. (point-max))
  3048. (next-overlay-change (point)))))
  3049. (unless (bolp)
  3050. (goto-char opoint))))
  3051. (let ((first t))
  3052. (while (or first (<= arg 0))
  3053. (if first
  3054. (beginning-of-line)
  3055. (or (zerop (forward-line -1))
  3056. (signal 'beginning-of-buffer nil)))
  3057. ;; If the newline we just moved to is invisible,
  3058. ;; don't count it.
  3059. (unless (bobp)
  3060. (let ((prop
  3061. (get-char-property (1- (point)) 'invisible)))
  3062. (unless (if (eq buffer-invisibility-spec t)
  3063. prop
  3064. (or (memq prop buffer-invisibility-spec)
  3065. (assq prop buffer-invisibility-spec)))
  3066. (setq arg (1+ arg)))))
  3067. (setq first nil))
  3068. ;; If invisible text follows, and it is a number of complete lines,
  3069. ;; skip it.
  3070. (let ((opoint (point)))
  3071. (while (and (not (bobp))
  3072. (let ((prop
  3073. (get-char-property (1- (point)) 'invisible)))
  3074. (if (eq buffer-invisibility-spec t)
  3075. prop
  3076. (or (memq prop buffer-invisibility-spec)
  3077. (assq prop buffer-invisibility-spec)))))
  3078. (goto-char
  3079. (if (get-text-property (1- (point)) 'invisible)
  3080. (or (previous-single-property-change (point) 'invisible)
  3081. (point-min))
  3082. (previous-overlay-change (point)))))
  3083. (unless (bolp)
  3084. (goto-char opoint)))))
  3085. ((beginning-of-buffer end-of-buffer)
  3086. nil)))
  3087. (defun end-of-visible-line ()
  3088. "Move to end of current visible line."
  3089. (end-of-line)
  3090. ;; If the following character is currently invisible,
  3091. ;; skip all characters with that same `invisible' property value,
  3092. ;; then find the next newline.
  3093. (while (and (not (eobp))
  3094. (save-excursion
  3095. (skip-chars-forward "^\n")
  3096. (let ((prop
  3097. (get-char-property (point) 'invisible)))
  3098. (if (eq buffer-invisibility-spec t)
  3099. prop
  3100. (or (memq prop buffer-invisibility-spec)
  3101. (assq prop buffer-invisibility-spec))))))
  3102. (skip-chars-forward "^\n")
  3103. (if (get-text-property (point) 'invisible)
  3104. (goto-char (next-single-property-change (point) 'invisible))
  3105. (goto-char (next-overlay-change (point))))
  3106. (end-of-line)))
  3107. (defun insert-buffer (buffer)
  3108. "Insert after point the contents of BUFFER.
  3109. Puts mark after the inserted text.
  3110. BUFFER may be a buffer or a buffer name.
  3111. This function is meant for the user to run interactively.
  3112. Don't call it from programs: use `insert-buffer-substring' instead!"
  3113. (interactive
  3114. (list
  3115. (progn
  3116. (barf-if-buffer-read-only)
  3117. (read-buffer "Insert buffer: "
  3118. (if (eq (selected-window) (next-window (selected-window)))
  3119. (other-buffer (current-buffer))
  3120. (window-buffer (next-window (selected-window))))
  3121. t))))
  3122. (push-mark
  3123. (save-excursion
  3124. (insert-buffer-substring (get-buffer buffer))
  3125. (point)))
  3126. nil)
  3127. (defun append-to-buffer (buffer start end)
  3128. "Append to specified buffer the text of the region.
  3129. It is inserted into that buffer before its point.
  3130. When calling from a program, give three arguments:
  3131. BUFFER (or buffer name), START and END.
  3132. START and END specify the portion of the current buffer to be copied."
  3133. (interactive
  3134. (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
  3135. (region-beginning) (region-end)))
  3136. (let* ((oldbuf (current-buffer))
  3137. (append-to (get-buffer-create buffer))
  3138. (windows (get-buffer-window-list append-to t t))
  3139. point)
  3140. (save-excursion
  3141. (with-current-buffer append-to
  3142. (setq point (point))
  3143. (barf-if-buffer-read-only)
  3144. (insert-buffer-substring oldbuf start end)
  3145. (dolist (window windows)
  3146. (when (= (window-point window) point)
  3147. (set-window-point window (point))))))))
  3148. (defun prepend-to-buffer (buffer start end)
  3149. "Prepend to specified buffer the text of the region.
  3150. It is inserted into that buffer after its point.
  3151. When calling from a program, give three arguments:
  3152. BUFFER (or buffer name), START and END.
  3153. START and END specify the portion of the current buffer to be copied."
  3154. (interactive "BPrepend to buffer: \nr")
  3155. (let ((oldbuf (current-buffer)))
  3156. (with-current-buffer (get-buffer-create buffer)
  3157. (barf-if-buffer-read-only)
  3158. (save-excursion
  3159. (insert-buffer-substring oldbuf start end)))))
  3160. (defun copy-to-buffer (buffer start end)
  3161. "Copy to specified buffer the text of the region.
  3162. It is inserted into that buffer, replacing existing text there.
  3163. When calling from a program, give three arguments:
  3164. BUFFER (or buffer name), START and END.
  3165. START and END specify the portion of the current buffer to be copied."
  3166. (interactive "BCopy to buffer: \nr")
  3167. (let ((oldbuf (current-buffer)))
  3168. (with-current-buffer (get-buffer-create buffer)
  3169. (barf-if-buffer-read-only)
  3170. (erase-buffer)
  3171. (save-excursion
  3172. (insert-buffer-substring oldbuf start end)))))
  3173. (put 'mark-inactive 'error-conditions '(mark-inactive error))
  3174. (put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
  3175. (defvar activate-mark-hook nil
  3176. "Hook run when the mark becomes active.
  3177. It is also run at the end of a command, if the mark is active and
  3178. it is possible that the region may have changed.")
  3179. (defvar deactivate-mark-hook nil
  3180. "Hook run when the mark becomes inactive.")
  3181. (defun mark (&optional force)
  3182. "Return this buffer's mark value as integer, or nil if never set.
  3183. In Transient Mark mode, this function signals an error if
  3184. the mark is not active. However, if `mark-even-if-inactive' is non-nil,
  3185. or the argument FORCE is non-nil, it disregards whether the mark
  3186. is active, and returns an integer or nil in the usual way.
  3187. If you are using this in an editing command, you are most likely making
  3188. a mistake; see the documentation of `set-mark'."
  3189. (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
  3190. (marker-position (mark-marker))
  3191. (signal 'mark-inactive nil)))
  3192. (defcustom select-active-regions nil
  3193. "If non-nil, an active region automatically becomes the window selection."
  3194. :type 'boolean
  3195. :group 'killing
  3196. :version "23.1")
  3197. (declare-function x-selection-owner-p "xselect.c" (&optional selection))
  3198. ;; Many places set mark-active directly, and several of them failed to also
  3199. ;; run deactivate-mark-hook. This shorthand should simplify.
  3200. (defsubst deactivate-mark (&optional force)
  3201. "Deactivate the mark by setting `mark-active' to nil.
  3202. Unless FORCE is non-nil, this function does nothing if Transient
  3203. Mark mode is disabled.
  3204. This function also runs `deactivate-mark-hook'."
  3205. (when (or transient-mark-mode force)
  3206. ;; Copy the latest region into the primary selection, if desired.
  3207. (and select-active-regions
  3208. mark-active
  3209. (display-selections-p)
  3210. (x-selection-owner-p 'PRIMARY)
  3211. (x-set-selection 'PRIMARY (buffer-substring-no-properties
  3212. (region-beginning) (region-end))))
  3213. (if (and (null force)
  3214. (or (eq transient-mark-mode 'lambda)
  3215. (and (eq (car-safe transient-mark-mode) 'only)
  3216. (null (cdr transient-mark-mode)))))
  3217. ;; When deactivating a temporary region, don't change
  3218. ;; `mark-active' or run `deactivate-mark-hook'.
  3219. (setq transient-mark-mode nil)
  3220. (if (eq (car-safe transient-mark-mode) 'only)
  3221. (setq transient-mark-mode (cdr transient-mark-mode)))
  3222. (setq mark-active nil)
  3223. (run-hooks 'deactivate-mark-hook))))
  3224. (defun activate-mark ()
  3225. "Activate the mark."
  3226. (when (mark t)
  3227. (setq mark-active t)
  3228. (unless transient-mark-mode
  3229. (setq transient-mark-mode 'lambda))
  3230. (when (and select-active-regions
  3231. (display-selections-p))
  3232. (x-set-selection 'PRIMARY (current-buffer)))))
  3233. (defun set-mark (pos)
  3234. "Set this buffer's mark to POS. Don't use this function!
  3235. That is to say, don't use this function unless you want
  3236. the user to see that the mark has moved, and you want the previous
  3237. mark position to be lost.
  3238. Normally, when a new mark is set, the old one should go on the stack.
  3239. This is why most applications should use `push-mark', not `set-mark'.
  3240. Novice Emacs Lisp programmers often try to use the mark for the wrong
  3241. purposes. The mark saves a location for the user's convenience.
  3242. Most editing commands should not alter the mark.
  3243. To remember a location for internal use in the Lisp program,
  3244. store it in a Lisp variable. Example:
  3245. (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
  3246. (if pos
  3247. (progn
  3248. (setq mark-active t)
  3249. (run-hooks 'activate-mark-hook)
  3250. (when (and select-active-regions
  3251. (display-selections-p))
  3252. (x-set-selection 'PRIMARY (current-buffer)))
  3253. (set-marker (mark-marker) pos (current-buffer)))
  3254. ;; Normally we never clear mark-active except in Transient Mark mode.
  3255. ;; But when we actually clear out the mark value too, we must
  3256. ;; clear mark-active in any mode.
  3257. (deactivate-mark t)
  3258. (set-marker (mark-marker) nil)))
  3259. (defcustom use-empty-active-region nil
  3260. "Whether \"region-aware\" commands should act on empty regions.
  3261. If nil, region-aware commands treat empty regions as inactive.
  3262. If non-nil, region-aware commands treat the region as active as
  3263. long as the mark is active, even if the region is empty.
  3264. Region-aware commands are those that act on the region if it is
  3265. active and Transient Mark mode is enabled, and on the text near
  3266. point otherwise."
  3267. :type 'boolean
  3268. :version "23.1"
  3269. :group 'editing-basics)
  3270. (defun use-region-p ()
  3271. "Return t if the region is active and it is appropriate to act on it.
  3272. This is used by commands that act specially on the region under
  3273. Transient Mark mode.
  3274. The return value is t provided Transient Mark mode is enabled and
  3275. the mark is active; and, when `use-empty-active-region' is
  3276. non-nil, provided the region is empty. Otherwise, the return
  3277. value is nil.
  3278. For some commands, it may be appropriate to ignore the value of
  3279. `use-empty-active-region'; in that case, use `region-active-p'."
  3280. (and (region-active-p)
  3281. (or use-empty-active-region (> (region-end) (region-beginning)))))
  3282. (defun region-active-p ()
  3283. "Return t if Transient Mark mode is enabled and the mark is active.
  3284. Some commands act specially on the region when Transient Mark
  3285. mode is enabled. Usually, such commands should use
  3286. `use-region-p' instead of this function, because `use-region-p'
  3287. also checks the value of `use-empty-active-region'."
  3288. (and transient-mark-mode mark-active))
  3289. (defvar mark-ring nil
  3290. "The list of former marks of the current buffer, most recent first.")
  3291. (make-variable-buffer-local 'mark-ring)
  3292. (put 'mark-ring 'permanent-local t)
  3293. (defcustom mark-ring-max 16
  3294. "Maximum size of mark ring. Start discarding off end if gets this big."
  3295. :type 'integer
  3296. :group 'editing-basics)
  3297. (defvar global-mark-ring nil
  3298. "The list of saved global marks, most recent first.")
  3299. (defcustom global-mark-ring-max 16
  3300. "Maximum size of global mark ring. \
  3301. Start discarding off end if gets this big."
  3302. :type 'integer
  3303. :group 'editing-basics)
  3304. (defun pop-to-mark-command ()
  3305. "Jump to mark, and pop a new position for mark off the ring.
  3306. \(Does not affect global mark ring\)."
  3307. (interactive)
  3308. (if (null (mark t))
  3309. (error "No mark set in this buffer")
  3310. (if (= (point) (mark t))
  3311. (message "Mark popped"))
  3312. (goto-char (mark t))
  3313. (pop-mark)))
  3314. (defun push-mark-command (arg &optional nomsg)
  3315. "Set mark at where point is.
  3316. If no prefix ARG and mark is already set there, just activate it.
  3317. Display `Mark set' unless the optional second arg NOMSG is non-nil."
  3318. (interactive "P")
  3319. (let ((mark (marker-position (mark-marker))))
  3320. (if (or arg (null mark) (/= mark (point)))
  3321. (push-mark nil nomsg t)
  3322. (setq mark-active t)
  3323. (run-hooks 'activate-mark-hook)
  3324. (unless nomsg
  3325. (message "Mark activated")))))
  3326. (defcustom set-mark-command-repeat-pop nil
  3327. "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
  3328. That means that C-u \\[set-mark-command] \\[set-mark-command]
  3329. will pop the mark twice, and
  3330. C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
  3331. will pop the mark three times.
  3332. A value of nil means \\[set-mark-command]'s behavior does not change
  3333. after C-u \\[set-mark-command]."
  3334. :type 'boolean
  3335. :group 'editing-basics)
  3336. (defcustom set-mark-default-inactive nil
  3337. "If non-nil, setting the mark does not activate it.
  3338. This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
  3339. behave the same whether or not `transient-mark-mode' is enabled."
  3340. :type 'boolean
  3341. :group 'editing-basics
  3342. :version "23.1")
  3343. (defun set-mark-command (arg)
  3344. "Set the mark where point is, or jump to the mark.
  3345. Setting the mark also alters the region, which is the text
  3346. between point and mark; this is the closest equivalent in
  3347. Emacs to what some editors call the \"selection\".
  3348. With no prefix argument, set the mark at point, and push the
  3349. old mark position on local mark ring. Also push the old mark on
  3350. global mark ring, if the previous mark was set in another buffer.
  3351. When Transient Mark Mode is off, immediately repeating this
  3352. command activates `transient-mark-mode' temporarily.
  3353. With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
  3354. jump to the mark, and set the mark from
  3355. position popped off the local mark ring \(this does not affect the global
  3356. mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
  3357. mark ring \(see `pop-global-mark'\).
  3358. If `set-mark-command-repeat-pop' is non-nil, repeating
  3359. the \\[set-mark-command] command with no prefix argument pops the next position
  3360. off the local (or global) mark ring and jumps there.
  3361. With \\[universal-argument] \\[universal-argument] as prefix
  3362. argument, unconditionally set mark where point is, even if
  3363. `set-mark-command-repeat-pop' is non-nil.
  3364. Novice Emacs Lisp programmers often try to use the mark for the wrong
  3365. purposes. See the documentation of `set-mark' for more information."
  3366. (interactive "P")
  3367. (cond ((eq transient-mark-mode 'lambda)
  3368. (setq transient-mark-mode nil))
  3369. ((eq (car-safe transient-mark-mode) 'only)
  3370. (deactivate-mark)))
  3371. (cond
  3372. ((and (consp arg) (> (prefix-numeric-value arg) 4))
  3373. (push-mark-command nil))
  3374. ((not (eq this-command 'set-mark-command))
  3375. (if arg
  3376. (pop-to-mark-command)
  3377. (push-mark-command t)))
  3378. ((and set-mark-command-repeat-pop
  3379. (eq last-command 'pop-to-mark-command))
  3380. (setq this-command 'pop-to-mark-command)
  3381. (pop-to-mark-command))
  3382. ((and set-mark-command-repeat-pop
  3383. (eq last-command 'pop-global-mark)
  3384. (not arg))
  3385. (setq this-command 'pop-global-mark)
  3386. (pop-global-mark))
  3387. (arg
  3388. (setq this-command 'pop-to-mark-command)
  3389. (pop-to-mark-command))
  3390. ((eq last-command 'set-mark-command)
  3391. (if (region-active-p)
  3392. (progn
  3393. (deactivate-mark)
  3394. (message "Mark deactivated"))
  3395. (activate-mark)
  3396. (message "Mark activated")))
  3397. (t
  3398. (push-mark-command nil)
  3399. (if set-mark-default-inactive (deactivate-mark)))))
  3400. (defun push-mark (&optional location nomsg activate)
  3401. "Set mark at LOCATION (point, by default) and push old mark on mark ring.
  3402. If the last global mark pushed was not in the current buffer,
  3403. also push LOCATION on the global mark ring.
  3404. Display `Mark set' unless the optional second arg NOMSG is non-nil.
  3405. Novice Emacs Lisp programmers often try to use the mark for the wrong
  3406. purposes. See the documentation of `set-mark' for more information.
  3407. In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
  3408. (unless (null (mark t))
  3409. (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
  3410. (when (> (length mark-ring) mark-ring-max)
  3411. (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
  3412. (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
  3413. (set-marker (mark-marker) (or location (point)) (current-buffer))
  3414. ;; Now push the mark on the global mark ring.
  3415. (if (and global-mark-ring
  3416. (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
  3417. ;; The last global mark pushed was in this same buffer.
  3418. ;; Don't push another one.
  3419. nil
  3420. (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
  3421. (when (> (length global-mark-ring) global-mark-ring-max)
  3422. (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
  3423. (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
  3424. (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
  3425. (message "Mark set"))
  3426. (if (or activate (not transient-mark-mode))
  3427. (set-mark (mark t)))
  3428. nil)
  3429. (defun pop-mark ()
  3430. "Pop off mark ring into the buffer's actual mark.
  3431. Does not set point. Does nothing if mark ring is empty."
  3432. (when mark-ring
  3433. (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
  3434. (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
  3435. (move-marker (car mark-ring) nil)
  3436. (if (null (mark t)) (ding))
  3437. (setq mark-ring (cdr mark-ring)))
  3438. (deactivate-mark))
  3439. (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
  3440. (defun exchange-point-and-mark (&optional arg)
  3441. "Put the mark where point is now, and point where the mark is now.
  3442. This command works even when the mark is not active,
  3443. and it reactivates the mark.
  3444. If Transient Mark mode is on, a prefix ARG deactivates the mark
  3445. if it is active, and otherwise avoids reactivating it. If
  3446. Transient Mark mode is off, a prefix ARG enables Transient Mark
  3447. mode temporarily."
  3448. (interactive "P")
  3449. (let ((omark (mark t))
  3450. (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
  3451. (if (null omark)
  3452. (error "No mark set in this buffer"))
  3453. (deactivate-mark)
  3454. (set-mark (point))
  3455. (goto-char omark)
  3456. (if set-mark-default-inactive (deactivate-mark))
  3457. (cond (temp-highlight
  3458. (setq transient-mark-mode (cons 'only transient-mark-mode)))
  3459. ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
  3460. (not (or arg (region-active-p))))
  3461. (deactivate-mark))
  3462. (t (activate-mark)))
  3463. nil))
  3464. (defcustom shift-select-mode t
  3465. "When non-nil, shifted motion keys activate the mark momentarily.
  3466. While the mark is activated in this way, any shift-translated point
  3467. motion key extends the region, and if Transient Mark mode was off, it
  3468. is temporarily turned on. Furthermore, the mark will be deactivated
  3469. by any subsequent point motion key that was not shift-translated, or
  3470. by any action that normally deactivates the mark in Transient Mark mode.
  3471. See `this-command-keys-shift-translated' for the meaning of
  3472. shift-translation."
  3473. :type 'boolean
  3474. :group 'editing-basics)
  3475. (defun handle-shift-selection ()
  3476. "Activate/deactivate mark depending on invocation thru shift translation.
  3477. This function is called by `call-interactively' when a command
  3478. with a `^' character in its `interactive' spec is invoked, before
  3479. running the command itself.
  3480. If `shift-select-mode' is enabled and the command was invoked
  3481. through shift translation, set the mark and activate the region
  3482. temporarily, unless it was already set in this way. See
  3483. `this-command-keys-shift-translated' for the meaning of shift
  3484. translation.
  3485. Otherwise, if the region has been activated temporarily,
  3486. deactivate it, and restore the variable `transient-mark-mode' to
  3487. its earlier value."
  3488. (cond ((and shift-select-mode this-command-keys-shift-translated)
  3489. (unless (and mark-active
  3490. (eq (car-safe transient-mark-mode) 'only))
  3491. (setq transient-mark-mode
  3492. (cons 'only
  3493. (unless (eq transient-mark-mode 'lambda)
  3494. transient-mark-mode)))
  3495. (push-mark nil nil t)))
  3496. ((eq (car-safe transient-mark-mode) 'only)
  3497. (setq transient-mark-mode (cdr transient-mark-mode))
  3498. (deactivate-mark))))
  3499. (define-minor-mode transient-mark-mode
  3500. "Toggle Transient Mark mode.
  3501. With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
  3502. In Transient Mark mode, when the mark is active, the region is highlighted.
  3503. Changing the buffer \"deactivates\" the mark.
  3504. So do certain other operations that set the mark
  3505. but whose main purpose is something else--for example,
  3506. incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
  3507. You can also deactivate the mark by typing \\[keyboard-quit] or
  3508. \\[keyboard-escape-quit].
  3509. Many commands change their behavior when Transient Mark mode is in effect
  3510. and the mark is active, by acting on the region instead of their usual
  3511. default part of the buffer's text. Examples of such commands include
  3512. \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
  3513. \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
  3514. Invoke \\[apropos-documentation] and type \"transient\" or
  3515. \"mark.*active\" at the prompt, to see the documentation of
  3516. commands which are sensitive to the Transient Mark mode."
  3517. :global t
  3518. :init-value (not noninteractive)
  3519. :initialize 'custom-initialize-delay
  3520. :group 'editing-basics)
  3521. ;; The variable transient-mark-mode is ugly: it can take on special
  3522. ;; values. Document these here.
  3523. (defvar transient-mark-mode t
  3524. "*Non-nil if Transient Mark mode is enabled.
  3525. See the command `transient-mark-mode' for a description of this minor mode.
  3526. Non-nil also enables highlighting of the region whenever the mark is active.
  3527. The variable `highlight-nonselected-windows' controls whether to highlight
  3528. all windows or just the selected window.
  3529. If the value is `lambda', that enables Transient Mark mode temporarily.
  3530. After any subsequent action that would normally deactivate the mark
  3531. \(such as buffer modification), Transient Mark mode is turned off.
  3532. If the value is (only . OLDVAL), that enables Transient Mark mode
  3533. temporarily. After any subsequent point motion command that is not
  3534. shift-translated, or any other action that would normally deactivate
  3535. the mark (such as buffer modification), the value of
  3536. `transient-mark-mode' is set to OLDVAL.")
  3537. (defvar widen-automatically t
  3538. "Non-nil means it is ok for commands to call `widen' when they want to.
  3539. Some commands will do this in order to go to positions outside
  3540. the current accessible part of the buffer.
  3541. If `widen-automatically' is nil, these commands will do something else
  3542. as a fallback, and won't change the buffer bounds.")
  3543. (defvar non-essential nil
  3544. "Whether the currently executing code is performing an essential task.
  3545. This variable should be non-nil only when running code which should not
  3546. disturb the user. E.g. it can be used to prevent Tramp from prompting the
  3547. user for a password when we are simply scanning a set of files in the
  3548. background or displaying possible completions before the user even asked
  3549. for it.")
  3550. (defun pop-global-mark ()
  3551. "Pop off global mark ring and jump to the top location."
  3552. (interactive)
  3553. ;; Pop entries which refer to non-existent buffers.
  3554. (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
  3555. (setq global-mark-ring (cdr global-mark-ring)))
  3556. (or global-mark-ring
  3557. (error "No global mark set"))
  3558. (let* ((marker (car global-mark-ring))
  3559. (buffer (marker-buffer marker))
  3560. (position (marker-position marker)))
  3561. (setq global-mark-ring (nconc (cdr global-mark-ring)
  3562. (list (car global-mark-ring))))
  3563. (set-buffer buffer)
  3564. (or (and (>= position (point-min))
  3565. (<= position (point-max)))
  3566. (if widen-automatically
  3567. (widen)
  3568. (error "Global mark position is outside accessible part of buffer")))
  3569. (goto-char position)
  3570. (switch-to-buffer buffer)))
  3571. (defcustom next-line-add-newlines nil
  3572. "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
  3573. :type 'boolean
  3574. :version "21.1"
  3575. :group 'editing-basics)
  3576. (defun next-line (&optional arg try-vscroll)
  3577. "Move cursor vertically down ARG lines.
  3578. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  3579. If there is no character in the target line exactly under the current column,
  3580. the cursor is positioned after the character in that line which spans this
  3581. column, or at the end of the line if it is not long enough.
  3582. If there is no line in the buffer after this one, behavior depends on the
  3583. value of `next-line-add-newlines'. If non-nil, it inserts a newline character
  3584. to create a line, and moves the cursor to that line. Otherwise it moves the
  3585. cursor to the end of the buffer.
  3586. If the variable `line-move-visual' is non-nil, this command moves
  3587. by display lines. Otherwise, it moves by buffer lines, without
  3588. taking variable-width characters or continued lines into account.
  3589. The command \\[set-goal-column] can be used to create
  3590. a semipermanent goal column for this command.
  3591. Then instead of trying to move exactly vertically (or as close as possible),
  3592. this command moves to the specified goal column (or as close as possible).
  3593. The goal column is stored in the variable `goal-column', which is nil
  3594. when there is no goal column.
  3595. If you are thinking of using this in a Lisp program, consider
  3596. using `forward-line' instead. It is usually easier to use
  3597. and more reliable (no dependence on goal column, etc.)."
  3598. (interactive "^p\np")
  3599. (or arg (setq arg 1))
  3600. (if (and next-line-add-newlines (= arg 1))
  3601. (if (save-excursion (end-of-line) (eobp))
  3602. ;; When adding a newline, don't expand an abbrev.
  3603. (let ((abbrev-mode nil))
  3604. (end-of-line)
  3605. (insert (if use-hard-newlines hard-newline "\n")))
  3606. (line-move arg nil nil try-vscroll))
  3607. (if (called-interactively-p 'interactive)
  3608. (condition-case err
  3609. (line-move arg nil nil try-vscroll)
  3610. ((beginning-of-buffer end-of-buffer)
  3611. (signal (car err) (cdr err))))
  3612. (line-move arg nil nil try-vscroll)))
  3613. nil)
  3614. (defun previous-line (&optional arg try-vscroll)
  3615. "Move cursor vertically up ARG lines.
  3616. Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
  3617. If there is no character in the target line exactly over the current column,
  3618. the cursor is positioned after the character in that line which spans this
  3619. column, or at the end of the line if it is not long enough.
  3620. If the variable `line-move-visual' is non-nil, this command moves
  3621. by display lines. Otherwise, it moves by buffer lines, without
  3622. taking variable-width characters or continued lines into account.
  3623. The command \\[set-goal-column] can be used to create
  3624. a semipermanent goal column for this command.
  3625. Then instead of trying to move exactly vertically (or as close as possible),
  3626. this command moves to the specified goal column (or as close as possible).
  3627. The goal column is stored in the variable `goal-column', which is nil
  3628. when there is no goal column.
  3629. If you are thinking of using this in a Lisp program, consider using
  3630. `forward-line' with a negative argument instead. It is usually easier
  3631. to use and more reliable (no dependence on goal column, etc.)."
  3632. (interactive "^p\np")
  3633. (or arg (setq arg 1))
  3634. (if (called-interactively-p 'interactive)
  3635. (condition-case err
  3636. (line-move (- arg) nil nil try-vscroll)
  3637. ((beginning-of-buffer end-of-buffer)
  3638. (signal (car err) (cdr err))))
  3639. (line-move (- arg) nil nil try-vscroll))
  3640. nil)
  3641. (defcustom track-eol nil
  3642. "Non-nil means vertical motion starting at end of line keeps to ends of lines.
  3643. This means moving to the end of each line moved onto.
  3644. The beginning of a blank line does not count as the end of a line.
  3645. This has no effect when `line-move-visual' is non-nil."
  3646. :type 'boolean
  3647. :group 'editing-basics)
  3648. (defcustom goal-column nil
  3649. "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
  3650. :type '(choice integer
  3651. (const :tag "None" nil))
  3652. :group 'editing-basics)
  3653. (make-variable-buffer-local 'goal-column)
  3654. (defvar temporary-goal-column 0
  3655. "Current goal column for vertical motion.
  3656. It is the column where point was at the start of the current run
  3657. of vertical motion commands.
  3658. When moving by visual lines via `line-move-visual', it is a cons
  3659. cell (COL . HSCROLL), where COL is the x-position, in pixels,
  3660. divided by the default column width, and HSCROLL is the number of
  3661. columns by which window is scrolled from left margin.
  3662. When the `track-eol' feature is doing its job, the value is
  3663. `most-positive-fixnum'.")
  3664. (defcustom line-move-ignore-invisible t
  3665. "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
  3666. Outline mode sets this."
  3667. :type 'boolean
  3668. :group 'editing-basics)
  3669. (defcustom line-move-visual t
  3670. "When non-nil, `line-move' moves point by visual lines.
  3671. This movement is based on where the cursor is displayed on the
  3672. screen, instead of relying on buffer contents alone. It takes
  3673. into account variable-width characters and line continuation."
  3674. :type 'boolean
  3675. :group 'editing-basics)
  3676. ;; Returns non-nil if partial move was done.
  3677. (defun line-move-partial (arg noerror to-end)
  3678. (if (< arg 0)
  3679. ;; Move backward (up).
  3680. ;; If already vscrolled, reduce vscroll
  3681. (let ((vs (window-vscroll nil t)))
  3682. (when (> vs (frame-char-height))
  3683. (set-window-vscroll nil (- vs (frame-char-height)) t)))
  3684. ;; Move forward (down).
  3685. (let* ((lh (window-line-height -1))
  3686. (vpos (nth 1 lh))
  3687. (ypos (nth 2 lh))
  3688. (rbot (nth 3 lh))
  3689. py vs)
  3690. (when (or (null lh)
  3691. (>= rbot (frame-char-height))
  3692. (<= ypos (- (frame-char-height))))
  3693. (unless lh
  3694. (let ((wend (pos-visible-in-window-p t nil t)))
  3695. (setq rbot (nth 3 wend)
  3696. vpos (nth 5 wend))))
  3697. (cond
  3698. ;; If last line of window is fully visible, move forward.
  3699. ((or (null rbot) (= rbot 0))
  3700. nil)
  3701. ;; If cursor is not in the bottom scroll margin, move forward.
  3702. ((and (> vpos 0)
  3703. (< (setq py
  3704. (or (nth 1 (window-line-height))
  3705. (let ((ppos (posn-at-point)))
  3706. (cdr (or (posn-actual-col-row ppos)
  3707. (posn-col-row ppos))))))
  3708. (min (- (window-text-height) scroll-margin 1) (1- vpos))))
  3709. nil)
  3710. ;; When already vscrolled, we vscroll some more if we can,
  3711. ;; or clear vscroll and move forward at end of tall image.
  3712. ((> (setq vs (window-vscroll nil t)) 0)
  3713. (when (> rbot 0)
  3714. (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
  3715. ;; If cursor just entered the bottom scroll margin, move forward,
  3716. ;; but also vscroll one line so redisplay wont recenter.
  3717. ((and (> vpos 0)
  3718. (= py (min (- (window-text-height) scroll-margin 1)
  3719. (1- vpos))))
  3720. (set-window-vscroll nil (frame-char-height) t)
  3721. (line-move-1 arg noerror to-end)
  3722. t)
  3723. ;; If there are lines above the last line, scroll-up one line.
  3724. ((> vpos 0)
  3725. (scroll-up 1)
  3726. t)
  3727. ;; Finally, start vscroll.
  3728. (t
  3729. (set-window-vscroll nil (frame-char-height) t)))))))
  3730. ;; This is like line-move-1 except that it also performs
  3731. ;; vertical scrolling of tall images if appropriate.
  3732. ;; That is not really a clean thing to do, since it mixes
  3733. ;; scrolling with cursor motion. But so far we don't have
  3734. ;; a cleaner solution to the problem of making C-n do something
  3735. ;; useful given a tall image.
  3736. (defun line-move (arg &optional noerror to-end try-vscroll)
  3737. (unless (and auto-window-vscroll try-vscroll
  3738. ;; Only vscroll for single line moves
  3739. (= (abs arg) 1)
  3740. ;; But don't vscroll in a keyboard macro.
  3741. (not defining-kbd-macro)
  3742. (not executing-kbd-macro)
  3743. (line-move-partial arg noerror to-end))
  3744. (set-window-vscroll nil 0 t)
  3745. (if line-move-visual
  3746. (line-move-visual arg noerror)
  3747. (line-move-1 arg noerror to-end))))
  3748. ;; Display-based alternative to line-move-1.
  3749. ;; Arg says how many lines to move. The value is t if we can move the
  3750. ;; specified number of lines.
  3751. (defun line-move-visual (arg &optional noerror)
  3752. (let ((opoint (point))
  3753. (hscroll (window-hscroll))
  3754. target-hscroll)
  3755. ;; Check if the previous command was a line-motion command, or if
  3756. ;; we were called from some other command.
  3757. (if (and (consp temporary-goal-column)
  3758. (memq last-command `(next-line previous-line ,this-command)))
  3759. ;; If so, there's no need to reset `temporary-goal-column',
  3760. ;; but we may need to hscroll.
  3761. (if (or (/= (cdr temporary-goal-column) hscroll)
  3762. (> (cdr temporary-goal-column) 0))
  3763. (setq target-hscroll (cdr temporary-goal-column)))
  3764. ;; Otherwise, we should reset `temporary-goal-column'.
  3765. (let ((posn (posn-at-point)))
  3766. (cond
  3767. ;; Handle the `overflow-newline-into-fringe' case:
  3768. ((eq (nth 1 posn) 'right-fringe)
  3769. (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
  3770. ((car (posn-x-y posn))
  3771. (setq temporary-goal-column
  3772. (cons (/ (float (car (posn-x-y posn)))
  3773. (frame-char-width)) hscroll))))))
  3774. (if target-hscroll
  3775. (set-window-hscroll (selected-window) target-hscroll))
  3776. (or (and (= (vertical-motion
  3777. (cons (or goal-column
  3778. (if (consp temporary-goal-column)
  3779. (truncate (car temporary-goal-column))
  3780. temporary-goal-column))
  3781. arg))
  3782. arg)
  3783. (or (>= arg 0)
  3784. (/= (point) opoint)
  3785. ;; If the goal column lies on a display string,
  3786. ;; `vertical-motion' advances the cursor to the end
  3787. ;; of the string. For arg < 0, this can cause the
  3788. ;; cursor to get stuck. (Bug#3020).
  3789. (= (vertical-motion arg) arg)))
  3790. (unless noerror
  3791. (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
  3792. nil)))))
  3793. ;; This is the guts of next-line and previous-line.
  3794. ;; Arg says how many lines to move.
  3795. ;; The value is t if we can move the specified number of lines.
  3796. (defun line-move-1 (arg &optional noerror to-end)
  3797. ;; Don't run any point-motion hooks, and disregard intangibility,
  3798. ;; for intermediate positions.
  3799. (let ((inhibit-point-motion-hooks t)
  3800. (opoint (point))
  3801. (orig-arg arg))
  3802. (if (consp temporary-goal-column)
  3803. (setq temporary-goal-column (+ (car temporary-goal-column)
  3804. (cdr temporary-goal-column))))
  3805. (unwind-protect
  3806. (progn
  3807. (if (not (memq last-command '(next-line previous-line)))
  3808. (setq temporary-goal-column
  3809. (if (and track-eol (eolp)
  3810. ;; Don't count beg of empty line as end of line
  3811. ;; unless we just did explicit end-of-line.
  3812. (or (not (bolp)) (eq last-command 'move-end-of-line)))
  3813. most-positive-fixnum
  3814. (current-column))))
  3815. (if (not (or (integerp selective-display)
  3816. line-move-ignore-invisible))
  3817. ;; Use just newline characters.
  3818. ;; Set ARG to 0 if we move as many lines as requested.
  3819. (or (if (> arg 0)
  3820. (progn (if (> arg 1) (forward-line (1- arg)))
  3821. ;; This way of moving forward ARG lines
  3822. ;; verifies that we have a newline after the last one.
  3823. ;; It doesn't get confused by intangible text.
  3824. (end-of-line)
  3825. (if (zerop (forward-line 1))
  3826. (setq arg 0)))
  3827. (and (zerop (forward-line arg))
  3828. (bolp)
  3829. (setq arg 0)))
  3830. (unless noerror
  3831. (signal (if (< arg 0)
  3832. 'beginning-of-buffer
  3833. 'end-of-buffer)
  3834. nil)))
  3835. ;; Move by arg lines, but ignore invisible ones.
  3836. (let (done)
  3837. (while (and (> arg 0) (not done))
  3838. ;; If the following character is currently invisible,
  3839. ;; skip all characters with that same `invisible' property value.
  3840. (while (and (not (eobp)) (invisible-p (point)))
  3841. (goto-char (next-char-property-change (point))))
  3842. ;; Move a line.
  3843. ;; We don't use `end-of-line', since we want to escape
  3844. ;; from field boundaries ocurring exactly at point.
  3845. (goto-char (constrain-to-field
  3846. (let ((inhibit-field-text-motion t))
  3847. (line-end-position))
  3848. (point) t t
  3849. 'inhibit-line-move-field-capture))
  3850. ;; If there's no invisibility here, move over the newline.
  3851. (cond
  3852. ((eobp)
  3853. (if (not noerror)
  3854. (signal 'end-of-buffer nil)
  3855. (setq done t)))
  3856. ((and (> arg 1) ;; Use vertical-motion for last move
  3857. (not (integerp selective-display))
  3858. (not (invisible-p (point))))
  3859. ;; We avoid vertical-motion when possible
  3860. ;; because that has to fontify.
  3861. (forward-line 1))
  3862. ;; Otherwise move a more sophisticated way.
  3863. ((zerop (vertical-motion 1))
  3864. (if (not noerror)
  3865. (signal 'end-of-buffer nil)
  3866. (setq done t))))
  3867. (unless done
  3868. (setq arg (1- arg))))
  3869. ;; The logic of this is the same as the loop above,
  3870. ;; it just goes in the other direction.
  3871. (while (and (< arg 0) (not done))
  3872. ;; For completely consistency with the forward-motion
  3873. ;; case, we should call beginning-of-line here.
  3874. ;; However, if point is inside a field and on a
  3875. ;; continued line, the call to (vertical-motion -1)
  3876. ;; below won't move us back far enough; then we return
  3877. ;; to the same column in line-move-finish, and point
  3878. ;; gets stuck -- cyd
  3879. (forward-line 0)
  3880. (cond
  3881. ((bobp)
  3882. (if (not noerror)
  3883. (signal 'beginning-of-buffer nil)
  3884. (setq done t)))
  3885. ((and (< arg -1) ;; Use vertical-motion for last move
  3886. (not (integerp selective-display))
  3887. (not (invisible-p (1- (point)))))
  3888. (forward-line -1))
  3889. ((zerop (vertical-motion -1))
  3890. (if (not noerror)
  3891. (signal 'beginning-of-buffer nil)
  3892. (setq done t))))
  3893. (unless done
  3894. (setq arg (1+ arg))
  3895. (while (and ;; Don't move over previous invis lines
  3896. ;; if our target is the middle of this line.
  3897. (or (zerop (or goal-column temporary-goal-column))
  3898. (< arg 0))
  3899. (not (bobp)) (invisible-p (1- (point))))
  3900. (goto-char (previous-char-property-change (point))))))))
  3901. ;; This is the value the function returns.
  3902. (= arg 0))
  3903. (cond ((> arg 0)
  3904. ;; If we did not move down as far as desired, at least go
  3905. ;; to end of line. Be sure to call point-entered and
  3906. ;; point-left-hooks.
  3907. (let* ((npoint (prog1 (line-end-position)
  3908. (goto-char opoint)))
  3909. (inhibit-point-motion-hooks nil))
  3910. (goto-char npoint)))
  3911. ((< arg 0)
  3912. ;; If we did not move up as far as desired,
  3913. ;; at least go to beginning of line.
  3914. (let* ((npoint (prog1 (line-beginning-position)
  3915. (goto-char opoint)))
  3916. (inhibit-point-motion-hooks nil))
  3917. (goto-char npoint)))
  3918. (t
  3919. (line-move-finish (or goal-column temporary-goal-column)
  3920. opoint (> orig-arg 0)))))))
  3921. (defun line-move-finish (column opoint forward)
  3922. (let ((repeat t))
  3923. (while repeat
  3924. ;; Set REPEAT to t to repeat the whole thing.
  3925. (setq repeat nil)
  3926. (let (new
  3927. (old (point))
  3928. (line-beg (save-excursion (beginning-of-line) (point)))
  3929. (line-end
  3930. ;; Compute the end of the line
  3931. ;; ignoring effectively invisible newlines.
  3932. (save-excursion
  3933. ;; Like end-of-line but ignores fields.
  3934. (skip-chars-forward "^\n")
  3935. (while (and (not (eobp)) (invisible-p (point)))
  3936. (goto-char (next-char-property-change (point)))
  3937. (skip-chars-forward "^\n"))
  3938. (point))))
  3939. ;; Move to the desired column.
  3940. (line-move-to-column (truncate column))
  3941. ;; Corner case: suppose we start out in a field boundary in
  3942. ;; the middle of a continued line. When we get to
  3943. ;; line-move-finish, point is at the start of a new *screen*
  3944. ;; line but the same text line; then line-move-to-column would
  3945. ;; move us backwards. Test using C-n with point on the "x" in
  3946. ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
  3947. (and forward
  3948. (< (point) old)
  3949. (goto-char old))
  3950. (setq new (point))
  3951. ;; Process intangibility within a line.
  3952. ;; With inhibit-point-motion-hooks bound to nil, a call to
  3953. ;; goto-char moves point past intangible text.
  3954. ;; However, inhibit-point-motion-hooks controls both the
  3955. ;; intangibility and the point-entered/point-left hooks. The
  3956. ;; following hack avoids calling the point-* hooks
  3957. ;; unnecessarily. Note that we move *forward* past intangible
  3958. ;; text when the initial and final points are the same.
  3959. (goto-char new)
  3960. (let ((inhibit-point-motion-hooks nil))
  3961. (goto-char new)
  3962. ;; If intangibility moves us to a different (later) place
  3963. ;; in the same line, use that as the destination.
  3964. (if (<= (point) line-end)
  3965. (setq new (point))
  3966. ;; If that position is "too late",
  3967. ;; try the previous allowable position.
  3968. ;; See if it is ok.
  3969. (backward-char)
  3970. (if (if forward
  3971. ;; If going forward, don't accept the previous
  3972. ;; allowable position if it is before the target line.
  3973. (< line-beg (point))
  3974. ;; If going backward, don't accept the previous
  3975. ;; allowable position if it is still after the target line.
  3976. (<= (point) line-end))
  3977. (setq new (point))
  3978. ;; As a last resort, use the end of the line.
  3979. (setq new line-end))))
  3980. ;; Now move to the updated destination, processing fields
  3981. ;; as well as intangibility.
  3982. (goto-char opoint)
  3983. (let ((inhibit-point-motion-hooks nil))
  3984. (goto-char
  3985. ;; Ignore field boundaries if the initial and final
  3986. ;; positions have the same `field' property, even if the
  3987. ;; fields are non-contiguous. This seems to be "nicer"
  3988. ;; behavior in many situations.
  3989. (if (eq (get-char-property new 'field)
  3990. (get-char-property opoint 'field))
  3991. new
  3992. (constrain-to-field new opoint t t
  3993. 'inhibit-line-move-field-capture))))
  3994. ;; If all this moved us to a different line,
  3995. ;; retry everything within that new line.
  3996. (when (or (< (point) line-beg) (> (point) line-end))
  3997. ;; Repeat the intangibility and field processing.
  3998. (setq repeat t))))))
  3999. (defun line-move-to-column (col)
  4000. "Try to find column COL, considering invisibility.
  4001. This function works only in certain cases,
  4002. because what we really need is for `move-to-column'
  4003. and `current-column' to be able to ignore invisible text."
  4004. (if (zerop col)
  4005. (beginning-of-line)
  4006. (move-to-column col))
  4007. (when (and line-move-ignore-invisible
  4008. (not (bolp)) (invisible-p (1- (point))))
  4009. (let ((normal-location (point))
  4010. (normal-column (current-column)))
  4011. ;; If the following character is currently invisible,
  4012. ;; skip all characters with that same `invisible' property value.
  4013. (while (and (not (eobp))
  4014. (invisible-p (point)))
  4015. (goto-char (next-char-property-change (point))))
  4016. ;; Have we advanced to a larger column position?
  4017. (if (> (current-column) normal-column)
  4018. ;; We have made some progress towards the desired column.
  4019. ;; See if we can make any further progress.
  4020. (line-move-to-column (+ (current-column) (- col normal-column)))
  4021. ;; Otherwise, go to the place we originally found
  4022. ;; and move back over invisible text.
  4023. ;; that will get us to the same place on the screen
  4024. ;; but with a more reasonable buffer position.
  4025. (goto-char normal-location)
  4026. (let ((line-beg (save-excursion (beginning-of-line) (point))))
  4027. (while (and (not (bolp)) (invisible-p (1- (point))))
  4028. (goto-char (previous-char-property-change (point) line-beg))))))))
  4029. (defun move-end-of-line (arg)
  4030. "Move point to end of current line as displayed.
  4031. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  4032. If point reaches the beginning or end of buffer, it stops there.
  4033. To ignore the effects of the `intangible' text or overlay
  4034. property, bind `inhibit-point-motion-hooks' to t.
  4035. If there is an image in the current line, this function
  4036. disregards newlines that are part of the text on which the image
  4037. rests."
  4038. (interactive "^p")
  4039. (or arg (setq arg 1))
  4040. (let (done)
  4041. (while (not done)
  4042. (let ((newpos
  4043. (save-excursion
  4044. (let ((goal-column 0)
  4045. (line-move-visual nil))
  4046. (and (line-move arg t)
  4047. (not (bobp))
  4048. (progn
  4049. (while (and (not (bobp)) (invisible-p (1- (point))))
  4050. (goto-char (previous-single-char-property-change
  4051. (point) 'invisible)))
  4052. (backward-char 1)))
  4053. (point)))))
  4054. (goto-char newpos)
  4055. (if (and (> (point) newpos)
  4056. (eq (preceding-char) ?\n))
  4057. (backward-char 1)
  4058. (if (and (> (point) newpos) (not (eobp))
  4059. (not (eq (following-char) ?\n)))
  4060. ;; If we skipped something intangible and now we're not
  4061. ;; really at eol, keep going.
  4062. (setq arg 1)
  4063. (setq done t)))))))
  4064. (defun move-beginning-of-line (arg)
  4065. "Move point to beginning of current line as displayed.
  4066. \(If there's an image in the line, this disregards newlines
  4067. which are part of the text that the image rests on.)
  4068. With argument ARG not nil or 1, move forward ARG - 1 lines first.
  4069. If point reaches the beginning or end of buffer, it stops there.
  4070. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  4071. (interactive "^p")
  4072. (or arg (setq arg 1))
  4073. (let ((orig (point))
  4074. first-vis first-vis-field-value)
  4075. ;; Move by lines, if ARG is not 1 (the default).
  4076. (if (/= arg 1)
  4077. (let ((line-move-visual nil))
  4078. (line-move (1- arg) t)))
  4079. ;; Move to beginning-of-line, ignoring fields and invisibles.
  4080. (skip-chars-backward "^\n")
  4081. (while (and (not (bobp)) (invisible-p (1- (point))))
  4082. (goto-char (previous-char-property-change (point)))
  4083. (skip-chars-backward "^\n"))
  4084. ;; Now find first visible char in the line
  4085. (while (and (not (eobp)) (invisible-p (point)))
  4086. (goto-char (next-char-property-change (point))))
  4087. (setq first-vis (point))
  4088. ;; See if fields would stop us from reaching FIRST-VIS.
  4089. (setq first-vis-field-value
  4090. (constrain-to-field first-vis orig (/= arg 1) t nil))
  4091. (goto-char (if (/= first-vis-field-value first-vis)
  4092. ;; If yes, obey them.
  4093. first-vis-field-value
  4094. ;; Otherwise, move to START with attention to fields.
  4095. ;; (It is possible that fields never matter in this case.)
  4096. (constrain-to-field (point) orig
  4097. (/= arg 1) t nil)))))
  4098. ;; Many people have said they rarely use this feature, and often type
  4099. ;; it by accident. Maybe it shouldn't even be on a key.
  4100. (put 'set-goal-column 'disabled t)
  4101. (defun set-goal-column (arg)
  4102. "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
  4103. Those commands will move to this position in the line moved to
  4104. rather than trying to keep the same horizontal position.
  4105. With a non-nil argument ARG, clears out the goal column
  4106. so that \\[next-line] and \\[previous-line] resume vertical motion.
  4107. The goal column is stored in the variable `goal-column'."
  4108. (interactive "P")
  4109. (if arg
  4110. (progn
  4111. (setq goal-column nil)
  4112. (message "No goal column"))
  4113. (setq goal-column (current-column))
  4114. ;; The older method below can be erroneous if `set-goal-column' is bound
  4115. ;; to a sequence containing %
  4116. ;;(message (substitute-command-keys
  4117. ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
  4118. ;;goal-column)
  4119. (message "%s"
  4120. (concat
  4121. (format "Goal column %d " goal-column)
  4122. (substitute-command-keys
  4123. "(use \\[set-goal-column] with an arg to unset it)")))
  4124. )
  4125. nil)
  4126. ;;; Editing based on visual lines, as opposed to logical lines.
  4127. (defun end-of-visual-line (&optional n)
  4128. "Move point to end of current visual line.
  4129. With argument N not nil or 1, move forward N - 1 visual lines first.
  4130. If point reaches the beginning or end of buffer, it stops there.
  4131. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  4132. (interactive "^p")
  4133. (or n (setq n 1))
  4134. (if (/= n 1)
  4135. (let ((line-move-visual t))
  4136. (line-move (1- n) t)))
  4137. ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
  4138. ;; constrain to field boundaries, so we don't either.
  4139. (vertical-motion (cons (window-width) 0)))
  4140. (defun beginning-of-visual-line (&optional n)
  4141. "Move point to beginning of current visual line.
  4142. With argument N not nil or 1, move forward N - 1 visual lines first.
  4143. If point reaches the beginning or end of buffer, it stops there.
  4144. To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
  4145. (interactive "^p")
  4146. (or n (setq n 1))
  4147. (let ((opoint (point)))
  4148. (if (/= n 1)
  4149. (let ((line-move-visual t))
  4150. (line-move (1- n) t)))
  4151. (vertical-motion 0)
  4152. ;; Constrain to field boundaries, like `move-beginning-of-line'.
  4153. (goto-char (constrain-to-field (point) opoint (/= n 1)))))
  4154. (defun kill-visual-line (&optional arg)
  4155. "Kill the rest of the visual line.
  4156. With prefix argument ARG, kill that many visual lines from point.
  4157. If ARG is negative, kill visual lines backward.
  4158. If ARG is zero, kill the text before point on the current visual
  4159. line.
  4160. If you want to append the killed line to the last killed text,
  4161. use \\[append-next-kill] before \\[kill-line].
  4162. If the buffer is read-only, Emacs will beep and refrain from deleting
  4163. the line, but put the line in the kill ring anyway. This means that
  4164. you can use this command to copy text from a read-only buffer.
  4165. \(If the variable `kill-read-only-ok' is non-nil, then this won't
  4166. even beep.)"
  4167. (interactive "P")
  4168. ;; Like in `kill-line', it's better to move point to the other end
  4169. ;; of the kill before killing.
  4170. (let ((opoint (point))
  4171. (kill-whole-line (and kill-whole-line (bolp))))
  4172. (if arg
  4173. (vertical-motion (prefix-numeric-value arg))
  4174. (end-of-visual-line 1)
  4175. (if (= (point) opoint)
  4176. (vertical-motion 1)
  4177. ;; Skip any trailing whitespace at the end of the visual line.
  4178. ;; We used to do this only if `show-trailing-whitespace' is
  4179. ;; nil, but that's wrong; the correct thing would be to check
  4180. ;; whether the trailing whitespace is highlighted. But, it's
  4181. ;; OK to just do this unconditionally.
  4182. (skip-chars-forward " \t")))
  4183. (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
  4184. (1+ (point))
  4185. (point)))))
  4186. (defun next-logical-line (&optional arg try-vscroll)
  4187. "Move cursor vertically down ARG lines.
  4188. This is identical to `next-line', except that it always moves
  4189. by logical lines instead of visual lines, ignoring the value of
  4190. the variable `line-move-visual'."
  4191. (interactive "^p\np")
  4192. (let ((line-move-visual nil))
  4193. (with-no-warnings
  4194. (next-line arg try-vscroll))))
  4195. (defun previous-logical-line (&optional arg try-vscroll)
  4196. "Move cursor vertically up ARG lines.
  4197. This is identical to `previous-line', except that it always moves
  4198. by logical lines instead of visual lines, ignoring the value of
  4199. the variable `line-move-visual'."
  4200. (interactive "^p\np")
  4201. (let ((line-move-visual nil))
  4202. (with-no-warnings
  4203. (previous-line arg try-vscroll))))
  4204. (defgroup visual-line nil
  4205. "Editing based on visual lines."
  4206. :group 'convenience
  4207. :version "23.1")
  4208. (defvar visual-line-mode-map
  4209. (let ((map (make-sparse-keymap)))
  4210. (define-key map [remap kill-line] 'kill-visual-line)
  4211. (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
  4212. (define-key map [remap move-end-of-line] 'end-of-visual-line)
  4213. ;; These keybindings interfere with xterm function keys. Are
  4214. ;; there any other suitable bindings?
  4215. ;; (define-key map "\M-[" 'previous-logical-line)
  4216. ;; (define-key map "\M-]" 'next-logical-line)
  4217. map))
  4218. (defcustom visual-line-fringe-indicators '(nil nil)
  4219. "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
  4220. The value should be a list of the form (LEFT RIGHT), where LEFT
  4221. and RIGHT are symbols representing the bitmaps to display, to
  4222. indicate wrapped lines, in the left and right fringes respectively.
  4223. See also `fringe-indicator-alist'.
  4224. The default is not to display fringe indicators for wrapped lines.
  4225. This variable does not affect fringe indicators displayed for
  4226. other purposes."
  4227. :type '(list (choice (const :tag "Hide left indicator" nil)
  4228. (const :tag "Left curly arrow" left-curly-arrow)
  4229. (symbol :tag "Other bitmap"))
  4230. (choice (const :tag "Hide right indicator" nil)
  4231. (const :tag "Right curly arrow" right-curly-arrow)
  4232. (symbol :tag "Other bitmap")))
  4233. :set (lambda (symbol value)
  4234. (dolist (buf (buffer-list))
  4235. (with-current-buffer buf
  4236. (when (and (boundp 'visual-line-mode)
  4237. (symbol-value 'visual-line-mode))
  4238. (setq fringe-indicator-alist
  4239. (cons (cons 'continuation value)
  4240. (assq-delete-all
  4241. 'continuation
  4242. (copy-tree fringe-indicator-alist)))))))
  4243. (set-default symbol value)))
  4244. (defvar visual-line--saved-state nil)
  4245. (define-minor-mode visual-line-mode
  4246. "Redefine simple editing commands to act on visual lines, not logical lines.
  4247. This also turns on `word-wrap' in the buffer."
  4248. :keymap visual-line-mode-map
  4249. :group 'visual-line
  4250. :lighter " Wrap"
  4251. (if visual-line-mode
  4252. (progn
  4253. (set (make-local-variable 'visual-line--saved-state) nil)
  4254. ;; Save the local values of some variables, to be restored if
  4255. ;; visual-line-mode is turned off.
  4256. (dolist (var '(line-move-visual truncate-lines
  4257. truncate-partial-width-windows
  4258. word-wrap fringe-indicator-alist))
  4259. (if (local-variable-p var)
  4260. (push (cons var (symbol-value var))
  4261. visual-line--saved-state)))
  4262. (set (make-local-variable 'line-move-visual) t)
  4263. (set (make-local-variable 'truncate-partial-width-windows) nil)
  4264. (setq truncate-lines nil
  4265. word-wrap t
  4266. fringe-indicator-alist
  4267. (cons (cons 'continuation visual-line-fringe-indicators)
  4268. fringe-indicator-alist)))
  4269. (kill-local-variable 'line-move-visual)
  4270. (kill-local-variable 'word-wrap)
  4271. (kill-local-variable 'truncate-lines)
  4272. (kill-local-variable 'truncate-partial-width-windows)
  4273. (kill-local-variable 'fringe-indicator-alist)
  4274. (dolist (saved visual-line--saved-state)
  4275. (set (make-local-variable (car saved)) (cdr saved)))
  4276. (kill-local-variable 'visual-line--saved-state)))
  4277. (defun turn-on-visual-line-mode ()
  4278. (visual-line-mode 1))
  4279. (define-globalized-minor-mode global-visual-line-mode
  4280. visual-line-mode turn-on-visual-line-mode
  4281. :lighter " vl")
  4282. (defun transpose-chars (arg)
  4283. "Interchange characters around point, moving forward one character.
  4284. With prefix arg ARG, effect is to take character before point
  4285. and drag it forward past ARG other characters (backward if ARG negative).
  4286. If no argument and at end of line, the previous two chars are exchanged."
  4287. (interactive "*P")
  4288. (and (null arg) (eolp) (forward-char -1))
  4289. (transpose-subr 'forward-char (prefix-numeric-value arg)))
  4290. (defun transpose-words (arg)
  4291. "Interchange words around point, leaving point at end of them.
  4292. With prefix arg ARG, effect is to take word before or around point
  4293. and drag it forward past ARG other words (backward if ARG negative).
  4294. If ARG is zero, the words around or after point and around or after mark
  4295. are interchanged."
  4296. ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
  4297. (interactive "*p")
  4298. (transpose-subr 'forward-word arg))
  4299. (defun transpose-sexps (arg)
  4300. "Like \\[transpose-words] but applies to sexps.
  4301. Does not work on a sexp that point is in the middle of
  4302. if it is a list or string."
  4303. (interactive "*p")
  4304. (transpose-subr
  4305. (lambda (arg)
  4306. ;; Here we should try to simulate the behavior of
  4307. ;; (cons (progn (forward-sexp x) (point))
  4308. ;; (progn (forward-sexp (- x)) (point)))
  4309. ;; Except that we don't want to rely on the second forward-sexp
  4310. ;; putting us back to where we want to be, since forward-sexp-function
  4311. ;; might do funny things like infix-precedence.
  4312. (if (if (> arg 0)
  4313. (looking-at "\\sw\\|\\s_")
  4314. (and (not (bobp))
  4315. (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
  4316. ;; Jumping over a symbol. We might be inside it, mind you.
  4317. (progn (funcall (if (> arg 0)
  4318. 'skip-syntax-backward 'skip-syntax-forward)
  4319. "w_")
  4320. (cons (save-excursion (forward-sexp arg) (point)) (point)))
  4321. ;; Otherwise, we're between sexps. Take a step back before jumping
  4322. ;; to make sure we'll obey the same precedence no matter which direction
  4323. ;; we're going.
  4324. (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
  4325. (cons (save-excursion (forward-sexp arg) (point))
  4326. (progn (while (or (forward-comment (if (> arg 0) 1 -1))
  4327. (not (zerop (funcall (if (> arg 0)
  4328. 'skip-syntax-forward
  4329. 'skip-syntax-backward)
  4330. ".")))))
  4331. (point)))))
  4332. arg 'special))
  4333. (defun transpose-lines (arg)
  4334. "Exchange current line and previous line, leaving point after both.
  4335. With argument ARG, takes previous line and moves it past ARG lines.
  4336. With argument 0, interchanges line point is in with line mark is in."
  4337. (interactive "*p")
  4338. (transpose-subr (function
  4339. (lambda (arg)
  4340. (if (> arg 0)
  4341. (progn
  4342. ;; Move forward over ARG lines,
  4343. ;; but create newlines if necessary.
  4344. (setq arg (forward-line arg))
  4345. (if (/= (preceding-char) ?\n)
  4346. (setq arg (1+ arg)))
  4347. (if (> arg 0)
  4348. (newline arg)))
  4349. (forward-line arg))))
  4350. arg))
  4351. ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
  4352. ;; which seems inconsistent with the ARG /= 0 case.
  4353. ;; FIXME document SPECIAL.
  4354. (defun transpose-subr (mover arg &optional special)
  4355. "Subroutine to do the work of transposing objects.
  4356. Works for lines, sentences, paragraphs, etc. MOVER is a function that
  4357. moves forward by units of the given object (e.g. forward-sentence,
  4358. forward-paragraph). If ARG is zero, exchanges the current object
  4359. with the one containing mark. If ARG is an integer, moves the
  4360. current object past ARG following (if ARG is positive) or
  4361. preceding (if ARG is negative) objects, leaving point after the
  4362. current object."
  4363. (let ((aux (if special mover
  4364. (lambda (x)
  4365. (cons (progn (funcall mover x) (point))
  4366. (progn (funcall mover (- x)) (point))))))
  4367. pos1 pos2)
  4368. (cond
  4369. ((= arg 0)
  4370. (save-excursion
  4371. (setq pos1 (funcall aux 1))
  4372. (goto-char (or (mark) (error "No mark set in this buffer")))
  4373. (setq pos2 (funcall aux 1))
  4374. (transpose-subr-1 pos1 pos2))
  4375. (exchange-point-and-mark))
  4376. ((> arg 0)
  4377. (setq pos1 (funcall aux -1))
  4378. (setq pos2 (funcall aux arg))
  4379. (transpose-subr-1 pos1 pos2)
  4380. (goto-char (car pos2)))
  4381. (t
  4382. (setq pos1 (funcall aux -1))
  4383. (goto-char (car pos1))
  4384. (setq pos2 (funcall aux arg))
  4385. (transpose-subr-1 pos1 pos2)))))
  4386. (defun transpose-subr-1 (pos1 pos2)
  4387. (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
  4388. (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
  4389. (when (> (car pos1) (car pos2))
  4390. (let ((swap pos1))
  4391. (setq pos1 pos2 pos2 swap)))
  4392. (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
  4393. (atomic-change-group
  4394. (let (word2)
  4395. ;; FIXME: We first delete the two pieces of text, so markers that
  4396. ;; used to point to after the text end up pointing to before it :-(
  4397. (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
  4398. (goto-char (car pos2))
  4399. (insert (delete-and-extract-region (car pos1) (cdr pos1)))
  4400. (goto-char (car pos1))
  4401. (insert word2))))
  4402. (defun backward-word (&optional arg)
  4403. "Move backward until encountering the beginning of a word.
  4404. With argument ARG, do this that many times."
  4405. (interactive "^p")
  4406. (forward-word (- (or arg 1))))
  4407. (defun mark-word (&optional arg allow-extend)
  4408. "Set mark ARG words away from point.
  4409. The place mark goes is the same place \\[forward-word] would
  4410. move to with the same argument.
  4411. Interactively, if this command is repeated
  4412. or (in Transient Mark mode) if the mark is active,
  4413. it marks the next ARG words after the ones already marked."
  4414. (interactive "P\np")
  4415. (cond ((and allow-extend
  4416. (or (and (eq last-command this-command) (mark t))
  4417. (region-active-p)))
  4418. (setq arg (if arg (prefix-numeric-value arg)
  4419. (if (< (mark) (point)) -1 1)))
  4420. (set-mark
  4421. (save-excursion
  4422. (goto-char (mark))
  4423. (forward-word arg)
  4424. (point))))
  4425. (t
  4426. (push-mark
  4427. (save-excursion
  4428. (forward-word (prefix-numeric-value arg))
  4429. (point))
  4430. nil t))))
  4431. (defun kill-word (arg)
  4432. "Kill characters forward until encountering the end of a word.
  4433. With argument ARG, do this that many times."
  4434. (interactive "p")
  4435. (kill-region (point) (progn (forward-word arg) (point))))
  4436. (defun backward-kill-word (arg)
  4437. "Kill characters backward until encountering the beginning of a word.
  4438. With argument ARG, do this that many times."
  4439. (interactive "p")
  4440. (kill-word (- arg)))
  4441. (defun current-word (&optional strict really-word)
  4442. "Return the symbol or word that point is on (or a nearby one) as a string.
  4443. The return value includes no text properties.
  4444. If optional arg STRICT is non-nil, return nil unless point is within
  4445. or adjacent to a symbol or word. In all cases the value can be nil
  4446. if there is no word nearby.
  4447. The function, belying its name, normally finds a symbol.
  4448. If optional arg REALLY-WORD is non-nil, it finds just a word."
  4449. (save-excursion
  4450. (let* ((oldpoint (point)) (start (point)) (end (point))
  4451. (syntaxes (if really-word "w" "w_"))
  4452. (not-syntaxes (concat "^" syntaxes)))
  4453. (skip-syntax-backward syntaxes) (setq start (point))
  4454. (goto-char oldpoint)
  4455. (skip-syntax-forward syntaxes) (setq end (point))
  4456. (when (and (eq start oldpoint) (eq end oldpoint)
  4457. ;; Point is neither within nor adjacent to a word.
  4458. (not strict))
  4459. ;; Look for preceding word in same line.
  4460. (skip-syntax-backward not-syntaxes
  4461. (save-excursion (beginning-of-line)
  4462. (point)))
  4463. (if (bolp)
  4464. ;; No preceding word in same line.
  4465. ;; Look for following word in same line.
  4466. (progn
  4467. (skip-syntax-forward not-syntaxes
  4468. (save-excursion (end-of-line)
  4469. (point)))
  4470. (setq start (point))
  4471. (skip-syntax-forward syntaxes)
  4472. (setq end (point)))
  4473. (setq end (point))
  4474. (skip-syntax-backward syntaxes)
  4475. (setq start (point))))
  4476. ;; If we found something nonempty, return it as a string.
  4477. (unless (= start end)
  4478. (buffer-substring-no-properties start end)))))
  4479. (defcustom fill-prefix nil
  4480. "String for filling to insert at front of new line, or nil for none."
  4481. :type '(choice (const :tag "None" nil)
  4482. string)
  4483. :group 'fill)
  4484. (make-variable-buffer-local 'fill-prefix)
  4485. (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
  4486. (defcustom auto-fill-inhibit-regexp nil
  4487. "Regexp to match lines which should not be auto-filled."
  4488. :type '(choice (const :tag "None" nil)
  4489. regexp)
  4490. :group 'fill)
  4491. ;; This function is used as the auto-fill-function of a buffer
  4492. ;; when Auto-Fill mode is enabled.
  4493. ;; It returns t if it really did any work.
  4494. ;; (Actually some major modes use a different auto-fill function,
  4495. ;; but this one is the default one.)
  4496. (defun do-auto-fill ()
  4497. (let (fc justify give-up
  4498. (fill-prefix fill-prefix))
  4499. (if (or (not (setq justify (current-justification)))
  4500. (null (setq fc (current-fill-column)))
  4501. (and (eq justify 'left)
  4502. (<= (current-column) fc))
  4503. (and auto-fill-inhibit-regexp
  4504. (save-excursion (beginning-of-line)
  4505. (looking-at auto-fill-inhibit-regexp))))
  4506. nil ;; Auto-filling not required
  4507. (if (memq justify '(full center right))
  4508. (save-excursion (unjustify-current-line)))
  4509. ;; Choose a fill-prefix automatically.
  4510. (when (and adaptive-fill-mode
  4511. (or (null fill-prefix) (string= fill-prefix "")))
  4512. (let ((prefix
  4513. (fill-context-prefix
  4514. (save-excursion (backward-paragraph 1) (point))
  4515. (save-excursion (forward-paragraph 1) (point)))))
  4516. (and prefix (not (equal prefix ""))
  4517. ;; Use auto-indentation rather than a guessed empty prefix.
  4518. (not (and fill-indent-according-to-mode
  4519. (string-match "\\`[ \t]*\\'" prefix)))
  4520. (setq fill-prefix prefix))))
  4521. (while (and (not give-up) (> (current-column) fc))
  4522. ;; Determine where to split the line.
  4523. (let* (after-prefix
  4524. (fill-point
  4525. (save-excursion
  4526. (beginning-of-line)
  4527. (setq after-prefix (point))
  4528. (and fill-prefix
  4529. (looking-at (regexp-quote fill-prefix))
  4530. (setq after-prefix (match-end 0)))
  4531. (move-to-column (1+ fc))
  4532. (fill-move-to-break-point after-prefix)
  4533. (point))))
  4534. ;; See whether the place we found is any good.
  4535. (if (save-excursion
  4536. (goto-char fill-point)
  4537. (or (bolp)
  4538. ;; There is no use breaking at end of line.
  4539. (save-excursion (skip-chars-forward " ") (eolp))
  4540. ;; It is futile to split at the end of the prefix
  4541. ;; since we would just insert the prefix again.
  4542. (and after-prefix (<= (point) after-prefix))
  4543. ;; Don't split right after a comment starter
  4544. ;; since we would just make another comment starter.
  4545. (and comment-start-skip
  4546. (let ((limit (point)))
  4547. (beginning-of-line)
  4548. (and (re-search-forward comment-start-skip
  4549. limit t)
  4550. (eq (point) limit))))))
  4551. ;; No good place to break => stop trying.
  4552. (setq give-up t)
  4553. ;; Ok, we have a useful place to break the line. Do it.
  4554. (let ((prev-column (current-column)))
  4555. ;; If point is at the fill-point, do not `save-excursion'.
  4556. ;; Otherwise, if a comment prefix or fill-prefix is inserted,
  4557. ;; point will end up before it rather than after it.
  4558. (if (save-excursion
  4559. (skip-chars-backward " \t")
  4560. (= (point) fill-point))
  4561. (default-indent-new-line t)
  4562. (save-excursion
  4563. (goto-char fill-point)
  4564. (default-indent-new-line t)))
  4565. ;; Now do justification, if required
  4566. (if (not (eq justify 'left))
  4567. (save-excursion
  4568. (end-of-line 0)
  4569. (justify-current-line justify nil t)))
  4570. ;; If making the new line didn't reduce the hpos of
  4571. ;; the end of the line, then give up now;
  4572. ;; trying again will not help.
  4573. (if (>= (current-column) prev-column)
  4574. (setq give-up t))))))
  4575. ;; Justify last line.
  4576. (justify-current-line justify t t)
  4577. t)))
  4578. (defvar comment-line-break-function 'comment-indent-new-line
  4579. "*Mode-specific function which line breaks and continues a comment.
  4580. This function is called during auto-filling when a comment syntax
  4581. is defined.
  4582. The function should take a single optional argument, which is a flag
  4583. indicating whether it should use soft newlines.")
  4584. (defun default-indent-new-line (&optional soft)
  4585. "Break line at point and indent.
  4586. If a comment syntax is defined, call `comment-indent-new-line'.
  4587. The inserted newline is marked hard if variable `use-hard-newlines' is true,
  4588. unless optional argument SOFT is non-nil."
  4589. (interactive)
  4590. (if comment-start
  4591. (funcall comment-line-break-function soft)
  4592. ;; Insert the newline before removing empty space so that markers
  4593. ;; get preserved better.
  4594. (if soft (insert-and-inherit ?\n) (newline 1))
  4595. (save-excursion (forward-char -1) (delete-horizontal-space))
  4596. (delete-horizontal-space)
  4597. (if (and fill-prefix (not adaptive-fill-mode))
  4598. ;; Blindly trust a non-adaptive fill-prefix.
  4599. (progn
  4600. (indent-to-left-margin)
  4601. (insert-before-markers-and-inherit fill-prefix))
  4602. (cond
  4603. ;; If there's an adaptive prefix, use it unless we're inside
  4604. ;; a comment and the prefix is not a comment starter.
  4605. (fill-prefix
  4606. (indent-to-left-margin)
  4607. (insert-and-inherit fill-prefix))
  4608. ;; If we're not inside a comment, just try to indent.
  4609. (t (indent-according-to-mode))))))
  4610. (defvar normal-auto-fill-function 'do-auto-fill
  4611. "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
  4612. Some major modes set this.")
  4613. (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
  4614. ;; `functions' and `hooks' are usually unsafe to set, but setting
  4615. ;; auto-fill-function to nil in a file-local setting is safe and
  4616. ;; can be useful to prevent auto-filling.
  4617. (put 'auto-fill-function 'safe-local-variable 'null)
  4618. ;; FIXME: turn into a proper minor mode.
  4619. ;; Add a global minor mode version of it.
  4620. (defun auto-fill-mode (&optional arg)
  4621. "Toggle Auto Fill mode.
  4622. With ARG, turn Auto Fill mode on if and only if ARG is positive.
  4623. In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
  4624. automatically breaks the line at a previous space.
  4625. The value of `normal-auto-fill-function' specifies the function to use
  4626. for `auto-fill-function' when turning Auto Fill mode on."
  4627. (interactive "P")
  4628. (prog1 (setq auto-fill-function
  4629. (if (if (null arg)
  4630. (not auto-fill-function)
  4631. (> (prefix-numeric-value arg) 0))
  4632. normal-auto-fill-function
  4633. nil))
  4634. (force-mode-line-update)))
  4635. ;; This holds a document string used to document auto-fill-mode.
  4636. (defun auto-fill-function ()
  4637. "Automatically break line at a previous space, in insertion of text."
  4638. nil)
  4639. (defun turn-on-auto-fill ()
  4640. "Unconditionally turn on Auto Fill mode."
  4641. (auto-fill-mode 1))
  4642. (defun turn-off-auto-fill ()
  4643. "Unconditionally turn off Auto Fill mode."
  4644. (auto-fill-mode -1))
  4645. (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
  4646. (defun set-fill-column (arg)
  4647. "Set `fill-column' to specified argument.
  4648. Use \\[universal-argument] followed by a number to specify a column.
  4649. Just \\[universal-argument] as argument means to use the current column."
  4650. (interactive
  4651. (list (or current-prefix-arg
  4652. ;; We used to use current-column silently, but C-x f is too easily
  4653. ;; typed as a typo for C-x C-f, so we turned it into an error and
  4654. ;; now an interactive prompt.
  4655. (read-number "Set fill-column to: " (current-column)))))
  4656. (if (consp arg)
  4657. (setq arg (current-column)))
  4658. (if (not (integerp arg))
  4659. ;; Disallow missing argument; it's probably a typo for C-x C-f.
  4660. (error "set-fill-column requires an explicit argument")
  4661. (message "Fill column set to %d (was %d)" arg fill-column)
  4662. (setq fill-column arg)))
  4663. (defun set-selective-display (arg)
  4664. "Set `selective-display' to ARG; clear it if no arg.
  4665. When the value of `selective-display' is a number > 0,
  4666. lines whose indentation is >= that value are not displayed.
  4667. The variable `selective-display' has a separate value for each buffer."
  4668. (interactive "P")
  4669. (if (eq selective-display t)
  4670. (error "selective-display already in use for marked lines"))
  4671. (let ((current-vpos
  4672. (save-restriction
  4673. (narrow-to-region (point-min) (point))
  4674. (goto-char (window-start))
  4675. (vertical-motion (window-height)))))
  4676. (setq selective-display
  4677. (and arg (prefix-numeric-value arg)))
  4678. (recenter current-vpos))
  4679. (set-window-start (selected-window) (window-start (selected-window)))
  4680. (princ "selective-display set to " t)
  4681. (prin1 selective-display t)
  4682. (princ "." t))
  4683. (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
  4684. (defun toggle-truncate-lines (&optional arg)
  4685. "Toggle whether to fold or truncate long lines for the current buffer.
  4686. With prefix argument ARG, truncate long lines if ARG is positive,
  4687. otherwise don't truncate them. Note that in side-by-side windows,
  4688. this command has no effect if `truncate-partial-width-windows'
  4689. is non-nil."
  4690. (interactive "P")
  4691. (setq truncate-lines
  4692. (if (null arg)
  4693. (not truncate-lines)
  4694. (> (prefix-numeric-value arg) 0)))
  4695. (force-mode-line-update)
  4696. (unless truncate-lines
  4697. (let ((buffer (current-buffer)))
  4698. (walk-windows (lambda (window)
  4699. (if (eq buffer (window-buffer window))
  4700. (set-window-hscroll window 0)))
  4701. nil t)))
  4702. (message "Truncate long lines %s"
  4703. (if truncate-lines "enabled" "disabled")))
  4704. (defun toggle-word-wrap (&optional arg)
  4705. "Toggle whether to use word-wrapping for continuation lines.
  4706. With prefix argument ARG, wrap continuation lines at word boundaries
  4707. if ARG is positive, otherwise wrap them at the right screen edge.
  4708. This command toggles the value of `word-wrap'. It has no effect
  4709. if long lines are truncated."
  4710. (interactive "P")
  4711. (setq word-wrap
  4712. (if (null arg)
  4713. (not word-wrap)
  4714. (> (prefix-numeric-value arg) 0)))
  4715. (force-mode-line-update)
  4716. (message "Word wrapping %s"
  4717. (if word-wrap "enabled" "disabled")))
  4718. (defvar overwrite-mode-textual (purecopy " Ovwrt")
  4719. "The string displayed in the mode line when in overwrite mode.")
  4720. (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
  4721. "The string displayed in the mode line when in binary overwrite mode.")
  4722. (defun overwrite-mode (arg)
  4723. "Toggle overwrite mode.
  4724. With prefix argument ARG, turn overwrite mode on if ARG is positive,
  4725. otherwise turn it off. In overwrite mode, printing characters typed
  4726. in replace existing text on a one-for-one basis, rather than pushing
  4727. it to the right. At the end of a line, such characters extend the line.
  4728. Before a tab, such characters insert until the tab is filled in.
  4729. \\[quoted-insert] still inserts characters in overwrite mode; this
  4730. is supposed to make it easier to insert characters when necessary."
  4731. (interactive "P")
  4732. (setq overwrite-mode
  4733. (if (if (null arg) (not overwrite-mode)
  4734. (> (prefix-numeric-value arg) 0))
  4735. 'overwrite-mode-textual))
  4736. (force-mode-line-update))
  4737. (defun binary-overwrite-mode (arg)
  4738. "Toggle binary overwrite mode.
  4739. With prefix argument ARG, turn binary overwrite mode on if ARG is
  4740. positive, otherwise turn it off. In binary overwrite mode, printing
  4741. characters typed in replace existing text. Newlines are not treated
  4742. specially, so typing at the end of a line joins the line to the next,
  4743. with the typed character between them. Typing before a tab character
  4744. simply replaces the tab with the character typed. \\[quoted-insert]
  4745. replaces the text at the cursor, just as ordinary typing characters do.
  4746. Note that binary overwrite mode is not its own minor mode; it is a
  4747. specialization of overwrite mode, entered by setting the
  4748. `overwrite-mode' variable to `overwrite-mode-binary'."
  4749. (interactive "P")
  4750. (setq overwrite-mode
  4751. (if (if (null arg)
  4752. (not (eq overwrite-mode 'overwrite-mode-binary))
  4753. (> (prefix-numeric-value arg) 0))
  4754. 'overwrite-mode-binary))
  4755. (force-mode-line-update))
  4756. (define-minor-mode line-number-mode
  4757. "Toggle Line Number mode.
  4758. With ARG, turn Line Number mode on if ARG is positive, otherwise
  4759. turn it off. When Line Number mode is enabled, the line number
  4760. appears in the mode line.
  4761. Line numbers do not appear for very large buffers and buffers
  4762. with very long lines; see variables `line-number-display-limit'
  4763. and `line-number-display-limit-width'."
  4764. :init-value t :global t :group 'mode-line)
  4765. (define-minor-mode column-number-mode
  4766. "Toggle Column Number mode.
  4767. With ARG, turn Column Number mode on if ARG is positive,
  4768. otherwise turn it off. When Column Number mode is enabled, the
  4769. column number appears in the mode line."
  4770. :global t :group 'mode-line)
  4771. (define-minor-mode size-indication-mode
  4772. "Toggle Size Indication mode.
  4773. With ARG, turn Size Indication mode on if ARG is positive,
  4774. otherwise turn it off. When Size Indication mode is enabled, the
  4775. size of the accessible part of the buffer appears in the mode line."
  4776. :global t :group 'mode-line)
  4777. (defgroup paren-blinking nil
  4778. "Blinking matching of parens and expressions."
  4779. :prefix "blink-matching-"
  4780. :group 'paren-matching)
  4781. (defcustom blink-matching-paren t
  4782. "Non-nil means show matching open-paren when close-paren is inserted."
  4783. :type 'boolean
  4784. :group 'paren-blinking)
  4785. (defcustom blink-matching-paren-on-screen t
  4786. "Non-nil means show matching open-paren when it is on screen.
  4787. If nil, don't show it (but the open-paren can still be shown
  4788. when it is off screen).
  4789. This variable has no effect if `blink-matching-paren' is nil.
  4790. \(In that case, the open-paren is never shown.)
  4791. It is also ignored if `show-paren-mode' is enabled."
  4792. :type 'boolean
  4793. :group 'paren-blinking)
  4794. (defcustom blink-matching-paren-distance (* 100 1024)
  4795. "If non-nil, maximum distance to search backwards for matching open-paren.
  4796. If nil, search stops at the beginning of the accessible portion of the buffer."
  4797. :version "23.2" ; 25->100k
  4798. :type '(choice (const nil) integer)
  4799. :group 'paren-blinking)
  4800. (defcustom blink-matching-delay 1
  4801. "Time in seconds to delay after showing a matching paren."
  4802. :type 'number
  4803. :group 'paren-blinking)
  4804. (defcustom blink-matching-paren-dont-ignore-comments nil
  4805. "If nil, `blink-matching-paren' ignores comments.
  4806. More precisely, when looking for the matching parenthesis,
  4807. it skips the contents of comments that end before point."
  4808. :type 'boolean
  4809. :group 'paren-blinking)
  4810. (defun blink-matching-open ()
  4811. "Move cursor momentarily to the beginning of the sexp before point."
  4812. (interactive)
  4813. (when (and (> (point) (point-min))
  4814. blink-matching-paren
  4815. ;; Verify an even number of quoting characters precede the close.
  4816. (= 1 (logand 1 (- (point)
  4817. (save-excursion
  4818. (forward-char -1)
  4819. (skip-syntax-backward "/\\")
  4820. (point))))))
  4821. (let* ((oldpos (point))
  4822. (message-log-max nil) ; Don't log messages about paren matching.
  4823. (atdollar (eq (syntax-class (syntax-after (1- oldpos))) 8))
  4824. (isdollar)
  4825. (blinkpos
  4826. (save-excursion
  4827. (save-restriction
  4828. (if blink-matching-paren-distance
  4829. (narrow-to-region
  4830. (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
  4831. (- (point) blink-matching-paren-distance))
  4832. oldpos))
  4833. (let ((parse-sexp-ignore-comments
  4834. (and parse-sexp-ignore-comments
  4835. (not blink-matching-paren-dont-ignore-comments))))
  4836. (condition-case ()
  4837. (scan-sexps oldpos -1)
  4838. (error nil))))))
  4839. (matching-paren
  4840. (and blinkpos
  4841. ;; Not syntax '$'.
  4842. (not (setq isdollar
  4843. (eq (syntax-class (syntax-after blinkpos)) 8)))
  4844. (let ((syntax (syntax-after blinkpos)))
  4845. (and (consp syntax)
  4846. (eq (syntax-class syntax) 4)
  4847. (cdr syntax))))))
  4848. (cond
  4849. ;; isdollar is for:
  4850. ;; http://lists.gnu.org/archive/html/emacs-devel/2007-10/msg00871.html
  4851. ((not (or (and isdollar blinkpos)
  4852. (and atdollar (not blinkpos)) ; see below
  4853. (eq matching-paren (char-before oldpos))
  4854. ;; The cdr might hold a new paren-class info rather than
  4855. ;; a matching-char info, in which case the two CDRs
  4856. ;; should match.
  4857. (eq matching-paren (cdr (syntax-after (1- oldpos))))))
  4858. (if (minibufferp)
  4859. (minibuffer-message " [Mismatched parentheses]")
  4860. (message "Mismatched parentheses")))
  4861. ((not blinkpos)
  4862. (or blink-matching-paren-distance
  4863. ;; Don't complain when `$' with no blinkpos, because it
  4864. ;; could just be the first one typed in the buffer.
  4865. atdollar
  4866. (if (minibufferp)
  4867. (minibuffer-message " [Unmatched parenthesis]")
  4868. (message "Unmatched parenthesis"))))
  4869. ((pos-visible-in-window-p blinkpos)
  4870. ;; Matching open within window, temporarily move to blinkpos but only
  4871. ;; if `blink-matching-paren-on-screen' is non-nil.
  4872. (and blink-matching-paren-on-screen
  4873. (not show-paren-mode)
  4874. (save-excursion
  4875. (goto-char blinkpos)
  4876. (sit-for blink-matching-delay))))
  4877. (t
  4878. (save-excursion
  4879. (goto-char blinkpos)
  4880. (let ((open-paren-line-string
  4881. ;; Show what precedes the open in its line, if anything.
  4882. (cond
  4883. ((save-excursion (skip-chars-backward " \t") (not (bolp)))
  4884. (buffer-substring (line-beginning-position)
  4885. (1+ blinkpos)))
  4886. ;; Show what follows the open in its line, if anything.
  4887. ((save-excursion
  4888. (forward-char 1)
  4889. (skip-chars-forward " \t")
  4890. (not (eolp)))
  4891. (buffer-substring blinkpos
  4892. (line-end-position)))
  4893. ;; Otherwise show the previous nonblank line,
  4894. ;; if there is one.
  4895. ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
  4896. (concat
  4897. (buffer-substring (progn
  4898. (skip-chars-backward "\n \t")
  4899. (line-beginning-position))
  4900. (progn (end-of-line)
  4901. (skip-chars-backward " \t")
  4902. (point)))
  4903. ;; Replace the newline and other whitespace with `...'.
  4904. "..."
  4905. (buffer-substring blinkpos (1+ blinkpos))))
  4906. ;; There is nothing to show except the char itself.
  4907. (t (buffer-substring blinkpos (1+ blinkpos))))))
  4908. (message "Matches %s"
  4909. (substring-no-properties open-paren-line-string)))))))))
  4910. (setq blink-paren-function 'blink-matching-open)
  4911. ;; This executes C-g typed while Emacs is waiting for a command.
  4912. ;; Quitting out of a program does not go through here;
  4913. ;; that happens in the QUIT macro at the C code level.
  4914. (defun keyboard-quit ()
  4915. "Signal a `quit' condition.
  4916. During execution of Lisp code, this character causes a quit directly.
  4917. At top-level, as an editor command, this simply beeps."
  4918. (interactive)
  4919. (deactivate-mark)
  4920. (if (fboundp 'kmacro-keyboard-quit)
  4921. (kmacro-keyboard-quit))
  4922. (setq defining-kbd-macro nil)
  4923. (signal 'quit nil))
  4924. (defvar buffer-quit-function nil
  4925. "Function to call to \"quit\" the current buffer, or nil if none.
  4926. \\[keyboard-escape-quit] calls this function when its more local actions
  4927. \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
  4928. (defun keyboard-escape-quit ()
  4929. "Exit the current \"mode\" (in a generalized sense of the word).
  4930. This command can exit an interactive command such as `query-replace',
  4931. can clear out a prefix argument or a region,
  4932. can get out of the minibuffer or other recursive edit,
  4933. cancel the use of the current buffer (for special-purpose buffers),
  4934. or go back to just one window (by deleting all but the selected window)."
  4935. (interactive)
  4936. (cond ((eq last-command 'mode-exited) nil)
  4937. ((region-active-p)
  4938. (deactivate-mark))
  4939. ((> (minibuffer-depth) 0)
  4940. (abort-recursive-edit))
  4941. (current-prefix-arg
  4942. nil)
  4943. ((> (recursion-depth) 0)
  4944. (exit-recursive-edit))
  4945. (buffer-quit-function
  4946. (funcall buffer-quit-function))
  4947. ((not (one-window-p t))
  4948. (delete-other-windows))
  4949. ((string-match "^ \\*" (buffer-name (current-buffer)))
  4950. (bury-buffer))))
  4951. (defun play-sound-file (file &optional volume device)
  4952. "Play sound stored in FILE.
  4953. VOLUME and DEVICE correspond to the keywords of the sound
  4954. specification for `play-sound'."
  4955. (interactive "fPlay sound file: ")
  4956. (let ((sound (list :file file)))
  4957. (if volume
  4958. (plist-put sound :volume volume))
  4959. (if device
  4960. (plist-put sound :device device))
  4961. (push 'sound sound)
  4962. (play-sound sound)))
  4963. (defcustom read-mail-command 'rmail
  4964. "Your preference for a mail reading package.
  4965. This is used by some keybindings which support reading mail.
  4966. See also `mail-user-agent' concerning sending mail."
  4967. :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
  4968. (function-item :tag "Gnus" :format "%t\n" gnus)
  4969. (function-item :tag "Emacs interface to MH"
  4970. :format "%t\n" mh-rmail)
  4971. (function :tag "Other"))
  4972. :version "21.1"
  4973. :group 'mail)
  4974. (defcustom mail-user-agent 'message-user-agent
  4975. "Your preference for a mail composition package.
  4976. Various Emacs Lisp packages (e.g. Reporter) require you to compose an
  4977. outgoing email message. This variable lets you specify which
  4978. mail-sending package you prefer.
  4979. Valid values include:
  4980. `message-user-agent' -- use the Message package.
  4981. See Info node `(message)'.
  4982. `sendmail-user-agent' -- use the Mail package.
  4983. See Info node `(emacs)Sending Mail'.
  4984. `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
  4985. See Info node `(mh-e)'.
  4986. `gnus-user-agent' -- like `message-user-agent', but with Gnus
  4987. paraphernalia, particularly the Gcc: header for
  4988. archiving.
  4989. Additional valid symbols may be available; check with the author of
  4990. your package for details. The function should return non-nil if it
  4991. succeeds.
  4992. See also `read-mail-command' concerning reading mail."
  4993. :type '(radio (function-item :tag "Message package"
  4994. :format "%t\n"
  4995. message-user-agent)
  4996. (function-item :tag "Mail package"
  4997. :format "%t\n"
  4998. sendmail-user-agent)
  4999. (function-item :tag "Emacs interface to MH"
  5000. :format "%t\n"
  5001. mh-e-user-agent)
  5002. (function-item :tag "Message with full Gnus features"
  5003. :format "%t\n"
  5004. gnus-user-agent)
  5005. (function :tag "Other"))
  5006. :version "23.2" ; sendmail->message
  5007. :group 'mail)
  5008. (defcustom compose-mail-user-agent-warnings t
  5009. "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
  5010. If the value of `mail-user-agent' is the default, and the user
  5011. appears to have customizations applying to the old default,
  5012. `compose-mail' issues a warning."
  5013. :type 'boolean
  5014. :version "23.2"
  5015. :group 'mail)
  5016. (define-mail-user-agent 'sendmail-user-agent
  5017. 'sendmail-user-agent-compose
  5018. 'mail-send-and-exit)
  5019. (defun rfc822-goto-eoh ()
  5020. ;; Go to header delimiter line in a mail message, following RFC822 rules
  5021. (goto-char (point-min))
  5022. (when (re-search-forward
  5023. "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
  5024. (goto-char (match-beginning 0))))
  5025. (defun sendmail-user-agent-compose (&optional to subject other-headers continue
  5026. switch-function yank-action
  5027. send-actions)
  5028. (if switch-function
  5029. (let ((special-display-buffer-names nil)
  5030. (special-display-regexps nil)
  5031. (same-window-buffer-names nil)
  5032. (same-window-regexps nil))
  5033. (funcall switch-function "*mail*")))
  5034. (let ((cc (cdr (assoc-string "cc" other-headers t)))
  5035. (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
  5036. (body (cdr (assoc-string "body" other-headers t))))
  5037. (or (mail continue to subject in-reply-to cc yank-action send-actions)
  5038. continue
  5039. (error "Message aborted"))
  5040. (save-excursion
  5041. (rfc822-goto-eoh)
  5042. (while other-headers
  5043. (unless (member-ignore-case (car (car other-headers))
  5044. '("in-reply-to" "cc" "body"))
  5045. (insert (car (car other-headers)) ": "
  5046. (cdr (car other-headers))
  5047. (if use-hard-newlines hard-newline "\n")))
  5048. (setq other-headers (cdr other-headers)))
  5049. (when body
  5050. (forward-line 1)
  5051. (insert body))
  5052. t)))
  5053. (defun compose-mail (&optional to subject other-headers continue
  5054. switch-function yank-action send-actions)
  5055. "Start composing a mail message to send.
  5056. This uses the user's chosen mail composition package
  5057. as selected with the variable `mail-user-agent'.
  5058. The optional arguments TO and SUBJECT specify recipients
  5059. and the initial Subject field, respectively.
  5060. OTHER-HEADERS is an alist specifying additional
  5061. header fields. Elements look like (HEADER . VALUE) where both
  5062. HEADER and VALUE are strings.
  5063. CONTINUE, if non-nil, says to continue editing a message already
  5064. being composed. Interactively, CONTINUE is the prefix argument.
  5065. SWITCH-FUNCTION, if non-nil, is a function to use to
  5066. switch to and display the buffer used for mail composition.
  5067. YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
  5068. to insert the raw text of the message being replied to.
  5069. It has the form (FUNCTION . ARGS). The user agent will apply
  5070. FUNCTION to ARGS, to insert the raw text of the original message.
  5071. \(The user agent will also run `mail-citation-hook', *after* the
  5072. original text has been inserted in this way.)
  5073. SEND-ACTIONS is a list of actions to call when the message is sent.
  5074. Each action has the form (FUNCTION . ARGS)."
  5075. (interactive
  5076. (list nil nil nil current-prefix-arg))
  5077. ;; In Emacs 23.2, the default value of `mail-user-agent' changed
  5078. ;; from sendmail-user-agent to message-user-agent. Some users may
  5079. ;; encounter incompatibilities. This hack tries to detect problems
  5080. ;; and warn about them.
  5081. (and compose-mail-user-agent-warnings
  5082. (eq mail-user-agent 'message-user-agent)
  5083. (let (warn-vars)
  5084. (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
  5085. mail-yank-hooks mail-archive-file-name
  5086. mail-default-reply-to mail-mailing-lists
  5087. mail-self-blind))
  5088. (and (boundp var)
  5089. (symbol-value var)
  5090. (push var warn-vars)))
  5091. (when warn-vars
  5092. (display-warning 'mail
  5093. (format "\
  5094. The default mail mode is now Message mode.
  5095. You have the following Mail mode variable%s customized:
  5096. \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
  5097. To disable this warning, set `compose-mail-check-user-agent' to nil."
  5098. (if (> (length warn-vars) 1) "s" "")
  5099. (mapconcat 'symbol-name
  5100. warn-vars " "))))))
  5101. (let ((function (get mail-user-agent 'composefunc)))
  5102. (funcall function to subject other-headers continue
  5103. switch-function yank-action send-actions)))
  5104. (defun compose-mail-other-window (&optional to subject other-headers continue
  5105. yank-action send-actions)
  5106. "Like \\[compose-mail], but edit the outgoing message in another window."
  5107. (interactive
  5108. (list nil nil nil current-prefix-arg))
  5109. (compose-mail to subject other-headers continue
  5110. 'switch-to-buffer-other-window yank-action send-actions))
  5111. (defun compose-mail-other-frame (&optional to subject other-headers continue
  5112. yank-action send-actions)
  5113. "Like \\[compose-mail], but edit the outgoing message in another frame."
  5114. (interactive
  5115. (list nil nil nil current-prefix-arg))
  5116. (compose-mail to subject other-headers continue
  5117. 'switch-to-buffer-other-frame yank-action send-actions))
  5118. (defvar set-variable-value-history nil
  5119. "History of values entered with `set-variable'.
  5120. Maximum length of the history list is determined by the value
  5121. of `history-length', which see.")
  5122. (defun set-variable (variable value &optional make-local)
  5123. "Set VARIABLE to VALUE. VALUE is a Lisp object.
  5124. VARIABLE should be a user option variable name, a Lisp variable
  5125. meant to be customized by users. You should enter VALUE in Lisp syntax,
  5126. so if you want VALUE to be a string, you must surround it with doublequotes.
  5127. VALUE is used literally, not evaluated.
  5128. If VARIABLE has a `variable-interactive' property, that is used as if
  5129. it were the arg to `interactive' (which see) to interactively read VALUE.
  5130. If VARIABLE has been defined with `defcustom', then the type information
  5131. in the definition is used to check that VALUE is valid.
  5132. With a prefix argument, set VARIABLE to VALUE buffer-locally."
  5133. (interactive
  5134. (let* ((default-var (variable-at-point))
  5135. (var (if (user-variable-p default-var)
  5136. (read-variable (format "Set variable (default %s): " default-var)
  5137. default-var)
  5138. (read-variable "Set variable: ")))
  5139. (minibuffer-help-form '(describe-variable var))
  5140. (prop (get var 'variable-interactive))
  5141. (obsolete (car (get var 'byte-obsolete-variable)))
  5142. (prompt (format "Set %s %s to value: " var
  5143. (cond ((local-variable-p var)
  5144. "(buffer-local)")
  5145. ((or current-prefix-arg
  5146. (local-variable-if-set-p var))
  5147. "buffer-locally")
  5148. (t "globally"))))
  5149. (val (progn
  5150. (when obsolete
  5151. (message (concat "`%S' is obsolete; "
  5152. (if (symbolp obsolete) "use `%S' instead" "%s"))
  5153. var obsolete)
  5154. (sit-for 3))
  5155. (if prop
  5156. ;; Use VAR's `variable-interactive' property
  5157. ;; as an interactive spec for prompting.
  5158. (call-interactively `(lambda (arg)
  5159. (interactive ,prop)
  5160. arg))
  5161. (read
  5162. (read-string prompt nil
  5163. 'set-variable-value-history
  5164. (format "%S" (symbol-value var))))))))
  5165. (list var val current-prefix-arg)))
  5166. (and (custom-variable-p variable)
  5167. (not (get variable 'custom-type))
  5168. (custom-load-symbol variable))
  5169. (let ((type (get variable 'custom-type)))
  5170. (when type
  5171. ;; Match with custom type.
  5172. (require 'cus-edit)
  5173. (setq type (widget-convert type))
  5174. (unless (widget-apply type :match value)
  5175. (error "Value `%S' does not match type %S of %S"
  5176. value (car type) variable))))
  5177. (if make-local
  5178. (make-local-variable variable))
  5179. (set variable value)
  5180. ;; Force a thorough redisplay for the case that the variable
  5181. ;; has an effect on the display, like `tab-width' has.
  5182. (force-mode-line-update))
  5183. ;; Define the major mode for lists of completions.
  5184. (defvar completion-list-mode-map
  5185. (let ((map (make-sparse-keymap)))
  5186. (define-key map [mouse-2] 'mouse-choose-completion)
  5187. (define-key map [follow-link] 'mouse-face)
  5188. (define-key map [down-mouse-2] nil)
  5189. (define-key map "\C-m" 'choose-completion)
  5190. (define-key map "\e\e\e" 'delete-completion-window)
  5191. (define-key map [left] 'previous-completion)
  5192. (define-key map [right] 'next-completion)
  5193. (define-key map "q" 'quit-window)
  5194. map)
  5195. "Local map for completion list buffers.")
  5196. ;; Completion mode is suitable only for specially formatted data.
  5197. (put 'completion-list-mode 'mode-class 'special)
  5198. (defvar completion-reference-buffer nil
  5199. "Record the buffer that was current when the completion list was requested.
  5200. This is a local variable in the completion list buffer.
  5201. Initial value is nil to avoid some compiler warnings.")
  5202. (defvar completion-no-auto-exit nil
  5203. "Non-nil means `choose-completion-string' should never exit the minibuffer.
  5204. This also applies to other functions such as `choose-completion'.")
  5205. (defvar completion-base-position nil
  5206. "Position of the base of the text corresponding to the shown completions.
  5207. This variable is used in the *Completions* buffers.
  5208. Its value is a list of the form (START END) where START is the place
  5209. where the completion should be inserted and END (if non-nil) is the end
  5210. of the text to replace. If END is nil, point is used instead.")
  5211. (defvar completion-base-size nil
  5212. "Number of chars before point not involved in completion.
  5213. This is a local variable in the completion list buffer.
  5214. It refers to the chars in the minibuffer if completing in the
  5215. minibuffer, or in `completion-reference-buffer' otherwise.
  5216. Only characters in the field at point are included.
  5217. If nil, Emacs determines which part of the tail end of the
  5218. buffer's text is involved in completion by comparing the text
  5219. directly.")
  5220. (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
  5221. (defun delete-completion-window ()
  5222. "Delete the completion list window.
  5223. Go to the window from which completion was requested."
  5224. (interactive)
  5225. (let ((buf completion-reference-buffer))
  5226. (if (one-window-p t)
  5227. (if (window-dedicated-p (selected-window))
  5228. (delete-frame (selected-frame)))
  5229. (delete-window (selected-window))
  5230. (if (get-buffer-window buf)
  5231. (select-window (get-buffer-window buf))))))
  5232. (defun previous-completion (n)
  5233. "Move to the previous item in the completion list."
  5234. (interactive "p")
  5235. (next-completion (- n)))
  5236. (defun next-completion (n)
  5237. "Move to the next item in the completion list.
  5238. With prefix argument N, move N items (negative N means move backward)."
  5239. (interactive "p")
  5240. (let ((beg (point-min)) (end (point-max)))
  5241. (while (and (> n 0) (not (eobp)))
  5242. ;; If in a completion, move to the end of it.
  5243. (when (get-text-property (point) 'mouse-face)
  5244. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  5245. ;; Move to start of next one.
  5246. (unless (get-text-property (point) 'mouse-face)
  5247. (goto-char (next-single-property-change (point) 'mouse-face nil end)))
  5248. (setq n (1- n)))
  5249. (while (and (< n 0) (not (bobp)))
  5250. (let ((prop (get-text-property (1- (point)) 'mouse-face)))
  5251. ;; If in a completion, move to the start of it.
  5252. (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
  5253. (goto-char (previous-single-property-change
  5254. (point) 'mouse-face nil beg)))
  5255. ;; Move to end of the previous completion.
  5256. (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
  5257. (goto-char (previous-single-property-change
  5258. (point) 'mouse-face nil beg)))
  5259. ;; Move to the start of that one.
  5260. (goto-char (previous-single-property-change
  5261. (point) 'mouse-face nil beg))
  5262. (setq n (1+ n))))))
  5263. (defun choose-completion (&optional event)
  5264. "Choose the completion at point."
  5265. (interactive (list last-nonmenu-event))
  5266. ;; In case this is run via the mouse, give temporary modes such as
  5267. ;; isearch a chance to turn off.
  5268. (run-hooks 'mouse-leave-buffer-hook)
  5269. (let (buffer base-size base-position choice)
  5270. (with-current-buffer (window-buffer (posn-window (event-start event)))
  5271. (setq buffer completion-reference-buffer)
  5272. (setq base-size completion-base-size)
  5273. (setq base-position completion-base-position)
  5274. (save-excursion
  5275. (goto-char (posn-point (event-start event)))
  5276. (let (beg end)
  5277. (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
  5278. (setq end (point) beg (1+ (point))))
  5279. (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
  5280. (setq end (1- (point)) beg (point)))
  5281. (if (null beg)
  5282. (error "No completion here"))
  5283. (setq beg (previous-single-property-change beg 'mouse-face))
  5284. (setq end (or (next-single-property-change end 'mouse-face)
  5285. (point-max)))
  5286. (setq choice (buffer-substring-no-properties beg end)))))
  5287. (let ((owindow (selected-window)))
  5288. (select-window (posn-window (event-start event)))
  5289. (if (and (one-window-p t 'selected-frame)
  5290. (window-dedicated-p (selected-window)))
  5291. ;; This is a special buffer's frame
  5292. (iconify-frame (selected-frame))
  5293. (or (window-dedicated-p (selected-window))
  5294. (bury-buffer)))
  5295. (select-window
  5296. (or (and (buffer-live-p buffer)
  5297. (get-buffer-window buffer 0))
  5298. owindow)))
  5299. (choose-completion-string
  5300. choice buffer
  5301. (or base-position
  5302. (when base-size
  5303. ;; Someone's using old completion code that doesn't know
  5304. ;; about base-position yet.
  5305. (list (+ base-size (with-current-buffer buffer (field-beginning)))))
  5306. ;; If all else fails, just guess.
  5307. (with-current-buffer buffer
  5308. (list (choose-completion-guess-base-position choice)))))))
  5309. ;; Delete the longest partial match for STRING
  5310. ;; that can be found before POINT.
  5311. (defun choose-completion-guess-base-position (string)
  5312. (save-excursion
  5313. (let ((opoint (point))
  5314. len)
  5315. ;; Try moving back by the length of the string.
  5316. (goto-char (max (- (point) (length string))
  5317. (minibuffer-prompt-end)))
  5318. ;; See how far back we were actually able to move. That is the
  5319. ;; upper bound on how much we can match and delete.
  5320. (setq len (- opoint (point)))
  5321. (if completion-ignore-case
  5322. (setq string (downcase string)))
  5323. (while (and (> len 0)
  5324. (let ((tail (buffer-substring (point) opoint)))
  5325. (if completion-ignore-case
  5326. (setq tail (downcase tail)))
  5327. (not (string= tail (substring string 0 len)))))
  5328. (setq len (1- len))
  5329. (forward-char 1))
  5330. (point))))
  5331. (defun choose-completion-delete-max-match (string)
  5332. (delete-region (choose-completion-guess-base-position string) (point)))
  5333. (make-obsolete 'choose-completion-delete-max-match
  5334. 'choose-completion-guess-base-position "23.2")
  5335. (defvar choose-completion-string-functions nil
  5336. "Functions that may override the normal insertion of a completion choice.
  5337. These functions are called in order with four arguments:
  5338. CHOICE - the string to insert in the buffer,
  5339. BUFFER - the buffer in which the choice should be inserted,
  5340. MINI-P - non-nil if BUFFER is a minibuffer, and
  5341. BASE-SIZE - the number of characters in BUFFER before
  5342. the string being completed.
  5343. If a function in the list returns non-nil, that function is supposed
  5344. to have inserted the CHOICE in the BUFFER, and possibly exited
  5345. the minibuffer; no further functions will be called.
  5346. If all functions in the list return nil, that means to use
  5347. the default method of inserting the completion in BUFFER.")
  5348. (defun choose-completion-string (choice &optional buffer base-position)
  5349. "Switch to BUFFER and insert the completion choice CHOICE.
  5350. BASE-POSITION, says where to insert the completion."
  5351. ;; If BUFFER is the minibuffer, exit the minibuffer
  5352. ;; unless it is reading a file name and CHOICE is a directory,
  5353. ;; or completion-no-auto-exit is non-nil.
  5354. ;; Some older code may call us passing `base-size' instead of
  5355. ;; `base-position'. It's difficult to make any use of `base-size',
  5356. ;; so we just ignore it.
  5357. (unless (consp base-position)
  5358. (message "Obsolete `base-size' passed to choose-completion-string")
  5359. (setq base-position nil))
  5360. (let* ((buffer (or buffer completion-reference-buffer))
  5361. (mini-p (minibufferp buffer)))
  5362. ;; If BUFFER is a minibuffer, barf unless it's the currently
  5363. ;; active minibuffer.
  5364. (if (and mini-p
  5365. (or (not (active-minibuffer-window))
  5366. (not (equal buffer
  5367. (window-buffer (active-minibuffer-window))))))
  5368. (error "Minibuffer is not active for completion")
  5369. ;; Set buffer so buffer-local choose-completion-string-functions works.
  5370. (set-buffer buffer)
  5371. (unless (run-hook-with-args-until-success
  5372. 'choose-completion-string-functions
  5373. ;; The fourth arg used to be `mini-p' but was useless
  5374. ;; (since minibufferp can be used on the `buffer' arg)
  5375. ;; and indeed unused. The last used to be `base-size', so we
  5376. ;; keep it to try and avoid breaking old code.
  5377. choice buffer base-position nil)
  5378. ;; Insert the completion into the buffer where it was requested.
  5379. (delete-region (or (car base-position) (point))
  5380. (or (cadr base-position) (point)))
  5381. (insert choice)
  5382. (remove-text-properties (- (point) (length choice)) (point)
  5383. '(mouse-face nil))
  5384. ;; Update point in the window that BUFFER is showing in.
  5385. (let ((window (get-buffer-window buffer t)))
  5386. (set-window-point window (point)))
  5387. ;; If completing for the minibuffer, exit it with this choice.
  5388. (and (not completion-no-auto-exit)
  5389. (minibufferp buffer)
  5390. minibuffer-completion-table
  5391. ;; If this is reading a file name, and the file name chosen
  5392. ;; is a directory, don't exit the minibuffer.
  5393. (let* ((result (buffer-substring (field-beginning) (point)))
  5394. (bounds
  5395. (completion-boundaries result minibuffer-completion-table
  5396. minibuffer-completion-predicate
  5397. "")))
  5398. (if (eq (car bounds) (length result))
  5399. ;; The completion chosen leads to a new set of completions
  5400. ;; (e.g. it's a directory): don't exit the minibuffer yet.
  5401. (let ((mini (active-minibuffer-window)))
  5402. (select-window mini)
  5403. (when minibuffer-auto-raise
  5404. (raise-frame (window-frame mini))))
  5405. (exit-minibuffer))))))))
  5406. (define-derived-mode completion-list-mode nil "Completion List"
  5407. "Major mode for buffers showing lists of possible completions.
  5408. Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
  5409. to select the completion near point.
  5410. Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
  5411. with the mouse.
  5412. \\{completion-list-mode-map}"
  5413. (set (make-local-variable 'completion-base-size) nil))
  5414. (defun completion-list-mode-finish ()
  5415. "Finish setup of the completions buffer.
  5416. Called from `temp-buffer-show-hook'."
  5417. (when (eq major-mode 'completion-list-mode)
  5418. (toggle-read-only 1)))
  5419. (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
  5420. ;; Variables and faces used in `completion-setup-function'.
  5421. (defcustom completion-show-help t
  5422. "Non-nil means show help message in *Completions* buffer."
  5423. :type 'boolean
  5424. :version "22.1"
  5425. :group 'completion)
  5426. ;; This function goes in completion-setup-hook, so that it is called
  5427. ;; after the text of the completion list buffer is written.
  5428. (defun completion-setup-function ()
  5429. (let* ((mainbuf (current-buffer))
  5430. (base-dir
  5431. ;; When reading a file name in the minibuffer,
  5432. ;; try and find the right default-directory to set in the
  5433. ;; completion list buffer.
  5434. ;; FIXME: Why do we do that, actually? --Stef
  5435. (if minibuffer-completing-file-name
  5436. (file-name-as-directory
  5437. (expand-file-name
  5438. (substring (minibuffer-completion-contents)
  5439. 0 (or completion-base-size 0)))))))
  5440. (with-current-buffer standard-output
  5441. (let ((base-size completion-base-size) ;Read before killing localvars.
  5442. (base-position completion-base-position))
  5443. (completion-list-mode)
  5444. (set (make-local-variable 'completion-base-size) base-size)
  5445. (set (make-local-variable 'completion-base-position) base-position))
  5446. (set (make-local-variable 'completion-reference-buffer) mainbuf)
  5447. (if base-dir (setq default-directory base-dir))
  5448. ;; Maybe insert help string.
  5449. (when completion-show-help
  5450. (goto-char (point-min))
  5451. (if (display-mouse-p)
  5452. (insert (substitute-command-keys
  5453. "Click \\[mouse-choose-completion] on a completion to select it.\n")))
  5454. (insert (substitute-command-keys
  5455. "In this buffer, type \\[choose-completion] to \
  5456. select the completion near point.\n\n"))))))
  5457. (add-hook 'completion-setup-hook 'completion-setup-function)
  5458. (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
  5459. (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
  5460. (defun switch-to-completions ()
  5461. "Select the completion list window."
  5462. (interactive)
  5463. (let ((window (or (get-buffer-window "*Completions*" 0)
  5464. ;; Make sure we have a completions window.
  5465. (progn (minibuffer-completion-help)
  5466. (get-buffer-window "*Completions*" 0)))))
  5467. (when window
  5468. (select-window window)
  5469. ;; In the new buffer, go to the first completion.
  5470. ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
  5471. (when (bobp)
  5472. (next-completion 1)))))
  5473. ;;; Support keyboard commands to turn on various modifiers.
  5474. ;; These functions -- which are not commands -- each add one modifier
  5475. ;; to the following event.
  5476. (defun event-apply-alt-modifier (ignore-prompt)
  5477. "\\<function-key-map>Add the Alt modifier to the following event.
  5478. For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
  5479. (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
  5480. (defun event-apply-super-modifier (ignore-prompt)
  5481. "\\<function-key-map>Add the Super modifier to the following event.
  5482. For example, type \\[event-apply-super-modifier] & to enter Super-&."
  5483. (vector (event-apply-modifier (read-event) 'super 23 "s-")))
  5484. (defun event-apply-hyper-modifier (ignore-prompt)
  5485. "\\<function-key-map>Add the Hyper modifier to the following event.
  5486. For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
  5487. (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
  5488. (defun event-apply-shift-modifier (ignore-prompt)
  5489. "\\<function-key-map>Add the Shift modifier to the following event.
  5490. For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
  5491. (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
  5492. (defun event-apply-control-modifier (ignore-prompt)
  5493. "\\<function-key-map>Add the Ctrl modifier to the following event.
  5494. For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
  5495. (vector (event-apply-modifier (read-event) 'control 26 "C-")))
  5496. (defun event-apply-meta-modifier (ignore-prompt)
  5497. "\\<function-key-map>Add the Meta modifier to the following event.
  5498. For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
  5499. (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
  5500. (defun event-apply-modifier (event symbol lshiftby prefix)
  5501. "Apply a modifier flag to event EVENT.
  5502. SYMBOL is the name of this modifier, as a symbol.
  5503. LSHIFTBY is the numeric value of this modifier, in keyboard events.
  5504. PREFIX is the string that represents this modifier in an event type symbol."
  5505. (if (numberp event)
  5506. (cond ((eq symbol 'control)
  5507. (if (and (<= (downcase event) ?z)
  5508. (>= (downcase event) ?a))
  5509. (- (downcase event) ?a -1)
  5510. (if (and (<= (downcase event) ?Z)
  5511. (>= (downcase event) ?A))
  5512. (- (downcase event) ?A -1)
  5513. (logior (lsh 1 lshiftby) event))))
  5514. ((eq symbol 'shift)
  5515. (if (and (<= (downcase event) ?z)
  5516. (>= (downcase event) ?a))
  5517. (upcase event)
  5518. (logior (lsh 1 lshiftby) event)))
  5519. (t
  5520. (logior (lsh 1 lshiftby) event)))
  5521. (if (memq symbol (event-modifiers event))
  5522. event
  5523. (let ((event-type (if (symbolp event) event (car event))))
  5524. (setq event-type (intern (concat prefix (symbol-name event-type))))
  5525. (if (symbolp event)
  5526. event-type
  5527. (cons event-type (cdr event)))))))
  5528. (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
  5529. (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
  5530. (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
  5531. (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
  5532. (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
  5533. (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
  5534. ;;;; Keypad support.
  5535. ;; Make the keypad keys act like ordinary typing keys. If people add
  5536. ;; bindings for the function key symbols, then those bindings will
  5537. ;; override these, so this shouldn't interfere with any existing
  5538. ;; bindings.
  5539. ;; Also tell read-char how to handle these keys.
  5540. (mapc
  5541. (lambda (keypad-normal)
  5542. (let ((keypad (nth 0 keypad-normal))
  5543. (normal (nth 1 keypad-normal)))
  5544. (put keypad 'ascii-character normal)
  5545. (define-key function-key-map (vector keypad) (vector normal))))
  5546. '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
  5547. (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
  5548. (kp-space ?\s)
  5549. (kp-tab ?\t)
  5550. (kp-enter ?\r)
  5551. (kp-multiply ?*)
  5552. (kp-add ?+)
  5553. (kp-separator ?,)
  5554. (kp-subtract ?-)
  5555. (kp-decimal ?.)
  5556. (kp-divide ?/)
  5557. (kp-equal ?=)
  5558. ;; Do the same for various keys that are represented as symbols under
  5559. ;; GUIs but naturally correspond to characters.
  5560. (backspace 127)
  5561. (delete 127)
  5562. (tab ?\t)
  5563. (linefeed ?\n)
  5564. (clear ?\C-l)
  5565. (return ?\C-m)
  5566. (escape ?\e)
  5567. ))
  5568. ;;;;
  5569. ;;;; forking a twin copy of a buffer.
  5570. ;;;;
  5571. (defvar clone-buffer-hook nil
  5572. "Normal hook to run in the new buffer at the end of `clone-buffer'.")
  5573. (defvar clone-indirect-buffer-hook nil
  5574. "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
  5575. (defun clone-process (process &optional newname)
  5576. "Create a twin copy of PROCESS.
  5577. If NEWNAME is nil, it defaults to PROCESS' name;
  5578. NEWNAME is modified by adding or incrementing <N> at the end as necessary.
  5579. If PROCESS is associated with a buffer, the new process will be associated
  5580. with the current buffer instead.
  5581. Returns nil if PROCESS has already terminated."
  5582. (setq newname (or newname (process-name process)))
  5583. (if (string-match "<[0-9]+>\\'" newname)
  5584. (setq newname (substring newname 0 (match-beginning 0))))
  5585. (when (memq (process-status process) '(run stop open))
  5586. (let* ((process-connection-type (process-tty-name process))
  5587. (new-process
  5588. (if (memq (process-status process) '(open))
  5589. (let ((args (process-contact process t)))
  5590. (setq args (plist-put args :name newname))
  5591. (setq args (plist-put args :buffer
  5592. (if (process-buffer process)
  5593. (current-buffer))))
  5594. (apply 'make-network-process args))
  5595. (apply 'start-process newname
  5596. (if (process-buffer process) (current-buffer))
  5597. (process-command process)))))
  5598. (set-process-query-on-exit-flag
  5599. new-process (process-query-on-exit-flag process))
  5600. (set-process-inherit-coding-system-flag
  5601. new-process (process-inherit-coding-system-flag process))
  5602. (set-process-filter new-process (process-filter process))
  5603. (set-process-sentinel new-process (process-sentinel process))
  5604. (set-process-plist new-process (copy-sequence (process-plist process)))
  5605. new-process)))
  5606. ;; things to maybe add (currently partly covered by `funcall mode'):
  5607. ;; - syntax-table
  5608. ;; - overlays
  5609. (defun clone-buffer (&optional newname display-flag)
  5610. "Create and return a twin copy of the current buffer.
  5611. Unlike an indirect buffer, the new buffer can be edited
  5612. independently of the old one (if it is not read-only).
  5613. NEWNAME is the name of the new buffer. It may be modified by
  5614. adding or incrementing <N> at the end as necessary to create a
  5615. unique buffer name. If nil, it defaults to the name of the
  5616. current buffer, with the proper suffix. If DISPLAY-FLAG is
  5617. non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
  5618. clone a file-visiting buffer, or a buffer whose major mode symbol
  5619. has a non-nil `no-clone' property, results in an error.
  5620. Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
  5621. current buffer with appropriate suffix. However, if a prefix
  5622. argument is given, then the command prompts for NEWNAME in the
  5623. minibuffer.
  5624. This runs the normal hook `clone-buffer-hook' in the new buffer
  5625. after it has been set up properly in other respects."
  5626. (interactive
  5627. (progn
  5628. (if buffer-file-name
  5629. (error "Cannot clone a file-visiting buffer"))
  5630. (if (get major-mode 'no-clone)
  5631. (error "Cannot clone a buffer in %s mode" mode-name))
  5632. (list (if current-prefix-arg
  5633. (read-buffer "Name of new cloned buffer: " (current-buffer)))
  5634. t)))
  5635. (if buffer-file-name
  5636. (error "Cannot clone a file-visiting buffer"))
  5637. (if (get major-mode 'no-clone)
  5638. (error "Cannot clone a buffer in %s mode" mode-name))
  5639. (setq newname (or newname (buffer-name)))
  5640. (if (string-match "<[0-9]+>\\'" newname)
  5641. (setq newname (substring newname 0 (match-beginning 0))))
  5642. (let ((buf (current-buffer))
  5643. (ptmin (point-min))
  5644. (ptmax (point-max))
  5645. (pt (point))
  5646. (mk (if mark-active (mark t)))
  5647. (modified (buffer-modified-p))
  5648. (mode major-mode)
  5649. (lvars (buffer-local-variables))
  5650. (process (get-buffer-process (current-buffer)))
  5651. (new (generate-new-buffer (or newname (buffer-name)))))
  5652. (save-restriction
  5653. (widen)
  5654. (with-current-buffer new
  5655. (insert-buffer-substring buf)))
  5656. (with-current-buffer new
  5657. (narrow-to-region ptmin ptmax)
  5658. (goto-char pt)
  5659. (if mk (set-mark mk))
  5660. (set-buffer-modified-p modified)
  5661. ;; Clone the old buffer's process, if any.
  5662. (when process (clone-process process))
  5663. ;; Now set up the major mode.
  5664. (funcall mode)
  5665. ;; Set up other local variables.
  5666. (mapc (lambda (v)
  5667. (condition-case () ;in case var is read-only
  5668. (if (symbolp v)
  5669. (makunbound v)
  5670. (set (make-local-variable (car v)) (cdr v)))
  5671. (error nil)))
  5672. lvars)
  5673. ;; Run any hooks (typically set up by the major mode
  5674. ;; for cloning to work properly).
  5675. (run-hooks 'clone-buffer-hook))
  5676. (if display-flag
  5677. ;; Presumably the current buffer is shown in the selected frame, so
  5678. ;; we want to display the clone elsewhere.
  5679. (let ((same-window-regexps nil)
  5680. (same-window-buffer-names))
  5681. (pop-to-buffer new)))
  5682. new))
  5683. (defun clone-indirect-buffer (newname display-flag &optional norecord)
  5684. "Create an indirect buffer that is a twin copy of the current buffer.
  5685. Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
  5686. from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
  5687. or if not called with a prefix arg, NEWNAME defaults to the current
  5688. buffer's name. The name is modified by adding a `<N>' suffix to it
  5689. or by incrementing the N in an existing suffix. Trying to clone a
  5690. buffer whose major mode symbol has a non-nil `no-clone-indirect'
  5691. property results in an error.
  5692. DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
  5693. This is always done when called interactively.
  5694. Optional third arg NORECORD non-nil means do not put this buffer at the
  5695. front of the list of recently selected ones."
  5696. (interactive
  5697. (progn
  5698. (if (get major-mode 'no-clone-indirect)
  5699. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  5700. (list (if current-prefix-arg
  5701. (read-buffer "Name of indirect buffer: " (current-buffer)))
  5702. t)))
  5703. (if (get major-mode 'no-clone-indirect)
  5704. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  5705. (setq newname (or newname (buffer-name)))
  5706. (if (string-match "<[0-9]+>\\'" newname)
  5707. (setq newname (substring newname 0 (match-beginning 0))))
  5708. (let* ((name (generate-new-buffer-name newname))
  5709. (buffer (make-indirect-buffer (current-buffer) name t)))
  5710. (with-current-buffer buffer
  5711. (run-hooks 'clone-indirect-buffer-hook))
  5712. (when display-flag
  5713. (pop-to-buffer buffer norecord))
  5714. buffer))
  5715. (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
  5716. "Like `clone-indirect-buffer' but display in another window."
  5717. (interactive
  5718. (progn
  5719. (if (get major-mode 'no-clone-indirect)
  5720. (error "Cannot indirectly clone a buffer in %s mode" mode-name))
  5721. (list (if current-prefix-arg
  5722. (read-buffer "Name of indirect buffer: " (current-buffer)))
  5723. t)))
  5724. (let ((pop-up-windows t))
  5725. (clone-indirect-buffer newname display-flag norecord)))
  5726. ;;; Handling of Backspace and Delete keys.
  5727. (defcustom normal-erase-is-backspace 'maybe
  5728. "Set the default behavior of the Delete and Backspace keys.
  5729. If set to t, Delete key deletes forward and Backspace key deletes
  5730. backward.
  5731. If set to nil, both Delete and Backspace keys delete backward.
  5732. If set to 'maybe (which is the default), Emacs automatically
  5733. selects a behavior. On window systems, the behavior depends on
  5734. the keyboard used. If the keyboard has both a Backspace key and
  5735. a Delete key, and both are mapped to their usual meanings, the
  5736. option's default value is set to t, so that Backspace can be used
  5737. to delete backward, and Delete can be used to delete forward.
  5738. If not running under a window system, customizing this option
  5739. accomplishes a similar effect by mapping C-h, which is usually
  5740. generated by the Backspace key, to DEL, and by mapping DEL to C-d
  5741. via `keyboard-translate'. The former functionality of C-h is
  5742. available on the F1 key. You should probably not use this
  5743. setting if you don't have both Backspace, Delete and F1 keys.
  5744. Setting this variable with setq doesn't take effect. Programmatically,
  5745. call `normal-erase-is-backspace-mode' (which see) instead."
  5746. :type '(choice (const :tag "Off" nil)
  5747. (const :tag "Maybe" maybe)
  5748. (other :tag "On" t))
  5749. :group 'editing-basics
  5750. :version "21.1"
  5751. :set (lambda (symbol value)
  5752. ;; The fboundp is because of a problem with :set when
  5753. ;; dumping Emacs. It doesn't really matter.
  5754. (if (fboundp 'normal-erase-is-backspace-mode)
  5755. (normal-erase-is-backspace-mode (or value 0))
  5756. (set-default symbol value))))
  5757. (defun normal-erase-is-backspace-setup-frame (&optional frame)
  5758. "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
  5759. (unless frame (setq frame (selected-frame)))
  5760. (with-selected-frame frame
  5761. (unless (terminal-parameter nil 'normal-erase-is-backspace)
  5762. (normal-erase-is-backspace-mode
  5763. (if (if (eq normal-erase-is-backspace 'maybe)
  5764. (and (not noninteractive)
  5765. (or (memq system-type '(ms-dos windows-nt))
  5766. (and (memq window-system '(x))
  5767. (fboundp 'x-backspace-delete-keys-p)
  5768. (x-backspace-delete-keys-p))
  5769. ;; If the terminal Emacs is running on has erase char
  5770. ;; set to ^H, use the Backspace key for deleting
  5771. ;; backward, and the Delete key for deleting forward.
  5772. (and (null window-system)
  5773. (eq tty-erase-char ?\^H))))
  5774. normal-erase-is-backspace)
  5775. 1 0)))))
  5776. (defun normal-erase-is-backspace-mode (&optional arg)
  5777. "Toggle the Erase and Delete mode of the Backspace and Delete keys.
  5778. With numeric ARG, turn the mode on if and only if ARG is positive.
  5779. On window systems, when this mode is on, Delete is mapped to C-d
  5780. and Backspace is mapped to DEL; when this mode is off, both
  5781. Delete and Backspace are mapped to DEL. (The remapping goes via
  5782. `local-function-key-map', so binding Delete or Backspace in the
  5783. global or local keymap will override that.)
  5784. In addition, on window systems, the bindings of C-Delete, M-Delete,
  5785. C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
  5786. the global keymap in accordance with the functionality of Delete and
  5787. Backspace. For example, if Delete is remapped to C-d, which deletes
  5788. forward, C-Delete is bound to `kill-word', but if Delete is remapped
  5789. to DEL, which deletes backward, C-Delete is bound to
  5790. `backward-kill-word'.
  5791. If not running on a window system, a similar effect is accomplished by
  5792. remapping C-h (normally produced by the Backspace key) and DEL via
  5793. `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
  5794. to C-d; if it's off, the keys are not remapped.
  5795. When not running on a window system, and this mode is turned on, the
  5796. former functionality of C-h is available on the F1 key. You should
  5797. probably not turn on this mode on a text-only terminal if you don't
  5798. have both Backspace, Delete and F1 keys.
  5799. See also `normal-erase-is-backspace'."
  5800. (interactive "P")
  5801. (let ((enabled (or (and arg (> (prefix-numeric-value arg) 0))
  5802. (not (or arg
  5803. (eq 1 (terminal-parameter
  5804. nil 'normal-erase-is-backspace)))))))
  5805. (set-terminal-parameter nil 'normal-erase-is-backspace
  5806. (if enabled 1 0))
  5807. (cond ((or (memq window-system '(x w32 ns pc))
  5808. (memq system-type '(ms-dos windows-nt)))
  5809. (let* ((bindings
  5810. `(([M-delete] [M-backspace])
  5811. ([C-M-delete] [C-M-backspace])
  5812. ([?\e C-delete] [?\e C-backspace])))
  5813. (old-state (lookup-key local-function-key-map [delete])))
  5814. (if enabled
  5815. (progn
  5816. (define-key local-function-key-map [delete] [?\C-d])
  5817. (define-key local-function-key-map [kp-delete] [?\C-d])
  5818. (define-key local-function-key-map [backspace] [?\C-?])
  5819. (dolist (b bindings)
  5820. ;; Not sure if input-decode-map is really right, but
  5821. ;; keyboard-translate-table (used below) only works
  5822. ;; for integer events, and key-translation-table is
  5823. ;; global (like the global-map, used earlier).
  5824. (define-key input-decode-map (car b) nil)
  5825. (define-key input-decode-map (cadr b) nil)))
  5826. (define-key local-function-key-map [delete] [?\C-?])
  5827. (define-key local-function-key-map [kp-delete] [?\C-?])
  5828. (define-key local-function-key-map [backspace] [?\C-?])
  5829. (dolist (b bindings)
  5830. (define-key input-decode-map (car b) (cadr b))
  5831. (define-key input-decode-map (cadr b) (car b))))))
  5832. (t
  5833. (if enabled
  5834. (progn
  5835. (keyboard-translate ?\C-h ?\C-?)
  5836. (keyboard-translate ?\C-? ?\C-d))
  5837. (keyboard-translate ?\C-h ?\C-h)
  5838. (keyboard-translate ?\C-? ?\C-?))))
  5839. (run-hooks 'normal-erase-is-backspace-hook)
  5840. (if (called-interactively-p 'interactive)
  5841. (message "Delete key deletes %s"
  5842. (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
  5843. "forward" "backward")))))
  5844. (defvar vis-mode-saved-buffer-invisibility-spec nil
  5845. "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
  5846. (define-minor-mode visible-mode
  5847. "Toggle Visible mode.
  5848. With argument ARG turn Visible mode on if ARG is positive, otherwise
  5849. turn it off.
  5850. Enabling Visible mode makes all invisible text temporarily visible.
  5851. Disabling Visible mode turns off that effect. Visible mode works by
  5852. saving the value of `buffer-invisibility-spec' and setting it to nil."
  5853. :lighter " Vis"
  5854. :group 'editing-basics
  5855. (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
  5856. (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
  5857. (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
  5858. (when visible-mode
  5859. (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
  5860. buffer-invisibility-spec)
  5861. (setq buffer-invisibility-spec nil)))
  5862. ;; Partial application of functions (similar to "currying").
  5863. ;; This function is here rather than in subr.el because it uses CL.
  5864. (defun apply-partially (fun &rest args)
  5865. "Return a function that is a partial application of FUN to ARGS.
  5866. ARGS is a list of the first N arguments to pass to FUN.
  5867. The result is a new function which does the same as FUN, except that
  5868. the first N arguments are fixed at the values with which this function
  5869. was called."
  5870. (lexical-let ((fun fun) (args1 args))
  5871. (lambda (&rest args2) (apply fun (append args1 args2)))))
  5872. ;; This function is here rather than in subr.el because it uses CL.
  5873. (defmacro with-wrapper-hook (var args &rest body)
  5874. "Run BODY wrapped with the VAR hook.
  5875. VAR is a special hook: its functions are called with a first argument
  5876. which is the \"original\" code (the BODY), so the hook function can wrap
  5877. the original function, or call it any number of times (including not calling
  5878. it at all). This is similar to an `around' advice.
  5879. VAR is normally a symbol (a variable) in which case it is treated like
  5880. a hook, with a buffer-local and a global part. But it can also be an
  5881. arbitrary expression.
  5882. ARGS is a list of variables which will be passed as additional arguments
  5883. to each function, after the initial argument, and which the first argument
  5884. expects to receive when called."
  5885. (declare (indent 2) (debug t))
  5886. ;; We need those two gensyms because CL's lexical scoping is not available
  5887. ;; for function arguments :-(
  5888. (let ((funs (make-symbol "funs"))
  5889. (global (make-symbol "global"))
  5890. (argssym (make-symbol "args")))
  5891. ;; Since the hook is a wrapper, the loop has to be done via
  5892. ;; recursion: a given hook function will call its parameter in order to
  5893. ;; continue looping.
  5894. `(labels ((runrestofhook (,funs ,global ,argssym)
  5895. ;; `funs' holds the functions left on the hook and `global'
  5896. ;; holds the functions left on the global part of the hook
  5897. ;; (in case the hook is local).
  5898. (lexical-let ((funs ,funs)
  5899. (global ,global))
  5900. (if (consp funs)
  5901. (if (eq t (car funs))
  5902. (runrestofhook
  5903. (append global (cdr funs)) nil ,argssym)
  5904. (apply (car funs)
  5905. (lambda (&rest ,argssym)
  5906. (runrestofhook (cdr funs) global ,argssym))
  5907. ,argssym))
  5908. ;; Once there are no more functions on the hook, run
  5909. ;; the original body.
  5910. (apply (lambda ,args ,@body) ,argssym)))))
  5911. (runrestofhook ,var
  5912. ;; The global part of the hook, if any.
  5913. ,(if (symbolp var)
  5914. `(if (local-variable-p ',var)
  5915. (default-value ',var)))
  5916. (list ,@args)))))
  5917. ;; Minibuffer prompt stuff.
  5918. ;(defun minibuffer-prompt-modification (start end)
  5919. ; (error "You cannot modify the prompt"))
  5920. ;
  5921. ;
  5922. ;(defun minibuffer-prompt-insertion (start end)
  5923. ; (let ((inhibit-modification-hooks t))
  5924. ; (delete-region start end)
  5925. ; ;; Discard undo information for the text insertion itself
  5926. ; ;; and for the text deletion.above.
  5927. ; (when (consp buffer-undo-list)
  5928. ; (setq buffer-undo-list (cddr buffer-undo-list)))
  5929. ; (message "You cannot modify the prompt")))
  5930. ;
  5931. ;
  5932. ;(setq minibuffer-prompt-properties
  5933. ; (list 'modification-hooks '(minibuffer-prompt-modification)
  5934. ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
  5935. ;
  5936. ;;;; Problematic external packages.
  5937. ;; rms says this should be done by specifying symbols that define
  5938. ;; versions together with bad values. This is therefore not as
  5939. ;; flexible as it could be. See the thread:
  5940. ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
  5941. (defconst bad-packages-alist
  5942. ;; Not sure exactly which semantic versions have problems.
  5943. ;; Definitely 2.0pre3, probably all 2.0pre's before this.
  5944. '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
  5945. "The version of `semantic' loaded does not work in Emacs 22.
  5946. It can cause constant high CPU load.
  5947. Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
  5948. ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
  5949. ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
  5950. ;; provided the `CUA-mode' feature. Since this is no longer true,
  5951. ;; we can warn the user if the `CUA-mode' feature is ever provided.
  5952. (CUA-mode t nil
  5953. "CUA-mode is now part of the standard GNU Emacs distribution,
  5954. so you can now enable CUA via the Options menu or by customizing `cua-mode'.
  5955. You have loaded an older version of CUA-mode which does not work
  5956. correctly with this version of Emacs. You should remove the old
  5957. version and use the one distributed with Emacs."))
  5958. "Alist of packages known to cause problems in this version of Emacs.
  5959. Each element has the form (PACKAGE SYMBOL REGEXP STRING).
  5960. PACKAGE is either a regular expression to match file names, or a
  5961. symbol (a feature name); see the documentation of
  5962. `after-load-alist', to which this variable adds functions.
  5963. SYMBOL is either the name of a string variable, or `t'. Upon
  5964. loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
  5965. warning using STRING as the message.")
  5966. (defun bad-package-check (package)
  5967. "Run a check using the element from `bad-packages-alist' matching PACKAGE."
  5968. (condition-case nil
  5969. (let* ((list (assoc package bad-packages-alist))
  5970. (symbol (nth 1 list)))
  5971. (and list
  5972. (boundp symbol)
  5973. (or (eq symbol t)
  5974. (and (stringp (setq symbol (eval symbol)))
  5975. (string-match-p (nth 2 list) symbol)))
  5976. (display-warning package (nth 3 list) :warning)))
  5977. (error nil)))
  5978. (mapc (lambda (elem)
  5979. (eval-after-load (car elem) `(bad-package-check ',(car elem))))
  5980. bad-packages-alist)
  5981. (provide 'simple)
  5982. ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
  5983. ;;; simple.el ends here