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