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