XEmacs 21.2-b1
[chise/xemacs-chise.git.1] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for XEmacs
2
3 ;; Copyright (C) 1985-7, 1993-5, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Tinker Systems and INS Engineering Corp.
5
6 ;; Maintainer: XEmacs Development Team
7 ;; Keywords: lisp, extensions, internal, dumped
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24 ;; 02111-1307, USA.
25
26 ;;; Synched up with: FSF 19.34 [But not very closely].
27
28 ;;; Commentary:
29
30 ;; This file is dumped with XEmacs.
31
32 ;; A grab-bag of basic XEmacs commands not specifically related to some
33 ;; major mode or to file-handling.
34
35 ;; Changes for zmacs-style active-regions:
36 ;;
37 ;; beginning-of-buffer, end-of-buffer, count-lines-region,
38 ;; count-lines-buffer, what-line, what-cursor-position, set-goal-column,
39 ;; set-fill-column, prefix-arg-internal, and line-move (which is used by
40 ;; next-line and previous-line) set zmacs-region-stays to t, so that they
41 ;; don't affect the current region-hilighting state.
42 ;;
43 ;; mark-whole-buffer, mark-word, exchange-point-and-mark, and
44 ;; set-mark-command (without an argument) call zmacs-activate-region.
45 ;;
46 ;; mark takes an optional arg like the new Fmark_marker() does.  When
47 ;; the region is not active, mark returns nil unless the optional arg is true.
48 ;;
49 ;; push-mark, pop-mark, exchange-point-and-mark, and set-marker, and
50 ;; set-mark-command use (mark t) so that they can access the mark whether
51 ;; the region is active or not.
52 ;;
53 ;; shell-command, shell-command-on-region, yank, and yank-pop (which all
54 ;; push a mark) have been altered to call exchange-point-and-mark with an
55 ;; argument, meaning "don't activate the region".  These commands  only use
56 ;; exchange-point-and-mark to position the newly-pushed mark correctly, so
57 ;; this isn't a user-visible change.  These functions have also been altered
58 ;; to use (mark t) for the same reason.
59
60 ;; 97/3/14 Jareth Hein (jhod@po.iijnet.or.jp) added kinsoku processing (support
61 ;; for filling of Asian text) into the fill code. This was ripped bleeding from
62 ;; Mule-2.3, and could probably use some feature additions (like additional wrap
63 ;; styles, etc)
64
65 ;; 97/06/11 Steve Baur (steve@altair.xemacs.org) Convert use of
66 ;;  (preceding|following)-char to char-(after|before).
67
68 ;;; Code:
69
70 (defgroup editing-basics nil
71   "Most basic editing variables."
72   :group 'editing)
73
74 (defgroup killing nil
75   "Killing and yanking commands."
76   :group 'editing)
77
78 (defgroup fill-comments nil
79   "Indenting and filling of comments."
80   :prefix "comment-"
81   :group 'fill)
82
83 (defgroup paren-matching nil
84   "Highlight (un)matching of parens and expressions."
85   :prefix "paren-"
86   :group 'matching)
87
88 (defgroup log-message nil
89   "Messages logging and display customizations."
90   :group 'minibuffer)
91
92 (defgroup warnings nil
93   "Warnings customizations."
94   :group 'minibuffer)
95
96
97 (defun newline (&optional arg)
98   "Insert a newline, and move to left margin of the new line if it's blank.
99 The newline is marked with the text-property `hard'.
100 With arg, insert that many newlines.
101 In Auto Fill mode, if no numeric arg, break the preceding line if it's long."
102   (interactive "*P")
103   (barf-if-buffer-read-only nil (point))
104   ;; Inserting a newline at the end of a line produces better redisplay in
105   ;; try_window_id than inserting at the beginning of a line, and the textual
106   ;; result is the same.  So, if we're at beginning of line, pretend to be at
107   ;; the end of the previous line.
108   ;; #### Does this have any relevance in XEmacs?
109   (let ((flag (and (not (bobp))
110                    (bolp)
111                    ;; Make sure the newline before point isn't intangible.
112                    (not (get-char-property (1- (point)) 'intangible))
113                    ;; Make sure the newline before point isn't read-only.
114                    (not (get-char-property (1- (point)) 'read-only))
115                    ;; Make sure the newline before point isn't invisible.
116                    (not (get-char-property (1- (point)) 'invisible))
117                    ;; This should probably also test for the previous char
118                    ;;  being the *last* character too.
119                    (not (get-char-property (1- (point)) 'end-open))
120                    ;; Make sure the newline before point has the same
121                    ;; properties as the char before it (if any).
122                    (< (or (previous-extent-change (point)) -2)
123                       (- (point) 2))))
124         (was-page-start (and (bolp)
125                              (looking-at page-delimiter)))
126         (beforepos (point)))
127     (if flag (backward-char 1))
128     ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
129     ;; Set last-command-char to tell self-insert what to insert.
130     (let ((last-command-char ?\n)
131           ;; Don't auto-fill if we have a numeric argument.
132           ;; Also not if flag is true (it would fill wrong line);
133           ;; there is no need to since we're at BOL.
134           (auto-fill-function (if (or arg flag) nil auto-fill-function)))
135       (unwind-protect
136           (self-insert-command (prefix-numeric-value arg))
137         ;; If we get an error in self-insert-command, put point at right place.
138         (if flag (forward-char 1))))
139     ;; If we did *not* get an error, cancel that forward-char.
140     (if flag (backward-char 1))
141     ;; Mark the newline(s) `hard'.
142     (if use-hard-newlines
143         (let* ((from (- (point) (if arg (prefix-numeric-value arg) 1)))
144                (sticky (get-text-property from 'end-open))) ; XEmacs
145           (put-text-property from (point) 'hard 't)
146           ;; If end-open is not "t", add 'hard to end-open list
147           (if (and (listp sticky) (not (memq 'hard sticky)))
148               (put-text-property from (point) 'end-open ; XEmacs
149                                  (cons 'hard sticky)))))
150     ;; If the newline leaves the previous line blank,
151     ;; and we have a left margin, delete that from the blank line.
152     (or flag
153         (save-excursion
154           (goto-char beforepos)
155           (beginning-of-line)
156           (and (looking-at "[ \t]$")
157                (> (current-left-margin) 0)
158                (delete-region (point) (progn (end-of-line) (point))))))
159     (if flag (forward-char 1))
160     ;; Indent the line after the newline, except in one case:
161     ;; when we added the newline at the beginning of a line
162     ;; which starts a page.
163     (or was-page-start
164         (move-to-left-margin nil t)))
165   nil)
166
167 (defun set-hard-newline-properties (from to)
168   (let ((sticky (get-text-property from 'rear-nonsticky)))
169     (put-text-property from to 'hard 't)
170     ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
171     (if (and (listp sticky) (not (memq 'hard sticky)))
172         (put-text-property from (point) 'rear-nonsticky
173                            (cons 'hard sticky)))))
174
175 (defun open-line (arg)
176   "Insert a newline and leave point before it.
177 If there is a fill prefix and/or a left-margin, insert them on the new line
178 if the line would have been blank.
179 With arg N, insert N newlines."
180   (interactive "*p")
181   (let* ((do-fill-prefix (and fill-prefix (bolp)))
182          (do-left-margin (and (bolp) (> (current-left-margin) 0)))
183          (loc (point)))
184     (newline arg)
185     (goto-char loc)
186     (while (> arg 0)
187       (cond ((bolp)
188              (if do-left-margin (indent-to (current-left-margin)))
189              (if do-fill-prefix (insert fill-prefix))))
190       (forward-line 1)
191       (setq arg (1- arg)))
192     (goto-char loc)
193     (end-of-line)))
194
195 (defun split-line ()
196   "Split current line, moving portion beyond point vertically down."
197   (interactive "*")
198   (skip-chars-forward " \t")
199   (let ((col (current-column))
200         (pos (point)))
201     (newline 1)
202     (indent-to col 0)
203     (goto-char pos)))
204
205 (defun quoted-insert (arg)
206   "Read next input character and insert it.
207 This is useful for inserting control characters.
208 You may also type up to 3 octal digits, to insert a character with that code.
209
210 In overwrite mode, this function inserts the character anyway, and
211 does not handle octal digits specially.  This means that if you use
212 overwrite as your normal editing mode, you can use this function to
213 insert characters when necessary.
214
215 In binary overwrite mode, this function does overwrite, and octal
216 digits are interpreted as a character code.  This is supposed to make
217 this function useful in editing binary files."
218   (interactive "*p")
219   (let ((char (if (or (not overwrite-mode)
220                       (eq overwrite-mode 'overwrite-mode-binary))
221                   (read-quoted-char)
222                 ;; read-char obeys C-g, so we should protect.  FSF
223                 ;; doesn't have the protection here, but it's a bug in
224                 ;; FSF.
225                 (let ((inhibit-quit t))
226                   (read-char)))))
227     (if (> arg 0)
228         (if (eq overwrite-mode 'overwrite-mode-binary)
229             (delete-char arg)))
230     (while (> arg 0)
231       (insert char)
232       (setq arg (1- arg)))))
233
234 (defun delete-indentation (&optional arg)
235   "Join this line to previous and fix up whitespace at join.
236 If there is a fill prefix, delete it from the beginning of this line.
237 With argument, join this line to following line."
238   (interactive "*P")
239   (beginning-of-line)
240   (if arg (forward-line 1))
241   (if (eq (char-before (point)) ?\n)
242       (progn
243         (delete-region (point) (1- (point)))
244         ;; If the second line started with the fill prefix,
245         ;; delete the prefix.
246         (if (and fill-prefix
247                  (<= (+ (point) (length fill-prefix)) (point-max))
248                  (string= fill-prefix
249                           (buffer-substring (point)
250                                             (+ (point) (length fill-prefix)))))
251             (delete-region (point) (+ (point) (length fill-prefix))))
252         (fixup-whitespace))))
253
254 (defun fixup-whitespace ()
255   "Fixup white space between objects around point.
256 Leave one space or none, according to the context."
257   (interactive "*")
258   (save-excursion
259     (delete-horizontal-space)
260     (if (or (looking-at "^\\|\\s)")
261             (save-excursion (forward-char -1)
262                             (looking-at "$\\|\\s(\\|\\s'")))
263         nil
264       (insert ?\ ))))
265
266 (defun delete-horizontal-space ()
267   "Delete all spaces and tabs around point."
268   (interactive "*")
269   (skip-chars-backward " \t")
270   (delete-region (point) (progn (skip-chars-forward " \t") (point))))
271
272 (defun just-one-space ()
273   "Delete all spaces and tabs around point, leaving one space."
274   (interactive "*")
275   (if abbrev-mode ; XEmacs
276       (expand-abbrev))
277   (skip-chars-backward " \t")
278   (if (eq (char-after (point)) ? ) ; XEmacs
279       (forward-char 1)
280     (insert ? ))
281   (delete-region (point) (progn (skip-chars-forward " \t") (point))))
282
283 (defun delete-blank-lines ()
284   "On blank line, delete all surrounding blank lines, leaving just one.
285 On isolated blank line, delete that one.
286 On nonblank line, delete any immediately following blank lines."
287   (interactive "*")
288   (let (thisblank singleblank)
289     (save-excursion
290       (beginning-of-line)
291       (setq thisblank (looking-at "[ \t]*$"))
292       ;; Set singleblank if there is just one blank line here.
293       (setq singleblank
294             (and thisblank
295                  (not (looking-at "[ \t]*\n[ \t]*$"))
296                  (or (bobp)
297                      (progn (forward-line -1)
298                             (not (looking-at "[ \t]*$")))))))
299     ;; Delete preceding blank lines, and this one too if it's the only one.
300     (if thisblank
301         (progn
302           (beginning-of-line)
303           (if singleblank (forward-line 1))
304           (delete-region (point)
305                          (if (re-search-backward "[^ \t\n]" nil t)
306                              (progn (forward-line 1) (point))
307                            (point-min)))))
308     ;; Delete following blank lines, unless the current line is blank
309     ;; and there are no following blank lines.
310     (if (not (and thisblank singleblank))
311         (save-excursion
312           (end-of-line)
313           (forward-line 1)
314           (delete-region (point)
315                          (if (re-search-forward "[^ \t\n]" nil t)
316                              (progn (beginning-of-line) (point))
317                            (point-max)))))
318     ;; Handle the special case where point is followed by newline and eob.
319     ;; Delete the line, leaving point at eob.
320     (if (looking-at "^[ \t]*\n\\'")
321         (delete-region (point) (point-max)))))
322
323 (defun back-to-indentation ()
324   "Move point to the first non-whitespace character on this line."
325   ;; XEmacs change
326   (interactive "_")
327   (beginning-of-line 1)
328   (skip-chars-forward " \t"))
329
330 (defun newline-and-indent ()
331   "Insert a newline, then indent according to major mode.
332 Indentation is done using the value of `indent-line-function'.
333 In programming language modes, this is the same as TAB.
334 In some text modes, where TAB inserts a tab, this command indents to the
335 column specified by the function `current-left-margin'."
336   (interactive "*")
337   (delete-region (point) (progn (skip-chars-backward " \t") (point)))
338   (newline)
339   (indent-according-to-mode))
340
341 (defun reindent-then-newline-and-indent ()
342   "Reindent current line, insert newline, then indent the new line.
343 Indentation of both lines is done according to the current major mode,
344 which means calling the current value of `indent-line-function'.
345 In programming language modes, this is the same as TAB.
346 In some text modes, where TAB inserts a tab, this indents to the
347 column specified by the function `current-left-margin'."
348   (interactive "*")
349   (save-excursion
350     (delete-region (point) (progn (skip-chars-backward " \t") (point)))
351     (indent-according-to-mode))
352   (newline)
353   (indent-according-to-mode))
354
355 ;; Internal subroutine of delete-char
356 (defun kill-forward-chars (arg)
357   (if (listp arg) (setq arg (car arg)))
358   (if (eq arg '-) (setq arg -1))
359   (kill-region (point) (+ (point) arg)))
360
361 ;; Internal subroutine of backward-delete-char
362 (defun kill-backward-chars (arg)
363   (if (listp arg) (setq arg (car arg)))
364   (if (eq arg '-) (setq arg -1))
365   (kill-region (point) (- (point) arg)))
366
367 (defun backward-delete-char-untabify (arg &optional killp)
368   "Delete characters backward, changing tabs into spaces.
369 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
370 Interactively, ARG is the prefix arg (default 1)
371 and KILLP is t if a prefix arg was specified."
372   (interactive "*p\nP")
373   (let ((count arg))
374     (save-excursion
375       (while (and (> count 0) (not (bobp)))
376         (if (eq (char-before (point)) ?\t) ; XEmacs
377             (let ((col (current-column)))
378               (forward-char -1)
379               (setq col (- col (current-column)))
380               (insert-char ?\ col)
381               (delete-char 1)))
382         (forward-char -1)
383         (setq count (1- count)))))
384   (delete-backward-char arg killp)
385   ;; XEmacs: In overwrite mode, back over columns while clearing them out,
386   ;; unless at end of line.
387   (and overwrite-mode (not (eolp))
388        (save-excursion (insert-char ?\  arg))))
389
390 (defcustom delete-key-deletes-forward nil
391   "*If non-nil, the DEL key will erase one character forwards.
392 If nil, the DEL key will erase one character backwards."
393   :type 'boolean
394   :group 'editing-basics)
395
396 (defcustom backward-delete-function 'backward-delete-char
397   "*Function called to delete backwards on a delete keypress.
398 If `delete-key-deletes-forward' is nil, `backward-or-forward-delete-char'
399 calls this function to erase one character backwards.  Default value
400 is 'backward-delete-char, with 'backward-delete-char-untabify being a
401 popular alternate setting."
402   :type 'function
403   :group 'editing-basics)
404
405 ;; Trash me, baby.
406 (defsubst delete-forward-p ()
407   (and delete-key-deletes-forward
408        (or (not (eq (device-type) 'x))
409            (x-keysym-on-keyboard-sans-modifiers-p 'backspace))))
410
411 (defun backward-or-forward-delete-char (arg)
412   "Delete either one character backwards or one character forwards.
413 Controlled by the state of `delete-key-deletes-forward' and whether the
414 BackSpace keysym even exists on your keyboard.  If you don't have a
415 BackSpace keysym, the delete key should always delete one character
416 backwards."
417   (interactive "*p")
418   (if (delete-forward-p)
419       (delete-char arg)
420     (funcall backward-delete-function arg)))
421
422 (defun backward-or-forward-kill-word (arg)
423   "Delete either one word backwards or one word forwards.
424 Controlled by the state of `delete-key-deletes-forward' and whether the
425 BackSpace keysym even exists on your keyboard.  If you don't have a
426 BackSpace keysym, the delete key should always delete one character
427 backwards."
428   (interactive "*p")
429   (if (delete-forward-p)
430       (kill-word arg)
431     (backward-kill-word arg)))
432
433 (defun backward-or-forward-kill-sentence (arg)
434     "Delete either one sentence backwards or one sentence forwards.
435 Controlled by the state of `delete-key-deletes-forward' and whether the
436 BackSpace keysym even exists on your keyboard.  If you don't have a
437 BackSpace keysym, the delete key should always delete one character
438 backwards."
439   (interactive "*P")
440   (if (delete-forward-p)
441       (kill-sentence arg)
442     (backward-kill-sentence (prefix-numeric-value arg))))
443
444 (defun backward-or-forward-kill-sexp (arg)
445     "Delete either one sexpr backwards or one sexpr forwards.
446 Controlled by the state of `delete-key-deletes-forward' and whether the
447 BackSpace keysym even exists on your keyboard.  If you don't have a
448 BackSpace keysym, the delete key should always delete one character
449 backwards."
450   (interactive "*p")
451   (if (delete-forward-p)
452       (kill-sexp arg)
453     (backward-kill-sexp arg)))
454
455 (defun zap-to-char (arg char)
456   "Kill up to and including ARG'th occurrence of CHAR.
457 Goes backward if ARG is negative; error if CHAR not found."
458   (interactive "*p\ncZap to char: ")
459   (kill-region (point) (progn
460                          (search-forward (char-to-string char) nil nil arg)
461 ;                        (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
462                          (point))))
463
464 (defun zap-up-to-char (arg char)
465   "Kill up to ARG'th occurrence of CHAR.
466 Goes backward if ARG is negative; error if CHAR not found."
467   (interactive "*p\ncZap up to char: ")
468   (kill-region (point) (progn
469                        (search-forward (char-to-string char) nil nil arg)
470                        (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
471                        (point))))
472
473 (defun beginning-of-buffer (&optional arg)
474   "Move point to the beginning of the buffer; leave mark at previous position.
475 With arg N, put point N/10 of the way from the beginning.
476
477 If the buffer is narrowed, this command uses the beginning and size
478 of the accessible part of the buffer.
479
480 Don't use this command in Lisp programs!
481 \(goto-char (point-min)) is faster and avoids clobbering the mark."
482   ;; XEmacs change
483   (interactive "_P")
484   (push-mark)
485   (let ((size (- (point-max) (point-min))))
486     (goto-char (if arg
487                    (+ (point-min)
488                       (if (> size 10000)
489                           ;; Avoid overflow for large buffer sizes!
490                           (* (prefix-numeric-value arg)
491                              (/ size 10))
492                         (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
493                  (point-min))))
494   (if arg (forward-line 1)))
495
496 (defun end-of-buffer (&optional arg)
497   "Move point to the end of the buffer; leave mark at previous position.
498 With arg N, put point N/10 of the way from the end.
499
500 If the buffer is narrowed, this command uses the beginning and size
501 of the accessible part of the buffer.
502
503 Don't use this command in Lisp programs!
504 \(goto-char (point-max)) is faster and avoids clobbering the mark."
505   ;; XEmacs change
506   (interactive "_P")
507   (push-mark)
508   ;; XEmacs changes here.
509   (let ((scroll-to-end (not (pos-visible-in-window-p (point-max))))
510         (size (- (point-max) (point-min))))
511     (goto-char (if arg
512                    (- (point-max)
513                       (if (> size 10000)
514                           ;; Avoid overflow for large buffer sizes!
515                           (* (prefix-numeric-value arg)
516                              (/ size 10))
517                         (/ (* size (prefix-numeric-value arg)) 10)))
518                  (point-max)))
519     (cond (arg
520            ;; If we went to a place in the middle of the buffer,
521            ;; adjust it to the beginning of a line.
522            (forward-line 1))
523           ;; XEmacs change
524           (scroll-to-end
525            ;; If the end of the buffer is not already on the screen,
526            ;; then scroll specially to put it near, but not at, the bottom.
527            (recenter -3)))))
528
529 ;; XEmacs (not in FSF)
530 (defun mark-beginning-of-buffer (&optional arg)
531   "Push a mark at the beginning of the buffer; leave point where it is.
532 With arg N, push mark N/10 of the way from the true beginning."
533   (interactive "P")
534   (push-mark (if arg
535                  (if (> (buffer-size) 10000)
536                      ;; Avoid overflow for large buffer sizes!
537                      (* (prefix-numeric-value arg)
538                         (/ (buffer-size) 10))
539                    (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
540                (point-min))
541              nil
542              t))
543 (define-function 'mark-bob 'mark-beginning-of-buffer)
544
545 ;; XEmacs (not in FSF)
546 (defun mark-end-of-buffer (&optional arg)
547   "Push a mark at the end of the buffer; leave point where it is.
548 With arg N, push mark N/10 of the way from the true end."
549   (interactive "P")
550   (push-mark (if arg
551                  (- (1+ (buffer-size))
552                     (if (> (buffer-size) 10000)
553                         ;; Avoid overflow for large buffer sizes!
554                         (* (prefix-numeric-value arg)
555                            (/ (buffer-size) 10))
556                       (/ (* (buffer-size) (prefix-numeric-value arg)) 10)))
557                  (point-max))
558              nil
559              t))
560 (define-function 'mark-eob 'mark-end-of-buffer)
561
562 (defun mark-whole-buffer ()
563   "Put point at beginning and mark at end of buffer.
564 You probably should not use this function in Lisp programs;
565 it is usually a mistake for a Lisp function to use any subroutine
566 that uses or sets the mark."
567   (interactive)
568   (push-mark (point))
569   (push-mark (point-max) nil t)
570   (goto-char (point-min)))
571
572 ;; XEmacs
573 (defun eval-current-buffer (&optional printflag)
574   "Evaluate the current buffer as Lisp code.
575 Programs can pass argument PRINTFLAG which controls printing of output:
576 nil means discard it; anything else is stream for print."
577   (interactive)
578   (eval-buffer (current-buffer) printflag))
579
580 ;; XEmacs
581 (defun count-words-buffer (&optional buffer)
582   "Print the number of words in BUFFER.
583 If called noninteractively, the value is returned rather than printed.
584 BUFFER defaults to the current buffer."
585   (interactive)
586   (let ((words (count-words-region (point-min) (point-max) buffer)))
587     (when (interactive-p)
588       (message "Buffer has %d words" words))
589     words))
590
591 ;; XEmacs
592 (defun count-words-region (start end &optional buffer)
593   "Print the number of words in region between START and END in BUFFER.
594 If called noninteractively, the value is returned rather than printed.
595 BUFFER defaults to the current buffer."
596   (interactive "_r")
597   (save-excursion
598     (set-buffer (or buffer (current-buffer)))
599     (let ((words 0))
600       (goto-char start)
601       (while (< (point) end)
602         (when (forward-word 1)
603           (incf words)))
604       (when  (interactive-p)
605         (message "Region has %d words" words))
606       words)))
607
608 (defun count-lines-region (start end)
609   "Print number of lines and characters in the region."
610   ;; XEmacs change
611   (interactive "_r")
612   (message "Region has %d lines, %d characters"
613            (count-lines start end) (- end start)))
614
615 ;; XEmacs
616 (defun count-lines-buffer (&optional buffer)
617   "Print number of lines and characters in BUFFER."
618   (interactive)
619   (with-current-buffer (or buffer (current-buffer))
620     (let ((cnt (count-lines (point-min) (point-max))))
621       (message "Buffer has %d lines, %d characters"
622                cnt (- (point-max) (point-min)))
623       cnt)))
624
625 ;;; Modified by Bob Weiner, 8/24/95, to print narrowed line number also.
626 ;;; Expanded by Bob Weiner, Altrasoft, on 02/12/1997
627 (defun what-line ()
628   "Print the following variants of the line number of point:
629      Region line     - displayed line within the active region
630      Collapsed line  - includes only selectively displayed lines;
631      Buffer line     - physical line in the buffer;
632      Narrowed line   - line number from the start of the buffer narrowing."
633   ;; XEmacs change
634   (interactive "_")
635   (let ((opoint (point)) start)
636     (save-excursion
637       (save-restriction
638         (if (region-active-p)
639             (goto-char (region-beginning))
640           (goto-char (point-min)))
641         (widen)
642         (beginning-of-line)
643         (setq start (point))
644         (goto-char opoint)
645         (beginning-of-line)
646         (let* ((buffer-line (1+ (count-lines 1 (point))))
647                (narrowed-p (or (/= start 1)
648                                (/= (point-max) (1+ (buffer-size)))))
649                (narrowed-line (if narrowed-p (1+ (count-lines start (point)))))
650                (selective-line (if selective-display
651                                    (1+ (count-lines start (point) t))))
652                (region-line (if (region-active-p)
653                                 (1+ (count-lines start (point) selective-display)))))
654           (cond (region-line
655                  (message "Region line %d; Buffer line %d"
656                           region-line buffer-line))
657                 ((and narrowed-p selective-line (/= selective-line narrowed-line))
658                  ;; buffer narrowed and some lines selectively displayed
659                  (message "Collapsed line %d; Buffer line %d; Narrowed line %d"
660                           selective-line buffer-line narrowed-line))
661                 (narrowed-p
662                  ;; buffer narrowed
663                  (message "Buffer line %d; Narrowed line %d"
664                           buffer-line narrowed-line))
665                 ((and selective-line (/= selective-line buffer-line))
666                  ;; some lines selectively displayed
667                  (message "Collapsed line %d; Buffer line %d"
668                           selective-line buffer-line))
669                 (t
670                  ;; give a basic line count
671                  (message "Line %d" buffer-line)))))))
672   (setq zmacs-region-stays t))
673
674 ;;; Bob Weiner, Altrasoft, 02/12/1998
675 ;;; Added the 3rd arg in `count-lines' to conditionalize the counting of
676 ;;; collapsed lines.
677 (defun count-lines (start end &optional ignore-invisible-lines-flag)
678   "Return number of lines between START and END.
679 This is usually the number of newlines between them,
680 but can be one more if START is not equal to END
681 and the greater of them is not at the start of a line.
682
683 With optional IGNORE-INVISIBLE-LINES-FLAG non-nil, lines collapsed with
684 selective-display are excluded from the line count."
685   (save-excursion
686     (save-restriction
687       (narrow-to-region start end)
688       (goto-char (point-min))
689       (if (and (not ignore-invisible-lines-flag) (eq selective-display t))
690           (save-match-data
691             (let ((done 0))
692               (while (re-search-forward "[\n\C-m]" nil t 40)
693                 (setq done (+ 40 done)))
694               (while (re-search-forward "[\n\C-m]" nil t 1)
695                 (setq done (+ 1 done)))
696               (goto-char (point-max))
697               (if (and (/= start end)
698                        (not (bolp)))
699                   (1+ done)
700                 done)))
701         (- (buffer-size) (forward-line (buffer-size)))))))
702
703 (defun what-cursor-position ()
704   "Print info on cursor position (on screen and within buffer)."
705   ;; XEmacs change
706   (interactive "_")
707   (let* ((char (char-after (point))) ; XEmacs
708          (beg (point-min))
709          (end (point-max))
710          (pos (point))
711          (total (buffer-size))
712          (percent (if (> total 50000)
713                       ;; Avoid overflow from multiplying by 100!
714                       (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
715                     (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
716          (hscroll (if (= (window-hscroll) 0)
717                       ""
718                     (format " Hscroll=%d" (window-hscroll))))
719          (col (+ (current-column) (if column-number-start-at-one 1 0))))
720     (if (= pos end)
721         (if (or (/= beg 1) (/= end (1+ total)))
722             (message "point=%d of %d(%d%%) <%d - %d>  column %d %s"
723                      pos total percent beg end col hscroll)
724           (message "point=%d of %d(%d%%)  column %d %s"
725                    pos total percent col hscroll))
726       ;; XEmacs: don't use single-key-description
727       (if (or (/= beg 1) (/= end (1+ total)))
728           (message "Char: %s (0%o, %d, 0x%x)  point=%d of %d(%d%%) <%d - %d>  column %d %s"
729                    (text-char-description char) char char char pos total
730                    percent beg end col hscroll)
731         (message "Char: %s (0%o, %d, 0x%x)  point=%d of %d(%d%%)  column %d %s"
732                  (text-char-description char) char char char pos total
733                  percent col hscroll)))))
734
735 (defun fundamental-mode ()
736   "Major mode not specialized for anything in particular.
737 Other major modes are defined by comparison with this one."
738   (interactive)
739   (kill-all-local-variables))
740
741 ;; XEmacs the following are declared elsewhere
742 ;(defvar read-expression-map (cons 'keymap minibuffer-local-map)
743 ;  "Minibuffer keymap used for reading Lisp expressions.")
744 ;(define-key read-expression-map "\M-\t" 'lisp-complete-symbol)
745
746 ;(put 'eval-expression 'disabled t)
747
748 ;(defvar read-expression-history nil)
749
750 ;; We define this, rather than making `eval' interactive,
751 ;; for the sake of completion of names like eval-region, eval-current-buffer.
752 (defun eval-expression (expression &optional eval-expression-insert-value)
753   "Evaluate EXPRESSION and print value in minibuffer.
754 Value is also consed on to front of the variable `values'.
755 With prefix argument, insert the result to the current buffer."
756   ;(interactive "xEval: ")
757   (interactive
758    (list (read-from-minibuffer "Eval: "
759                                nil read-expression-map t
760                                'read-expression-history)
761          current-prefix-arg))
762   (setq values (cons (eval expression) values))
763   (prin1 (car values)
764          (if eval-expression-insert-value (current-buffer) t)))
765
766 ;; XEmacs -- extra parameter (variant, but equivalent logic)
767 (defun edit-and-eval-command (prompt command &optional history)
768   "Prompting with PROMPT, let user edit COMMAND and eval result.
769 COMMAND is a Lisp expression.  Let user edit that expression in
770 the minibuffer, then read and evaluate the result."
771   (let ((command (read-expression prompt
772                                   ;; first try to format the thing readably;
773                                   ;; and if that fails, print it normally.
774                                   (condition-case ()
775                                       (let ((print-readably t))
776                                         (prin1-to-string command))
777                                     (error (prin1-to-string command)))
778                                   (or history '(command-history . 1)))))
779     (or history (setq history 'command-history))
780     (if (consp history)
781         (setq history (car history)))
782     (if (eq history t)
783         nil
784       ;; If command was added to the history as a string,
785       ;; get rid of that.  We want only evallable expressions there.
786       (if (stringp (car (symbol-value history)))
787           (set history (cdr (symbol-value history))))
788
789       ;; If command to be redone does not match front of history,
790       ;; add it to the history.
791       (or (equal command (car (symbol-value history)))
792           (set history (cons command (symbol-value history)))))
793     (eval command)))
794
795 (defun repeat-complex-command (arg)
796   "Edit and re-evaluate last complex command, or ARGth from last.
797 A complex command is one which used the minibuffer.
798 The command is placed in the minibuffer as a Lisp form for editing.
799 The result is executed, repeating the command as changed.
800 If the command has been changed or is not the most recent previous command
801 it is added to the front of the command history.
802 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
803 to get different commands to edit and resubmit."
804   (interactive "p")
805   ;; XEmacs: It looks like our version is better -sb
806   (let ((print-level nil))
807     (edit-and-eval-command "Redo: "
808                            (or (nth (1- arg) command-history)
809                                (error ""))
810                            (cons 'command-history arg))))
811
812 ;; XEmacs: Functions moved to minibuf.el
813 ;; previous-matching-history-element
814 ;; next-matching-history-element
815 ;; next-history-element
816 ;; previous-history-element
817 ;; next-complete-history-element
818 ;; previous-complete-history-element
819 \f
820 (defun goto-line (arg)
821   "Goto line ARG, counting from line 1 at beginning of buffer."
822   (interactive "NGoto line: ")
823   (setq arg (prefix-numeric-value arg))
824   (save-restriction
825     (widen)
826     (goto-char 1)
827     (if (eq selective-display t)
828         (re-search-forward "[\n\C-m]" nil 'end (1- arg))
829       (forward-line (1- arg)))))
830
831 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
832 (define-function 'advertised-undo 'undo)
833
834 (defun undo (&optional arg)
835   "Undo some previous changes.
836 Repeat this command to undo more changes.
837 A numeric argument serves as a repeat count."
838   (interactive "*p")
839   ;; If we don't get all the way through, make last-command indicate that
840   ;; for the following command.
841   (setq this-command t)
842   (let ((modified (buffer-modified-p))
843         (recent-save (recent-auto-save-p)))
844     (or (eq (selected-window) (minibuffer-window))
845         (display-message 'command "Undo!"))
846     (or (and (eq last-command 'undo)
847              (eq (current-buffer) last-undo-buffer)) ; XEmacs
848         (progn (undo-start)
849                (undo-more 1)))
850     (undo-more (or arg 1))
851     ;; Don't specify a position in the undo record for the undo command.
852     ;; Instead, undoing this should move point to where the change is.
853     (let ((tail buffer-undo-list)
854           done)
855       (while (and tail (not done) (not (null (car tail))))
856         (if (integerp (car tail))
857             (progn
858               (setq done t)
859               (setq buffer-undo-list (delq (car tail) buffer-undo-list))))
860         (setq tail (cdr tail))))
861     (and modified (not (buffer-modified-p))
862          (delete-auto-save-file-if-necessary recent-save)))
863   ;; If we do get all the way through, make this-command indicate that.
864   (setq this-command 'undo))
865
866 (defvar pending-undo-list nil
867   "Within a run of consecutive undo commands, list remaining to be undone.")
868
869 (defvar last-undo-buffer nil)   ; XEmacs
870
871 (defun undo-start ()
872   "Set `pending-undo-list' to the front of the undo list.
873 The next call to `undo-more' will undo the most recently made change."
874   (if (eq buffer-undo-list t)
875       (error "No undo information in this buffer"))
876   (setq pending-undo-list buffer-undo-list))
877
878 (defun undo-more (count)
879   "Undo back N undo-boundaries beyond what was already undone recently.
880 Call `undo-start' to get ready to undo recent changes,
881 then call `undo-more' one or more times to undo them."
882   (or pending-undo-list
883       (error "No further undo information"))
884   (setq pending-undo-list (primitive-undo count pending-undo-list)
885         last-undo-buffer (current-buffer)))     ; XEmacs
886
887 ;; XEmacs
888 (defun call-with-transparent-undo (fn &rest args)
889   "Apply FN to ARGS, and then undo all changes made by FN to the current
890 buffer.  The undo records are processed even if FN returns non-locally.
891 There is no trace of the changes made by FN in the buffer's undo history.
892
893 You can use this in a write-file-hooks function with continue-save-buffer
894 to make the contents of a disk file differ from its in-memory buffer."
895   (let ((buffer-undo-list nil)
896         ;; Kludge to prevent undo list truncation:
897         (undo-high-threshold -1)
898         (undo-threshold -1)
899         (obuffer (current-buffer)))
900     (unwind-protect
901         (apply fn args)
902       ;; Go to the buffer we will restore and make it writable:
903       (set-buffer obuffer)
904       (save-excursion
905         (let ((buffer-read-only nil))
906           (save-restriction
907             (widen)
908             ;; Perform all undos, with further undo logging disabled:
909             (let ((tail buffer-undo-list))
910               (setq buffer-undo-list t)
911               (while tail
912                 (setq tail (primitive-undo (length tail) tail))))))))))
913
914 ;; XEmacs: The following are in other files
915 ;; shell-command-history
916 ;; shell-command-switch
917 ;; shell-command
918 ;; shell-command-sentinel
919
920 \f
921 (defconst universal-argument-map
922   (let ((map (make-sparse-keymap)))
923     (set-keymap-default-binding map 'universal-argument-other-key)
924     ;FSFmacs (define-key map [switch-frame] nil)
925     (define-key map [(t)] 'universal-argument-other-key)
926     (define-key map [(meta t)] 'universal-argument-other-key)
927     (define-key map [(control u)] 'universal-argument-more)
928     (define-key map [?-] 'universal-argument-minus)
929     (define-key map [?0] 'digit-argument)
930     (define-key map [?1] 'digit-argument)
931     (define-key map [?2] 'digit-argument)
932     (define-key map [?3] 'digit-argument)
933     (define-key map [?4] 'digit-argument)
934     (define-key map [?5] 'digit-argument)
935     (define-key map [?6] 'digit-argument)
936     (define-key map [?7] 'digit-argument)
937     (define-key map [?8] 'digit-argument)
938     (define-key map [?9] 'digit-argument)
939     map)
940   "Keymap used while processing \\[universal-argument].")
941
942 (defvar universal-argument-num-events nil
943   "Number of argument-specifying events read by `universal-argument'.
944 `universal-argument-other-key' uses this to discard those events
945 from (this-command-keys), and reread only the final command.")
946
947 (defun universal-argument ()
948   "Begin a numeric argument for the following command.
949 Digits or minus sign following \\[universal-argument] make up the numeric argument.
950 \\[universal-argument] following the digits or minus sign ends the argument.
951 \\[universal-argument] without digits or minus sign provides 4 as argument.
952 Repeating \\[universal-argument] without digits or minus sign
953  multiplies the argument by 4 each time."
954   (interactive)
955   (setq prefix-arg (list 4))
956   (setq zmacs-region-stays t)   ; XEmacs
957   (setq universal-argument-num-events (length (this-command-keys)))
958   (setq overriding-terminal-local-map universal-argument-map))
959
960 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
961 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
962 (defun universal-argument-more (arg)
963   (interactive "_P")                    ; XEmacs
964   (if (consp arg)
965       (setq prefix-arg (list (* 4 (car arg))))
966     (setq prefix-arg arg)
967     (setq overriding-terminal-local-map nil))
968   (setq universal-argument-num-events (length (this-command-keys))))
969
970 (defun negative-argument (arg)
971   "Begin a negative numeric argument for the next command.
972 \\[universal-argument] following digits or minus sign ends the argument."
973   (interactive "_P")                    ; XEmacs
974   (cond ((integerp arg)
975           (setq prefix-arg (- arg)))
976          ((eq arg '-)
977           (setq prefix-arg nil))
978          (t
979           (setq prefix-arg '-)))
980   (setq universal-argument-num-events (length (this-command-keys)))
981   (setq overriding-terminal-local-map universal-argument-map))
982
983 ;; XEmacs:  This function not synched with FSF
984 (defun digit-argument (arg)
985   "Part of the numeric argument for the next command.
986 \\[universal-argument] following digits or minus sign ends the argument."
987   (interactive "_P")                    ; XEmacs
988   (let* ((event last-command-event)
989          (key (and (key-press-event-p event)
990                    (event-key event)))
991          (digit (and key (characterp key) (>= key ?0) (<= key ?9)
992                      (- key ?0))))
993     (if (null digit)
994         (universal-argument-other-key arg)
995       (cond ((integerp arg)
996              (setq prefix-arg (+ (* arg 10)
997                                  (if (< arg 0) (- digit) digit))))
998             ((eq arg '-)
999              ;; Treat -0 as just -, so that -01 will work.
1000              (setq prefix-arg (if (zerop digit) '- (- digit))))
1001             (t
1002              (setq prefix-arg digit)))
1003       (setq universal-argument-num-events (length (this-command-keys)))
1004       (setq overriding-terminal-local-map universal-argument-map))))
1005
1006 ;; For backward compatibility, minus with no modifiers is an ordinary
1007 ;; command if digits have already been entered.
1008 (defun universal-argument-minus (arg)
1009   (interactive "_P") ; XEmacs
1010   (if (integerp arg)
1011       (universal-argument-other-key arg)
1012     (negative-argument arg)))
1013
1014 ;; Anything else terminates the argument and is left in the queue to be
1015 ;; executed as a command.
1016 (defun universal-argument-other-key (arg)
1017   (interactive "_P")                    ; XEmacs
1018   (setq prefix-arg arg)
1019   (let* ((key (this-command-keys))
1020          ;; FSF calls silly function `listify-key-sequence' here.
1021           (keylist (append key nil)))
1022     (setq unread-command-events
1023            (append (nthcdr universal-argument-num-events keylist)
1024                    unread-command-events)))
1025   (reset-this-command-lengths)
1026   (setq overriding-terminal-local-map nil))
1027
1028 \f
1029 ;; XEmacs -- keep zmacs-region active.
1030 (defun forward-to-indentation (arg)
1031   "Move forward ARG lines and position at first nonblank character."
1032   (interactive "_p")
1033   (forward-line arg)
1034   (skip-chars-forward " \t"))
1035
1036 (defun backward-to-indentation (arg)
1037   "Move backward ARG lines and position at first nonblank character."
1038   (interactive "_p")
1039   (forward-line (- arg))
1040   (skip-chars-forward " \t"))
1041
1042 (defcustom kill-whole-line nil
1043   "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
1044   :type 'boolean
1045   :group 'killing)
1046
1047 (defun kill-line (&optional arg)
1048   "Kill the rest of the current line; if no nonblanks there, kill thru newline.
1049 With prefix argument, kill that many lines from point.
1050 Negative arguments kill lines backward.
1051
1052 When calling from a program, nil means \"no arg\",
1053 a number counts as a prefix arg.
1054
1055 If `kill-whole-line' is non-nil, then kill the whole line
1056 when given no argument at the beginning of a line."
1057   (interactive "*P")
1058   (kill-region (point)
1059                ;; Don't shift point before doing the delete; that way,
1060                ;; undo will record the right position of point.
1061 ;; FSF
1062 ;              ;; It is better to move point to the other end of the kill
1063 ;              ;; before killing.  That way, in a read-only buffer, point
1064 ;              ;; moves across the text that is copied to the kill ring.
1065 ;              ;; The choice has no effect on undo now that undo records
1066 ;              ;; the value of point from before the command was run.
1067 ;              (progn
1068                (save-excursion
1069                  (if arg
1070                      (forward-line (prefix-numeric-value arg))
1071                    (if (eobp)
1072                        (signal 'end-of-buffer nil))
1073                    (if (or (looking-at "[ \t]*$") (and kill-whole-line (bolp)))
1074                        (forward-line 1)
1075                      (end-of-line)))
1076                  (point))))
1077
1078 ;; XEmacs
1079 (defun backward-kill-line nil
1080   "Kill back to the beginning of the line."
1081   (interactive)
1082   (let ((point (point)))
1083     (beginning-of-line nil)
1084     (kill-region (point) point)))
1085
1086 \f
1087 ;;;; Window system cut and paste hooks.
1088 ;;;
1089 ;;; I think that kill-hooks is a better name and more general mechanism
1090 ;;; than interprogram-cut-function (from FSFmacs).  I don't like the behavior
1091 ;;; of interprogram-paste-function: ^Y should always come from the kill ring,
1092 ;;; not the X selection.  But if that were provided, it should be called (and
1093 ;;; behave as) yank-hooks instead.  -- jwz
1094
1095 ;; [... code snipped ...]
1096
1097 (defcustom kill-hooks nil
1098   "*Functions run when something is added to the XEmacs kill ring.
1099 These functions are called with one argument, the string most recently
1100 cut or copied.  You can use this to, for example, make the most recent
1101 kill become the X Clipboard selection."
1102   :type 'hook
1103   :group 'killing)
1104
1105 ;;; `kill-hooks' seems not sufficient because
1106 ;;; `interprogram-cut-function' requires more variable about to rotate
1107 ;;; the cut buffers.  I'm afraid to change interface of `kill-hooks',
1108 ;;; so I add it. (1997-11-03 by MORIOKA Tomohiko)
1109
1110 (defvar interprogram-cut-function nil
1111   "Function to call to make a killed region available to other programs.
1112
1113 Most window systems provide some sort of facility for cutting and
1114 pasting text between the windows of different programs.
1115 This variable holds a function that Emacs calls whenever text
1116 is put in the kill ring, to make the new kill available to other
1117 programs.
1118
1119 The function takes one or two arguments.
1120 The first argument, TEXT, is a string containing
1121 the text which should be made available.
1122 The second, PUSH, if non-nil means this is a \"new\" kill;
1123 nil means appending to an \"old\" kill.")
1124
1125 (defvar interprogram-paste-function nil
1126   "Function to call to get text cut from other programs.
1127
1128 Most window systems provide some sort of facility for cutting and
1129 pasting text between the windows of different programs.
1130 This variable holds a function that Emacs calls to obtain
1131 text that other programs have provided for pasting.
1132
1133 The function should be called with no arguments.  If the function
1134 returns nil, then no other program has provided such text, and the top
1135 of the Emacs kill ring should be used.  If the function returns a
1136 string, that string should be put in the kill ring as the latest kill.
1137
1138 Note that the function should return a string only if a program other
1139 than Emacs has provided a string for pasting; if Emacs provided the
1140 most recent string, the function should return nil.  If it is
1141 difficult to tell whether Emacs or some other program provided the
1142 current string, it is probably good enough to return nil if the string
1143 is equal (according to `string=') to the last text Emacs provided.")
1144
1145 \f
1146 ;;;; The kill ring data structure.
1147
1148 (defvar kill-ring nil
1149   "List of killed text sequences.
1150 Since the kill ring is supposed to interact nicely with cut-and-paste
1151 facilities offered by window systems, use of this variable should
1152 interact nicely with `interprogram-cut-function' and
1153 `interprogram-paste-function'.  The functions `kill-new',
1154 `kill-append', and `current-kill' are supposed to implement this
1155 interaction; you may want to use them instead of manipulating the kill
1156 ring directly.")
1157
1158 (defcustom kill-ring-max 30
1159   "*Maximum length of kill ring before oldest elements are thrown away."
1160   :type 'integer
1161   :group 'killing)
1162
1163 (defvar kill-ring-yank-pointer nil
1164   "The tail of the kill ring whose car is the last thing yanked.")
1165
1166 (defun kill-new (string &optional replace)
1167   "Make STRING the latest kill in the kill ring.
1168 Set the kill-ring-yank pointer to point to it.
1169 Run `kill-hooks'.
1170 Optional second argument REPLACE non-nil means that STRING will replace
1171 the front of the kill ring, rather than being added to the list."
1172 ;  (and (fboundp 'menu-bar-update-yank-menu)
1173 ;       (menu-bar-update-yank-menu string (and replace (car kill-ring))))
1174   (if replace
1175       (setcar kill-ring string)
1176     (setq kill-ring (cons string kill-ring))
1177     (if (> (length kill-ring) kill-ring-max)
1178         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
1179   (setq kill-ring-yank-pointer kill-ring)
1180   (if interprogram-cut-function
1181       (funcall interprogram-cut-function string (not replace)))
1182   (run-hook-with-args 'kill-hooks string))
1183
1184 (defun kill-append (string before-p)
1185   "Append STRING to the end of the latest kill in the kill ring.
1186 If BEFORE-P is non-nil, prepend STRING to the kill.
1187 Run `kill-hooks'."
1188   (kill-new (if before-p
1189                 (concat string (car kill-ring))
1190               (concat (car kill-ring) string)) t))
1191
1192 (defun current-kill (n &optional do-not-move)
1193   "Rotate the yanking point by N places, and then return that kill.
1194 If N is zero, `interprogram-paste-function' is set, and calling it
1195 returns a string, then that string is added to the front of the
1196 kill ring and returned as the latest kill.
1197 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
1198 yanking point\; just return the Nth kill forward."
1199   (let ((interprogram-paste (and (= n 0)
1200                                  interprogram-paste-function
1201                                  (funcall interprogram-paste-function))))
1202     (if interprogram-paste
1203         (progn
1204           ;; Disable the interprogram cut function when we add the new
1205           ;; text to the kill ring, so Emacs doesn't try to own the
1206           ;; selection, with identical text.
1207           (let ((interprogram-cut-function nil))
1208             (kill-new interprogram-paste))
1209           interprogram-paste)
1210       (or kill-ring (error "Kill ring is empty"))
1211       (let* ((tem (nthcdr (mod (- n (length kill-ring-yank-pointer))
1212                                (length kill-ring))
1213                           kill-ring)))
1214         (or do-not-move
1215             (setq kill-ring-yank-pointer tem))
1216         (car tem)))))
1217
1218
1219 \f
1220 ;;;; Commands for manipulating the kill ring.
1221
1222 ;; In FSF killing read-only text just pastes it into kill-ring.  Which
1223 ;; is a very bad idea -- see Jamie's comment below.
1224
1225 ;(defvar kill-read-only-ok nil
1226 ;  "*Non-nil means don't signal an error for killing read-only text.")
1227
1228 (defun kill-region (beg end &optional verbose) ; verbose is XEmacs addition
1229   "Kill between point and mark.
1230 The text is deleted but saved in the kill ring.
1231 The command \\[yank] can retrieve it from there.
1232 \(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
1233
1234 This is the primitive for programs to kill text (as opposed to deleting it).
1235 Supply two arguments, character numbers indicating the stretch of text
1236  to be killed.
1237 Any command that calls this function is a \"kill command\".
1238 If the previous command was also a kill command,
1239 the text killed this time appends to the text killed last time
1240 to make one entry in the kill ring."
1241   (interactive "*r\np")
1242 ;  (interactive
1243 ;   (let ((region-hack (and zmacs-regions (eq last-command 'yank))))
1244 ;     ;; This lets "^Y^W" work.  I think this is dumb, but zwei did it.
1245 ;     (if region-hack (zmacs-activate-region))
1246 ;     (prog1
1247 ;        (list (point) (mark) current-prefix-arg)
1248 ;       (if region-hack (zmacs-deactivate-region)))))
1249   ;; beg and end can be markers but the rest of this function is
1250   ;; written as if they are only integers
1251   (if (markerp beg) (setq beg (marker-position beg)))
1252   (if (markerp end) (setq end (marker-position end)))
1253   (or (and beg end) (if zmacs-regions ;; rewritten for I18N3 snarfing
1254                         (error "The region is not active now")
1255                       (error "The mark is not set now")))
1256   (if verbose (if buffer-read-only
1257                   (lmessage 'command "Copying %d characters"
1258                             (- (max beg end) (min beg end)))
1259                 (lmessage 'command "Killing %d characters"
1260                           (- (max beg end) (min beg end)))))
1261   (cond
1262
1263    ;; I don't like this large change in behavior -- jwz
1264    ;; Read-Only text means it shouldn't be deleted, so I'm restoring
1265    ;; this code, but only for text-properties and not full extents. -sb
1266    ;; If the buffer is read-only, we should beep, in case the person
1267    ;; just isn't aware of this.  However, there's no harm in putting
1268    ;; the region's text in the kill ring, anyway.
1269    ((or (and buffer-read-only (not inhibit-read-only))
1270         (text-property-not-all (min beg end) (max beg end) 'read-only nil))
1271    ;; This is redundant.
1272    ;; (if verbose (message "Copying %d characters"
1273    ;;                    (- (max beg end) (min beg end))))
1274     (copy-region-as-kill beg end)
1275    ;; ;; This should always barf, and give us the correct error.
1276    ;; (if kill-read-only-ok
1277    ;;     (message "Read only text copied to kill ring")
1278     (setq this-command 'kill-region)
1279     (barf-if-buffer-read-only)
1280     (signal 'buffer-read-only (list (current-buffer))))
1281
1282    ;; In certain cases, we can arrange for the undo list and the kill
1283    ;; ring to share the same string object.  This code does that.
1284    ((not (or (eq buffer-undo-list t)
1285              (eq last-command 'kill-region)
1286              ;; Use = since positions may be numbers or markers.
1287              (= beg end)))
1288     ;; Don't let the undo list be truncated before we can even access it.
1289     ;; FSF calls this `undo-strong-limit'
1290     (let ((undo-high-threshold (+ (- end beg) 100))
1291           ;(old-list buffer-undo-list)
1292           tail)
1293       (delete-region beg end)
1294       ;; Search back in buffer-undo-list for this string,
1295       ;; in case a change hook made property changes.
1296       (setq tail buffer-undo-list)
1297       (while (and tail
1298                   (not (stringp (car-safe (car-safe tail))))) ; XEmacs
1299         (pop tail))
1300       ;; Take the same string recorded for undo
1301       ;; and put it in the kill-ring.
1302       (and tail
1303            (kill-new (car (car tail))))))
1304
1305    (t
1306     ;; if undo is not kept, grab the string then delete it (which won't
1307     ;; add another string to the undo list).
1308     (copy-region-as-kill beg end)
1309     (delete-region beg end)))
1310   (setq this-command 'kill-region))
1311
1312 ;; copy-region-as-kill no longer sets this-command, because it's confusing
1313 ;; to get two copies of the text when the user accidentally types M-w and
1314 ;; then corrects it with the intended C-w.
1315 (defun copy-region-as-kill (beg end)
1316   "Save the region as if killed, but don't kill it.
1317 Run `kill-hooks'."
1318   (interactive "r")
1319   (if (eq last-command 'kill-region)
1320       (kill-append (buffer-substring beg end) (< end beg))
1321     (kill-new (buffer-substring beg end)))
1322   nil)
1323
1324 (defun kill-ring-save (beg end)
1325   "Save the region as if killed, but don't kill it.
1326 This command is similar to `copy-region-as-kill', except that it gives
1327 visual feedback indicating the extent of the region being copied."
1328   (interactive "r")
1329   (copy-region-as-kill beg end)
1330   ;; copy before delay, for xclipboard's benefit
1331   (if (interactive-p)
1332       (let ((other-end (if (= (point) beg) end beg))
1333             (opoint (point))
1334             ;; Inhibit quitting so we can make a quit here
1335             ;; look like a C-g typed as a command.
1336             (inhibit-quit t))
1337         (if (pos-visible-in-window-p other-end (selected-window))
1338             (progn
1339               ;; FSF (I'm not sure what this does -sb)
1340 ;             ;; Swap point and mark.
1341 ;             (set-marker (mark-marker) (point) (current-buffer))
1342               (goto-char other-end)
1343               (sit-for 1)
1344 ;             ;; Swap back.
1345 ;             (set-marker (mark-marker) other-end (current-buffer))
1346               (goto-char opoint)
1347               ;; If user quit, deactivate the mark
1348               ;; as C-g would as a command.
1349               (and quit-flag (mark)
1350                    (zmacs-deactivate-region)))
1351           ;; too noisy. -- jwz
1352 ;         (let* ((killed-text (current-kill 0))
1353 ;                (message-len (min (length killed-text) 40)))
1354 ;           (if (= (point) beg)
1355 ;               ;; Don't say "killed"; that is misleading.
1356 ;               (message "Saved text until \"%s\""
1357 ;                       (substring killed-text (- message-len)))
1358 ;             (message "Saved text from \"%s\""
1359 ;                     (substring killed-text 0 message-len))))
1360           ))))
1361
1362 (defun append-next-kill ()
1363   "Cause following command, if it kills, to append to previous kill."
1364   ;; XEmacs
1365   (interactive "_")
1366   (if (interactive-p)
1367       (progn
1368         (setq this-command 'kill-region)
1369         (display-message 'command
1370           "If the next command is a kill, it will append"))
1371     (setq last-command 'kill-region)))
1372
1373 (defun yank-pop (arg)
1374   "Replace just-yanked stretch of killed text with a different stretch.
1375 This command is allowed only immediately after a `yank' or a `yank-pop'.
1376 At such a time, the region contains a stretch of reinserted
1377 previously-killed text.  `yank-pop' deletes that text and inserts in its
1378 place a different stretch of killed text.
1379
1380 With no argument, the previous kill is inserted.
1381 With argument N, insert the Nth previous kill.
1382 If N is negative, this is a more recent kill.
1383
1384 The sequence of kills wraps around, so that after the oldest one
1385 comes the newest one."
1386   (interactive "*p")
1387   (if (not (eq last-command 'yank))
1388       (error "Previous command was not a yank"))
1389   (setq this-command 'yank)
1390   (let ((inhibit-read-only t)
1391         (before (< (point) (mark t))))
1392     (delete-region (point) (mark t))
1393     ;;(set-marker (mark-marker) (point) (current-buffer))
1394     (set-mark (point))
1395     (insert (current-kill arg))
1396     (if before
1397         ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1398         ;; It is cleaner to avoid activation, even though the command
1399         ;; loop would deactivate the mark because we inserted text.
1400         (goto-char (prog1 (mark t)
1401                      (set-marker (mark-marker t) (point) (current-buffer))))))
1402   nil)
1403
1404
1405 (defun yank (&optional arg)
1406   "Reinsert the last stretch of killed text.
1407 More precisely, reinsert the stretch of killed text most recently
1408 killed OR yanked.  Put point at end, and set mark at beginning.
1409 With just C-u as argument, same but put point at beginning (and mark at end).
1410 With argument N, reinsert the Nth most recently killed stretch of killed
1411 text.
1412 See also the command \\[yank-pop]."
1413   (interactive "*P")
1414   ;; If we don't get all the way through, make last-command indicate that
1415   ;; for the following command.
1416   (setq this-command t)
1417   (push-mark (point))
1418   (insert (current-kill (cond
1419                          ((listp arg) 0)
1420                          ((eq arg '-) -1)
1421                          (t (1- arg)))))
1422   (if (consp arg)
1423       ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1424       ;; It is cleaner to avoid activation, even though the command
1425       ;; loop would deactivate the mark because we inserted text.
1426       ;; (But it's an unnecessary kludge in XEmacs.)
1427       ;(goto-char (prog1 (mark t)
1428                    ;(set-marker (mark-marker) (point) (current-buffer)))))
1429       (exchange-point-and-mark t))
1430   ;; If we do get all the way thru, make this-command indicate that.
1431   (setq this-command 'yank)
1432   nil)
1433
1434 (defun rotate-yank-pointer (arg)
1435   "Rotate the yanking point in the kill ring.
1436 With argument, rotate that many kills forward (or backward, if negative)."
1437   (interactive "p")
1438   (current-kill arg))
1439
1440 \f
1441 (defun insert-buffer (buffer)
1442   "Insert after point the contents of BUFFER.
1443 Puts mark after the inserted text.
1444 BUFFER may be a buffer or a buffer name."
1445   (interactive
1446    (list
1447     (progn
1448       (barf-if-buffer-read-only)
1449       (read-buffer "Insert buffer: "
1450                    ;; XEmacs: we have different args
1451                    (other-buffer (current-buffer) nil t)
1452                    t))))
1453   (or (bufferp buffer)
1454       (setq buffer (get-buffer buffer)))
1455   (let (start end newmark)
1456     (save-excursion
1457       (save-excursion
1458         (set-buffer buffer)
1459         (setq start (point-min) end (point-max)))
1460       (insert-buffer-substring buffer start end)
1461       (setq newmark (point)))
1462     (push-mark newmark))
1463   nil)
1464
1465 (defun append-to-buffer (buffer start end)
1466   "Append to specified buffer the text of the region.
1467 It is inserted into that buffer before its point.
1468
1469 When calling from a program, give three arguments:
1470 BUFFER (or buffer name), START and END.
1471 START and END specify the portion of the current buffer to be copied."
1472   (interactive
1473    ;; XEmacs: we have different args to other-buffer
1474    (list (read-buffer "Append to buffer: " (other-buffer (current-buffer)
1475                                                          nil t))
1476          (region-beginning) (region-end)))
1477   (let ((oldbuf (current-buffer)))
1478     (save-excursion
1479       (set-buffer (get-buffer-create buffer))
1480       (insert-buffer-substring oldbuf start end))))
1481
1482 (defun prepend-to-buffer (buffer start end)
1483   "Prepend to specified buffer the text of the region.
1484 It is inserted into that buffer after its point.
1485
1486 When calling from a program, give three arguments:
1487 BUFFER (or buffer name), START and END.
1488 START and END specify the portion of the current buffer to be copied."
1489   (interactive "BPrepend to buffer: \nr")
1490   (let ((oldbuf (current-buffer)))
1491     (save-excursion
1492       (set-buffer (get-buffer-create buffer))
1493       (save-excursion
1494         (insert-buffer-substring oldbuf start end)))))
1495
1496 (defun copy-to-buffer (buffer start end)
1497   "Copy to specified buffer the text of the region.
1498 It is inserted into that buffer, replacing existing text there.
1499
1500 When calling from a program, give three arguments:
1501 BUFFER (or buffer name), START and END.
1502 START and END specify the portion of the current buffer to be copied."
1503   (interactive "BCopy to buffer: \nr")
1504   (let ((oldbuf (current-buffer)))
1505     (save-excursion
1506       (set-buffer (get-buffer-create buffer))
1507       (erase-buffer)
1508       (save-excursion
1509         (insert-buffer-substring oldbuf start end)))))
1510 \f
1511 ;FSFmacs
1512 ;(put 'mark-inactive 'error-conditions '(mark-inactive error))
1513 ;(put 'mark-inactive 'error-message "The mark is not active now")
1514
1515 (defun mark (&optional force buffer)
1516   "Return this buffer's mark value as integer, or nil if no mark.
1517
1518 If `zmacs-regions' is true, then this returns nil unless the region is
1519 currently in the active (highlighted) state.  With an argument of t, this
1520 returns the mark (if there is one) regardless of the active-region state.
1521 You should *generally* not use the mark unless the region is active, if
1522 the user has expressed a preference for the active-region model.
1523
1524 If you are using this in an editing command, you are most likely making
1525 a mistake; see the documentation of `set-mark'."
1526   (setq buffer (decode-buffer buffer))
1527 ;FSFmacs version:
1528 ;  (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
1529 ;      (marker-position (mark-marker))
1530 ;    (signal 'mark-inactive nil)))
1531   (let ((m (mark-marker force buffer)))
1532     (and m (marker-position m))))
1533
1534 ;;;#### FSFmacs
1535 ;;; Many places set mark-active directly, and several of them failed to also
1536 ;;; run deactivate-mark-hook.  This shorthand should simplify.
1537 ;(defsubst deactivate-mark ()
1538 ;  "Deactivate the mark by setting `mark-active' to nil.
1539 ;\(That makes a difference only in Transient Mark mode.)
1540 ;Also runs the hook `deactivate-mark-hook'."
1541 ;  (if transient-mark-mode
1542 ;      (progn
1543 ;       (setq mark-active nil)
1544 ;       (run-hooks 'deactivate-mark-hook))))
1545
1546 (defun set-mark (pos &optional buffer)
1547   "Set this buffer's mark to POS.  Don't use this function!
1548 That is to say, don't use this function unless you want
1549 the user to see that the mark has moved, and you want the previous
1550 mark position to be lost.
1551
1552 Normally, when a new mark is set, the old one should go on the stack.
1553 This is why most applications should use push-mark, not set-mark.
1554
1555 Novice Emacs Lisp programmers often try to use the mark for the wrong
1556 purposes.  The mark saves a location for the user's convenience.
1557 Most editing commands should not alter the mark.
1558 To remember a location for internal use in the Lisp program,
1559 store it in a Lisp variable.  Example:
1560
1561    (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
1562
1563   (setq buffer (decode-buffer buffer))
1564   (set-marker (mark-marker t buffer) pos buffer))
1565 ;; FSF
1566 ;  (if pos
1567 ;     (progn
1568 ;       (setq mark-active t)
1569 ;       (run-hooks 'activate-mark-hook)
1570 ;       (set-marker (mark-marker) pos (current-buffer)))
1571 ;    ;; Normally we never clear mark-active except in Transient Mark mode.
1572 ;    ;; But when we actually clear out the mark value too,
1573 ;    ;; we must clear mark-active in any mode.
1574 ;    (setq mark-active nil)
1575 ;    (run-hooks 'deactivate-mark-hook)
1576 ;    (set-marker (mark-marker) nil)))
1577
1578 (defvar mark-ring nil
1579   "The list of former marks of the current buffer, most recent first.")
1580 (make-variable-buffer-local 'mark-ring)
1581 (put 'mark-ring 'permanent-local t)
1582
1583 (defcustom mark-ring-max 16
1584   "*Maximum size of mark ring.  Start discarding off end if gets this big."
1585   :type 'integer
1586   :group 'killing)
1587
1588 (defvar global-mark-ring nil
1589   "The list of saved global marks, most recent first.")
1590
1591 (defcustom global-mark-ring-max 16
1592   "*Maximum size of global mark ring.  \
1593 Start discarding off end if gets this big."
1594   :type 'integer
1595   :group 'killing)
1596
1597 (defun set-mark-command (arg)
1598   "Set mark at where point is, or jump to mark.
1599 With no prefix argument, set mark, push old mark position on local mark
1600 ring, and push mark on global mark ring.
1601 With argument, jump to mark, and pop a new position for mark off the ring
1602 \(does not affect global mark ring\).
1603
1604 Novice Emacs Lisp programmers often try to use the mark for the wrong
1605 purposes.  See the documentation of `set-mark' for more information."
1606   (interactive "P")
1607   (if (null arg)
1608       (push-mark nil nil t)
1609     (if (null (mark t))
1610         (error "No mark set in this buffer")
1611       (goto-char (mark t))
1612       (pop-mark))))
1613
1614 ;; XEmacs: Extra parameter
1615 (defun push-mark (&optional location nomsg activate-region buffer)
1616   "Set mark at LOCATION (point, by default) and push old mark on mark ring.
1617 If the last global mark pushed was not in the current buffer,
1618 also push LOCATION on the global mark ring.
1619 Display `Mark set' unless the optional second arg NOMSG is non-nil.
1620 Activate mark if optional third arg ACTIVATE-REGION non-nil.
1621
1622 Novice Emacs Lisp programmers often try to use the mark for the wrong
1623 purposes.  See the documentation of `set-mark' for more information."
1624   (setq buffer (decode-buffer buffer)) ; XEmacs
1625   (if (null (mark t buffer)) ; XEmacs
1626       nil
1627     ;; The save-excursion / set-buffer is necessary because mark-ring
1628     ;; is a buffer local variable
1629     (save-excursion
1630       (set-buffer buffer)
1631       (setq mark-ring (cons (copy-marker (mark-marker t buffer)) mark-ring))
1632       (if (> (length mark-ring) mark-ring-max)
1633           (progn
1634             (move-marker (car (nthcdr mark-ring-max mark-ring)) nil buffer)
1635             (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))))
1636   (set-mark (or location (point buffer)) buffer)
1637 ; (set-marker (mark-marker) (or location (point)) (current-buffer)) ; FSF
1638   ;; Now push the mark on the global mark ring.
1639   (if (or (null global-mark-ring)
1640           (not (eq (marker-buffer (car global-mark-ring)) buffer)))
1641       ;; The last global mark pushed wasn't in this same buffer.
1642       (progn
1643         (setq global-mark-ring (cons (copy-marker (mark-marker t buffer))
1644                                      global-mark-ring))
1645         (if (> (length global-mark-ring) global-mark-ring-max)
1646             (progn
1647               (move-marker (car (nthcdr global-mark-ring-max global-mark-ring))
1648                            nil buffer)
1649               (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))))
1650   (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
1651       (display-message 'command "Mark set"))
1652   (if activate-region
1653       (progn
1654         (setq zmacs-region-stays t)
1655         (zmacs-activate-region)))
1656 ; (if (or activate (not transient-mark-mode)) ; FSF
1657 ;     (set-mark (mark t))) ; FSF
1658   nil)
1659
1660 (defun pop-mark ()
1661   "Pop off mark ring into the buffer's actual mark.
1662 Does not set point.  Does nothing if mark ring is empty."
1663   (if mark-ring
1664       (progn
1665         (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker t)))))
1666         (set-mark (car mark-ring))
1667         (move-marker (car mark-ring) nil)
1668         (if (null (mark t)) (ding))
1669         (setq mark-ring (cdr mark-ring)))))
1670
1671 (define-function 'exchange-dot-and-mark 'exchange-point-and-mark)
1672 (defun exchange-point-and-mark (&optional dont-activate-region)
1673   "Put the mark where point is now, and point where the mark is now.
1674 The mark is activated unless DONT-ACTIVATE-REGION is non-nil."
1675   (interactive nil)
1676   (let ((omark (mark t)))
1677     (if (null omark)
1678         (error "No mark set in this buffer"))
1679     (set-mark (point))
1680     (goto-char omark)
1681     (or dont-activate-region (zmacs-activate-region)) ; XEmacs
1682     nil))
1683
1684 ;; XEmacs
1685 (defun mark-something (mark-fn movement-fn arg)
1686   "internal function used by mark-sexp, mark-word, etc."
1687   (let (newmark (pushp t))
1688     (save-excursion
1689       (if (and (eq last-command mark-fn) (mark))
1690           ;; Extend the previous state in the same direction:
1691           (progn
1692             (if (< (mark) (point)) (setq arg (- arg)))
1693             (goto-char (mark))
1694             (setq pushp nil)))
1695       (funcall movement-fn arg)
1696       (setq newmark (point)))
1697     (if pushp
1698         (push-mark newmark nil t)
1699       ;; Do not mess with the mark stack, but merely adjust the previous state:
1700       (set-mark newmark)
1701       (activate-region))))
1702
1703 ;(defun transient-mark-mode (arg)
1704 ;  "Toggle Transient Mark mode.
1705 ;With arg, turn Transient Mark mode on if arg is positive, off otherwise.
1706 ;
1707 ;In Transient Mark mode, when the mark is active, the region is highlighted.
1708 ;Changing the buffer \"deactivates\" the mark.
1709 ;So do certain other operations that set the mark
1710 ;but whose main purpose is something else--for example,
1711 ;incremental search, \\[beginning-of-buffer], and \\[end-of-buffer]."
1712 ;  (interactive "P")
1713 ;  (setq transient-mark-mode
1714 ;       (if (null arg)
1715 ;           (not transient-mark-mode)
1716 ;         (> (prefix-numeric-value arg) 0))))
1717
1718 (defun pop-global-mark ()
1719   "Pop off global mark ring and jump to the top location."
1720   (interactive)
1721   ;; Pop entries which refer to non-existent buffers.
1722   (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
1723     (setq global-mark-ring (cdr global-mark-ring)))
1724   (or global-mark-ring
1725       (error "No global mark set"))
1726   (let* ((marker (car global-mark-ring))
1727          (buffer (marker-buffer marker))
1728          (position (marker-position marker)))
1729     (setq global-mark-ring (nconc (cdr global-mark-ring)
1730                                   (list (car global-mark-ring))))
1731     (set-buffer buffer)
1732     (or (and (>= position (point-min))
1733              (<= position (point-max)))
1734         (widen))
1735     (goto-char position)
1736     (switch-to-buffer buffer)))
1737
1738 \f
1739 (defcustom signal-error-on-buffer-boundary t
1740   "*Non-nil value causes XEmacs to beep or signal an error when certain interactive commands would move point past (point-min) or (point-max).
1741 The commands that honor this variable are
1742
1743 forward-char-command
1744 backward-char-command
1745 next-line
1746 previous-line
1747 scroll-up-command
1748 scroll-down-command"
1749   :type 'boolean
1750   :group 'editing-basics)
1751
1752 ;;; After 8 years of waiting ... -sb
1753 (defcustom next-line-add-newlines nil  ; XEmacs
1754   "*If non-nil, `next-line' inserts newline when the point is at end of buffer.
1755 This behavior used to be the default, and is still default in FSF Emacs.
1756 We think it is an unnecessary and unwanted side-effect."
1757   :type 'boolean
1758   :group 'editing-basics)
1759
1760 (defun forward-char-command (&optional arg buffer)
1761   "Move point right ARG characters (left if ARG negative) in BUFFER.
1762 On attempt to pass end of buffer, stop and signal `end-of-buffer'.
1763 On attempt to pass beginning of buffer, stop and signal `beginning-of-buffer'.
1764 Error signaling is suppressed if `signal-error-on-buffer-boundary'
1765 is nil.  If BUFFER is nil, the current buffer is assumed."
1766   (interactive "_p")
1767   (if signal-error-on-buffer-boundary
1768       (forward-char arg buffer)
1769     (condition-case nil
1770         (forward-char arg buffer)
1771       (beginning-of-buffer nil)
1772       (end-of-buffer nil))))
1773
1774 (defun backward-char-command (&optional arg buffer)
1775   "Move point left ARG characters (right if ARG negative) in BUFFER.
1776 On attempt to pass end of buffer, stop and signal `end-of-buffer'.
1777 On attempt to pass beginning of buffer, stop and signal `beginning-of-buffer'.
1778 Error signaling is suppressed if `signal-error-on-buffer-boundary'
1779 is nil.  If BUFFER is nil, the current buffer is assumed."
1780   (interactive "_p")
1781   (if signal-error-on-buffer-boundary
1782       (backward-char arg buffer)
1783     (condition-case nil
1784         (backward-char arg buffer)
1785       (beginning-of-buffer nil)
1786       (end-of-buffer nil))))
1787
1788 (defun scroll-up-command (&optional n)
1789   "Scroll text of current window upward ARG lines; or near full screen if no ARG.
1790 A near full screen is `next-screen-context-lines' less than a full screen.
1791 Negative ARG means scroll downward.
1792 When calling from a program, supply a number as argument or nil.
1793 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
1794 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
1795 signaled.
1796
1797 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
1798 boundaries do not cause an error to be signaled."
1799   (interactive "_P")
1800   (if signal-error-on-buffer-boundary
1801       (scroll-up n)
1802     (condition-case nil
1803         (scroll-up n)
1804       (beginning-of-buffer nil)
1805       (end-of-buffer nil))))
1806
1807 (defun scroll-down-command (&optional n)
1808   "Scroll text of current window downward ARG lines; or near full screen if no ARG.
1809 A near full screen is `next-screen-context-lines' less than a full screen.
1810 Negative ARG means scroll upward.
1811 When calling from a program, supply a number as argument or nil.
1812 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
1813 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
1814 signaled.
1815
1816 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
1817 boundaries do not cause an error to be signaled."
1818   (interactive "_P")
1819   (if signal-error-on-buffer-boundary
1820       (scroll-down n)
1821     (condition-case nil
1822         (scroll-down n)
1823       (beginning-of-buffer nil)
1824       (end-of-buffer nil))))
1825
1826 (defun next-line (arg)
1827   "Move cursor vertically down ARG lines.
1828 If there is no character in the target line exactly under the current column,
1829 the cursor is positioned after the character in that line which spans this
1830 column, or at the end of the line if it is not long enough.
1831
1832 If there is no line in the buffer after this one, behavior depends on the
1833 value of `next-line-add-newlines'.  If non-nil, it inserts a newline character
1834 to create a line, and moves the cursor to that line.  Otherwise it moves the
1835 cursor to the end of the buffer.
1836
1837 The command \\[set-goal-column] can be used to create
1838 a semipermanent goal column to which this command always moves.
1839 Then it does not try to move vertically.  This goal column is stored
1840 in `goal-column', which is nil when there is none.
1841
1842 If you are thinking of using this in a Lisp program, consider
1843 using `forward-line' instead.  It is usually easier to use
1844 and more reliable (no dependence on goal column, etc.)."
1845   (interactive "_p") ; XEmacs
1846   (if (and next-line-add-newlines (= arg 1))
1847       (let ((opoint (point)))
1848         (end-of-line)
1849         (if (eobp)
1850             (newline 1)
1851           (goto-char opoint)
1852           (line-move arg)))
1853     (if (interactive-p)
1854         ;; XEmacs:  Not sure what to do about this.  It's inconsistent. -sb
1855         (condition-case nil
1856             (line-move arg)
1857           ((beginning-of-buffer end-of-buffer)
1858            (when signal-error-on-buffer-boundary
1859              (ding nil 'buffer-bound))))
1860       (line-move arg)))
1861   nil)
1862
1863 (defun previous-line (arg)
1864   "Move cursor vertically up ARG lines.
1865 If there is no character in the target line exactly over the current column,
1866 the cursor is positioned after the character in that line which spans this
1867 column, or at the end of the line if it is not long enough.
1868
1869 The command \\[set-goal-column] can be used to create
1870 a semipermanent goal column to which this command always moves.
1871 Then it does not try to move vertically.
1872
1873 If you are thinking of using this in a Lisp program, consider using
1874 `forward-line' with a negative argument instead.  It is usually easier
1875 to use and more reliable (no dependence on goal column, etc.)."
1876   (interactive "_p") ; XEmacs
1877   (if (interactive-p)
1878       (condition-case nil
1879           (line-move (- arg))
1880         ((beginning-of-buffer end-of-buffer)
1881          (when signal-error-on-buffer-boundary ; XEmacs
1882            (ding nil 'buffer-bound))))
1883     (line-move (- arg)))
1884   nil)
1885
1886 (defcustom track-eol nil
1887   "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
1888 This means moving to the end of each line moved onto.
1889 The beginning of a blank line does not count as the end of a line."
1890   :type 'boolean
1891   :group 'editing-basics)
1892
1893 (defcustom goal-column nil
1894   "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
1895   :type '(choice integer (const :tag "None" nil))
1896   :group 'editing-basics)
1897 (make-variable-buffer-local 'goal-column)
1898
1899 (defvar temporary-goal-column 0
1900   "Current goal column for vertical motion.
1901 It is the column where point was
1902 at the start of current run of vertical motion commands.
1903 When the `track-eol' feature is doing its job, the value is 9999.")
1904 (make-variable-buffer-local 'temporary-goal-column)
1905
1906 ;XEmacs: not yet ported, so avoid compiler warnings
1907 (eval-when-compile
1908   (defvar inhibit-point-motion-hooks))
1909
1910 (defcustom line-move-ignore-invisible nil
1911   "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
1912 Use with care, as it slows down movement significantly.  Outline mode sets this."
1913   :type 'boolean
1914   :group 'editing-basics)
1915
1916 ;; This is the guts of next-line and previous-line.
1917 ;; Arg says how many lines to move.
1918 (defun line-move (arg)
1919   ;; Don't run any point-motion hooks, and disregard intangibility,
1920   ;; for intermediate positions.
1921   (let ((inhibit-point-motion-hooks t)
1922         (opoint (point))
1923         new)
1924     (unwind-protect
1925         (progn
1926           (if (not (or (eq last-command 'next-line)
1927                        (eq last-command 'previous-line)))
1928               (setq temporary-goal-column
1929                     (if (and track-eol (eolp)
1930                              ;; Don't count beg of empty line as end of line
1931                              ;; unless we just did explicit end-of-line.
1932                              (or (not (bolp)) (eq last-command 'end-of-line)))
1933                         9999
1934                       (current-column))))
1935           (if (and (not (integerp selective-display))
1936                    (not line-move-ignore-invisible))
1937               ;; Use just newline characters.
1938               (or (if (> arg 0)
1939                       (progn (if (> arg 1) (forward-line (1- arg)))
1940                              ;; This way of moving forward ARG lines
1941                              ;; verifies that we have a newline after the last one.
1942                              ;; It doesn't get confused by intangible text.
1943                              (end-of-line)
1944                              (zerop (forward-line 1)))
1945                     (and (zerop (forward-line arg))
1946                          (bolp)))
1947                   (signal (if (< arg 0)
1948                               'beginning-of-buffer
1949                             'end-of-buffer)
1950                           nil))
1951             ;; Move by arg lines, but ignore invisible ones.
1952             (while (> arg 0)
1953               (end-of-line)
1954               (and (zerop (vertical-motion 1))
1955                    (signal 'end-of-buffer nil))
1956               ;; If the following character is currently invisible,
1957               ;; skip all characters with that same `invisible' property value.
1958               (while (and (not (eobp))
1959                           (let ((prop
1960                                  (get-char-property (point) 'invisible)))
1961                             (if (eq buffer-invisibility-spec t)
1962                                 prop
1963                               (or (memq prop buffer-invisibility-spec)
1964                                   (assq prop buffer-invisibility-spec)))))
1965                 (if (get-text-property (point) 'invisible)
1966                     (goto-char (next-single-property-change (point) 'invisible))
1967                   (goto-char (next-extent-change (point))))) ; XEmacs
1968               (setq arg (1- arg)))
1969             (while (< arg 0)
1970               (beginning-of-line)
1971               (and (zerop (vertical-motion -1))
1972                    (signal 'beginning-of-buffer nil))
1973               (while (and (not (bobp))
1974                           (let ((prop
1975                                  (get-char-property (1- (point)) 'invisible)))
1976                             (if (eq buffer-invisibility-spec t)
1977                                 prop
1978                               (or (memq prop buffer-invisibility-spec)
1979                                   (assq prop buffer-invisibility-spec)))))
1980                 (if (get-text-property (1- (point)) 'invisible)
1981                     (goto-char (previous-single-property-change (point) 'invisible))
1982                   (goto-char (previous-extent-change (point))))) ; XEmacs
1983               (setq arg (1+ arg))))
1984           (move-to-column (or goal-column temporary-goal-column)))
1985       ;; Remember where we moved to, go back home,
1986       ;; then do the motion over again
1987       ;; in just one step, with intangibility and point-motion hooks
1988       ;; enabled this time.
1989       (setq new (point))
1990       (goto-char opoint)
1991       (setq inhibit-point-motion-hooks nil)
1992       (goto-char new)))
1993   nil)
1994
1995 ;;; Many people have said they rarely use this feature, and often type
1996 ;;; it by accident.  Maybe it shouldn't even be on a key.
1997 ;; It's not on a key, as of 20.2.  So no need for this.
1998 ;(put 'set-goal-column 'disabled t)
1999
2000 (defun set-goal-column (arg)
2001   "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2002 Those commands will move to this position in the line moved to
2003 rather than trying to keep the same horizontal position.
2004 With a non-nil argument, clears out the goal column
2005 so that \\[next-line] and \\[previous-line] resume vertical motion.
2006 The goal column is stored in the variable `goal-column'."
2007   (interactive "_P") ; XEmacs
2008   (if arg
2009       (progn
2010         (setq goal-column nil)
2011         (display-message 'command "No goal column"))
2012     (setq goal-column (current-column))
2013     (lmessage 'command
2014         "Goal column %d (use %s with an arg to unset it)"
2015       goal-column
2016       (substitute-command-keys "\\[set-goal-column]")))
2017   nil)
2018 \f
2019 ;; deleted FSFmacs terminal randomness hscroll-point-visible stuff.
2020 ;; hscroll-step
2021 ;; hscroll-point-visible
2022 ;; hscroll-window-column
2023 ;; right-arrow
2024 ;; left-arrow
2025
2026 (defun scroll-other-window-down (lines)
2027   "Scroll the \"other window\" down.
2028 For more details, see the documentation for `scroll-other-window'."
2029   (interactive "P")
2030   (scroll-other-window
2031    ;; Just invert the argument's meaning.
2032    ;; We can do that without knowing which window it will be.
2033    (if (eq lines '-) nil
2034      (if (null lines) '-
2035        (- (prefix-numeric-value lines))))))
2036 ;(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
2037
2038 (defun beginning-of-buffer-other-window (arg)
2039   "Move point to the beginning of the buffer in the other window.
2040 Leave mark at previous position.
2041 With arg N, put point N/10 of the way from the true beginning."
2042   (interactive "P")
2043   (let ((orig-window (selected-window))
2044         (window (other-window-for-scrolling)))
2045     ;; We use unwind-protect rather than save-window-excursion
2046     ;; because the latter would preserve the things we want to change.
2047     (unwind-protect
2048         (progn
2049           (select-window window)
2050           ;; Set point and mark in that window's buffer.
2051           (beginning-of-buffer arg)
2052           ;; Set point accordingly.
2053           (recenter '(t)))
2054       (select-window orig-window))))
2055
2056 (defun end-of-buffer-other-window (arg)
2057   "Move point to the end of the buffer in the other window.
2058 Leave mark at previous position.
2059 With arg N, put point N/10 of the way from the true end."
2060   (interactive "P")
2061   ;; See beginning-of-buffer-other-window for comments.
2062   (let ((orig-window (selected-window))
2063         (window (other-window-for-scrolling)))
2064     (unwind-protect
2065         (progn
2066           (select-window window)
2067           (end-of-buffer arg)
2068           (recenter '(t)))
2069       (select-window orig-window))))
2070 \f
2071 (defun transpose-chars (arg)
2072   "Interchange characters around point, moving forward one character.
2073 With prefix arg ARG, effect is to take character before point
2074 and drag it forward past ARG other characters (backward if ARG negative).
2075 If no argument and at end of line, the previous two chars are exchanged."
2076   (interactive "*P")
2077   (and (null arg) (eolp) (forward-char -1))
2078   (transpose-subr 'forward-char (prefix-numeric-value arg)))
2079
2080 ;;; A very old implementation of transpose-chars from the old days ...
2081 (defun transpose-preceding-chars (arg)
2082   "Interchange characters before point.
2083 With prefix arg ARG, effect is to take character before point
2084 and drag it forward past ARG other characters (backward if ARG negative).
2085 If no argument and not at start of line, the previous two chars are exchanged."
2086   (interactive "*P")
2087   (and (null arg) (not (bolp)) (forward-char -1))
2088   (transpose-subr 'forward-char (prefix-numeric-value arg)))
2089
2090
2091 (defun transpose-words (arg)
2092   "Interchange words around point, leaving point at end of them.
2093 With prefix arg ARG, effect is to take word before or around point
2094 and drag it forward past ARG other words (backward if ARG negative).
2095 If ARG is zero, the words around or after point and around or after mark
2096 are interchanged."
2097   (interactive "*p")
2098   (transpose-subr 'forward-word arg))
2099
2100 (defun transpose-sexps (arg)
2101   "Like \\[transpose-words] but applies to sexps.
2102 Does not work on a sexp that point is in the middle of
2103 if it is a list or string."
2104   (interactive "*p")
2105   (transpose-subr 'forward-sexp arg))
2106
2107 (defun transpose-lines (arg)
2108   "Exchange current line and previous line, leaving point after both.
2109 With argument ARG, takes previous line and moves it past ARG lines.
2110 With argument 0, interchanges line point is in with line mark is in."
2111   (interactive "*p")
2112   (transpose-subr #'(lambda (arg)
2113                      (if (= arg 1)
2114                          (progn
2115                            ;; Move forward over a line,
2116                            ;; but create a newline if none exists yet.
2117                            (end-of-line)
2118                            (if (eobp)
2119                                (newline)
2120                              (forward-char 1)))
2121                        (forward-line arg)))
2122                   arg))
2123
2124 (eval-when-compile
2125   ;; avoid byte-compiler warnings...
2126   (defvar start1)
2127   (defvar start2)
2128   (defvar end1)
2129   (defvar end2))
2130
2131 ; start[12] and end[12] used in transpose-subr-1 below
2132 (defun transpose-subr (mover arg)
2133   (let (start1 end1 start2 end2)
2134     (if (= arg 0)
2135         (progn
2136           (save-excursion
2137             (funcall mover 1)
2138             (setq end2 (point))
2139             (funcall mover -1)
2140             (setq start2 (point))
2141             (goto-char (mark t)) ; XEmacs
2142             (funcall mover 1)
2143             (setq end1 (point))
2144             (funcall mover -1)
2145             (setq start1 (point))
2146             (transpose-subr-1))
2147           (exchange-point-and-mark t))) ; XEmacs
2148     (while (> arg 0)
2149       (funcall mover -1)
2150       (setq start1 (point))
2151       (funcall mover 1)
2152       (setq end1 (point))
2153       (funcall mover 1)
2154       (setq end2 (point))
2155       (funcall mover -1)
2156       (setq start2 (point))
2157       (transpose-subr-1)
2158       (goto-char end2)
2159       (setq arg (1- arg)))
2160     (while (< arg 0)
2161       (funcall mover -1)
2162       (setq start2 (point))
2163       (funcall mover -1)
2164       (setq start1 (point))
2165       (funcall mover 1)
2166       (setq end1 (point))
2167       (funcall mover 1)
2168       (setq end2 (point))
2169       (transpose-subr-1)
2170       (setq arg (1+ arg)))))
2171
2172 ; start[12] and end[12] used free
2173 (defun transpose-subr-1 ()
2174   (if (> (min end1 end2) (max start1 start2))
2175       (error "Don't have two things to transpose"))
2176   (let ((word1 (buffer-substring start1 end1))
2177         (word2 (buffer-substring start2 end2)))
2178     (delete-region start2 end2)
2179     (goto-char start2)
2180     (insert word1)
2181     (goto-char (if (< start1 start2) start1
2182                  (+ start1 (- (length word1) (length word2)))))
2183     (delete-char (length word1))
2184     (insert word2)))
2185 \f
2186 (defcustom comment-column 32
2187   "*Column to indent right-margin comments to.
2188 Setting this variable automatically makes it local to the current buffer.
2189 Each mode establishes a different default value for this variable; you
2190 can set the value for a particular mode using that mode's hook."
2191   :type 'integer
2192   :group 'fill-comments)
2193 (make-variable-buffer-local 'comment-column)
2194
2195 (defcustom comment-start nil
2196   "*String to insert to start a new comment, or nil if no comment syntax."
2197   :type '(choice (const :tag "None" nil)
2198                  string)
2199   :group 'fill-comments)
2200
2201 (defcustom comment-start-skip nil
2202   "*Regexp to match the start of a comment plus everything up to its body.
2203 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
2204 at the place matched by the close of the first pair."
2205   :type '(choice (const :tag "None" nil)
2206                  regexp)
2207   :group 'fill-comments)
2208
2209 (defcustom comment-end ""
2210   "*String to insert to end a new comment.
2211 Should be an empty string if comments are terminated by end-of-line."
2212   :type 'string
2213   :group 'fill-comments)
2214
2215 (defconst comment-indent-hook nil
2216   "Obsolete variable for function to compute desired indentation for a comment.
2217 Use `comment-indent-function' instead.
2218 This function is called with no args with point at the beginning of
2219 the comment's starting delimiter.")
2220
2221 (defconst comment-indent-function
2222   ;; XEmacs - add at least one space after the end of the text on the
2223   ;; current line...
2224   (lambda ()
2225     (save-excursion
2226       (beginning-of-line)
2227       (let ((eol (save-excursion (end-of-line) (point))))
2228         (and comment-start-skip
2229              (re-search-forward comment-start-skip eol t)
2230              (setq eol (match-beginning 0)))
2231         (goto-char eol)
2232         (skip-chars-backward " \t")
2233         (max comment-column (1+ (current-column))))))
2234   "Function to compute desired indentation for a comment.
2235 This function is called with no args with point at the beginning of
2236 the comment's starting delimiter.")
2237
2238 (defcustom block-comment-start nil
2239   "*String to insert to start a new comment on a line by itself.
2240 If nil, use `comment-start' instead.
2241 Note that the regular expression `comment-start-skip' should skip this string
2242 as well as the `comment-start' string."
2243   :type '(choice (const :tag "Use `comment-start'" nil)
2244                  string)
2245   :group 'fill-comments)
2246
2247 (defcustom block-comment-end nil
2248   "*String to insert to end a new comment on a line by itself.
2249 Should be an empty string if comments are terminated by end-of-line.
2250 If nil, use `comment-end' instead."
2251   :type '(choice (const :tag "Use `comment-end'" nil)
2252                  string)
2253   :group 'fill-comments)
2254
2255 (defun indent-for-comment ()
2256   "Indent this line's comment to comment column, or insert an empty comment."
2257   (interactive "*")
2258   (let* ((empty (save-excursion (beginning-of-line)
2259                                 (looking-at "[ \t]*$")))
2260          (starter (or (and empty block-comment-start) comment-start))
2261          (ender (or (and empty block-comment-end) comment-end)))
2262     (if (null starter)
2263         (error "No comment syntax defined")
2264       (let* ((eolpos (save-excursion (end-of-line) (point)))
2265              cpos indent begpos)
2266         (beginning-of-line)
2267         (if (re-search-forward comment-start-skip eolpos 'move)
2268             (progn (setq cpos (point-marker))
2269                    ;; Find the start of the comment delimiter.
2270                    ;; If there were paren-pairs in comment-start-skip,
2271                    ;; position at the end of the first pair.
2272                    (if (match-end 1)
2273                        (goto-char (match-end 1))
2274                      ;; If comment-start-skip matched a string with
2275                      ;; internal whitespace (not final whitespace) then
2276                      ;; the delimiter start at the end of that
2277                      ;; whitespace.  Otherwise, it starts at the
2278                      ;; beginning of what was matched.
2279                      (skip-syntax-backward " " (match-beginning 0))
2280                      (skip-syntax-backward "^ " (match-beginning 0)))))
2281         (setq begpos (point))
2282         ;; Compute desired indent.
2283         (if (= (current-column)
2284                (setq indent (funcall comment-indent-function)))
2285             (goto-char begpos)
2286           ;; If that's different from current, change it.
2287           (skip-chars-backward " \t")
2288           (delete-region (point) begpos)
2289           (indent-to indent))
2290         ;; An existing comment?
2291         (if cpos
2292             (progn (goto-char cpos)
2293                    (set-marker cpos nil))
2294           ;; No, insert one.
2295           (insert starter)
2296           (save-excursion
2297             (insert ender)))))))
2298
2299 (defun set-comment-column (arg)
2300   "Set the comment column based on point.
2301 With no arg, set the comment column to the current column.
2302 With just minus as arg, kill any comment on this line.
2303 With any other arg, set comment column to indentation of the previous comment
2304  and then align or create a comment on this line at that column."
2305   (interactive "P")
2306   (if (eq arg '-)
2307       (kill-comment nil)
2308     (if arg
2309         (progn
2310           (save-excursion
2311             (beginning-of-line)
2312             (re-search-backward comment-start-skip)
2313             (beginning-of-line)
2314             (re-search-forward comment-start-skip)
2315             (goto-char (match-beginning 0))
2316             (setq comment-column (current-column))
2317             (lmessage 'command "Comment column set to %d" comment-column))
2318           (indent-for-comment))
2319       (setq comment-column (current-column))
2320       (lmessage 'command "Comment column set to %d" comment-column))))
2321
2322 (defun kill-comment (arg)
2323   "Kill the comment on this line, if any.
2324 With argument, kill comments on that many lines starting with this one."
2325   ;; this function loses in a lot of situations.  it incorrectly recognises
2326   ;; comment delimiters sometimes (ergo, inside a string), doesn't work
2327   ;; with multi-line comments, can kill extra whitespace if comment wasn't
2328   ;; through end-of-line, et cetera.
2329   (interactive "*P")
2330   (or comment-start-skip (error "No comment syntax defined"))
2331   (let ((count (prefix-numeric-value arg)) endc)
2332     (while (> count 0)
2333       (save-excursion
2334         (end-of-line)
2335         (setq endc (point))
2336         (beginning-of-line)
2337         (and (string< "" comment-end)
2338              (setq endc
2339                    (progn
2340                      (re-search-forward (regexp-quote comment-end) endc 'move)
2341                      (skip-chars-forward " \t")
2342                      (point))))
2343         (beginning-of-line)
2344         (if (re-search-forward comment-start-skip endc t)
2345             (progn
2346               (goto-char (match-beginning 0))
2347               (skip-chars-backward " \t")
2348               (kill-region (point) endc)
2349               ;; to catch comments a line beginnings
2350               (indent-according-to-mode))))
2351       (if arg (forward-line 1))
2352       (setq count (1- count)))))
2353
2354 (defun comment-region (beg end &optional arg)
2355   "Comment or uncomment each line in the region.
2356 With just C-u prefix arg, uncomment each line in region.
2357 Numeric prefix arg ARG means use ARG comment characters.
2358 If ARG is negative, delete that many comment characters instead.
2359 Comments are terminated on each line, even for syntax in which newline does
2360 not end the comment.  Blank lines do not get comments."
2361   ;; if someone wants it to only put a comment-start at the beginning and
2362   ;; comment-end at the end then typing it, C-x C-x, closing it, C-x C-x
2363   ;; is easy enough.  No option is made here for other than commenting
2364   ;; every line.
2365   (interactive "r\nP")
2366   (or comment-start (error "No comment syntax is defined"))
2367   (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
2368   (save-excursion
2369     (save-restriction
2370       (let ((cs comment-start) (ce comment-end)
2371             numarg)
2372         (if (consp arg) (setq numarg t)
2373           (setq numarg (prefix-numeric-value arg))
2374           ;; For positive arg > 1, replicate the comment delims now,
2375           ;; then insert the replicated strings just once.
2376           (while (> numarg 1)
2377             (setq cs (concat cs comment-start)
2378                   ce (concat ce comment-end))
2379             (setq numarg (1- numarg))))
2380         ;; Loop over all lines from BEG to END.
2381         (narrow-to-region beg end)
2382         (goto-char beg)
2383         (while (not (eobp))
2384           (if (or (eq numarg t) (< numarg 0))
2385               (progn
2386                 ;; Delete comment start from beginning of line.
2387                 (if (eq numarg t)
2388                     (while (looking-at (regexp-quote cs))
2389                       (delete-char (length cs)))
2390                   (let ((count numarg))
2391                     (while (and (> 1 (setq count (1+ count)))
2392                                 (looking-at (regexp-quote cs)))
2393                       (delete-char (length cs)))))
2394                 ;; Delete comment end from end of line.
2395                 (if (string= "" ce)
2396                     nil
2397                   (if (eq numarg t)
2398                       (progn
2399                         (end-of-line)
2400                         ;; This is questionable if comment-end ends in
2401                         ;; whitespace.  That is pretty brain-damaged,
2402                         ;; though.
2403                         (skip-chars-backward " \t")
2404                         (if (and (>= (- (point) (point-min)) (length ce))
2405                                  (save-excursion
2406                                    (backward-char (length ce))
2407                                    (looking-at (regexp-quote ce))))
2408                             (delete-char (- (length ce)))))
2409                     (let ((count numarg))
2410                       (while (> 1 (setq count (1+ count)))
2411                         (end-of-line)
2412                         ;; This is questionable if comment-end ends in
2413                         ;; whitespace.  That is pretty brain-damaged though
2414                         (skip-chars-backward " \t")
2415                         (save-excursion
2416                           (backward-char (length ce))
2417                           (if (looking-at (regexp-quote ce))
2418                               (delete-char (length ce))))))))
2419                 (forward-line 1))
2420             ;; Insert at beginning and at end.
2421             (if (looking-at "[ \t]*$") ()
2422               (insert cs)
2423               (if (string= "" ce) ()
2424                 (end-of-line)
2425                 (insert ce)))
2426             (search-forward "\n" nil 'move)))))))
2427
2428 ;; XEmacs
2429 (defun prefix-region (prefix)
2430   "Add a prefix string to each line between mark and point."
2431   (interactive "sPrefix string: ")
2432   (if prefix
2433       (let ((count (count-lines (mark) (point))))
2434         (goto-char (min (mark) (point)))
2435         (while (> count 0)
2436           (setq count (1- count))
2437           (beginning-of-line 1)
2438           (insert prefix)
2439           (end-of-line 1)
2440           (forward-char 1)))))
2441
2442 \f
2443 ;; XEmacs - extra parameter
2444 (defun backward-word (arg &optional buffer)
2445   "Move backward until encountering the end of a word.
2446 With argument, do this that many times.
2447 In programs, it is faster to call `forward-word' with negative arg."
2448   (interactive "_p") ; XEmacs
2449   (forward-word (- arg) buffer))
2450
2451 (defun mark-word (arg)
2452   "Set mark arg words away from point."
2453   (interactive "p")
2454   (mark-something 'mark-word 'forward-word arg))
2455
2456 ;; XEmacs modified
2457 (defun kill-word (arg)
2458   "Kill characters forward until encountering the end of a word.
2459 With argument, do this that many times."
2460   (interactive "*p")
2461   (kill-region (point) (save-excursion (forward-word arg) (point))))
2462
2463 (defun backward-kill-word (arg)
2464   "Kill characters backward until encountering the end of a word.
2465 With argument, do this that many times."
2466   (interactive "*p") ; XEmacs
2467   (kill-word (- arg)))
2468
2469 (defun current-word (&optional strict)
2470   "Return the word point is on (or a nearby word) as a string.
2471 If optional arg STRICT is non-nil, return nil unless point is within
2472 or adjacent to a word.
2473 If point is not between two word-constituent characters, but immediately
2474 follows one, move back first.
2475 Otherwise, if point precedes a word constituent, move forward first.
2476 Otherwise, move backwards until a word constituent is found and get that word;
2477 if you a newlines is reached first, move forward instead."
2478   (save-excursion
2479     (let ((oldpoint (point)) (start (point)) (end (point)))
2480       (skip-syntax-backward "w_") (setq start (point))
2481       (goto-char oldpoint)
2482       (skip-syntax-forward "w_") (setq end (point))
2483       (if (and (eq start oldpoint) (eq end oldpoint))
2484           ;; Point is neither within nor adjacent to a word.
2485           (and (not strict)
2486                (progn
2487                  ;; Look for preceding word in same line.
2488                  (skip-syntax-backward "^w_"
2489                                        (save-excursion
2490                                          (beginning-of-line) (point)))
2491                  (if (bolp)
2492                      ;; No preceding word in same line.
2493                      ;; Look for following word in same line.
2494                      (progn
2495                        (skip-syntax-forward "^w_"
2496                                             (save-excursion
2497                                               (end-of-line) (point)))
2498                        (setq start (point))
2499                        (skip-syntax-forward "w_")
2500                        (setq end (point)))
2501                      (setq end (point))
2502                      (skip-syntax-backward "w_")
2503                      (setq start (point)))
2504                  (buffer-substring start end)))
2505           (buffer-substring start end)))))
2506 \f
2507 (defcustom fill-prefix nil
2508   "*String for filling to insert at front of new line, or nil for none.
2509 Setting this variable automatically makes it local to the current buffer."
2510   :type '(choice (const :tag "None" nil)
2511                  string)
2512   :group 'fill)
2513 (make-variable-buffer-local 'fill-prefix)
2514
2515 (defcustom auto-fill-inhibit-regexp nil
2516   "*Regexp to match lines which should not be auto-filled."
2517   :type '(choice (const :tag "None" nil)
2518                  regexp)
2519   :group 'fill)
2520
2521 (defvar comment-line-break-function 'indent-new-comment-line
2522   "*Mode-specific function which line breaks and continues a comment.
2523
2524 This function is only called during auto-filling of a comment section.
2525 The function should take a single optional argument which is a flag
2526 indicating whether soft newlines should be inserted.")
2527
2528 ;; defined in mule-base/mule-category.el
2529 (defvar word-across-newline)
2530
2531 ;; This function is the auto-fill-function of a buffer
2532 ;; when Auto-Fill mode is enabled.
2533 ;; It returns t if it really did any work.
2534 ;; XEmacs:  This function is totally different.
2535 (defun do-auto-fill ()
2536   (let (give-up)
2537     (or (and auto-fill-inhibit-regexp
2538              (save-excursion (beginning-of-line)
2539                              (looking-at auto-fill-inhibit-regexp)))
2540         (while (and (not give-up) (> (current-column) fill-column))
2541           ;; Determine where to split the line.
2542           (let ((fill-prefix fill-prefix)
2543                 (fill-point
2544                  (let ((opoint (point))
2545                        bounce
2546                        ;; 97/3/14 jhod: Kinsoku
2547                        (re-break-point (if (featurep 'mule)
2548                                             (concat "[ \t\n]\\|" word-across-newline)
2549                                         "[ \t\n]"))
2550                        ;; end patch
2551                        (first t))
2552                    (save-excursion
2553                      (move-to-column (1+ fill-column))
2554                      ;; Move back to a word boundary.
2555                      (while (or first
2556                                 ;; If this is after period and a single space,
2557                                 ;; move back once more--we don't want to break
2558                                 ;; the line there and make it look like a
2559                                 ;; sentence end.
2560                                 (and (not (bobp))
2561                                      (not bounce)
2562                                      sentence-end-double-space
2563                                      (save-excursion (forward-char -1)
2564                                                      (and (looking-at "\\. ")
2565                                                           (not (looking-at "\\.  "))))))
2566                        (setq first nil)
2567                        ;; 97/3/14 jhod: Kinsoku
2568                        ; (skip-chars-backward "^ \t\n"))
2569                        (fill-move-backward-to-break-point re-break-point)
2570                        ;; end patch
2571                        ;; If we find nowhere on the line to break it,
2572                        ;; break after one word.  Set bounce to t
2573                        ;; so we will not keep going in this while loop.
2574                        (if (bolp)
2575                            (progn
2576                              ;; 97/3/14 jhod: Kinsoku
2577                              ; (re-search-forward "[ \t]" opoint t)
2578                              (fill-move-forward-to-break-point re-break-point
2579                                                                opoint)
2580                              ;; end patch
2581                              (setq bounce t)))
2582                        (skip-chars-backward " \t"))
2583                      (if (and (featurep 'mule)
2584                               (or bounce (bolp))) (kinsoku-process)) ;; 97/3/14 jhod: Kinsoku
2585                      ;; Let fill-point be set to the place where we end up.
2586                      (point)))))
2587
2588             ;; I'm not sure why Stig made this change but it breaks
2589             ;; auto filling in at least C mode so I'm taking it back
2590             ;; out.  --cet
2591             ;; XEmacs - adaptive fill.
2592             ;;(maybe-adapt-fill-prefix
2593             ;; (or from (setq from (save-excursion (beginning-of-line)
2594             ;;                                   (point))))
2595             ;; (or to   (setq to (save-excursion (beginning-of-line 2)
2596             ;;                                 (point))))
2597             ;; t)
2598
2599             ;; If that place is not the beginning of the line,
2600             ;; break the line there.
2601             (if (save-excursion
2602                   (goto-char fill-point)
2603                   (not (or (bolp) (eolp)))) ; 97/3/14 jhod: during kinsoku processing it is possible to move beyond
2604                 (let ((prev-column (current-column)))
2605                   ;; If point is at the fill-point, do not `save-excursion'.
2606                   ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2607                   ;; point will end up before it rather than after it.
2608                   (if (save-excursion
2609                         (skip-chars-backward " \t")
2610                         (= (point) fill-point))
2611                       ;; 97/3/14 jhod: Kinsoku processing
2612                       ;(indent-new-comment-line)
2613                       (let ((spacep (memq (char-before (point)) '(?\  ?\t))))
2614                         (funcall comment-line-break-function)
2615                         ;; if user type space explicitly, leave SPC
2616                         ;; even if there is no WAN.
2617                         (if spacep
2618                             (save-excursion
2619                               (goto-char fill-point)
2620                               ;; put SPC except that there is SPC
2621                               ;; already or there is sentence end.
2622                               (or (memq (char-after (point)) '(?\  ?\t))
2623                                   (fill-end-of-sentence-p)
2624                                   (insert ?\ )))))
2625                     (save-excursion
2626                       (goto-char fill-point)
2627                       (funcall comment-line-break-function)))
2628                   ;; If making the new line didn't reduce the hpos of
2629                   ;; the end of the line, then give up now;
2630                   ;; trying again will not help.
2631                   (if (>= (current-column) prev-column)
2632                       (setq give-up t)))
2633               ;; No place to break => stop trying.
2634               (setq give-up t)))))))
2635
2636 ;; Put FSF one in until I can one or the other working properly, then the
2637 ;; other one is history.
2638 ;(defun fsf:do-auto-fill ()
2639 ;  (let (fc justify
2640 ;          ;; bol
2641 ;          give-up
2642 ;          (fill-prefix fill-prefix))
2643 ;    (if (or (not (setq justify (current-justification)))
2644 ;           (null (setq fc (current-fill-column)))
2645 ;           (and (eq justify 'left)
2646 ;                (<= (current-column) fc))
2647 ;           (save-excursion (beginning-of-line)
2648 ;                           ;; (setq bol (point))
2649 ;                           (and auto-fill-inhibit-regexp
2650 ;                                (looking-at auto-fill-inhibit-regexp))))
2651 ;       nil ;; Auto-filling not required
2652 ;      (if (memq justify '(full center right))
2653 ;         (save-excursion (unjustify-current-line)))
2654
2655 ;      ;; Choose a fill-prefix automatically.
2656 ;      (if (and adaptive-fill-mode
2657 ;              (or (null fill-prefix) (string= fill-prefix "")))
2658 ;         (let ((prefix
2659 ;                (fill-context-prefix
2660 ;                 (save-excursion (backward-paragraph 1) (point))
2661 ;                 (save-excursion (forward-paragraph 1) (point))
2662 ;                 ;; Don't accept a non-whitespace fill prefix
2663 ;                 ;; from the first line of a paragraph.
2664 ;                 "^[ \t]*$")))
2665 ;           (and prefix (not (equal prefix ""))
2666 ;                (setq fill-prefix prefix))))
2667
2668 ;      (while (and (not give-up) (> (current-column) fc))
2669 ;       ;; Determine where to split the line.
2670 ;       (let ((fill-point
2671 ;              (let ((opoint (point))
2672 ;                    bounce
2673 ;                    (first t))
2674 ;                (save-excursion
2675 ;                  (move-to-column (1+ fc))
2676 ;                  ;; Move back to a word boundary.
2677 ;                  (while (or first
2678 ;                             ;; If this is after period and a single space,
2679 ;                             ;; move back once more--we don't want to break
2680 ;                             ;; the line there and make it look like a
2681 ;                             ;; sentence end.
2682 ;                             (and (not (bobp))
2683 ;                                  (not bounce)
2684 ;                                  sentence-end-double-space
2685 ;                                  (save-excursion (forward-char -1)
2686 ;                                                  (and (looking-at "\\. ")
2687 ;                                                       (not (looking-at "\\.  "))))))
2688 ;                    (setq first nil)
2689 ;                    (skip-chars-backward "^ \t\n")
2690 ;                    ;; If we find nowhere on the line to break it,
2691 ;                    ;; break after one word.  Set bounce to t
2692 ;                    ;; so we will not keep going in this while loop.
2693 ;                    (if (bolp)
2694 ;                        (progn
2695 ;                          (re-search-forward "[ \t]" opoint t)
2696 ;                          (setq bounce t)))
2697 ;                    (skip-chars-backward " \t"))
2698 ;                  ;; Let fill-point be set to the place where we end up.
2699 ;                  (point)))))
2700 ;         ;; If that place is not the beginning of the line,
2701 ;         ;; break the line there.
2702 ;         (if (save-excursion
2703 ;               (goto-char fill-point)
2704 ;               (not (bolp)))
2705 ;             (let ((prev-column (current-column)))
2706 ;               ;; If point is at the fill-point, do not `save-excursion'.
2707 ;               ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2708 ;               ;; point will end up before it rather than after it.
2709 ;               (if (save-excursion
2710 ;                     (skip-chars-backward " \t")
2711 ;                     (= (point) fill-point))
2712 ;                   (funcall comment-line-break-function t)
2713 ;                 (save-excursion
2714 ;                   (goto-char fill-point)
2715 ;                   (funcall comment-line-break-function t)))
2716 ;               ;; Now do justification, if required
2717 ;               (if (not (eq justify 'left))
2718 ;                   (save-excursion
2719 ;                     (end-of-line 0)
2720 ;                     (justify-current-line justify nil t)))
2721 ;               ;; If making the new line didn't reduce the hpos of
2722 ;               ;; the end of the line, then give up now;
2723 ;               ;; trying again will not help.
2724 ;               (if (>= (current-column) prev-column)
2725 ;                   (setq give-up t)))
2726 ;           ;; No place to break => stop trying.
2727 ;           (setq give-up t))))
2728 ;      ;; Justify last line.
2729 ;      (justify-current-line justify t t)
2730 ;      t)))
2731
2732 (defvar normal-auto-fill-function 'do-auto-fill
2733   "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
2734 Some major modes set this.")
2735
2736 (defun auto-fill-mode (&optional arg)
2737   "Toggle auto-fill mode.
2738 With arg, turn auto-fill mode on if and only if arg is positive.
2739 In Auto-Fill mode, inserting a space at a column beyond `current-fill-column'
2740 automatically breaks the line at a previous space.
2741
2742 The value of `normal-auto-fill-function' specifies the function to use
2743 for `auto-fill-function' when turning Auto Fill mode on."
2744   (interactive "P")
2745   (prog1 (setq auto-fill-function
2746                (if (if (null arg)
2747                        (not auto-fill-function)
2748                        (> (prefix-numeric-value arg) 0))
2749                    normal-auto-fill-function
2750                    nil))
2751     (redraw-modeline)))
2752
2753 ;; This holds a document string used to document auto-fill-mode.
2754 (defun auto-fill-function ()
2755   "Automatically break line at a previous space, in insertion of text."
2756   nil)
2757
2758 (defun turn-on-auto-fill ()
2759   "Unconditionally turn on Auto Fill mode."
2760   (auto-fill-mode 1))
2761
2762 (defun set-fill-column (arg)
2763   "Set `fill-column' to specified argument.
2764 Just \\[universal-argument] as argument means to use the current column
2765 The variable `fill-column' has a separate value for each buffer."
2766   (interactive "_P") ; XEmacs
2767   (cond ((integerp arg)
2768          (setq fill-column arg))
2769         ((consp arg)
2770          (setq fill-column (current-column)))
2771         ;; Disallow missing argument; it's probably a typo for C-x C-f.
2772         (t
2773          (error "set-fill-column requires an explicit argument")))
2774   (lmessage 'command "fill-column set to %d" fill-column))
2775 \f
2776 (defcustom comment-multi-line t ; XEmacs - this works well with adaptive fill
2777   "*Non-nil means \\[indent-new-comment-line] should continue same comment
2778 on new line, with no new terminator or starter.
2779 This is obsolete because you might as well use \\[newline-and-indent]."
2780   :type 'boolean
2781   :group 'fill-comments)
2782
2783 (defun indent-new-comment-line (&optional soft)
2784   "Break line at point and indent, continuing comment if within one.
2785 This indents the body of the continued comment
2786 under the previous comment line.
2787
2788 This command is intended for styles where you write a comment per line,
2789 starting a new comment (and terminating it if necessary) on each line.
2790 If you want to continue one comment across several lines, use \\[newline-and-indent].
2791
2792 If a fill column is specified, it overrides the use of the comment column
2793 or comment indentation.
2794
2795 The inserted newline is marked hard if `use-hard-newlines' is true,
2796 unless optional argument SOFT is non-nil."
2797   (interactive)
2798   (let (comcol comstart)
2799     (skip-chars-backward " \t")
2800     ;; 97/3/14 jhod: Kinsoku processing
2801     (if (featurep 'mule)
2802         (kinsoku-process))
2803     (delete-region (point)
2804                    (progn (skip-chars-forward " \t")
2805                           (point)))
2806     (if soft (insert ?\n) (newline 1))
2807     (if fill-prefix
2808         (progn
2809           (indent-to-left-margin)
2810           (insert fill-prefix))
2811     ;; #### - Eric Eide reverts to v18 semantics for this function in
2812     ;; fa-extras, which I'm not gonna do.  His changes are to (1) execute
2813     ;; the save-excursion below unconditionally, and (2) uncomment the check
2814     ;; for (not comment-multi-line) further below.  --Stig
2815       ;;#### jhod: probably need to fix this for kinsoku processing
2816       (if (not comment-multi-line)
2817           (save-excursion
2818             (if (and comment-start-skip
2819                      (let ((opoint (point)))
2820                        (forward-line -1)
2821                        (re-search-forward comment-start-skip opoint t)))
2822                 ;; The old line is a comment.
2823                 ;; Set WIN to the pos of the comment-start.
2824                 ;; But if the comment is empty, look at preceding lines
2825                 ;; to find one that has a nonempty comment.
2826
2827                 ;; If comment-start-skip contains a \(...\) pair,
2828                 ;; the real comment delimiter starts at the end of that pair.
2829                 (let ((win (or (match-end 1) (match-beginning 0))))
2830                   (while (and (eolp) (not (bobp))
2831                               (let (opoint)
2832                                 (beginning-of-line)
2833                                 (setq opoint (point))
2834                                 (forward-line -1)
2835                                 (re-search-forward comment-start-skip opoint t)))
2836                     (setq win (or (match-end 1) (match-beginning 0))))
2837                   ;; Indent this line like what we found.
2838                   (goto-char win)
2839                   (setq comcol (current-column))
2840                   (setq comstart
2841                         (buffer-substring (point) (match-end 0)))))))
2842       (if (and comcol (not fill-prefix))  ; XEmacs - (ENE) from fa-extras.
2843           (let ((comment-column comcol)
2844                 (comment-start comstart)
2845                 (comment-end comment-end))
2846             (and comment-end (not (equal comment-end ""))
2847   ;            (if (not comment-multi-line)
2848                      (progn
2849                        (forward-char -1)
2850                        (insert comment-end)
2851                        (forward-char 1))
2852   ;              (setq comment-column (+ comment-column (length comment-start))
2853   ;                    comment-start "")
2854   ;                )
2855                  )
2856             (if (not (eolp))
2857                 (setq comment-end ""))
2858             (insert ?\n)
2859             (forward-char -1)
2860             (indent-for-comment)
2861             (save-excursion
2862               ;; Make sure we delete the newline inserted above.
2863               (end-of-line)
2864               (delete-char 1)))
2865         (indent-according-to-mode)))))
2866
2867 \f
2868 (defun set-selective-display (arg)
2869   "Set `selective-display' to ARG; clear it if no arg.
2870 When the value of `selective-display' is a number > 0,
2871 lines whose indentation is >= that value are not displayed.
2872 The variable `selective-display' has a separate value for each buffer."
2873   (interactive "P")
2874   (if (eq selective-display t)
2875       (error "selective-display already in use for marked lines"))
2876   (let ((current-vpos
2877          (save-restriction
2878            (narrow-to-region (point-min) (point))
2879            (goto-char (window-start))
2880            (vertical-motion (window-height)))))
2881     (setq selective-display
2882           (and arg (prefix-numeric-value arg)))
2883     (recenter current-vpos))
2884   (set-window-start (selected-window) (window-start (selected-window)))
2885   ;; #### doesn't localize properly:
2886   (princ "selective-display set to " t)
2887   (prin1 selective-display t)
2888   (princ "." t))
2889
2890 ;; XEmacs
2891 (defun nuke-selective-display ()
2892   "Ensure that the buffer is not in selective-display mode.
2893 If `selective-display' is t, then restore the buffer text to its original
2894 state before disabling selective display."
2895   ;; by Stig@hackvan.com
2896   (interactive)
2897   (and (eq t selective-display)
2898        (save-excursion
2899          (save-restriction
2900            (widen)
2901            (goto-char (point-min))
2902            (let ((mod-p (buffer-modified-p))
2903                  (buffer-read-only nil))
2904              (while (search-forward "\r" nil t)
2905                (delete-char -1)
2906                (insert "\n"))
2907              (set-buffer-modified-p mod-p)
2908              ))))
2909   (setq selective-display nil))
2910
2911 (add-hook 'change-major-mode-hook 'nuke-selective-display)
2912
2913 (defconst overwrite-mode-textual (purecopy " Ovwrt")
2914   "The string displayed in the mode line when in overwrite mode.")
2915 (defconst overwrite-mode-binary (purecopy " Bin Ovwrt")
2916   "The string displayed in the mode line when in binary overwrite mode.")
2917
2918 (defun overwrite-mode (arg)
2919   "Toggle overwrite mode.
2920 With arg, turn overwrite mode on iff arg is positive.
2921 In overwrite mode, printing characters typed in replace existing text
2922 on a one-for-one basis, rather than pushing it to the right.  At the
2923 end of a line, such characters extend the line.  Before a tab,
2924 such characters insert until the tab is filled in.
2925 \\[quoted-insert] still inserts characters in overwrite mode; this
2926 is supposed to make it easier to insert characters when necessary."
2927   (interactive "P")
2928   (setq overwrite-mode
2929         (if (if (null arg) (not overwrite-mode)
2930               (> (prefix-numeric-value arg) 0))
2931             'overwrite-mode-textual))
2932   (redraw-modeline))
2933
2934 (defun binary-overwrite-mode (arg)
2935   "Toggle binary overwrite mode.
2936 With arg, turn binary overwrite mode on iff arg is positive.
2937 In binary overwrite mode, printing characters typed in replace
2938 existing text.  Newlines are not treated specially, so typing at the
2939 end of a line joins the line to the next, with the typed character
2940 between them.  Typing before a tab character simply replaces the tab
2941 with the character typed.
2942 \\[quoted-insert] replaces the text at the cursor, just as ordinary
2943 typing characters do.
2944
2945 Note that binary overwrite mode is not its own minor mode; it is a
2946 specialization of overwrite-mode, entered by setting the
2947 `overwrite-mode' variable to `overwrite-mode-binary'."
2948   (interactive "P")
2949   (setq overwrite-mode
2950         (if (if (null arg)
2951                 (not (eq overwrite-mode 'overwrite-mode-binary))
2952               (> (prefix-numeric-value arg) 0))
2953             'overwrite-mode-binary))
2954   (redraw-modeline))
2955 \f
2956 (defcustom line-number-mode nil
2957   "*Non-nil means display line number in modeline."
2958   :type 'boolean
2959   :group 'editing-basics)
2960
2961 (defun line-number-mode (arg)
2962   "Toggle Line Number mode.
2963 With arg, turn Line Number mode on iff arg is positive.
2964 When Line Number mode is enabled, the line number appears
2965 in the mode line."
2966   (interactive "P")
2967   (setq line-number-mode
2968         (if (null arg) (not line-number-mode)
2969           (> (prefix-numeric-value arg) 0)))
2970   (redraw-modeline))
2971
2972 (defcustom column-number-mode nil
2973   "*Non-nil means display column number in mode line."
2974   :type 'boolean
2975   :group 'editing-basics)
2976
2977 (defun column-number-mode (arg)
2978   "Toggle Column Number mode.
2979 With arg, turn Column Number mode on iff arg is positive.
2980 When Column Number mode is enabled, the column number appears
2981 in the mode line."
2982   (interactive "P")
2983   (setq column-number-mode
2984         (if (null arg) (not column-number-mode)
2985           (> (prefix-numeric-value arg) 0)))
2986   (redraw-modeline))
2987
2988 \f
2989 (defcustom blink-matching-paren t
2990   "*Non-nil means show matching open-paren when close-paren is inserted."
2991   :type 'boolean
2992   :group 'paren-blinking)
2993
2994 (defcustom blink-matching-paren-on-screen t
2995   "*Non-nil means show matching open-paren when it is on screen.
2996 nil means don't show it (but the open-paren can still be shown
2997 when it is off screen."
2998   :type 'boolean
2999   :group 'paren-blinking)
3000
3001 (defcustom blink-matching-paren-distance 12000
3002   "*If non-nil, is maximum distance to search for matching open-paren."
3003   :type '(choice integer (const nil))
3004   :group 'paren-blinking)
3005
3006 (defcustom blink-matching-delay 1
3007   "*The number of seconds that `blink-matching-open' will delay at a match."
3008   :type 'number
3009   :group 'paren-blinking)
3010
3011 (defcustom blink-matching-paren-dont-ignore-comments nil
3012   "*Non-nil means `blink-matching-paren' should not ignore comments."
3013   :type 'boolean
3014   :group 'paren-blinking)
3015
3016 (defun blink-matching-open ()
3017   "Move cursor momentarily to the beginning of the sexp before point."
3018   (interactive "_") ; XEmacs
3019   (and (> (point) (1+ (point-min)))
3020        blink-matching-paren
3021        ;; Verify an even number of quoting characters precede the close.
3022        (= 1 (logand 1 (- (point)
3023                          (save-excursion
3024                            (forward-char -1)
3025                            (skip-syntax-backward "/\\")
3026                            (point)))))
3027        (let* ((oldpos (point))
3028               (blinkpos)
3029               (mismatch))
3030          (save-excursion
3031            (save-restriction
3032              (if blink-matching-paren-distance
3033                  (narrow-to-region (max (point-min)
3034                                         (- (point) blink-matching-paren-distance))
3035                                    oldpos))
3036              (condition-case ()
3037                  (let ((parse-sexp-ignore-comments
3038                         (and parse-sexp-ignore-comments
3039                              (not blink-matching-paren-dont-ignore-comments))))
3040                    (setq blinkpos (scan-sexps oldpos -1)))
3041                (error nil)))
3042            (and blinkpos
3043                 (/= (char-syntax (char-after blinkpos))
3044                     ?\$)
3045                 (setq mismatch
3046                       (or (null (matching-paren (char-after blinkpos)))
3047                           (/= (char-after (1- oldpos))
3048                               (matching-paren (char-after blinkpos))))))
3049            (if mismatch (setq blinkpos nil))
3050            (if blinkpos
3051                (progn
3052                 (goto-char blinkpos)
3053                 (if (pos-visible-in-window-p)
3054                     (and blink-matching-paren-on-screen
3055                          (progn
3056                            (auto-show-make-point-visible)
3057                            (sit-for blink-matching-delay)))
3058                   (goto-char blinkpos)
3059                   (lmessage 'command "Matches %s"
3060                     ;; Show what precedes the open in its line, if anything.
3061                     (if (save-excursion
3062                           (skip-chars-backward " \t")
3063                           (not (bolp)))
3064                         (buffer-substring (progn (beginning-of-line) (point))
3065                                           (1+ blinkpos))
3066                       ;; Show what follows the open in its line, if anything.
3067                       (if (save-excursion
3068                             (forward-char 1)
3069                             (skip-chars-forward " \t")
3070                             (not (eolp)))
3071                           (buffer-substring blinkpos
3072                                             (progn (end-of-line) (point)))
3073                         ;; Otherwise show the previous nonblank line,
3074                         ;; if there is one.
3075                         (if (save-excursion
3076                               (skip-chars-backward "\n \t")
3077                               (not (bobp)))
3078                             (concat
3079                              (buffer-substring (progn
3080                                                  (skip-chars-backward "\n \t")
3081                                                  (beginning-of-line)
3082                                                  (point))
3083                                                (progn (end-of-line)
3084                                                       (skip-chars-backward " \t")
3085                                                       (point)))
3086                              ;; Replace the newline and other whitespace with `...'.
3087                              "..."
3088                              (buffer-substring blinkpos (1+ blinkpos)))
3089                           ;; There is nothing to show except the char itself.
3090                           (buffer-substring blinkpos (1+ blinkpos))))))))
3091              (cond (mismatch
3092                     (display-message 'no-log "Mismatched parentheses"))
3093                    ((not blink-matching-paren-distance)
3094                     (display-message 'no-log "Unmatched parenthesis"))))))))
3095
3096 ;Turned off because it makes dbx bomb out.
3097 (setq blink-paren-function 'blink-matching-open)
3098 \f
3099 (eval-when-compile (defvar myhelp))     ; suppress compiler warning
3100
3101 ;; XEmacs: Some functions moved to cmdloop.el:
3102 ;; keyboard-quit
3103 ;; buffer-quit-function
3104 ;; keyboard-escape-quit
3105
3106 (defun assoc-ignore-case (key alist)
3107   "Like `assoc', but assumes KEY is a string and ignores case when comparing."
3108   (setq key (downcase key))
3109   (let (element)
3110     (while (and alist (not element))
3111       (if (equal key (downcase (car (car alist))))
3112           (setq element (car alist)))
3113       (setq alist (cdr alist)))
3114     element))
3115
3116 \f
3117 (defcustom mail-user-agent 'sendmail-user-agent
3118   "*Your preference for a mail composition package.
3119 Various Emacs Lisp packages (e.g. reporter) require you to compose an
3120 outgoing email message.  This variable lets you specify which
3121 mail-sending package you prefer.
3122
3123 Valid values include:
3124
3125     sendmail-user-agent -- use the default Emacs Mail package
3126     mh-e-user-agent     -- use the Emacs interface to the MH mail system
3127     message-user-agent  -- use the GNUS mail sending package
3128
3129 Additional valid symbols may be available; check with the author of
3130 your package for details."
3131   :type '(radio (function-item :tag "Default Emacs mail"
3132                                :format "%t\n"
3133                                sendmail-user-agent)
3134                 (function-item :tag "Gnus mail sending package"
3135                                :format "%t\n"
3136                                message-user-agent)
3137                 (function :tag "Other"))
3138   :group 'mail)
3139
3140 (defun define-mail-user-agent (symbol composefunc sendfunc
3141                                       &optional abortfunc hookvar)
3142   "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3143
3144 SYMBOL can be any Lisp symbol.  Its function definition and/or
3145 value as a variable do not matter for this usage; we use only certain
3146 properties on its property list, to encode the rest of the arguments.
3147
3148 COMPOSEFUNC is program callable function that composes an outgoing
3149 mail message buffer.  This function should set up the basics of the
3150 buffer without requiring user interaction.  It should populate the
3151 standard mail headers, leaving the `to:' and `subject:' headers blank
3152 by default.
3153
3154 COMPOSEFUNC should accept several optional arguments--the same
3155 arguments that `compose-mail' takes.  See that function's documentation.
3156
3157 SENDFUNC is the command a user would run to send the message.
3158
3159 Optional ABORTFUNC is the command a user would run to abort the
3160 message.  For mail packages that don't have a separate abort function,
3161 this can be `kill-buffer' (the equivalent of omitting this argument).
3162
3163 Optional HOOKVAR is a hook variable that gets run before the message
3164 is actually sent.  Callers that use the `mail-user-agent' may
3165 install a hook function temporarily on this hook variable.
3166 If HOOKVAR is nil, `mail-send-hook' is used.
3167
3168 The properties used on SYMBOL are `composefunc', `sendfunc',
3169 `abortfunc', and `hookvar'."
3170   (put symbol 'composefunc composefunc)
3171   (put symbol 'sendfunc sendfunc)
3172   (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3173   (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3174
3175 (define-mail-user-agent 'sendmail-user-agent
3176   'sendmail-user-agent-compose 'mail-send-and-exit)
3177
3178 (define-mail-user-agent 'message-user-agent
3179   'message-mail 'message-send-and-exit
3180   'message-kill-buffer 'message-send-hook)
3181
3182 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3183                                               switch-function yank-action
3184                                               send-actions)
3185   (if switch-function
3186       (let ((special-display-buffer-names nil)
3187             (special-display-regexps nil)
3188             (same-window-buffer-names nil)
3189             (same-window-regexps nil))
3190         (funcall switch-function "*mail*")))
3191   (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
3192         (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers))))
3193     (or (mail continue to subject in-reply-to cc yank-action send-actions)
3194         continue
3195         (error "Message aborted"))
3196     (save-excursion
3197       (goto-char (point-min))
3198       (search-forward mail-header-separator)
3199       (beginning-of-line)
3200       (while other-headers
3201         (if (not (member (car (car other-headers)) '("in-reply-to" "cc")))
3202             (insert (car (car other-headers)) ": "
3203                     (cdr (car other-headers)) "\n"))
3204         (setq other-headers (cdr other-headers)))
3205       t)))
3206
3207 (define-mail-user-agent 'mh-e-user-agent
3208   'mh-user-agent-compose 'mh-send-letter 'mh-fully-kill-draft
3209   'mh-before-send-letter-hook)
3210
3211 (defun compose-mail (&optional to subject other-headers continue
3212                                switch-function yank-action send-actions)
3213   "Start composing a mail message to send.
3214 This uses the user's chosen mail composition package
3215 as selected with the variable `mail-user-agent'.
3216 The optional arguments TO and SUBJECT specify recipients
3217 and the initial Subject field, respectively.
3218
3219 OTHER-HEADERS is an alist specifying additional
3220 header fields.  Elements look like (HEADER . VALUE) where both
3221 HEADER and VALUE are strings.
3222
3223 CONTINUE, if non-nil, says to continue editing a message already
3224 being composed.
3225
3226 SWITCH-FUNCTION, if non-nil, is a function to use to
3227 switch to and display the buffer used for mail composition.
3228
3229 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3230 to insert the raw text of the message being replied to.
3231 It has the form (FUNCTION . ARGS).  The user agent will apply
3232 FUNCTION to ARGS, to insert the raw text of the original message.
3233 \(The user agent will also run `mail-citation-hook', *after* the
3234 original text has been inserted in this way.)
3235
3236 SEND-ACTIONS is a list of actions to call when the message is sent.
3237 Each action has the form (FUNCTION . ARGS)."
3238   (interactive
3239    (list nil nil nil current-prefix-arg))
3240   (let ((function (get mail-user-agent 'composefunc)))
3241     (funcall function to subject other-headers continue
3242              switch-function yank-action send-actions)))
3243
3244 (defun compose-mail-other-window (&optional to subject other-headers continue
3245                                             yank-action send-actions)
3246   "Like \\[compose-mail], but edit the outgoing message in another window."
3247   (interactive
3248    (list nil nil nil current-prefix-arg))
3249   (compose-mail to subject other-headers continue
3250                 'switch-to-buffer-other-window yank-action send-actions))
3251
3252
3253 (defun compose-mail-other-frame (&optional to subject other-headers continue
3254                                             yank-action send-actions)
3255   "Like \\[compose-mail], but edit the outgoing message in another frame."
3256   (interactive
3257    (list nil nil nil current-prefix-arg))
3258   (compose-mail to subject other-headers continue
3259                 'switch-to-buffer-other-frame yank-action send-actions))
3260
3261 \f
3262 (defun set-variable (var val)
3263   "Set VARIABLE to VALUE.  VALUE is a Lisp object.
3264 When using this interactively, supply a Lisp expression for VALUE.
3265 If you want VALUE to be a string, you must surround it with doublequotes.
3266 If VARIABLE is a specifier, VALUE is added to it as an instantiator in
3267 the 'global locale with nil tag set (see `set-specifier').
3268
3269 If VARIABLE has a `variable-interactive' property, that is used as if
3270 it were the arg to `interactive' (which see) to interactively read the value."
3271   (interactive
3272    (let* ((var (read-variable "Set variable: "))
3273           ;; #### - yucky code replication here.  This should use something
3274           ;; from help.el or hyper-apropos.el
3275           (minibuffer-help-form
3276            '(funcall myhelp))
3277           (myhelp
3278            #'(lambda ()
3279               (with-output-to-temp-buffer "*Help*"
3280                 (prin1 var)
3281                 (princ "\nDocumentation:\n")
3282                 (princ (substring (documentation-property var 'variable-documentation)
3283                                   1))
3284                 (if (boundp var)
3285                     (let ((print-length 20))
3286                       (princ "\n\nCurrent value: ")
3287                       (prin1 (symbol-value var))))
3288                 (save-excursion
3289                   (set-buffer standard-output)
3290                   (help-mode))
3291                 nil))))
3292      (list var
3293            (let ((prop (get var 'variable-interactive)))
3294              (if prop
3295                  ;; Use VAR's `variable-interactive' property
3296                  ;; as an interactive spec for prompting.
3297                  (call-interactively (list 'lambda '(arg)
3298                                            (list 'interactive prop)
3299                                            'arg))
3300                (eval-minibuffer (format "Set %s to value: " var)))))))
3301   (if (and (boundp var) (specifierp (symbol-value var)))
3302       (set-specifier (symbol-value var) val)
3303     (set var val)))
3304 \f
3305 ;; XEmacs
3306 (defun activate-region ()
3307   "Activate the region, if `zmacs-regions' is true.
3308 Setting `zmacs-regions' to true causes LISPM-style active regions to be used.
3309 This function has no effect if `zmacs-regions' is false."
3310   (interactive)
3311   (and zmacs-regions (zmacs-activate-region)))
3312
3313 ;; XEmacs
3314 (defsubst region-exists-p ()
3315   "Return t if the region exists.
3316 If active regions are in use (i.e. `zmacs-regions' is true), this means that
3317  the region is active.  Otherwise, this means that the user has pushed
3318  a mark in this buffer at some point in the past.
3319 The functions `region-beginning' and `region-end' can be used to find the
3320  limits of the region."
3321   (not (null (mark))))
3322
3323 ;; XEmacs
3324 (defun region-active-p ()
3325   "Return non-nil if the region is active.
3326 If `zmacs-regions' is true, this is equivalent to `region-exists-p'.
3327 Otherwise, this function always returns false."
3328   (and zmacs-regions zmacs-region-extent))
3329
3330 ;; A bunch of stuff was moved elsewhere:
3331 ;; completion-list-mode-map
3332 ;; completion-reference-buffer
3333 ;; completion-base-size
3334 ;; delete-completion-window
3335 ;; previous-completion
3336 ;; next-completion
3337 ;; choose-completion
3338 ;; choose-completion-delete-max-match
3339 ;; choose-completion-string
3340 ;; completion-list-mode
3341 ;; completion-fixup-function
3342 ;; completion-setup-function
3343 ;; switch-to-completions
3344 ;; event stuffs
3345 ;; keypad stuffs
3346
3347 ;; The rest of this file is not in Lisp in FSF
3348 (defun capitalize-region-or-word (arg)
3349   "Capitalize the selected region or the following word (or ARG words)."
3350   (interactive "p")
3351   (if (region-active-p)
3352       (capitalize-region (region-beginning) (region-end))
3353     (capitalize-word arg)))
3354
3355 (defun upcase-region-or-word (arg)
3356   "Upcase the selected region or the following word (or ARG words)."
3357   (interactive "p")
3358   (if (region-active-p)
3359       (upcase-region (region-beginning) (region-end))
3360     (upcase-word arg)))
3361
3362 (defun downcase-region-or-word (arg)
3363   "Downcase the selected region or the following word (or ARG words)."
3364   (interactive "p")
3365   (if (region-active-p)
3366       (downcase-region (region-beginning) (region-end))
3367     (downcase-word arg)))
3368
3369 ;; Most of the zmacs code is now in elisp.  The only thing left in C
3370 ;; are the variables zmacs-regions, zmacs-region-active-p and
3371 ;; zmacs-region-stays plus the function zmacs_update_region which
3372 ;; simply calls the lisp level zmacs-update-region.  It must remain
3373 ;; for convenience, since it is called by core C code.
3374
3375 (defvar zmacs-activate-region-hook nil
3376   "Function or functions called when the region becomes active;
3377 see the variable `zmacs-regions'.")
3378
3379 (defvar zmacs-deactivate-region-hook nil
3380   "Function or functions called when the region becomes inactive;
3381 see the variable `zmacs-regions'.")
3382
3383 (defvar zmacs-update-region-hook nil
3384   "Function or functions called when the active region changes.
3385 This is called after each command that sets `zmacs-region-stays' to t.
3386 See the variable `zmacs-regions'.")
3387
3388 (defvar zmacs-region-extent nil
3389   "The extent of the zmacs region; don't use this.")
3390
3391 (defvar zmacs-region-rectangular-p nil
3392   "Whether the zmacs region is a rectangle; don't use this.")
3393
3394 (defun zmacs-make-extent-for-region (region)
3395   ;; Given a region, this makes an extent in the buffer which holds that
3396   ;; region, for highlighting purposes.  If the region isn't associated
3397   ;; with a buffer, this does nothing.
3398   (let ((buffer nil)
3399         (valid (and (extentp zmacs-region-extent)
3400                     (extent-object zmacs-region-extent)
3401                     (buffer-live-p (extent-object zmacs-region-extent))))
3402         start end)
3403     (cond ((consp region)
3404            (setq start (min (car region) (cdr region))
3405                  end (max (car region) (cdr region))
3406                  valid (and valid
3407                             (eq (marker-buffer (car region))
3408                                 (extent-object zmacs-region-extent)))
3409                  buffer (marker-buffer (car region))))
3410           (t
3411            (signal 'error (list "Invalid region" region))))
3412
3413     (if valid
3414         nil
3415       ;; The condition case is in case any of the extents are dead or
3416       ;; otherwise incapacitated.
3417       (condition-case ()
3418           (if (listp zmacs-region-extent)
3419               (mapc 'delete-extent zmacs-region-extent)
3420             (delete-extent zmacs-region-extent))
3421         (error nil)))
3422
3423     (if valid
3424         (set-extent-endpoints zmacs-region-extent start end)
3425       (setq zmacs-region-extent (make-extent start end buffer))
3426
3427       ;; Make the extent be closed on the right, which means that if
3428       ;; characters are inserted exactly at the end of the extent, the
3429       ;; extent will grow to cover them.  This is important for shell
3430       ;; buffers - suppose one makes a region, and one end is at point-max.
3431       ;; If the shell produces output, that marker will remain at point-max
3432       ;; (its position will increase).  So it's important that the extent
3433       ;; exhibit the same behavior, lest the region covered by the extent
3434       ;; (the visual indication), and the region between point and mark
3435       ;; (the actual region value) become different!
3436       (set-extent-property zmacs-region-extent 'end-open nil)
3437
3438       ;; use same priority as mouse-highlighting so that conflicts between
3439       ;; the region extent and a mouse-highlighted extent are resolved by
3440       ;; the usual size-and-endpoint-comparison method.
3441       (set-extent-priority zmacs-region-extent mouse-highlight-priority)
3442       (set-extent-face zmacs-region-extent 'zmacs-region)
3443
3444       ;; #### It might be better to actually break
3445       ;; default-mouse-track-next-move-rect out of mouse.el so that we
3446       ;; can use its logic here.
3447       (cond
3448        (zmacs-region-rectangular-p
3449         (setq zmacs-region-extent (list zmacs-region-extent))
3450         (default-mouse-track-next-move-rect start end zmacs-region-extent)
3451         ))
3452
3453       zmacs-region-extent)))
3454
3455 (defun zmacs-region-buffer ()
3456   "Return the buffer containing the zmacs region, or nil."
3457   ;; #### this is horrible and kludgy!  This stuff needs to be rethought.
3458   (and zmacs-regions zmacs-region-active-p
3459        (or (marker-buffer (mark-marker t))
3460            (and (extent-live-p zmacs-region-extent)
3461                 (buffer-live-p (extent-object zmacs-region-extent))
3462                 (extent-object zmacs-region-extent)))))
3463
3464 (defun zmacs-activate-region ()
3465   "Make the region between `point' and `mark' be active (highlighted),
3466 if `zmacs-regions' is true.  Only a very small number of commands
3467 should ever do this.  Calling this function will call the hook
3468 `zmacs-activate-region-hook', if the region was previously inactive.
3469 Calling this function ensures that the region stays active after the
3470 current command terminates, even if `zmacs-region-stays' is not set.
3471 Returns t if the region was activated (i.e. if `zmacs-regions' if t)."
3472   (if (not zmacs-regions)
3473       nil
3474     (setq zmacs-region-active-p t
3475           zmacs-region-stays t
3476           zmacs-region-rectangular-p (and (boundp 'mouse-track-rectangle-p)
3477                                           mouse-track-rectangle-p))
3478     (if (marker-buffer (mark-marker t))
3479         (zmacs-make-extent-for-region (cons (point-marker t) (mark-marker t))))
3480     (run-hooks 'zmacs-activate-region-hook)
3481     t))
3482
3483 (defun zmacs-deactivate-region ()
3484   "Make the region between `point' and `mark' no longer be active,
3485 if `zmacs-regions' is true.  You shouldn't need to call this; the
3486 command loop calls it when appropriate.  Calling this function will
3487 call the hook `zmacs-deactivate-region-hook', if the region was
3488 previously active.  Returns t if the region had been active, nil
3489 otherwise."
3490   (if (not zmacs-region-active-p)
3491       nil
3492     (setq zmacs-region-active-p nil
3493           zmacs-region-stays nil
3494           zmacs-region-rectangular-p nil)
3495     (if zmacs-region-extent
3496         (let ((inhibit-quit t))
3497           (if (listp zmacs-region-extent)
3498               (mapc 'delete-extent zmacs-region-extent)
3499             (delete-extent zmacs-region-extent))
3500           (setq zmacs-region-extent nil)))
3501     (run-hooks 'zmacs-deactivate-region-hook)
3502     t))
3503
3504 (defun zmacs-update-region ()
3505   "Update the highlighted region between `point' and `mark'.
3506 You shouldn't need to call this; the command loop calls it
3507 when appropriate.  Calling this function will call the hook
3508 `zmacs-update-region-hook', if the region is active."
3509   (when zmacs-region-active-p
3510     (when (marker-buffer (mark-marker t))
3511       (zmacs-make-extent-for-region (cons (point-marker t)
3512                                           (mark-marker t))))
3513     (run-hooks 'zmacs-update-region-hook)))
3514
3515 ;;;;;;
3516 ;;;;;; echo area stuff
3517 ;;;;;;
3518
3519 ;;; #### Should this be moved to a separate file, for clarity?
3520 ;;; -hniksic
3521
3522 ;;; The `message-stack' is an alist of labels with messages; the first
3523 ;;; message in this list is always in the echo area.  A call to
3524 ;;; `display-message' inserts a label/message pair at the head of the
3525 ;;; list, and removes any other pairs with that label.  Calling
3526 ;;; `clear-message' causes any pair with matching label to be removed,
3527 ;;; and this may cause the displayed message to change or vanish.  If
3528 ;;; the label arg is nil, the entire message stack is cleared.
3529 ;;;
3530 ;;; Message/error filtering will be a little tricker to implement than
3531 ;;; logging, since messages can be built up incrementally
3532 ;;; using clear-message followed by repeated calls to append-message
3533 ;;; (this happens with error messages).  For messages which aren't
3534 ;;; created this way, filtering could be implemented at display-message
3535 ;;; very easily.
3536 ;;;
3537 ;;; Bits of the logging code are borrowed from log-messages.el by
3538 ;;; Robert Potter (rpotter@grip.cis.upenn.edu).
3539
3540 ;; need this to terminate the currently-displayed message
3541 ;; ("Loading simple ...")
3542 (when (and
3543        (not (fboundp 'display-message))
3544        (not (featurep 'debug)))
3545   (send-string-to-terminal "\n"))
3546
3547 (defvar message-stack nil
3548   "An alist of label/string pairs representing active echo-area messages.
3549 The first element in the list is currently displayed in the echo area.
3550 Do not modify this directly--use the `message' or
3551 `display-message'/`clear-message' functions.")
3552
3553 (defvar remove-message-hook 'log-message
3554   "A function or list of functions to be called when a message is removed
3555 from the echo area at the bottom of the frame.  The label of the removed
3556 message is passed as the first argument, and the text of the message
3557 as the second argument.")
3558
3559 (defcustom log-message-max-size 50000
3560   "Maximum size of the \" *Message-Log*\" buffer.  See `log-message'."
3561   :type 'integer
3562   :group 'log-message)
3563 (make-compatible-variable 'message-log-max 'log-message-max-size)
3564
3565 ;; We used to reject quite a lot of stuff here, but it was a bad idea,
3566 ;; for two reasons:
3567 ;;
3568 ;; a) In most circumstances, you *want* to see the message in the log.
3569 ;;    The explicitly non-loggable messages should be marked as such by
3570 ;;    the issuer.  Gratuitous non-displaying of random regexps made
3571 ;;    debugging harder, too (because various reasonable debugging
3572 ;;    messages would get eaten).
3573 ;;
3574 ;; b) It slowed things down.  Yes, visibly.
3575 ;;
3576 ;; So, I left only a few of the really useless ones on this kill-list.
3577 ;;
3578 ;;                                            --hniksic
3579 (defcustom log-message-ignore-regexps
3580   '(;; Note: adding entries to this list slows down messaging
3581     ;; significantly.  Wherever possible, use message lables.
3582
3583     ;; Often-seen messages
3584     "\\`\\'"                            ; empty message
3585     "\\`\\(Beginning\\|End\\) of buffer\\'"
3586     ;;"^Quit$"
3587     ;; completions
3588     ;; Many packages print this -- impossible to categorize
3589     ;;"^Making completion list"
3590     ;; Gnus
3591     ;; "^No news is no news$"
3592     ;; "^No more\\( unread\\)? newsgroups$"
3593     ;; "^Opening [^ ]+ server\\.\\.\\."
3594     ;; "^[^:]+: Reading incoming mail"
3595     ;; "^Getting mail from "
3596     ;; "^\\(Generating Summary\\|Sorting threads\\|Making sparse threads\\|Scoring\\|Checking new news\\|Expiring articles\\|Sending\\)\\.\\.\\."
3597     ;; "^\\(Fetching headers for\\|Retrieving newsgroup\\|Reading active file\\)"
3598     ;; "^No more\\( unread\\)? articles"
3599     ;; "^Deleting article "
3600     ;; W3
3601     ;; "^Parsed [0-9]+ of [0-9]+ ([0-9]+%)"
3602     )
3603   "List of regular expressions matching messages which shouldn't be logged.
3604 See `log-message'.
3605
3606 Ideally, packages which generate messages which might need to be ignored
3607 should label them with 'progress, 'prompt, or 'no-log, so they can be
3608 filtered by the log-message-ignore-labels."
3609   :type '(repeat regexp)
3610   :group 'log-message)
3611
3612 (defcustom log-message-ignore-labels
3613   '(help-echo command progress prompt no-log garbage-collecting auto-saving)
3614   "List of symbols indicating labels of messages which shouldn't be logged.
3615 See `display-message' for some common labels.  See also `log-message'."
3616   :type '(repeat (symbol :tag "Label"))
3617   :group 'log-message)
3618
3619 ;;Subsumed by view-lossage
3620 ;; Not really, I'm adding it back by popular demand. -slb
3621 (defun show-message-log ()
3622   "Show the \" *Message-Log*\" buffer, which contains old messages and errors."
3623   (interactive)
3624   (pop-to-buffer (get-buffer-create " *Message-Log*")))
3625
3626 (defvar log-message-filter-function 'log-message-filter
3627   "Value must be a function of two arguments: a symbol (label) and
3628 a string (message).  It should return non-nil to indicate a message
3629 should be logged.  Possible values include 'log-message-filter and
3630 'log-message-filter-errors-only.")
3631
3632 (defun log-message-filter (label message)
3633   "Default value of `log-message-filter-function'.
3634 Messages whose text matches one of the `log-message-ignore-regexps'
3635 or whose label appears in `log-message-ignore-labels' are not saved."
3636   (let ((r  log-message-ignore-regexps)
3637         (ok (not (memq label log-message-ignore-labels))))
3638     (save-match-data
3639       (while (and r ok)
3640         (when (string-match (car r) message)
3641           (setq ok nil))
3642         (setq r (cdr r))))
3643     ok))
3644
3645 (defun log-message-filter-errors-only (label message)
3646   "For use as the `log-message-filter-function'.  Only logs error messages."
3647   (eq label 'error))
3648
3649 (defun log-message (label message)
3650   "Stuff a copy of the message into the \" *Message-Log*\" buffer,
3651 if it satisfies the `log-message-filter-function'.
3652
3653 For use on `remove-message-hook'."
3654   (when (and (not noninteractive)
3655              (funcall log-message-filter-function label message))
3656     ;; Use save-excursion rather than save-current-buffer because we
3657     ;; change the value of point.
3658     (save-excursion
3659       (set-buffer (get-buffer-create " *Message-Log*"))
3660       (goto-char (point-max))
3661       ;(insert (concat (upcase (symbol-name label)) ": "  message "\n"))
3662       (let (extent)
3663         ;; Mark multiline message with an extent, which `view-lossage'
3664         ;; will recognize.
3665         (when (string-match "\n" message)
3666           (setq extent (make-extent (point) (point)))
3667           (set-extent-properties extent '(end-open nil message-multiline t)))
3668         (insert message "\n")
3669         (when extent
3670           (set-extent-property extent 'end-open t)))
3671       (when (> (point-max) (max log-message-max-size (point-min)))
3672         ;; Trim log to ~90% of max size.
3673         (goto-char (max (- (point-max)
3674                            (truncate (* 0.9 log-message-max-size)))
3675                         (point-min)))
3676         (forward-line 1)
3677         (delete-region (point-min) (point))))))
3678
3679 (defun message-displayed-p (&optional return-string frame)
3680   "Return a non-nil value if a message is presently displayed in the\n\
3681 minibuffer's echo area.  If optional argument RETURN-STRING is non-nil,\n\
3682 return a string containing the message, otherwise just return t."
3683   ;; by definition, a message is displayed if the echo area buffer is
3684   ;; non-empty (see also echo_area_active()).  It had better also
3685   ;; be the case that message-stack is nil exactly when the echo area
3686   ;; is non-empty.
3687   (let ((buffer (get-buffer " *Echo Area*")))
3688     (and (< (point-min buffer) (point-max buffer))
3689          (if return-string
3690              (buffer-substring nil nil buffer)
3691            t))))
3692
3693 ;;; Returns the string which remains in the echo area, or nil if none.
3694 ;;; If label is nil, the whole message stack is cleared.
3695 (defun clear-message (&optional label frame stdout-p no-restore)
3696   "Remove any message with the given LABEL from the message-stack,
3697 erasing it from the echo area if it's currently displayed there.
3698 If a message remains at the head of the message-stack and NO-RESTORE
3699 is nil, it will be displayed.  The string which remains in the echo
3700 area will be returned, or nil if the message-stack is now empty.
3701 If LABEL is nil, the entire message-stack is cleared.
3702
3703 Unless you need the return value or you need to specify a label,
3704 you should just use (message nil)."
3705   (or frame (setq frame (selected-frame)))
3706   (let ((clear-stream (and message-stack (eq 'stream (frame-type frame)))))
3707     (remove-message label frame)
3708     (let ((inhibit-read-only t)
3709           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
3710       (erase-buffer " *Echo Area*"))
3711     (if clear-stream
3712         (send-string-to-terminal ?\n stdout-p))
3713     (if no-restore
3714         nil                     ; just preparing to put another msg up
3715       (if message-stack
3716           (let ((oldmsg (cdr (car message-stack))))
3717             (raw-append-message oldmsg frame stdout-p)
3718             oldmsg)
3719         ;; #### Should we (redisplay-echo-area) here?  Messes some
3720         ;; things up.
3721         nil))))
3722
3723 (defun remove-message (&optional label frame)
3724   ;; If label is nil, we want to remove all matching messages.
3725   ;; Must reverse the stack first to log them in the right order.
3726   (let ((log nil))
3727     (while (and message-stack
3728                 (or (null label)        ; null label means clear whole stack
3729                     (eq label (car (car message-stack)))))
3730       (push (car message-stack) log)
3731       (setq message-stack (cdr message-stack)))
3732     (let ((s  message-stack))
3733       (while (cdr s)
3734         (let ((msg (car (cdr s))))
3735           (if (eq label (car msg))
3736               (progn
3737                 (push msg log)
3738                 (setcdr s (cdr (cdr s))))
3739             (setq s (cdr s))))))
3740     ;; (possibly) log each removed message
3741     (while log
3742       (condition-case e
3743           (run-hook-with-args 'remove-message-hook
3744                               (car (car log)) (cdr (car log)))
3745         (error (setq remove-message-hook nil)
3746                (lwarn 'message-log 'warning
3747                  "Error caught in `remove-message-hook': %s"
3748                  (error-message-string e))
3749                (let ((inhibit-read-only t))
3750                  (erase-buffer " *Echo Area*"))
3751                (signal (car e) (cdr e))))
3752       (setq log (cdr log)))))
3753
3754 (defun append-message (label message &optional frame stdout-p)
3755   (or frame (setq frame (selected-frame)))
3756   ;; Add a new entry to the message-stack, or modify an existing one
3757   (let ((top (car message-stack)))
3758     (if (eq label (car top))
3759         (setcdr top (concat (cdr top) message))
3760       (push (cons label message) message-stack)))
3761   (raw-append-message message frame stdout-p))
3762
3763 ;; Really append the message to the echo area.  no fiddling with
3764 ;; message-stack.
3765 (defun raw-append-message (message &optional frame stdout-p)
3766   (unless (equal message "")
3767     (let ((inhibit-read-only t)
3768           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
3769       (insert-string message " *Echo Area*")
3770       ;; Conditionalizing on the device type in this way is not that clean,
3771       ;; but neither is having a device method, as I originally implemented
3772       ;; it: all non-stream devices behave in the same way.  Perhaps
3773       ;; the cleanest way is to make the concept of a "redisplayable"
3774       ;; device, which stream devices are not.  Look into this more if
3775       ;; we ever create another non-redisplayable device type (e.g.
3776       ;; processes?  printers?).
3777
3778       ;; Don't redisplay the echo area if we are executing a macro.
3779       (if (not executing-kbd-macro)
3780           (if (eq 'stream (frame-type frame))
3781               (send-string-to-terminal message stdout-p (frame-device frame))
3782             (redisplay-echo-area))))))
3783
3784 (defun display-message (label message &optional frame stdout-p)
3785   "Print a one-line message at the bottom of the frame.  First argument
3786 LABEL is an identifier for this message.  MESSAGE is the string to display.
3787 Use `clear-message' to remove a labelled message.
3788
3789 Here are some standard labels (those marked with `*' are not logged
3790 by default--see the `log-message-ignore-labels' variable):
3791     message       default label used by the `message' function
3792     error         default label used for reporting errors
3793   * progress      progress indicators like \"Converting... 45%\"
3794   * prompt        prompt-like messages like \"I-search: foo\"
3795   * command       helper command messages like \"Mark set\"
3796   * no-log        messages that should never be logged"
3797   (clear-message label frame stdout-p t)
3798   (append-message label message frame stdout-p))
3799
3800 (defun current-message (&optional frame)
3801   "Return the current message in the echo area, or nil.
3802 The FRAME argument is currently unused."
3803   (cdr (car message-stack)))
3804
3805 ;;; may eventually be frame-dependent
3806 (defun current-message-label (&optional frame)
3807   (car (car message-stack)))
3808
3809 (defun message (fmt &rest args)
3810   "Print a one-line message at the bottom of the frame.
3811 The arguments are the same as to `format'.
3812
3813 If the only argument is nil, clear any existing message; let the
3814 minibuffer contents show."
3815   ;; questionable junk in the C code
3816   ;; (if (framep default-minibuffer-frame)
3817   ;;     (make-frame-visible default-minibuffer-frame))
3818   (if (and (null fmt) (null args))
3819       (prog1 nil
3820         (clear-message nil))
3821     (let ((str (apply 'format fmt args)))
3822       (display-message 'message str)
3823       str)))
3824
3825 (defun lmessage (label fmt &rest args)
3826   "Print a one-line message at the bottom of the frame.
3827 First argument LABEL is an identifier for this message.  The rest of the
3828 arguments are the same as to `format'.
3829
3830 See `display-message' for a list of standard labels."
3831   (if (and (null fmt) (null args))
3832       (prog1 nil
3833         (clear-message label nil))
3834     (let ((str (apply 'format fmt args)))
3835       (display-message label str)
3836       str)))
3837
3838
3839 ;;;;;;
3840 ;;;;;; warning stuff
3841 ;;;;;;
3842
3843 (defcustom log-warning-minimum-level 'info
3844   "Minimum level of warnings that should be logged.
3845 The warnings in levels below this are completely ignored, as if they never
3846 happened.
3847
3848 The recognized warning levels, in decreasing order of priority, are
3849 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
3850 'debug.
3851
3852 See also `display-warning-minimum-level'.
3853
3854 You can also control which warnings are displayed on a class-by-class
3855 basis.  See `display-warning-suppressed-classes' and
3856 `log-warning-suppressed-classes'."
3857   :type '(choice (const emergency) (const alert) (const critical)
3858                  (const error) (const warning) (const notice)
3859                  (const info) (const debug))
3860   :group 'warnings)
3861
3862 (defcustom display-warning-minimum-level 'info
3863   "Minimum level of warnings that should be displayed.
3864 The warnings in levels below this will be generated, but not
3865 displayed.
3866
3867 The recognized warning levels, in decreasing order of priority, are
3868 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
3869 'debug.
3870
3871 See also `log-warning-minimum-level'.
3872
3873 You can also control which warnings are displayed on a class-by-class
3874 basis.  See `display-warning-suppressed-classes' and
3875 `log-warning-suppressed-classes'."
3876   :type '(choice (const emergency) (const alert) (const critical)
3877                  (const error) (const warning) (const notice)
3878                  (const info) (const debug))
3879   :group 'warnings)
3880
3881 (defvar log-warning-suppressed-classes nil
3882   "List of classes of warnings that shouldn't be logged or displayed.
3883 If any of the CLASS symbols associated with a warning is the same as
3884 any of the symbols listed here, the warning will be completely ignored,
3885 as it they never happened.
3886
3887 NOTE: In most circumstances, you should *not* set this variable.
3888 Set `display-warning-suppressed-classes' instead.  That way the suppressed
3889 warnings are not displayed but are still unobtrusively logged.
3890
3891 See also `log-warning-minimum-level' and `display-warning-minimum-level'.")
3892
3893 (defcustom display-warning-suppressed-classes nil
3894   "List of classes of warnings that shouldn't be displayed.
3895 If any of the CLASS symbols associated with a warning is the same as
3896 any of the symbols listed here, the warning will not be displayed.
3897 The warning will still logged in the *Warnings* buffer (unless also
3898 contained in `log-warning-suppressed-classes'), but the buffer will
3899 not be automatically popped up.
3900
3901 See also `log-warning-minimum-level' and `display-warning-minimum-level'."
3902   :type '(repeat symbol)
3903   :group 'warnings)
3904
3905 (defvar warning-count 0
3906   "Count of the number of warning messages displayed so far.")
3907
3908 (defconst warning-level-alist '((emergency . 8)
3909                                 (alert . 7)
3910                                 (critical . 6)
3911                                 (error . 5)
3912                                 (warning . 4)
3913                                 (notice . 3)
3914                                 (info . 2)
3915                                 (debug . 1)))
3916
3917 (defun warning-level-p (level)
3918   "Non-nil if LEVEL specifies a warning level."
3919   (and (symbolp level) (assq level warning-level-alist)))
3920
3921 ;; If you're interested in rewriting this function, be aware that it
3922 ;; could be called at arbitrary points in a Lisp program (when a
3923 ;; built-in function wants to issue a warning, it will call out to
3924 ;; this function the next time some Lisp code is evaluated).  Therefore,
3925 ;; this function *must* not permanently modify any global variables
3926 ;; (e.g. the current buffer) except those that specifically apply
3927 ;; to the warning system.
3928
3929 (defvar before-init-deferred-warnings nil)
3930
3931 (defun after-init-display-warnings ()
3932   "Display warnings deferred till after the init file is run.
3933 Warnings that occur before then are deferred so that warning
3934 suppression in the .emacs file will be honored."
3935   (while before-init-deferred-warnings
3936     (apply 'display-warning (car before-init-deferred-warnings))
3937     (setq before-init-deferred-warnings
3938           (cdr before-init-deferred-warnings))))
3939
3940 (add-hook 'after-init-hook 'after-init-display-warnings)
3941
3942 (defun display-warning (class message &optional level)
3943   "Display a warning message.
3944 CLASS should be a symbol describing what sort of warning this is, such
3945 as `resource' or `key-mapping'.  A list of such symbols is also
3946 accepted. (Individual classes can be suppressed; see
3947 `display-warning-suppressed-classes'.)  Optional argument LEVEL can
3948 be used to specify a priority for the warning, other than default priority
3949 `warning'. (See `display-warning-minimum-level').  The message is
3950 inserted into the *Warnings* buffer, which is made visible at appropriate
3951 times."
3952   (or level (setq level 'warning))
3953   (or (listp class) (setq class (list class)))
3954   (check-argument-type 'warning-level-p level)
3955   (if (and (not (featurep 'infodock))
3956            (not init-file-loaded))
3957       (push (list class message level) before-init-deferred-warnings)
3958     (catch 'ignored
3959       (let ((display-p t)
3960             (level-num (cdr (assq level warning-level-alist))))
3961         (if (< level-num (cdr (assq log-warning-minimum-level
3962                                     warning-level-alist)))
3963             (throw 'ignored nil))
3964         (if (intersection class log-warning-suppressed-classes)
3965             (throw 'ignored nil))
3966
3967         (if (< level-num (cdr (assq display-warning-minimum-level
3968                                     warning-level-alist)))
3969             (setq display-p nil))
3970         (if (and display-p
3971                  (intersection class display-warning-suppressed-classes))
3972             (setq display-p nil))
3973         (let ((buffer (get-buffer-create "*Warnings*")))
3974           (when display-p
3975             ;; The C code looks at display-warning-tick to determine
3976             ;; when it should call `display-warning-buffer'.  Change it
3977             ;; to get the C code's attention.
3978             (incf display-warning-tick))
3979           (with-current-buffer buffer
3980             (goto-char (point-max))
3981             (incf warning-count)
3982             (princ (format "(%d) (%s/%s) "
3983                            warning-count
3984                            (mapconcat 'symbol-name class ",")
3985                            level)
3986                    buffer)
3987             (princ message buffer)
3988             (terpri buffer)
3989             (terpri buffer)))))))
3990
3991 (defun warn (&rest args)
3992   "Display a warning message.
3993 The message is constructed by passing all args to `format'.  The message
3994 is placed in the *Warnings* buffer, which will be popped up at the next
3995 redisplay.  The class of the warning is `warning'.  See also
3996 `display-warning'."
3997   (display-warning 'warning (apply 'format args)))
3998
3999 (defun lwarn (class level &rest args)
4000   "Display a labeled warning message.
4001 CLASS should be a symbol describing what sort of warning this is, such
4002 as `resource' or `key-mapping'.  A list of such symbols is also
4003 accepted. (Individual classes can be suppressed; see
4004 `display-warning-suppressed-classes'.)  If non-nil, LEVEL can be used
4005 to specify a priority for the warning, other than default priority
4006 `warning'. (See `display-warning-minimum-level').  The message is
4007 inserted into the *Warnings* buffer, which is made visible at appropriate
4008 times.
4009
4010 The rest of the arguments are passed to `format'."
4011   (display-warning class (apply 'format args)
4012                    (or level 'warning)))
4013
4014 (defvar warning-marker nil)
4015
4016 ;; When this function is called by the C code, all non-local exits are
4017 ;; trapped and C-g is inhibited; therefore, it would be a very, very
4018 ;; bad idea for this function to get into an infinite loop.
4019
4020 (defun display-warning-buffer ()
4021   "Make the buffer that contains the warnings be visible.
4022 The C code calls this periodically, right before redisplay."
4023   (let ((buffer (get-buffer-create "*Warnings*")))
4024     (when (or (not warning-marker)
4025               (not (eq (marker-buffer warning-marker) buffer)))
4026       (setq warning-marker (make-marker))
4027       (set-marker warning-marker 1 buffer))
4028     (if temp-buffer-show-function
4029         (let ((show-buffer (get-buffer-create "*Warnings-Show*")))
4030           (save-excursion
4031             (set-buffer show-buffer)
4032             (setq buffer-read-only nil)
4033             (erase-buffer))
4034           (save-excursion
4035             (set-buffer buffer)
4036             (copy-to-buffer show-buffer
4037                             (marker-position warning-marker)
4038                             (point-max)))
4039           (funcall temp-buffer-show-function show-buffer))
4040       (set-window-start (display-buffer buffer) warning-marker))
4041     (set-marker warning-marker (point-max buffer) buffer)))
4042
4043 (defun emacs-name ()
4044   "Return the printable name of this instance of Emacs."
4045   (cond ((featurep 'infodock) "InfoDock")
4046         ((featurep 'xemacs) "XEmacs")
4047         (t "Emacs")))
4048
4049 ;;; simple.el ends here