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