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