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