simple.el 269 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1 2
;;; simple.el --- basic editing commands for Emacs

3
;; Copyright (C) 1985-1987, 1993-2012  Free Software Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4

Pavel Janík's avatar
Pavel Janík committed
5 6
;; Maintainer: FSF
;; Keywords: internal
7
;; Package: emacs
Pavel Janík's avatar
Pavel Janík committed
8

Jim Blandy's avatar
Jim Blandy committed
9 10
;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Jim Blandy's avatar
Jim Blandy committed
23

24 25 26 27 28
;;; Commentary:

;; A grab-bag of basic Emacs commands not specifically related to some
;; major mode or to file-handling.

Eric S. Raymond's avatar
Eric S. Raymond committed
29
;;; Code:
Jim Blandy's avatar
Jim Blandy committed
30

31
(eval-when-compile (require 'cl))       ;For define-minor-mode.
32

33 34
(declare-function widget-convert "wid-edit" (type &rest args))
(declare-function shell-mode "shell" ())
Gerd Moellmann's avatar
Gerd Moellmann committed
35

36
;;; From compile.el
37
(defvar compilation-current-error)
38
(defvar compilation-context-lines)
39

40
(defcustom idle-update-delay 0.5
41
  "Idle time delay before updating various things on the screen.
42 43 44 45 46
Various Emacs features that update auxiliary information when point moves
wait this many seconds after Emacs becomes idle before doing an update."
  :type 'number
  :group 'display
  :version "22.1")
Gerd Moellmann's avatar
Gerd Moellmann committed
47

48
(defgroup killing nil
49
  "Killing and yanking commands."
50 51 52 53 54
  :group 'editing)

(defgroup paren-matching nil
  "Highlight (un)matching of parens and expressions."
  :group 'matching)
55

56
;;; next-error support framework
57 58

(defgroup next-error nil
59
  "`next-error' support framework."
60
  :group 'compilation
61
  :version "22.1")
62 63 64 65 66

(defface next-error
  '((t (:inherit region)))
  "Face used to highlight next error locus."
  :group 'next-error
67
  :version "22.1")
68

69
(defcustom next-error-highlight 0.5
70
  "Highlighting of locations in selected source buffers.
71 72 73 74
If a number, highlight the locus in `next-error' face for the given time
in seconds, or until the next command is executed.
If t, highlight the locus until the next command is executed, or until
some other locus replaces it.
75
If nil, don't highlight the locus in the source buffer.
76 77
If `fringe-arrow', indicate the locus by the fringe arrow
indefinitely until some other locus replaces it."
78
  :type '(choice (number :tag "Highlight for specified time")
79
                 (const :tag "Semipermanent highlighting" t)
80
                 (const :tag "No highlighting" nil)
81
                 (const :tag "Fringe arrow" fringe-arrow))
82
  :group 'next-error
83
  :version "22.1")
84

85
(defcustom next-error-highlight-no-select 0.5
86
  "Highlighting of locations in `next-error-no-select'.
87
If number, highlight the locus in `next-error' face for given time in seconds.
88
If t, highlight the locus indefinitely until some other locus replaces it.
89
If nil, don't highlight the locus in the source buffer.
90 91
If `fringe-arrow', indicate the locus by the fringe arrow
indefinitely until some other locus replaces it."
92
  :type '(choice (number :tag "Highlight for specified time")
93
                 (const :tag "Semipermanent highlighting" t)
94
                 (const :tag "No highlighting" nil)
95
                 (const :tag "Fringe arrow" fringe-arrow))
96
  :group 'next-error
97
  :version "22.1")
98

99
(defcustom next-error-recenter nil
100
  "Display the line in the visited source file recentered as specified.
101 102 103
If non-nil, the value is passed directly to `recenter'."
  :type '(choice (integer :tag "Line to recenter to")
                 (const :tag "Center of window" (4))
104 105 106 107
                 (const :tag "No recentering" nil))
  :group 'next-error
  :version "23.1")

Juri Linkov's avatar
Juri Linkov committed
108
(defcustom next-error-hook nil
109
  "List of hook functions run by `next-error' after visiting source file."
Juri Linkov's avatar
Juri Linkov committed
110 111 112
  :type 'hook
  :group 'next-error)

113 114
(defvar next-error-highlight-timer nil)

115
(defvar next-error-overlay-arrow-position nil)
116
(put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
117 118
(add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)

119
(defvar next-error-last-buffer nil
120
  "The most recent `next-error' buffer.
121 122 123 124 125
A buffer becomes most recent when its compilation, grep, or
similar mode is started, or when it is used with \\[next-error]
or \\[compile-goto-error].")

(defvar next-error-function nil
126 127 128 129 130 131 132 133
  "Function to use to find the next error in the current buffer.
The function is called with 2 parameters:
ARG is an integer specifying by how many errors to move.
RESET is a boolean which, if non-nil, says to go back to the beginning
of the errors before moving.
Major modes providing compile-like functionality should set this variable
to indicate to `next-error' that this is a candidate buffer and how
to navigate in it.")
134 135
(make-variable-buffer-local 'next-error-function)

136 137 138 139 140 141 142 143
(defvar next-error-move-function nil
  "Function to use to move to an error locus.
It takes two arguments, a buffer position in the error buffer
and a buffer position in the error locus buffer.
The buffer for the error locus should already be current.
nil means use goto-char using the second argument position.")
(make-variable-buffer-local 'next-error-move-function)

144
(defsubst next-error-buffer-p (buffer
145
			       &optional avoid-current
146
			       extra-test-inclusive
147
			       extra-test-exclusive)
148
  "Test if BUFFER is a `next-error' capable buffer.
149 150 151 152 153 154 155 156

If AVOID-CURRENT is non-nil, treat the current buffer
as an absolute last resort only.

The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
that normally would not qualify.  If it returns t, the buffer
in question is treated as usable.

157
The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
158
that would normally be considered usable.  If it returns nil,
159 160 161 162 163 164 165 166 167 168 169 170 171 172
that buffer is rejected."
  (and (buffer-name buffer)		;First make sure it's live.
       (not (and avoid-current (eq buffer (current-buffer))))
       (with-current-buffer buffer
	 (if next-error-function   ; This is the normal test.
	     ;; Optionally reject some buffers.
	     (if extra-test-exclusive
		 (funcall extra-test-exclusive)
	       t)
	   ;; Optionally accept some other buffers.
	   (and extra-test-inclusive
		(funcall extra-test-inclusive))))))

(defun next-error-find-buffer (&optional avoid-current
173
					 extra-test-inclusive
174
					 extra-test-exclusive)
175
  "Return a `next-error' capable buffer.
176

177 178 179
If AVOID-CURRENT is non-nil, treat the current buffer
as an absolute last resort only.

180
The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 182 183
that normally would not qualify.  If it returns t, the buffer
in question is treated as usable.

184
The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 186
that would normally be considered usable.  If it returns nil,
that buffer is rejected."
187 188 189 190 191 192
  (or
   ;; 1. If one window on the selected frame displays such buffer, return it.
   (let ((window-buffers
          (delete-dups
           (delq nil (mapcar (lambda (w)
                               (if (next-error-buffer-p
193 194
				    (window-buffer w)
                                    avoid-current
195
                                    extra-test-inclusive extra-test-exclusive)
196 197 198 199
                                   (window-buffer w)))
                             (window-list))))))
     (if (eq (length window-buffers) 1)
         (car window-buffers)))
200
   ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201
   (if (and next-error-last-buffer
202
            (next-error-buffer-p next-error-last-buffer avoid-current
203
                                 extra-test-inclusive extra-test-exclusive))
204 205 206 207
       next-error-last-buffer)
   ;; 3. If the current buffer is acceptable, choose it.
   (if (next-error-buffer-p (current-buffer) avoid-current
			    extra-test-inclusive extra-test-exclusive)
208
       (current-buffer))
209
   ;; 4. Look for any acceptable buffer.
210 211
   (let ((buffers (buffer-list)))
     (while (and buffers
212 213 214
                 (not (next-error-buffer-p
		       (car buffers) avoid-current
		       extra-test-inclusive extra-test-exclusive)))
215
       (setq buffers (cdr buffers)))
216 217 218 219 220 221 222
     (car buffers))
   ;; 5. Use the current buffer as a last resort if it qualifies,
   ;; even despite AVOID-CURRENT.
   (and avoid-current
	(next-error-buffer-p (current-buffer) nil
			     extra-test-inclusive extra-test-exclusive)
	(progn
223
	  (message "This is the only buffer with error message locations")
224 225
	  (current-buffer)))
   ;; 6. Give up.
226
   (error "No buffers contain error message locations")))
227

228
(defun next-error (&optional arg reset)
229
  "Visit next `next-error' message and corresponding source code.
230 231 232 233

If all the error messages parsed so far have been processed already,
the message buffer is checked for new ones.

234
A prefix ARG specifies how many error messages to move;
235 236 237 238
negative means move back to previous error messages.
Just \\[universal-argument] as a prefix means reparse the error message buffer
and start at the first error.

239
The RESET argument specifies that we should restart from the beginning.
240 241 242 243 244 245

\\[next-error] normally uses the most recently started
compilation, grep, or occur buffer.  It can also operate on any
buffer with output from the \\[compile], \\[grep] commands, or,
more generally, on any buffer in Compilation mode or with
Compilation Minor mode enabled, or any buffer in which
246 247 248 249
`next-error-function' is bound to an appropriate function.
To specify use of a particular buffer for error messages, type
\\[next-error] in that buffer when it is the only one displayed
in the current frame.
250

Juri Linkov's avatar
Juri Linkov committed
251 252 253 254
Once \\[next-error] has chosen the buffer for error messages, it
runs `next-error-hook' with `run-hooks', and stays with that buffer
until you use it in some other buffer which uses Compilation mode
or Compilation Minor mode.
255

256 257
To control which errors are matched, customize the variable
`compilation-error-regexp-alist'."
258
  (interactive "P")
259
  (if (consp arg) (setq reset t arg nil))
260 261 262
  (when (setq next-error-last-buffer (next-error-find-buffer))
    ;; we know here that next-error-function is a valid symbol we can funcall
    (with-current-buffer next-error-last-buffer
Juri Linkov's avatar
Juri Linkov committed
263
      (funcall next-error-function (prefix-numeric-value arg) reset)
264 265
      (when next-error-recenter
        (recenter next-error-recenter))
Juri Linkov's avatar
Juri Linkov committed
266
      (run-hooks 'next-error-hook))))
267

268 269 270 271 272 273
(defun next-error-internal ()
  "Visit the source code corresponding to the `next-error' message at point."
  (setq next-error-last-buffer (current-buffer))
  ;; we know here that next-error-function is a valid symbol we can funcall
  (with-current-buffer next-error-last-buffer
    (funcall next-error-function 0 nil)
274 275
    (when next-error-recenter
      (recenter next-error-recenter))
276 277
    (run-hooks 'next-error-hook)))

278 279 280
(defalias 'goto-next-locus 'next-error)
(defalias 'next-match 'next-error)

281
(defun previous-error (&optional n)
282
  "Visit previous `next-error' message and corresponding source code.
283 284 285 286 287 288

Prefix arg N says how many error messages to move backwards (or
forwards, if negative).

This operates on the output from the \\[compile] and \\[grep] commands."
  (interactive "p")
289
  (next-error (- (or n 1))))
290

291
(defun first-error (&optional n)
292 293 294 295 296 297 298
  "Restart at the first error.
Visit corresponding source code.
With prefix arg N, visit the source code of the Nth error.
This operates on the output from the \\[compile] command, for instance."
  (interactive "p")
  (next-error n t))

299
(defun next-error-no-select (&optional n)
300
  "Move point to the next error in the `next-error' buffer and highlight match.
301 302 303 304 305
Prefix arg N says how many error messages to move forwards (or
backwards, if negative).
Finds and highlights the source line like \\[next-error], but does not
select the source buffer."
  (interactive "p")
306 307
  (let ((next-error-highlight next-error-highlight-no-select))
    (next-error n))
308 309
  (pop-to-buffer next-error-last-buffer))

310
(defun previous-error-no-select (&optional n)
311
  "Move point to the previous error in the `next-error' buffer and highlight match.
312 313 314 315 316
Prefix arg N says how many error messages to move backwards (or
forwards, if negative).
Finds and highlights the source line like \\[previous-error], but does not
select the source buffer."
  (interactive "p")
317
  (next-error-no-select (- (or n 1))))
318

319
;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 321
(defvar next-error-follow-last-line nil)

Eli Zaretskii's avatar
Eli Zaretskii committed
322
(define-minor-mode next-error-follow-minor-mode
323
  "Minor mode for compilation, occur and diff modes.
324 325 326
With a prefix argument ARG, enable mode if ARG is positive, and
disable it otherwise.  If called from Lisp, enable mode if ARG is
omitted or nil.
Eli Zaretskii's avatar
Eli Zaretskii committed
327
When turned on, cursor motion in the compilation, grep, occur or diff
328
buffer causes automatic display of the corresponding source code location."
329
  :group 'next-error :init-value nil :lighter " Fol"
330
  (if (not next-error-follow-minor-mode)
331 332
      (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
    (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
333
    (make-local-variable 'next-error-follow-last-line)))
334

335 336
;; Used as a `post-command-hook' by `next-error-follow-mode'
;; for the *Compilation* *grep* and *Occur* buffers.
337 338 339 340 341 342 343 344 345
(defun next-error-follow-mode-post-command-hook ()
  (unless (equal next-error-follow-last-line (line-number-at-pos))
    (setq next-error-follow-last-line (line-number-at-pos))
    (condition-case nil
	(let ((compilation-context-lines nil))
	  (setq compilation-current-error (point))
	  (next-error-no-select 0))
      (error t))))

346

347 348
;;;

Karl Heuer's avatar
Karl Heuer committed
349 350 351 352
(defun fundamental-mode ()
  "Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one."
  (interactive)
353
  (kill-all-local-variables)
354 355
  (unless delay-mode-hooks
    (run-hooks 'after-change-major-mode-hook)))
356

Stefan Monnier's avatar
Stefan Monnier committed
357 358 359 360 361 362
;; Special major modes to view specially formatted data rather than files.

(defvar special-mode-map
  (let ((map (make-sparse-keymap)))
    (suppress-keymap map)
    (define-key map "q" 'quit-window)
363 364
    (define-key map " " 'scroll-up-command)
    (define-key map "\C-?" 'scroll-down-command)
Stefan Monnier's avatar
Stefan Monnier committed
365
    (define-key map "?" 'describe-mode)
366
    (define-key map "h" 'describe-mode)
Stefan Monnier's avatar
Stefan Monnier committed
367 368 369
    (define-key map ">" 'end-of-buffer)
    (define-key map "<" 'beginning-of-buffer)
    (define-key map "g" 'revert-buffer)
370
    (define-key map "z" 'kill-this-buffer)
Stefan Monnier's avatar
Stefan Monnier committed
371
    map))
372

Stefan Monnier's avatar
Stefan Monnier committed
373 374 375 376 377
(put 'special-mode 'mode-class 'special)
(define-derived-mode special-mode nil "Special"
  "Parent major mode from which special major modes should inherit."
  (setq buffer-read-only t))

378 379
;; Major mode meant to be the parent of programming modes.

380 381 382 383 384 385 386 387 388 389 390 391 392
(defvar prog-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map [?\C-\M-q] 'prog-indent-sexp)
    map)
  "Keymap used for programming modes.")

(defun prog-indent-sexp ()
  "Indent the expression after point."
  (interactive)
  (let ((start (point))
        (end (save-excursion (forward-sexp 1) (point))))
    (indent-region start end nil)))

393 394 395
(define-derived-mode prog-mode fundamental-mode "Prog"
  "Major mode for editing programming language source code."
  (set (make-local-variable 'require-final-newline) mode-require-final-newline)
396 397 398
  (set (make-local-variable 'parse-sexp-ignore-comments) t)
  ;; Any programming language is always written left to right.
  (setq bidi-paragraph-direction 'left-to-right))
399

Karl Heuer's avatar
Karl Heuer committed
400 401
;; Making and deleting lines.

402 403
(defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
  "Propertized string representing a hard newline character.")
404

405
(defun newline (&optional arg)
406
  "Insert a newline, and move to left margin of the new line if it's blank.
Dave Love's avatar
Dave Love committed
407 408
If `use-hard-newlines' is non-nil, the newline is marked with the
text-property `hard'.
409
With ARG, insert that many newlines.
Dave Love's avatar
Dave Love committed
410
Call `auto-fill-function' if the current column number is greater
411
than the value of `fill-column' and ARG is nil."
412
  (interactive "*P")
413
  (barf-if-buffer-read-only)
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
  ;; Set last-command-event to tell self-insert what to insert.
  (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
         (beforepos (point))
         (last-command-event ?\n)
         ;; Don't auto-fill if we have a numeric argument.
         (auto-fill-function (if arg nil auto-fill-function))
         (postproc
          ;; Do the rest in post-self-insert-hook, because we want to do it
          ;; *before* other functions on that hook.
          (lambda ()
            ;; Mark the newline(s) `hard'.
            (if use-hard-newlines
                (set-hard-newline-properties
                 (- (point) (prefix-numeric-value arg)) (point)))
            ;; If the newline leaves the previous line blank, and we
            ;; have a left margin, delete that from the blank line.
            (save-excursion
              (goto-char beforepos)
              (beginning-of-line)
              (and (looking-at "[ \t]$")
                   (> (current-left-margin) 0)
                   (delete-region (point)
                                  (line-end-position))))
            ;; Indent the line after the newline, except in one case:
            ;; when we added the newline at the beginning of a line which
            ;; starts a page.
            (or was-page-start
                (move-to-left-margin nil t)))))
    (unwind-protect
        (progn
          (add-hook 'post-self-insert-hook postproc)
          (self-insert-command (prefix-numeric-value arg)))
      ;; We first used let-binding to protect the hook, but that was naive
      ;; since add-hook affects the symbol-default value of the variable,
      ;; whereas the let-binding might only protect the buffer-local value.
      (remove-hook 'post-self-insert-hook postproc)))
451 452
  nil)

453 454 455 456 457 458 459
(defun set-hard-newline-properties (from to)
  (let ((sticky (get-text-property from 'rear-nonsticky)))
    (put-text-property from to 'hard 't)
    ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
    (if (and (listp sticky) (not (memq 'hard sticky)))
	(put-text-property from (point) 'rear-nonsticky
			   (cons 'hard sticky)))))
460

461
(defun open-line (n)
462
  "Insert a newline and leave point before it.
463 464
If there is a fill prefix and/or a `left-margin', insert them
on the new line if the line would have been blank.
465
With arg N, insert N newlines."
Jim Blandy's avatar
Jim Blandy committed
466
  (interactive "*p")
467
  (let* ((do-fill-prefix (and fill-prefix (bolp)))
468
	 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
469
	 (loc (point-marker))
470 471
	 ;; Don't expand an abbrev before point.
	 (abbrev-mode nil))
472
    (newline n)
473
    (goto-char loc)
474
    (while (> n 0)
475 476 477 478
      (cond ((bolp)
	     (if do-left-margin (indent-to (current-left-margin)))
	     (if do-fill-prefix (insert-and-inherit fill-prefix))))
      (forward-line 1)
479
      (setq n (1- n)))
480 481
    (goto-char loc)
    (end-of-line)))
Jim Blandy's avatar
Jim Blandy committed
482

483 484 485
(defun split-line (&optional arg)
  "Split current line, moving portion beyond point vertically down.
If the current line starts with `fill-prefix', insert it on the new
486
line as well.  With prefix ARG, don't insert `fill-prefix' on new line.
487

488
When called from Lisp code, ARG may be a prefix string to copy."
489
  (interactive "*P")
Jim Blandy's avatar
Jim Blandy committed
490
  (skip-chars-forward " \t")
491 492 493 494 495 496 497 498 499 500 501
  (let* ((col (current-column))
	 (pos (point))
	 ;; What prefix should we check for (nil means don't).
	 (prefix (cond ((stringp arg) arg)
		       (arg nil)
		       (t fill-prefix)))
	 ;; Does this line start with it?
	 (have-prfx (and prefix
			 (save-excursion
			   (beginning-of-line)
			   (looking-at (regexp-quote prefix))))))
502
    (newline 1)
503
    (if have-prfx (insert-and-inherit prefix))
Jim Blandy's avatar
Jim Blandy committed
504 505 506 507 508
    (indent-to col 0)
    (goto-char pos)))

(defun delete-indentation (&optional arg)
  "Join this line to previous and fix up whitespace at join.
509
If there is a fill prefix, delete it from the beginning of this line.
Jim Blandy's avatar
Jim Blandy committed
510 511 512 513 514 515 516
With argument, join this line to following line."
  (interactive "*P")
  (beginning-of-line)
  (if arg (forward-line 1))
  (if (eq (preceding-char) ?\n)
      (progn
	(delete-region (point) (1- (point)))
517 518 519
	;; If the second line started with the fill prefix,
	;; delete the prefix.
	(if (and fill-prefix
520
		 (<= (+ (point) (length fill-prefix)) (point-max))
521 522 523 524
		 (string= fill-prefix
			  (buffer-substring (point)
					    (+ (point) (length fill-prefix)))))
	    (delete-region (point) (+ (point) (length fill-prefix))))
Jim Blandy's avatar
Jim Blandy committed
525 526
	(fixup-whitespace))))

Dave Love's avatar
Dave Love committed
527
(defalias 'join-line #'delete-indentation) ; easier to find
528

Jim Blandy's avatar
Jim Blandy committed
529 530 531
(defun delete-blank-lines ()
  "On blank line, delete all surrounding blank lines, leaving just one.
On isolated blank line, delete that one.
532
On nonblank line, delete any immediately following blank lines."
Jim Blandy's avatar
Jim Blandy committed
533 534 535 536 537
  (interactive "*")
  (let (thisblank singleblank)
    (save-excursion
      (beginning-of-line)
      (setq thisblank (looking-at "[ \t]*$"))
Jim Blandy's avatar
Jim Blandy committed
538
      ;; Set singleblank if there is just one blank line here.
Jim Blandy's avatar
Jim Blandy committed
539 540 541 542 543 544
      (setq singleblank
	    (and thisblank
		 (not (looking-at "[ \t]*\n[ \t]*$"))
		 (or (bobp)
		     (progn (forward-line -1)
			    (not (looking-at "[ \t]*$")))))))
Jim Blandy's avatar
Jim Blandy committed
545
    ;; Delete preceding blank lines, and this one too if it's the only one.
Jim Blandy's avatar
Jim Blandy committed
546 547 548 549 550 551 552 553
    (if thisblank
	(progn
	  (beginning-of-line)
	  (if singleblank (forward-line 1))
	  (delete-region (point)
			 (if (re-search-backward "[^ \t\n]" nil t)
			     (progn (forward-line 1) (point))
			   (point-min)))))
Jim Blandy's avatar
Jim Blandy committed
554 555
    ;; Delete following blank lines, unless the current line is blank
    ;; and there are no following blank lines.
Jim Blandy's avatar
Jim Blandy committed
556 557 558 559 560 561 562
    (if (not (and thisblank singleblank))
	(save-excursion
	  (end-of-line)
	  (forward-line 1)
	  (delete-region (point)
			 (if (re-search-forward "[^ \t\n]" nil t)
			     (progn (beginning-of-line) (point))
Jim Blandy's avatar
Jim Blandy committed
563 564 565 566 567
			   (point-max)))))
    ;; Handle the special case where point is followed by newline and eob.
    ;; Delete the line, leaving point at eob.
    (if (looking-at "^[ \t]*\n\\'")
	(delete-region (point) (point-max)))))
Jim Blandy's avatar
Jim Blandy committed
568

569
(defun delete-trailing-whitespace (&optional start end)
570 571
  "Delete all the trailing whitespace across the current buffer.
All whitespace after the last non-whitespace character in a line is deleted.
572
This respects narrowing, created by \\[narrow-to-region] and friends.
573
A formfeed is not considered whitespace by this function.
574
If END is nil, also delete all trailing lines at the end of the buffer.
575 576 577 578 579 580
If the region is active, only delete whitespace within the region."
  (interactive (progn
                 (barf-if-buffer-read-only)
                 (if (use-region-p)
                     (list (region-beginning) (region-end))
                   (list nil nil))))
581 582
  (save-match-data
    (save-excursion
583 584 585 586
      (let ((end-marker (copy-marker (or end (point-max))))
            (start (or start (point-min))))
        (goto-char start)
        (while (re-search-forward "\\s-$" end-marker t)
587
          (skip-syntax-backward "-" (line-beginning-position))
588
          ;; Don't delete formfeeds, even if they are considered whitespace.
589 590
          (if (looking-at-p ".*\f")
              (goto-char (match-end 0)))
591
          (delete-region (point) (match-end 0)))
592 593 594 595
        ;; Delete trailing empty lines.
        (goto-char end-marker)
        (when (and (not end)
                   ;; Really the end of buffer.
596 597
                   (save-restriction (widen) (eobp))
                   (<= (skip-chars-backward "\n") -2))
598
          (delete-region (1+ (point)) end-marker))
599 600 601
        (set-marker end-marker nil))))
  ;; Return nil for the benefit of `write-file-functions'.
  nil)
602

Jim Blandy's avatar
Jim Blandy committed
603 604
(defun newline-and-indent ()
  "Insert a newline, then indent according to major mode.
605
Indentation is done using the value of `indent-line-function'.
Jim Blandy's avatar
Jim Blandy committed
606
In programming language modes, this is the same as TAB.
607
In some text modes, where TAB inserts a tab, this command indents to the
608
column specified by the function `current-left-margin'."
Jim Blandy's avatar
Jim Blandy committed
609
  (interactive "*")
610
  (delete-horizontal-space t)
Jim Blandy's avatar
Jim Blandy committed
611
  (newline)
Jim Blandy's avatar
Jim Blandy committed
612 613 614 615 616
  (indent-according-to-mode))

(defun reindent-then-newline-and-indent ()
  "Reindent current line, insert newline, then indent the new line.
Indentation of both lines is done according to the current major mode,
617
which means calling the current value of `indent-line-function'.
Jim Blandy's avatar
Jim Blandy committed
618 619
In programming language modes, this is the same as TAB.
In some text modes, where TAB inserts a tab, this indents to the
620
column specified by the function `current-left-margin'."
Jim Blandy's avatar
Jim Blandy committed
621
  (interactive "*")
622 623 624 625 626 627
  (let ((pos (point)))
    ;; Be careful to insert the newline before indenting the line.
    ;; Otherwise, the indentation might be wrong.
    (newline)
    (save-excursion
      (goto-char pos)
628 629 630 631 632 633 634 635 636 637
      ;; We are at EOL before the call to indent-according-to-mode, and
      ;; after it we usually are as well, but not always.  We tried to
      ;; address it with `save-excursion' but that uses a normal marker
      ;; whereas we need `move after insertion', so we do the save/restore
      ;; by hand.
      (setq pos (copy-marker pos t))
      (indent-according-to-mode)
      (goto-char pos)
      ;; Remove the trailing white-space after indentation because
      ;; indentation may introduce the whitespace.
Kenichi Handa's avatar
Kenichi Handa committed
638
      (delete-horizontal-space t))
639
    (indent-according-to-mode)))
640

Karl Heuer's avatar
Karl Heuer committed
641 642 643
(defun quoted-insert (arg)
  "Read next input character and insert it.
This is useful for inserting control characters.
644
With argument, insert ARG copies of the character.
Jim Blandy's avatar
Jim Blandy committed
645

Karl Heuer's avatar
Karl Heuer committed
646 647 648 649 650 651
If the first character you type after this command is an octal digit,
you should type a sequence of octal digits which specify a character code.
Any nondigit terminates the sequence.  If the terminator is a RET,
it is discarded; any other terminator is used itself as input.
The variable `read-quoted-char-radix' specifies the radix for this feature;
set it to 10 or 16 to use decimal or hex instead of octal.
652

Karl Heuer's avatar
Karl Heuer committed
653 654 655 656
In overwrite mode, this function inserts the character anyway, and
does not handle octal digits specially.  This means that if you use
overwrite as your normal editing mode, you can use this function to
insert characters when necessary.
657

Karl Heuer's avatar
Karl Heuer committed
658 659 660 661
In binary overwrite mode, this function does overwrite, and octal
digits are interpreted as a character code.  This is intended to be
useful for editing binary files."
  (interactive "*p")
662 663 664 665 666 667 668 669
  (let* ((char
	  ;; Avoid "obsolete" warnings for translation-table-for-input.
	  (with-no-warnings
	    (let (translation-table-for-input input-method-function)
	      (if (or (not overwrite-mode)
		      (eq overwrite-mode 'overwrite-mode-binary))
		  (read-quoted-char)
		(read-char))))))
670 671 672 673 674 675 676 677
    ;; This used to assume character codes 0240 - 0377 stand for
    ;; characters in some single-byte character set, and converted them
    ;; to Emacs characters.  But in 23.1 this feature is deprecated
    ;; in favor of inserting the corresponding Unicode characters.
    ;; (if (and enable-multibyte-characters
    ;;          (>= char ?\240)
    ;;          (<= char ?\377))
    ;;     (setq char (unibyte-char-to-multibyte char)))
Karl Heuer's avatar
Karl Heuer committed
678 679 680 681 682 683
    (if (> arg 0)
	(if (eq overwrite-mode 'overwrite-mode-binary)
	    (delete-char arg)))
    (while (> arg 0)
      (insert-and-inherit char)
      (setq arg (1- arg)))))
684

Kenichi Handa's avatar
Kenichi Handa committed
685
(defun forward-to-indentation (&optional arg)
Karl Heuer's avatar
Karl Heuer committed
686
  "Move forward ARG lines and position at first nonblank character."
687
  (interactive "^p")
Kenichi Handa's avatar
Kenichi Handa committed
688
  (forward-line (or arg 1))
Karl Heuer's avatar
Karl Heuer committed
689
  (skip-chars-forward " \t"))
690

Kenichi Handa's avatar
Kenichi Handa committed
691
(defun backward-to-indentation (&optional arg)
Karl Heuer's avatar
Karl Heuer committed
692
  "Move backward ARG lines and position at first nonblank character."
693
  (interactive "^p")
Kenichi Handa's avatar
Kenichi Handa committed
694
  (forward-line (- (or arg 1)))
Karl Heuer's avatar
Karl Heuer committed
695
  (skip-chars-forward " \t"))
Jim Blandy's avatar
Jim Blandy committed
696

Karl Heuer's avatar
Karl Heuer committed
697 698
(defun back-to-indentation ()
  "Move point to the first non-whitespace character on this line."
699
  (interactive "^")
Karl Heuer's avatar
Karl Heuer committed
700
  (beginning-of-line 1)
701
  (skip-syntax-forward " " (line-end-position))
702 703
  ;; Move back over chars that have whitespace syntax but have the p flag.
  (backward-prefix-chars))
Karl Heuer's avatar
Karl Heuer committed
704 705 706 707 708 709 710 711 712 713 714

(defun fixup-whitespace ()
  "Fixup white space between objects around point.
Leave one space or none, according to the context."
  (interactive "*")
  (save-excursion
    (delete-horizontal-space)
    (if (or (looking-at "^\\|\\s)")
	    (save-excursion (forward-char -1)
			    (looking-at "$\\|\\s(\\|\\s'")))
	nil
715
      (insert ?\s))))
Karl Heuer's avatar
Karl Heuer committed
716

717 718
(defun delete-horizontal-space (&optional backward-only)
  "Delete all spaces and tabs around point.
719
If BACKWARD-ONLY is non-nil, only delete them before point."
720
  (interactive "*P")
721 722 723 724 725 726 727
  (let ((orig-pos (point)))
    (delete-region
     (if backward-only
	 orig-pos
       (progn
	 (skip-chars-forward " \t")
	 (constrain-to-field nil orig-pos t)))
728
     (progn
729 730
       (skip-chars-backward " \t")
       (constrain-to-field nil orig-pos)))))
Karl Heuer's avatar
Karl Heuer committed
731

732
(defun just-one-space (&optional n)
733
  "Delete all spaces and tabs around point, leaving one space (or N spaces).
734
If N is negative, delete newlines as well."
735
  (interactive "*p")
736
  (unless n (setq n 1))
737 738 739 740
  (let ((orig-pos (point))
        (skip-characters (if (< n 0) " \t\n\r" " \t"))
        (n (abs n)))
    (skip-chars-backward skip-characters)
741
    (constrain-to-field nil orig-pos)
742
    (dotimes (i n)
743
      (if (= (following-char) ?\s)
744
	  (forward-char 1)
745
	(insert ?\s)))
746 747 748
    (delete-region
     (point)
     (progn
749
       (skip-chars-forward skip-characters)
750
       (constrain-to-field nil orig-pos t)))))
751

Jim Blandy's avatar
Jim Blandy committed
752
(defun beginning-of-buffer (&optional arg)
753
  "Move point to the beginning of the buffer.
754
With numeric arg N, put point N/10 of the way from the beginning.
755 756
If the buffer is narrowed, this command uses the beginning of the
accessible part of the buffer.
757

758 759
If Transient Mark mode is disabled, leave mark at previous
position, unless a \\[universal-argument] prefix is supplied.
760 761

Don't use this command in Lisp programs!
762
\(goto-char (point-min)) is faster."
763
  (interactive "^P")
764
  (or (consp arg)
765
      (region-active-p)
766
      (push-mark))
767
  (let ((size (- (point-max) (point-min))))
768
    (goto-char (if (and arg (not (consp arg)))
769 770 771 772 773 774 775
		   (+ (point-min)
		      (if (> size 10000)
			  ;; Avoid overflow for large buffer sizes!
			  (* (prefix-numeric-value arg)
			     (/ size 10))
			(/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
		 (point-min))))
776
  (if (and arg (not (consp arg))) (forward-line 1)))
Jim Blandy's avatar
Jim Blandy committed
777 778

(defun end-of-buffer (&optional arg)
779
  "Move point to the end of the buffer.
780
With numeric arg N, put point N/10 of the way from the end.
781 782
If the buffer is narrowed, this command uses the end of the
accessible part of the buffer.
783

784 785
If Transient Mark mode is disabled, leave mark at previous
position, unless a \\[universal-argument] prefix is supplied.
786 787

Don't use this command in Lisp programs!
788
\(goto-char (point-max)) is faster."
789
  (interactive "^P")
790
  (or (consp arg) (region-active-p) (push-mark))
791
  (let ((size (- (point-max) (point-min))))
792
    (goto-char (if (and arg (not (consp arg)))
793 794 795 796 797 798 799
		   (- (point-max)
		      (if (> size 10000)
			  ;; Avoid overflow for large buffer sizes!
			  (* (prefix-numeric-value arg)
			     (/ size 10))
			(/ (* size (prefix-numeric-value arg)) 10)))
		 (point-max))))
Eric S. Raymond's avatar
Eric S. Raymond committed
800 801
  ;; If we went to a place in the middle of the buffer,
  ;; adjust it to the beginning of a line.
802
  (cond ((and arg (not (consp arg))) (forward-line 1))
803
	((> (point) (window-end nil t))
804 805 806 807
	 ;; If the end of the buffer is not already on the screen,
	 ;; then scroll specially to put it near, but not at, the bottom.
	 (overlay-recenter (point))
	 (recenter -3))))
Jim Blandy's avatar
Jim Blandy committed
808

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
(defcustom delete-active-region t
  "Whether single-char deletion commands delete an active region.
This has an effect only if Transient Mark mode is enabled, and
affects `delete-forward-char' and `delete-backward-char', though
not `delete-char'.

If the value is the symbol `kill', the active region is killed
instead of deleted."
  :type '(choice (const :tag "Delete active region" t)
                 (const :tag "Kill active region" kill)
                 (const :tag "Do ordinary deletion" nil))
  :group 'editing
  :version "24.1")

(defun delete-backward-char (n &optional killflag)
  "Delete the previous N characters (following if N is negative).
If Transient Mark mode is enabled, the mark is active, and N is 1,
delete the text in the region and deactivate the mark instead.
To disable this, set `delete-active-region' to nil.

Optional second arg KILLFLAG, if non-nil, means to kill (save in
kill ring) instead of delete.  Interactively, N is the prefix
arg, and KILLFLAG is set if N is explicitly specified.

In Overwrite mode, single character backward deletion may replace
tabs with spaces so as to back over columns, unless point is at
the end of the line."
  (interactive "p\nP")
  (unless (integerp n)
    (signal 'wrong-type-argument (list 'integerp n)))
  (cond ((and (use-region-p)
	      delete-active-region
	      (= n 1))
	 ;; If a region is active, kill or delete it.
	 (if (eq delete-active-region 'kill)
	     (kill-region (region-beginning) (region-end))
	   (delete-region (region-beginning) (region-end))))
	;; In Overwrite mode, maybe untabify while deleting
	((null (or (null overwrite-mode)
		   (<= n 0)
		   (memq (char-before) '(?\t ?\n))
		   (eobp)
		   (eq (char-after) ?\n)))
852 853
	 (let ((ocol (current-column)))
           (delete-char (- n) killflag)
854 855 856 857 858 859
	   (save-excursion
	     (insert-char ?\s (- ocol (current-column)) nil))))
	;; Otherwise, do simple deletion.
	(t (delete-char (- n) killflag))))

(defun delete-forward-char (n &optional killflag)
860
  "Delete the following N characters (previous if N is negative).
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
If Transient Mark mode is enabled, the mark is active, and N is 1,
delete the text in the region and deactivate the mark instead.
To disable this, set `delete-active-region' to nil.

Optional second arg KILLFLAG non-nil means to kill (save in kill
ring) instead of delete.  Interactively, N is the prefix arg, and
KILLFLAG is set if N was explicitly specified."
  (interactive "p\nP")
  (unless (integerp n)
    (signal 'wrong-type-argument (list 'integerp n)))
  (cond ((and (use-region-p)
	      delete-active-region
	      (= n 1))
	 ;; If a region is active, kill or delete it.
	 (if (eq delete-active-region 'kill)
	     (kill-region (region-beginning) (region-end))
	   (delete-region (region-beginning) (region-end))))
	;; Otherwise, do simple deletion.
	(t (delete-char n killflag))))

Jim Blandy's avatar
Jim Blandy committed
881
(defun mark-whole-buffer ()
Jim Blandy's avatar
Jim Blandy committed
882
  "Put point at beginning and mark at end of buffer.
883
If narrowing is in effect, only uses the accessible part of the buffer.
Jim Blandy's avatar
Jim Blandy committed
884 885 886
You probably should not use this function in Lisp programs;
it is usually a mistake for a Lisp function to use any subroutine
that uses or sets the mark."
Jim Blandy's avatar
Jim Blandy committed
887 888
  (interactive)
  (push-mark (point))
889
  (push-mark (point-max) nil t)
Jim Blandy's avatar
Jim Blandy committed
890
  (goto-char (point-min)))
891

892

Karl Heuer's avatar
Karl Heuer committed
893 894
;; Counting lines, one way or another.

Lute Kamstra's avatar
Lute Kamstra committed
895 896 897 898
(defun goto-line (line &optional buffer)
  "Goto LINE, counting from line 1 at beginning of buffer.
Normally, move point in the current buffer, and leave mark at the
previous position.  With just \\[universal-argument] as argument,
899
move point in the most recently selected other buffer, and switch to it.
Lute Kamstra's avatar
Lute Kamstra committed
900

901 902 903 904 905 906 907
If there's a number in the buffer at point, it is the default for LINE.

This function is usually the wrong thing to use in a Lisp program.
What you probably want instead is something like:
  (goto-char (point-min)) (forward-line (1- N))
If at all possible, an even better solution is to use char counts
rather than line counts."
908 909 910 911 912 913 914 915
  (interactive
   (if (and current-prefix-arg (not (consp current-prefix-arg)))
       (list (prefix-numeric-value current-prefix-arg))
     ;; Look for a default, a number in the buffer at point.
     (let* ((default
	      (save-excursion
		(skip-chars-backward "0-9")
		(if (looking-at "[0-9]")
Jose E. Marchesi's avatar
Jose E. Marchesi committed
916 917 918 919 920
		    (string-to-number
		     (buffer-substring-no-properties
		      (point)
		      (progn (skip-chars-forward "0-9")
			     (point)))))))
921 922 923 924 925 926 927 928 929
	    ;; Decide if we're switching buffers.
	    (buffer
	     (if (consp current-prefix-arg)
		 (other-buffer (current-buffer) t)))
	    (buffer-prompt
	     (if buffer
		 (concat " in " (buffer-name buffer))
	       "")))
       ;; Read the argument, offering that number (if any) as default.
930 931 932 933 934
       (list (read-number (format (if default "Goto line%s (%s): "
                                    "Goto line%s: ")
                                  buffer-prompt
                                  default)
                          default)
935 936 937 938 939 940
	     buffer))))
  ;; Switch to the desired buffer, one way or another.
  (if buffer
      (let ((window (get-buffer-window buffer)))
	(if window (select-window window)
	  (switch-to-buffer-other-window buffer))))
941
  ;; Leave mark at previous position
942
  (or (region-active-p) (push-mark))
943
  ;; Move to the specified line number in that buffer.
Karl Heuer's avatar
Karl Heuer committed
944 945
  (save-restriction
    (widen)
946
    (goto-char (point-min))
Karl Heuer's avatar
Karl Heuer committed
947
    (if (eq selective-display t)
Lute Kamstra's avatar
Lute Kamstra committed
948 949
	(re-search-forward "[\n\C-m]" nil 'end (1- line))
      (forward-line (1- line)))))
Jim Blandy's avatar
Jim Blandy committed
950

951
(defun count-words-region (start end)
952
  "Count the number of words in the region.
953
If called interactively, print a message reporting the number of
954 955 956
lines, words, and chars in the region.
If called from Lisp, return the number of words between positions
START and END."
957
  (interactive "r")
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
  (if (called-interactively-p 'any)
      (count-words--message "Region" start end)
    (count-words start end)))

(defun count-words (start end)
  "Count words between START and END.
If called interactively, START and END are normally the start and
end of the buffer; but if the region is active, START and END are
the start and end of the region.  Print a message reporting the
number of lines, words, and chars.

If called from Lisp, return the number of words between START and
END, without printing any message."
  (interactive (list nil nil))
  (cond ((not (called-interactively-p 'any))
	 (let ((words 0))
	   (save-excursion
	     (save-restriction
	       (narrow-to-region start end)
	       (goto-char (point-min))
	       (while (forward-word 1)
		 (setq words (1+ words)))))
	   words))
	((use-region-p)
	 (call-interactively 'count-words-region))
	(t
	 (count-words--message "Buffer" (point-min) (point-max)))))

(defun count-words--message (str start end)
  (let ((lines (count-lines start end))
	(words (count-words start end))
	(chars (- end start)))
    (message "%s has %d line%s, %d word%s, and %d character%s."
	     str
	     lines (if (= lines 1) "" "s")
	     words (if (= words 1) "" "s")
	     chars (if (= chars 1) "" "s"))))

(define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
Jim Blandy's avatar
Jim Blandy committed
997 998

(defun what-line ()
999
  "Print the current buffer line number and narrowed line number of point."
Jim Blandy's avatar
Jim Blandy committed