9ece9ae414a4006fe43e5c4600d61b864cf61345
[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-one ()
2005   "Scroll text of current window upward one line.
2006 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2007 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2008 signaled.
2009
2010 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2011 boundaries do not cause an error to be signaled."
2012   (interactive "_")
2013   (scroll-up-command 1))
2014
2015 (defun scroll-up-command (&optional n)
2016   "Scroll text of current window upward ARG lines; or near full screen if no ARG.
2017 A near full screen is `next-screen-context-lines' less than a full screen.
2018 Negative ARG means scroll downward.
2019 When calling from a program, supply a number as argument or nil.
2020 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2021 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2022 signaled.
2023
2024 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2025 boundaries do not cause an error to be signaled."
2026   (interactive "_P")
2027   (if signal-error-on-buffer-boundary
2028       (scroll-up n)
2029     (condition-case nil
2030         (scroll-up n)
2031       (beginning-of-buffer nil)
2032       (end-of-buffer nil))))
2033
2034 (defun scroll-down-one ()
2035   "Scroll text of current window downward one line.
2036 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2037 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2038 signaled.
2039
2040 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2041 boundaries do not cause an error to be signaled."
2042   (interactive "_")
2043   (scroll-down-command 1))
2044
2045 (defun scroll-down-command (&optional n)
2046   "Scroll text of current window downward ARG lines; or near full screen if no ARG.
2047 A near full screen is `next-screen-context-lines' less than a full screen.
2048 Negative ARG means scroll upward.
2049 When calling from a program, supply a number as argument or nil.
2050 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2051 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2052 signaled.
2053
2054 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2055 boundaries do not cause an error to be signaled."
2056   (interactive "_P")
2057   (if signal-error-on-buffer-boundary
2058       (scroll-down n)
2059     (condition-case nil
2060         (scroll-down n)
2061       (beginning-of-buffer nil)
2062       (end-of-buffer nil))))
2063
2064 (defun next-line (arg)
2065   "Move cursor vertically down ARG lines.
2066 If there is no character in the target line exactly under the current column,
2067 the cursor is positioned after the character in that line which spans this
2068 column, or at the end of the line if it is not long enough.
2069
2070 If there is no line in the buffer after this one, behavior depends on the
2071 value of `next-line-add-newlines'.  If non-nil, it inserts a newline character
2072 to create a line, and moves the cursor to that line.  Otherwise it moves the
2073 cursor to the end of the buffer.
2074
2075 The command \\[set-goal-column] can be used to create
2076 a semipermanent goal column to which this command always moves.
2077 Then it does not try to move vertically.  This goal column is stored
2078 in `goal-column', which is nil when there is none.
2079
2080 If you are thinking of using this in a Lisp program, consider
2081 using `forward-line' instead.  It is usually easier to use
2082 and more reliable (no dependence on goal column, etc.)."
2083   (interactive "_p")
2084   (if (and next-line-add-newlines (= arg 1))
2085       (let ((opoint (point)))
2086         (end-of-line)
2087         (if (eobp)
2088             (newline 1)
2089           (goto-char opoint)
2090           (line-move arg)))
2091     (if (interactive-p)
2092         ;; XEmacs:  Not sure what to do about this.  It's inconsistent. -sb
2093         (condition-case nil
2094             (line-move arg)
2095           ((beginning-of-buffer end-of-buffer)
2096            (when signal-error-on-buffer-boundary
2097              (ding nil 'buffer-bound))))
2098       (line-move arg)))
2099   nil)
2100
2101 (defun previous-line (arg)
2102   "Move cursor vertically up ARG lines.
2103 If there is no character in the target line exactly over the current column,
2104 the cursor is positioned after the character in that line which spans this
2105 column, or at the end of the line if it is not long enough.
2106
2107 The command \\[set-goal-column] can be used to create
2108 a semipermanent goal column to which this command always moves.
2109 Then it does not try to move vertically.
2110
2111 If you are thinking of using this in a Lisp program, consider using
2112 `forward-line' with a negative argument instead.  It is usually easier
2113 to use and more reliable (no dependence on goal column, etc.)."
2114   (interactive "_p")
2115   (if (interactive-p)
2116       (condition-case nil
2117           (line-move (- arg))
2118         ((beginning-of-buffer end-of-buffer)
2119          (when signal-error-on-buffer-boundary ; XEmacs
2120            (ding nil 'buffer-bound))))
2121     (line-move (- arg)))
2122   nil)
2123
2124 (defcustom block-movement-size 6
2125   "*Number of lines that \"block movement\" commands (\\[forward-block-of-lines], \\[backward-block-of-lines]) move by."
2126   :type 'integer
2127   :group 'editing-basics)
2128
2129 (defun backward-block-of-lines ()
2130   "Move backward by one \"block\" of lines.
2131 The number of lines that make up a block is controlled by
2132 `block-movement-size', which defaults to 6."
2133   (interactive "_")
2134   (forward-line (- block-movement-size)))
2135
2136 (defun forward-block-of-lines ()
2137   "Move forward by one \"block\" of lines.
2138 The number of lines that make up a block is controlled by
2139 `block-movement-size', which defaults to 6."
2140   (interactive "_")
2141   (forward-line block-movement-size))
2142
2143 (defcustom track-eol nil
2144   "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2145 This means moving to the end of each line moved onto.
2146 The beginning of a blank line does not count as the end of a line."
2147   :type 'boolean
2148   :group 'editing-basics)
2149
2150 (defcustom goal-column nil
2151   "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2152   :type '(choice integer (const :tag "None" nil))
2153   :group 'editing-basics)
2154 (make-variable-buffer-local 'goal-column)
2155
2156 (defvar temporary-goal-column 0
2157   "Current goal column for vertical motion.
2158 It is the column where point was
2159 at the start of current run of vertical motion commands.
2160 When the `track-eol' feature is doing its job, the value is 9999.")
2161 (make-variable-buffer-local 'temporary-goal-column)
2162
2163 ;XEmacs: not yet ported, so avoid compiler warnings
2164 (eval-when-compile
2165   (defvar inhibit-point-motion-hooks))
2166
2167 (defcustom line-move-ignore-invisible nil
2168   "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
2169 Use with care, as it slows down movement significantly.  Outline mode sets this."
2170   :type 'boolean
2171   :group 'editing-basics)
2172
2173 ;; This is the guts of next-line and previous-line.
2174 ;; Arg says how many lines to move.
2175 (defun line-move (arg)
2176   ;; Don't run any point-motion hooks, and disregard intangibility,
2177   ;; for intermediate positions.
2178   (let ((inhibit-point-motion-hooks t)
2179         (opoint (point))
2180         new)
2181     (unwind-protect
2182         (progn
2183           (if (not (or (eq last-command 'next-line)
2184                        (eq last-command 'previous-line)))
2185               (setq temporary-goal-column
2186                     (if (and track-eol (eolp)
2187                              ;; Don't count beg of empty line as end of line
2188                              ;; unless we just did explicit end-of-line.
2189                              (or (not (bolp)) (eq last-command 'end-of-line)))
2190                         9999
2191                       (current-column))))
2192           (if (and (not (integerp selective-display))
2193                    (not line-move-ignore-invisible))
2194               ;; Use just newline characters.
2195               (or (if (> arg 0)
2196                       (progn (if (> arg 1) (forward-line (1- arg)))
2197                              ;; This way of moving forward ARG lines
2198                              ;; verifies that we have a newline after the last one.
2199                              ;; It doesn't get confused by intangible text.
2200                              (end-of-line)
2201                              (zerop (forward-line 1)))
2202                     (and (zerop (forward-line arg))
2203                          (bolp)))
2204                   (signal (if (< arg 0)
2205                               'beginning-of-buffer
2206                             'end-of-buffer)
2207                           nil))
2208             ;; Move by arg lines, but ignore invisible ones.
2209             (while (> arg 0)
2210               (end-of-line)
2211               (and (zerop (vertical-motion 1))
2212                    (signal 'end-of-buffer nil))
2213               ;; If the following character is currently invisible,
2214               ;; skip all characters with that same `invisible' property value.
2215               (while (and (not (eobp))
2216                           (let ((prop
2217                                  (get-char-property (point) 'invisible)))
2218                             (if (eq buffer-invisibility-spec t)
2219                                 prop
2220                               (or (memq prop buffer-invisibility-spec)
2221                                   (assq prop buffer-invisibility-spec)))))
2222                 (if (get-text-property (point) 'invisible)
2223                     (goto-char (next-single-property-change (point) 'invisible))
2224                   (goto-char (next-extent-change (point))))) ; XEmacs
2225               (setq arg (1- arg)))
2226             (while (< arg 0)
2227               (beginning-of-line)
2228               (and (zerop (vertical-motion -1))
2229                    (signal 'beginning-of-buffer nil))
2230               (while (and (not (bobp))
2231                           (let ((prop
2232                                  (get-char-property (1- (point)) 'invisible)))
2233                             (if (eq buffer-invisibility-spec t)
2234                                 prop
2235                               (or (memq prop buffer-invisibility-spec)
2236                                   (assq prop buffer-invisibility-spec)))))
2237                 (if (get-text-property (1- (point)) 'invisible)
2238                     (goto-char (previous-single-property-change (point) 'invisible))
2239                   (goto-char (previous-extent-change (point))))) ; XEmacs
2240               (setq arg (1+ arg))))
2241           (move-to-column (or goal-column temporary-goal-column)))
2242       ;; Remember where we moved to, go back home,
2243       ;; then do the motion over again
2244       ;; in just one step, with intangibility and point-motion hooks
2245       ;; enabled this time.
2246       (setq new (point))
2247       (goto-char opoint)
2248       (setq inhibit-point-motion-hooks nil)
2249       (goto-char new)))
2250   nil)
2251
2252 ;;; Many people have said they rarely use this feature, and often type
2253 ;;; it by accident.  Maybe it shouldn't even be on a key.
2254 ;; It's not on a key, as of 20.2.  So no need for this.
2255 ;(put 'set-goal-column 'disabled t)
2256
2257 (defun set-goal-column (arg)
2258   "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2259 Those commands will move to this position in the line moved to
2260 rather than trying to keep the same horizontal position.
2261 With a non-nil argument, clears out the goal column
2262 so that \\[next-line] and \\[previous-line] resume vertical motion.
2263 The goal column is stored in the variable `goal-column'."
2264   (interactive "_P") ; XEmacs
2265   (if arg
2266       (progn
2267         (setq goal-column nil)
2268         (display-message 'command "No goal column"))
2269     (setq goal-column (current-column))
2270     (lmessage 'command
2271         "Goal column %d (use %s with an arg to unset it)"
2272       goal-column
2273       (substitute-command-keys "\\[set-goal-column]")))
2274   nil)
2275 \f
2276 ;; deleted FSFmacs terminal randomness hscroll-point-visible stuff.
2277 ;; hscroll-step
2278 ;; hscroll-point-visible
2279 ;; hscroll-window-column
2280 ;; right-arrow
2281 ;; left-arrow
2282
2283 (defun scroll-other-window-down (lines)
2284   "Scroll the \"other window\" down.
2285 For more details, see the documentation for `scroll-other-window'."
2286   (interactive "P")
2287   (scroll-other-window
2288    ;; Just invert the argument's meaning.
2289    ;; We can do that without knowing which window it will be.
2290    (if (eq lines '-) nil
2291      (if (null lines) '-
2292        (- (prefix-numeric-value lines))))))
2293 ;(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
2294
2295 (defun beginning-of-buffer-other-window (arg)
2296   "Move point to the beginning of the buffer in the other window.
2297 Leave mark at previous position.
2298 With arg N, put point N/10 of the way from the true beginning."
2299   (interactive "P")
2300   (let ((orig-window (selected-window))
2301         (window (other-window-for-scrolling)))
2302     ;; We use unwind-protect rather than save-window-excursion
2303     ;; because the latter would preserve the things we want to change.
2304     (unwind-protect
2305         (progn
2306           (select-window window)
2307           ;; Set point and mark in that window's buffer.
2308           (beginning-of-buffer arg)
2309           ;; Set point accordingly.
2310           (recenter '(t)))
2311       (select-window orig-window))))
2312
2313 (defun end-of-buffer-other-window (arg)
2314   "Move point to the end of the buffer in the other window.
2315 Leave mark at previous position.
2316 With arg N, put point N/10 of the way from the true end."
2317   (interactive "P")
2318   ;; See beginning-of-buffer-other-window for comments.
2319   (let ((orig-window (selected-window))
2320         (window (other-window-for-scrolling)))
2321     (unwind-protect
2322         (progn
2323           (select-window window)
2324           (end-of-buffer arg)
2325           (recenter '(t)))
2326       (select-window orig-window))))
2327 \f
2328 (defun transpose-chars (arg)
2329   "Interchange characters around point, moving forward one character.
2330 With prefix arg ARG, effect is to take character before point
2331 and drag it forward past ARG other characters (backward if ARG negative).
2332 If no argument and at end of line, the previous two chars are exchanged."
2333   (interactive "*P")
2334   (and (null arg) (eolp) (forward-char -1))
2335   (transpose-subr 'forward-char (prefix-numeric-value arg)))
2336
2337 ;;; A very old implementation of transpose-chars from the old days ...
2338 (defun transpose-preceding-chars (arg)
2339   "Interchange characters before point.
2340 With prefix arg ARG, effect is to take character before point
2341 and drag it forward past ARG other characters (backward if ARG negative).
2342 If no argument and not at start of line, the previous two chars are exchanged."
2343   (interactive "*P")
2344   (and (null arg) (not (bolp)) (forward-char -1))
2345   (transpose-subr 'forward-char (prefix-numeric-value arg)))
2346
2347
2348 (defun transpose-words (arg)
2349   "Interchange words around point, leaving point at end of them.
2350 With prefix arg ARG, effect is to take word before or around point
2351 and drag it forward past ARG other words (backward if ARG negative).
2352 If ARG is zero, the words around or after point and around or after mark
2353 are interchanged."
2354   (interactive "*p")
2355   (transpose-subr 'forward-word arg))
2356
2357 (defun transpose-sexps (arg)
2358   "Like \\[transpose-words] but applies to sexps.
2359 Does not work on a sexp that point is in the middle of
2360 if it is a list or string."
2361   (interactive "*p")
2362   (transpose-subr 'forward-sexp arg))
2363
2364 (defun transpose-lines (arg)
2365   "Exchange current line and previous line, leaving point after both.
2366 With argument ARG, takes previous line and moves it past ARG lines.
2367 With argument 0, interchanges line point is in with line mark is in."
2368   (interactive "*p")
2369   (transpose-subr #'(lambda (arg)
2370                      (if (= arg 1)
2371                          (progn
2372                            ;; Move forward over a line,
2373                            ;; but create a newline if none exists yet.
2374                            (end-of-line)
2375                            (if (eobp)
2376                                (newline)
2377                              (forward-char 1)))
2378                        (forward-line arg)))
2379                   arg))
2380
2381 (eval-when-compile
2382   ;; avoid byte-compiler warnings...
2383   (defvar start1)
2384   (defvar start2)
2385   (defvar end1)
2386   (defvar end2))
2387
2388 ; start[12] and end[12] used in transpose-subr-1 below
2389 (defun transpose-subr (mover arg)
2390   (let (start1 end1 start2 end2)
2391     (if (= arg 0)
2392         (progn
2393           (save-excursion
2394             (funcall mover 1)
2395             (setq end2 (point))
2396             (funcall mover -1)
2397             (setq start2 (point))
2398             (goto-char (mark t)) ; XEmacs
2399             (funcall mover 1)
2400             (setq end1 (point))
2401             (funcall mover -1)
2402             (setq start1 (point))
2403             (transpose-subr-1))
2404           (exchange-point-and-mark t))) ; XEmacs
2405     (while (> arg 0)
2406       (funcall mover -1)
2407       (setq start1 (point))
2408       (funcall mover 1)
2409       (setq end1 (point))
2410       (funcall mover 1)
2411       (setq end2 (point))
2412       (funcall mover -1)
2413       (setq start2 (point))
2414       (transpose-subr-1)
2415       (goto-char end2)
2416       (setq arg (1- arg)))
2417     (while (< arg 0)
2418       (funcall mover -1)
2419       (setq start2 (point))
2420       (funcall mover -1)
2421       (setq start1 (point))
2422       (funcall mover 1)
2423       (setq end1 (point))
2424       (funcall mover 1)
2425       (setq end2 (point))
2426       (transpose-subr-1)
2427       (setq arg (1+ arg)))))
2428
2429 ; start[12] and end[12] used free
2430 (defun transpose-subr-1 ()
2431   (if (> (min end1 end2) (max start1 start2))
2432       (error "Don't have two things to transpose"))
2433   (let ((word1 (buffer-substring start1 end1))
2434         (word2 (buffer-substring start2 end2)))
2435     (delete-region start2 end2)
2436     (goto-char start2)
2437     (insert word1)
2438     (goto-char (if (< start1 start2) start1
2439                  (+ start1 (- (length word1) (length word2)))))
2440     (delete-char (length word1))
2441     (insert word2)))
2442 \f
2443 (defcustom comment-column 32
2444   "*Column to indent right-margin comments to.
2445 Setting this variable automatically makes it local to the current buffer.
2446 Each mode establishes a different default value for this variable; you
2447 can set the value for a particular mode using that mode's hook."
2448   :type 'integer
2449   :group 'fill-comments)
2450 (make-variable-buffer-local 'comment-column)
2451
2452 (defcustom comment-start nil
2453   "*String to insert to start a new comment, or nil if no comment syntax."
2454   :type '(choice (const :tag "None" nil)
2455                  string)
2456   :group 'fill-comments)
2457
2458 (defcustom comment-start-skip nil
2459   "*Regexp to match the start of a comment plus everything up to its body.
2460 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
2461 at the place matched by the close of the first pair."
2462   :type '(choice (const :tag "None" nil)
2463                  regexp)
2464   :group 'fill-comments)
2465
2466 (defcustom comment-end ""
2467   "*String to insert to end a new comment.
2468 Should be an empty string if comments are terminated by end-of-line."
2469   :type 'string
2470   :group 'fill-comments)
2471
2472 (defconst comment-indent-hook nil
2473   "Obsolete variable for function to compute desired indentation for a comment.
2474 Use `comment-indent-function' instead.
2475 This function is called with no args with point at the beginning of
2476 the comment's starting delimiter.")
2477
2478 (defconst comment-indent-function
2479   ;; XEmacs - add at least one space after the end of the text on the
2480   ;; current line...
2481   (lambda ()
2482     (save-excursion
2483       (beginning-of-line)
2484       (let ((eol (save-excursion (end-of-line) (point))))
2485         (and comment-start-skip
2486              (re-search-forward comment-start-skip eol t)
2487              (setq eol (match-beginning 0)))
2488         (goto-char eol)
2489         (skip-chars-backward " \t")
2490         (max comment-column (1+ (current-column))))))
2491   "Function to compute desired indentation for a comment.
2492 This function is called with no args with point at the beginning of
2493 the comment's starting delimiter.")
2494
2495 (defcustom block-comment-start nil
2496   "*String to insert to start a new comment on a line by itself.
2497 If nil, use `comment-start' instead.
2498 Note that the regular expression `comment-start-skip' should skip this string
2499 as well as the `comment-start' string."
2500   :type '(choice (const :tag "Use `comment-start'" nil)
2501                  string)
2502   :group 'fill-comments)
2503
2504 (defcustom block-comment-end nil
2505   "*String to insert to end a new comment on a line by itself.
2506 Should be an empty string if comments are terminated by end-of-line.
2507 If nil, use `comment-end' instead."
2508   :type '(choice (const :tag "Use `comment-end'" nil)
2509                  string)
2510   :group 'fill-comments)
2511
2512 (defun indent-for-comment ()
2513   "Indent this line's comment to comment column, or insert an empty comment."
2514   (interactive "*")
2515   (let* ((empty (save-excursion (beginning-of-line)
2516                                 (looking-at "[ \t]*$")))
2517          (starter (or (and empty block-comment-start) comment-start))
2518          (ender (or (and empty block-comment-end) comment-end)))
2519     (if (null starter)
2520         (error "No comment syntax defined")
2521       (let* ((eolpos (save-excursion (end-of-line) (point)))
2522              cpos indent begpos)
2523         (beginning-of-line)
2524         (if (re-search-forward comment-start-skip eolpos 'move)
2525             (progn (setq cpos (point-marker))
2526                    ;; Find the start of the comment delimiter.
2527                    ;; If there were paren-pairs in comment-start-skip,
2528                    ;; position at the end of the first pair.
2529                    (if (match-end 1)
2530                        (goto-char (match-end 1))
2531                      ;; If comment-start-skip matched a string with
2532                      ;; internal whitespace (not final whitespace) then
2533                      ;; the delimiter start at the end of that
2534                      ;; whitespace.  Otherwise, it starts at the
2535                      ;; beginning of what was matched.
2536                      (skip-syntax-backward " " (match-beginning 0))
2537                      (skip-syntax-backward "^ " (match-beginning 0)))))
2538         (setq begpos (point))
2539         ;; Compute desired indent.
2540         (if (= (current-column)
2541                (setq indent (funcall comment-indent-function)))
2542             (goto-char begpos)
2543           ;; If that's different from current, change it.
2544           (skip-chars-backward " \t")
2545           (delete-region (point) begpos)
2546           (indent-to indent))
2547         ;; An existing comment?
2548         (if cpos
2549             (progn (goto-char cpos)
2550                    (set-marker cpos nil))
2551           ;; No, insert one.
2552           (insert starter)
2553           (save-excursion
2554             (insert ender)))))))
2555
2556 (defun set-comment-column (arg)
2557   "Set the comment column based on point.
2558 With no arg, set the comment column to the current column.
2559 With just minus as arg, kill any comment on this line.
2560 With any other arg, set comment column to indentation of the previous comment
2561  and then align or create a comment on this line at that column."
2562   (interactive "P")
2563   (if (eq arg '-)
2564       (kill-comment nil)
2565     (if arg
2566         (progn
2567           (save-excursion
2568             (beginning-of-line)
2569             (re-search-backward comment-start-skip)
2570             (beginning-of-line)
2571             (re-search-forward comment-start-skip)
2572             (goto-char (match-beginning 0))
2573             (setq comment-column (current-column))
2574             (lmessage 'command "Comment column set to %d" comment-column))
2575           (indent-for-comment))
2576       (setq comment-column (current-column))
2577       (lmessage 'command "Comment column set to %d" comment-column))))
2578
2579 (defun kill-comment (arg)
2580   "Kill the comment on this line, if any.
2581 With argument, kill comments on that many lines starting with this one."
2582   ;; this function loses in a lot of situations.  it incorrectly recognizes
2583   ;; comment delimiters sometimes (ergo, inside a string), doesn't work
2584   ;; with multi-line comments, can kill extra whitespace if comment wasn't
2585   ;; through end-of-line, et cetera.
2586   (interactive "*P")
2587   (or comment-start-skip (error "No comment syntax defined"))
2588   (let ((count (prefix-numeric-value arg)) endc)
2589     (while (> count 0)
2590       (save-excursion
2591         (end-of-line)
2592         (setq endc (point))
2593         (beginning-of-line)
2594         (and (string< "" comment-end)
2595              (setq endc
2596                    (progn
2597                      (re-search-forward (regexp-quote comment-end) endc 'move)
2598                      (skip-chars-forward " \t")
2599                      (point))))
2600         (beginning-of-line)
2601         (if (re-search-forward comment-start-skip endc t)
2602             (progn
2603               (goto-char (match-beginning 0))
2604               (skip-chars-backward " \t")
2605               (kill-region (point) endc)
2606               ;; to catch comments a line beginnings
2607               (indent-according-to-mode))))
2608       (if arg (forward-line 1))
2609       (setq count (1- count)))))
2610
2611 (defun comment-region (beg end &optional arg)
2612   "Comment or uncomment each line in the region.
2613 With just C-u prefix arg, uncomment each line in region.
2614 Numeric prefix arg ARG means use ARG comment characters.
2615 If ARG is negative, delete that many comment characters instead.
2616 Comments are terminated on each line, even for syntax in which newline does
2617 not end the comment.  Blank lines do not get comments."
2618   ;; if someone wants it to only put a comment-start at the beginning and
2619   ;; comment-end at the end then typing it, C-x C-x, closing it, C-x C-x
2620   ;; is easy enough.  No option is made here for other than commenting
2621   ;; every line.
2622   (interactive "r\nP")
2623   (or comment-start (error "No comment syntax is defined"))
2624   (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
2625   (save-excursion
2626     (save-restriction
2627       (let ((cs comment-start) (ce comment-end)
2628             numarg)
2629         (if (consp arg) (setq numarg t)
2630           (setq numarg (prefix-numeric-value arg))
2631           ;; For positive arg > 1, replicate the comment delims now,
2632           ;; then insert the replicated strings just once.
2633           (while (> numarg 1)
2634             (setq cs (concat cs comment-start)
2635                   ce (concat ce comment-end))
2636             (setq numarg (1- numarg))))
2637         ;; Loop over all lines from BEG to END.
2638         (narrow-to-region beg end)
2639         (goto-char beg)
2640         (while (not (eobp))
2641           (if (or (eq numarg t) (< numarg 0))
2642               (progn
2643                 ;; Delete comment start from beginning of line.
2644                 (if (eq numarg t)
2645                     (while (looking-at (regexp-quote cs))
2646                       (delete-char (length cs)))
2647                   (let ((count numarg))
2648                     (while (and (> 1 (setq count (1+ count)))
2649                                 (looking-at (regexp-quote cs)))
2650                       (delete-char (length cs)))))
2651                 ;; Delete comment end from end of line.
2652                 (if (string= "" ce)
2653                     nil
2654                   (if (eq numarg t)
2655                       (progn
2656                         (end-of-line)
2657                         ;; This is questionable if comment-end ends in
2658                         ;; whitespace.  That is pretty brain-damaged,
2659                         ;; though.
2660                         (skip-chars-backward " \t")
2661                         (if (and (>= (- (point) (point-min)) (length ce))
2662                                  (save-excursion
2663                                    (backward-char (length ce))
2664                                    (looking-at (regexp-quote ce))))
2665                             (delete-char (- (length ce)))))
2666                     (let ((count numarg))
2667                       (while (> 1 (setq count (1+ count)))
2668                         (end-of-line)
2669                         ;; This is questionable if comment-end ends in
2670                         ;; whitespace.  That is pretty brain-damaged though
2671                         (skip-chars-backward " \t")
2672                         (save-excursion
2673                           (backward-char (length ce))
2674                           (if (looking-at (regexp-quote ce))
2675                               (delete-char (length ce))))))))
2676                 (forward-line 1))
2677             ;; Insert at beginning and at end.
2678             (if (looking-at "[ \t]*$") ()
2679               (insert cs)
2680               (if (string= "" ce) ()
2681                 (end-of-line)
2682                 (insert ce)))
2683             (search-forward "\n" nil 'move)))))))
2684
2685 ;; XEmacs
2686 (defun prefix-region (prefix)
2687   "Add a prefix string to each line between mark and point."
2688   (interactive "sPrefix string: ")
2689   (if prefix
2690       (let ((count (count-lines (mark) (point))))
2691         (goto-char (min (mark) (point)))
2692         (while (> count 0)
2693           (setq count (1- count))
2694           (beginning-of-line 1)
2695           (insert prefix)
2696           (end-of-line 1)
2697           (forward-char 1)))))
2698
2699 \f
2700 ;; XEmacs - extra parameter
2701 (defun backward-word (arg &optional buffer)
2702   "Move backward until encountering the end of a word.
2703 With argument, do this that many times.
2704 In programs, it is faster to call `forward-word' with negative arg."
2705   (interactive "_p") ; XEmacs
2706   (forward-word (- arg) buffer))
2707
2708 (defun mark-word (arg)
2709   "Set mark arg words away from point."
2710   (interactive "p")
2711   (mark-something 'mark-word 'forward-word arg))
2712
2713 ;; XEmacs modified
2714 (defun kill-word (arg)
2715   "Kill characters forward until encountering the end of a word.
2716 With argument, do this that many times."
2717   (interactive "*p")
2718   (kill-region (point) (save-excursion (forward-word arg) (point))))
2719
2720 (defun backward-kill-word (arg)
2721   "Kill characters backward until encountering the end of a word.
2722 With argument, do this that many times."
2723   (interactive "*p") ; XEmacs
2724   (kill-word (- arg)))
2725
2726 (defun current-word (&optional strict)
2727   "Return the word point is on (or a nearby word) as a string.
2728 If optional arg STRICT is non-nil, return nil unless point is within
2729 or adjacent to a word.
2730 If point is not between two word-constituent characters, but immediately
2731 follows one, move back first.
2732 Otherwise, if point precedes a word constituent, move forward first.
2733 Otherwise, move backwards until a word constituent is found and get that word;
2734 if you a newlines is reached first, move forward instead."
2735   (save-excursion
2736     (let ((oldpoint (point)) (start (point)) (end (point)))
2737       (skip-syntax-backward "w_") (setq start (point))
2738       (goto-char oldpoint)
2739       (skip-syntax-forward "w_") (setq end (point))
2740       (if (and (eq start oldpoint) (eq end oldpoint))
2741           ;; Point is neither within nor adjacent to a word.
2742           (and (not strict)
2743                (progn
2744                  ;; Look for preceding word in same line.
2745                  (skip-syntax-backward "^w_"
2746                                        (save-excursion
2747                                          (beginning-of-line) (point)))
2748                  (if (bolp)
2749                      ;; No preceding word in same line.
2750                      ;; Look for following word in same line.
2751                      (progn
2752                        (skip-syntax-forward "^w_"
2753                                             (save-excursion
2754                                               (end-of-line) (point)))
2755                        (setq start (point))
2756                        (skip-syntax-forward "w_")
2757                        (setq end (point)))
2758                      (setq end (point))
2759                      (skip-syntax-backward "w_")
2760                      (setq start (point)))
2761                  (buffer-substring start end)))
2762           (buffer-substring start end)))))
2763 \f
2764 (defcustom fill-prefix nil
2765   "*String for filling to insert at front of new line, or nil for none.
2766 Setting this variable automatically makes it local to the current buffer."
2767   :type '(choice (const :tag "None" nil)
2768                  string)
2769   :group 'fill)
2770 (make-variable-buffer-local 'fill-prefix)
2771
2772 (defcustom auto-fill-inhibit-regexp nil
2773   "*Regexp to match lines which should not be auto-filled."
2774   :type '(choice (const :tag "None" nil)
2775                  regexp)
2776   :group 'fill)
2777
2778 (defvar comment-line-break-function 'indent-new-comment-line
2779   "*Mode-specific function which line breaks and continues a comment.
2780
2781 This function is only called during auto-filling of a comment section.
2782 The function should take a single optional argument which is a flag
2783 indicating whether soft newlines should be inserted.")
2784
2785 ;; defined in mule-base/mule-category.el
2786 (defvar word-across-newline)
2787
2788 ;; This function is the auto-fill-function of a buffer
2789 ;; when Auto-Fill mode is enabled.
2790 ;; It returns t if it really did any work.
2791 ;; XEmacs:  This function is totally different.
2792 (defun do-auto-fill ()
2793   (let (give-up)
2794     (or (and auto-fill-inhibit-regexp
2795              (save-excursion (beginning-of-line)
2796                              (looking-at auto-fill-inhibit-regexp)))
2797         (while (and (not give-up) (> (current-column) fill-column))
2798           ;; Determine where to split the line.
2799           (let ((fill-prefix fill-prefix)
2800                 (fill-point
2801                  (let ((opoint (point))
2802                        bounce
2803                        ;; 97/3/14 jhod: Kinsoku
2804                        (re-break-point (if (featurep 'mule)
2805                                             (concat "[ \t\n]\\|" word-across-newline
2806                                                     ".\\|." word-across-newline)
2807                                         "[ \t\n]"))
2808                        ;; end patch
2809                        (first t))
2810                    (save-excursion
2811                      (move-to-column (1+ fill-column))
2812                      ;; Move back to a word boundary.
2813                      (while (or first
2814                                 ;; If this is after period and a single space,
2815                                 ;; move back once more--we don't want to break
2816                                 ;; the line there and make it look like a
2817                                 ;; sentence end.
2818                                 (and (not (bobp))
2819                                      (not bounce)
2820                                      sentence-end-double-space
2821                                      (save-excursion (forward-char -1)
2822                                                      (and (looking-at "\\. ")
2823                                                           (not (looking-at "\\.  "))))))
2824                        (setq first nil)
2825                        ;; 97/3/14 jhod: Kinsoku
2826                        ; (skip-chars-backward "^ \t\n"))
2827                        (fill-move-backward-to-break-point re-break-point)
2828                        ;; end patch
2829                        ;; If we find nowhere on the line to break it,
2830                        ;; break after one word.  Set bounce to t
2831                        ;; so we will not keep going in this while loop.
2832                        (if (bolp)
2833                            (progn
2834                              ;; 97/3/14 jhod: Kinsoku
2835                              ; (re-search-forward "[ \t]" opoint t)
2836                              (fill-move-forward-to-break-point re-break-point
2837                                                                opoint)
2838                              ;; end patch
2839                              (setq bounce t)))
2840                        (skip-chars-backward " \t"))
2841                      (if (and (featurep 'mule)
2842                               (or bounce (bolp))) (kinsoku-process)) ;; 97/3/14 jhod: Kinsoku
2843                      ;; Let fill-point be set to the place where we end up.
2844                      (point)))))
2845
2846             ;; I'm not sure why Stig made this change but it breaks
2847             ;; auto filling in at least C mode so I'm taking it back
2848             ;; out.  --cet
2849             ;; XEmacs - adaptive fill.
2850             ;;(maybe-adapt-fill-prefix
2851             ;; (or from (setq from (save-excursion (beginning-of-line)
2852             ;;                                   (point))))
2853             ;; (or to   (setq to (save-excursion (beginning-of-line 2)
2854             ;;                                 (point))))
2855             ;; t)
2856
2857             ;; If that place is not the beginning of the line,
2858             ;; break the line there.
2859             (if (save-excursion
2860                   (goto-char fill-point)
2861                   (not (or (bolp) (eolp)))) ; 97/3/14 jhod: during kinsoku processing it is possible to move beyond
2862                 (let ((prev-column (current-column)))
2863                   ;; If point is at the fill-point, do not `save-excursion'.
2864                   ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2865                   ;; point will end up before it rather than after it.
2866                   (if (save-excursion
2867                         (skip-chars-backward " \t")
2868                         (= (point) fill-point))
2869                       ;; 1999-09-17 hniksic: turn off Kinsoku until
2870                       ;; it's debugged.
2871                       (indent-new-comment-line)
2872                       ;; 97/3/14 jhod: Kinsoku processing
2873 ;                     ;(indent-new-comment-line)
2874 ;                     (let ((spacep (memq (char-before (point)) '(?\  ?\t))))
2875 ;                       (funcall comment-line-break-function)
2876 ;                       ;; if user type space explicitly, leave SPC
2877 ;                       ;; even if there is no WAN.
2878 ;                       (if spacep
2879 ;                           (save-excursion
2880 ;                             (goto-char fill-point)
2881 ;                             ;; put SPC except that there is SPC
2882 ;                             ;; already or there is sentence end.
2883 ;                             (or (memq (char-after (point)) '(?\  ?\t))
2884 ;                                 (fill-end-of-sentence-p)
2885 ;                                 (insert ?\ )))))
2886                     (save-excursion
2887                       (goto-char fill-point)
2888                       (funcall comment-line-break-function)))
2889                   ;; If making the new line didn't reduce the hpos of
2890                   ;; the end of the line, then give up now;
2891                   ;; trying again will not help.
2892                   (if (>= (current-column) prev-column)
2893                       (setq give-up t)))
2894               ;; No place to break => stop trying.
2895               (setq give-up t)))))))
2896
2897 ;; Put FSF one in until I can one or the other working properly, then the
2898 ;; other one is history.
2899 ;(defun fsf:do-auto-fill ()
2900 ;  (let (fc justify
2901 ;          ;; bol
2902 ;          give-up
2903 ;          (fill-prefix fill-prefix))
2904 ;    (if (or (not (setq justify (current-justification)))
2905 ;           (null (setq fc (current-fill-column)))
2906 ;           (and (eq justify 'left)
2907 ;                (<= (current-column) fc))
2908 ;           (save-excursion (beginning-of-line)
2909 ;                           ;; (setq bol (point))
2910 ;                           (and auto-fill-inhibit-regexp
2911 ;                                (looking-at auto-fill-inhibit-regexp))))
2912 ;       nil ;; Auto-filling not required
2913 ;      (if (memq justify '(full center right))
2914 ;         (save-excursion (unjustify-current-line)))
2915
2916 ;      ;; Choose a fill-prefix automatically.
2917 ;      (if (and adaptive-fill-mode
2918 ;              (or (null fill-prefix) (string= fill-prefix "")))
2919 ;         (let ((prefix
2920 ;                (fill-context-prefix
2921 ;                 (save-excursion (backward-paragraph 1) (point))
2922 ;                 (save-excursion (forward-paragraph 1) (point))
2923 ;                 ;; Don't accept a non-whitespace fill prefix
2924 ;                 ;; from the first line of a paragraph.
2925 ;                 "^[ \t]*$")))
2926 ;           (and prefix (not (equal prefix ""))
2927 ;                (setq fill-prefix prefix))))
2928
2929 ;      (while (and (not give-up) (> (current-column) fc))
2930 ;       ;; Determine where to split the line.
2931 ;       (let ((fill-point
2932 ;              (let ((opoint (point))
2933 ;                    bounce
2934 ;                    (first t))
2935 ;                (save-excursion
2936 ;                  (move-to-column (1+ fc))
2937 ;                  ;; Move back to a word boundary.
2938 ;                  (while (or first
2939 ;                             ;; If this is after period and a single space,
2940 ;                             ;; move back once more--we don't want to break
2941 ;                             ;; the line there and make it look like a
2942 ;                             ;; sentence end.
2943 ;                             (and (not (bobp))
2944 ;                                  (not bounce)
2945 ;                                  sentence-end-double-space
2946 ;                                  (save-excursion (forward-char -1)
2947 ;                                                  (and (looking-at "\\. ")
2948 ;                                                       (not (looking-at "\\.  "))))))
2949 ;                    (setq first nil)
2950 ;                    (skip-chars-backward "^ \t\n")
2951 ;                    ;; If we find nowhere on the line to break it,
2952 ;                    ;; break after one word.  Set bounce to t
2953 ;                    ;; so we will not keep going in this while loop.
2954 ;                    (if (bolp)
2955 ;                        (progn
2956 ;                          (re-search-forward "[ \t]" opoint t)
2957 ;                          (setq bounce t)))
2958 ;                    (skip-chars-backward " \t"))
2959 ;                  ;; Let fill-point be set to the place where we end up.
2960 ;                  (point)))))
2961 ;         ;; If that place is not the beginning of the line,
2962 ;         ;; break the line there.
2963 ;         (if (save-excursion
2964 ;               (goto-char fill-point)
2965 ;               (not (bolp)))
2966 ;             (let ((prev-column (current-column)))
2967 ;               ;; If point is at the fill-point, do not `save-excursion'.
2968 ;               ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2969 ;               ;; point will end up before it rather than after it.
2970 ;               (if (save-excursion
2971 ;                     (skip-chars-backward " \t")
2972 ;                     (= (point) fill-point))
2973 ;                   (funcall comment-line-break-function t)
2974 ;                 (save-excursion
2975 ;                   (goto-char fill-point)
2976 ;                   (funcall comment-line-break-function t)))
2977 ;               ;; Now do justification, if required
2978 ;               (if (not (eq justify 'left))
2979 ;                   (save-excursion
2980 ;                     (end-of-line 0)
2981 ;                     (justify-current-line justify nil t)))
2982 ;               ;; If making the new line didn't reduce the hpos of
2983 ;               ;; the end of the line, then give up now;
2984 ;               ;; trying again will not help.
2985 ;               (if (>= (current-column) prev-column)
2986 ;                   (setq give-up t)))
2987 ;           ;; No place to break => stop trying.
2988 ;           (setq give-up t))))
2989 ;      ;; Justify last line.
2990 ;      (justify-current-line justify t t)
2991 ;      t)))
2992
2993 (defvar normal-auto-fill-function 'do-auto-fill
2994   "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
2995 Some major modes set this.")
2996
2997 (defun auto-fill-mode (&optional arg)
2998   "Toggle auto-fill mode.
2999 With arg, turn auto-fill mode on if and only if arg is positive.
3000 In Auto-Fill mode, inserting a space at a column beyond `current-fill-column'
3001 automatically breaks the line at a previous space.
3002
3003 The value of `normal-auto-fill-function' specifies the function to use
3004 for `auto-fill-function' when turning Auto Fill mode on."
3005   (interactive "P")
3006   (prog1 (setq auto-fill-function
3007                (if (if (null arg)
3008                        (not auto-fill-function)
3009                        (> (prefix-numeric-value arg) 0))
3010                    normal-auto-fill-function
3011                    nil))
3012     (redraw-modeline)))
3013
3014 ;; This holds a document string used to document auto-fill-mode.
3015 (defun auto-fill-function ()
3016   "Automatically break line at a previous space, in insertion of text."
3017   nil)
3018
3019 (defun turn-on-auto-fill ()
3020   "Unconditionally turn on Auto Fill mode."
3021   (auto-fill-mode 1))
3022
3023 (defun set-fill-column (arg)
3024   "Set `fill-column' to specified argument.
3025 Just \\[universal-argument] as argument means to use the current column
3026 The variable `fill-column' has a separate value for each buffer."
3027   (interactive "_P") ; XEmacs
3028   (cond ((integerp arg)
3029          (setq fill-column arg))
3030         ((consp arg)
3031          (setq fill-column (current-column)))
3032         ;; Disallow missing argument; it's probably a typo for C-x C-f.
3033         (t
3034          (error "set-fill-column requires an explicit argument")))
3035   (lmessage 'command "fill-column set to %d" fill-column))
3036 \f
3037 (defcustom comment-multi-line t ; XEmacs - this works well with adaptive fill
3038   "*Non-nil means \\[indent-new-comment-line] should continue same comment
3039 on new line, with no new terminator or starter.
3040 This is obsolete because you might as well use \\[newline-and-indent]."
3041   :type 'boolean
3042   :group 'fill-comments)
3043
3044 (defun indent-new-comment-line (&optional soft)
3045   "Break line at point and indent, continuing comment if within one.
3046 This indents the body of the continued comment
3047 under the previous comment line.
3048
3049 This command is intended for styles where you write a comment per line,
3050 starting a new comment (and terminating it if necessary) on each line.
3051 If you want to continue one comment across several lines, use \\[newline-and-indent].
3052
3053 If a fill column is specified, it overrides the use of the comment column
3054 or comment indentation.
3055
3056 The inserted newline is marked hard if `use-hard-newlines' is true,
3057 unless optional argument SOFT is non-nil."
3058   (interactive)
3059   (let (comcol comstart)
3060     (skip-chars-backward " \t")
3061     ;; 97/3/14 jhod: Kinsoku processing
3062     (if (featurep 'mule)
3063         (kinsoku-process))
3064     (delete-region (point)
3065                    (progn (skip-chars-forward " \t")
3066                           (point)))
3067     (if soft (insert ?\n) (newline 1))
3068     (if fill-prefix
3069         (progn
3070           (indent-to-left-margin)
3071           (insert fill-prefix))
3072     ;; #### - Eric Eide reverts to v18 semantics for this function in
3073     ;; fa-extras, which I'm not gonna do.  His changes are to (1) execute
3074     ;; the save-excursion below unconditionally, and (2) uncomment the check
3075     ;; for (not comment-multi-line) further below.  --Stig
3076       ;;#### jhod: probably need to fix this for kinsoku processing
3077       (if (not comment-multi-line)
3078           (save-excursion
3079             (if (and comment-start-skip
3080                      (let ((opoint (point)))
3081                        (forward-line -1)
3082                        (re-search-forward comment-start-skip opoint t)))
3083                 ;; The old line is a comment.
3084                 ;; Set WIN to the pos of the comment-start.
3085                 ;; But if the comment is empty, look at preceding lines
3086                 ;; to find one that has a nonempty comment.
3087
3088                 ;; If comment-start-skip contains a \(...\) pair,
3089                 ;; the real comment delimiter starts at the end of that pair.
3090                 (let ((win (or (match-end 1) (match-beginning 0))))
3091                   (while (and (eolp) (not (bobp))
3092                               (let (opoint)
3093                                 (beginning-of-line)
3094                                 (setq opoint (point))
3095                                 (forward-line -1)
3096                                 (re-search-forward comment-start-skip opoint t)))
3097                     (setq win (or (match-end 1) (match-beginning 0))))
3098                   ;; Indent this line like what we found.
3099                   (goto-char win)
3100                   (setq comcol (current-column))
3101                   (setq comstart
3102                         (buffer-substring (point) (match-end 0)))))))
3103       (if (and comcol (not fill-prefix))  ; XEmacs - (ENE) from fa-extras.
3104           (let ((comment-column comcol)
3105                 (comment-start comstart)
3106                 (block-comment-start comstart)
3107                 (comment-end comment-end))
3108             (and comment-end (not (equal comment-end ""))
3109   ;            (if (not comment-multi-line)
3110                      (progn
3111                        (forward-char -1)
3112                        (insert comment-end)
3113                        (forward-char 1))
3114   ;              (setq comment-column (+ comment-column (length comment-start))
3115   ;                    comment-start "")
3116   ;                )
3117                  )
3118             (if (not (eolp))
3119                 (setq comment-end ""))
3120             (insert ?\n)
3121             (forward-char -1)
3122             (indent-for-comment)
3123             (save-excursion
3124               ;; Make sure we delete the newline inserted above.
3125               (end-of-line)
3126               (delete-char 1)))
3127         (indent-according-to-mode)))))
3128
3129 \f
3130 (defun set-selective-display (arg)
3131   "Set `selective-display' to ARG; clear it if no arg.
3132 When the value of `selective-display' is a number > 0,
3133 lines whose indentation is >= that value are not displayed.
3134 The variable `selective-display' has a separate value for each buffer."
3135   (interactive "P")
3136   (if (eq selective-display t)
3137       (error "selective-display already in use for marked lines"))
3138   (let ((current-vpos
3139          (save-restriction
3140            (narrow-to-region (point-min) (point))
3141            (goto-char (window-start))
3142            (vertical-motion (window-height)))))
3143     (setq selective-display
3144           (and arg (prefix-numeric-value arg)))
3145     (recenter current-vpos))
3146   (set-window-start (selected-window) (window-start (selected-window)))
3147   ;; #### doesn't localize properly:
3148   (princ "selective-display set to " t)
3149   (prin1 selective-display t)
3150   (princ "." t))
3151
3152 ;; XEmacs
3153 (defun nuke-selective-display ()
3154   "Ensure that the buffer is not in selective-display mode.
3155 If `selective-display' is t, then restore the buffer text to its original
3156 state before disabling selective display."
3157   ;; by Stig@hackvan.com
3158   (interactive)
3159   (and (eq t selective-display)
3160        (save-excursion
3161          (save-restriction
3162            (widen)
3163            (goto-char (point-min))
3164            (let ((mod-p (buffer-modified-p))
3165                  (buffer-read-only nil))
3166              (while (search-forward "\r" nil t)
3167                (delete-char -1)
3168                (insert "\n"))
3169              (set-buffer-modified-p mod-p)
3170              ))))
3171   (setq selective-display nil))
3172
3173 (add-hook 'change-major-mode-hook 'nuke-selective-display)
3174
3175 (defconst overwrite-mode-textual (purecopy " Ovwrt")
3176   "The string displayed in the mode line when in overwrite mode.")
3177 (defconst overwrite-mode-binary (purecopy " Bin Ovwrt")
3178   "The string displayed in the mode line when in binary overwrite mode.")
3179
3180 (defun overwrite-mode (arg)
3181   "Toggle overwrite mode.
3182 With arg, turn overwrite mode on iff arg is positive.
3183 In overwrite mode, printing characters typed in replace existing text
3184 on a one-for-one basis, rather than pushing it to the right.  At the
3185 end of a line, such characters extend the line.  Before a tab,
3186 such characters insert until the tab is filled in.
3187 \\[quoted-insert] still inserts characters in overwrite mode; this
3188 is supposed to make it easier to insert characters when necessary."
3189   (interactive "P")
3190   (setq overwrite-mode
3191         (if (if (null arg) (not overwrite-mode)
3192               (> (prefix-numeric-value arg) 0))
3193             'overwrite-mode-textual))
3194   (redraw-modeline))
3195
3196 (defun binary-overwrite-mode (arg)
3197   "Toggle binary overwrite mode.
3198 With arg, turn binary overwrite mode on iff arg is positive.
3199 In binary overwrite mode, printing characters typed in replace
3200 existing text.  Newlines are not treated specially, so typing at the
3201 end of a line joins the line to the next, with the typed character
3202 between them.  Typing before a tab character simply replaces the tab
3203 with the character typed.
3204 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3205 typing characters do.
3206
3207 Note that binary overwrite mode is not its own minor mode; it is a
3208 specialization of overwrite-mode, entered by setting the
3209 `overwrite-mode' variable to `overwrite-mode-binary'."
3210   (interactive "P")
3211   (setq overwrite-mode
3212         (if (if (null arg)
3213                 (not (eq overwrite-mode 'overwrite-mode-binary))
3214               (> (prefix-numeric-value arg) 0))
3215             'overwrite-mode-binary))
3216   (redraw-modeline))
3217 \f
3218 (defcustom line-number-mode nil
3219   "*Non-nil means display line number in modeline."
3220   :type 'boolean
3221   :group 'editing-basics)
3222
3223 (defun line-number-mode (arg)
3224   "Toggle Line Number mode.
3225 With arg, turn Line Number mode on iff arg is positive.
3226 When Line Number mode is enabled, the line number appears
3227 in the mode line."
3228   (interactive "P")
3229   (setq line-number-mode
3230         (if (null arg) (not line-number-mode)
3231           (> (prefix-numeric-value arg) 0)))
3232   (redraw-modeline))
3233
3234 (defcustom column-number-mode nil
3235   "*Non-nil means display column number in mode line."
3236   :type 'boolean
3237   :group 'editing-basics)
3238
3239 (defun column-number-mode (arg)
3240   "Toggle Column Number mode.
3241 With arg, turn Column Number mode on iff arg is positive.
3242 When Column Number mode is enabled, the column number appears
3243 in the mode line."
3244   (interactive "P")
3245   (setq column-number-mode
3246         (if (null arg) (not column-number-mode)
3247           (> (prefix-numeric-value arg) 0)))
3248   (redraw-modeline))
3249
3250 \f
3251 (defcustom blink-matching-paren t
3252   "*Non-nil means show matching open-paren when close-paren is inserted."
3253   :type 'boolean
3254   :group 'paren-blinking)
3255
3256 (defcustom blink-matching-paren-on-screen t
3257   "*Non-nil means show matching open-paren when it is on screen.
3258 nil means don't show it (but the open-paren can still be shown
3259 when it is off screen."
3260   :type 'boolean
3261   :group 'paren-blinking)
3262
3263 (defcustom blink-matching-paren-distance 12000
3264   "*If non-nil, is maximum distance to search for matching open-paren."
3265   :type '(choice integer (const nil))
3266   :group 'paren-blinking)
3267
3268 (defcustom blink-matching-delay 1
3269   "*The number of seconds that `blink-matching-open' will delay at a match."
3270   :type 'number
3271   :group 'paren-blinking)
3272
3273 (defcustom blink-matching-paren-dont-ignore-comments nil
3274   "*Non-nil means `blink-matching-paren' should not ignore comments."
3275   :type 'boolean
3276   :group 'paren-blinking)
3277
3278 (defun blink-matching-open ()
3279   "Move cursor momentarily to the beginning of the sexp before point."
3280   (interactive "_") ; XEmacs
3281   (and (> (point) (1+ (point-min)))
3282        blink-matching-paren
3283        ;; Verify an even number of quoting characters precede the close.
3284        (= 1 (logand 1 (- (point)
3285                          (save-excursion
3286                            (forward-char -1)
3287                            (skip-syntax-backward "/\\")
3288                            (point)))))
3289        (let* ((oldpos (point))
3290               (blinkpos)
3291               (mismatch))
3292          (save-excursion
3293            (save-restriction
3294              (if blink-matching-paren-distance
3295                  (narrow-to-region (max (point-min)
3296                                         (- (point) blink-matching-paren-distance))
3297                                    oldpos))
3298              (condition-case ()
3299                  (let ((parse-sexp-ignore-comments
3300                         (and parse-sexp-ignore-comments
3301                              (not blink-matching-paren-dont-ignore-comments))))
3302                    (setq blinkpos (scan-sexps oldpos -1)))
3303                (error nil)))
3304            (and blinkpos
3305                 (/= (char-syntax (char-after blinkpos))
3306                     ?\$)
3307                 (setq mismatch
3308                       (or (null (matching-paren (char-after blinkpos)))
3309                           (/= (char-after (1- oldpos))
3310                               (matching-paren (char-after blinkpos))))))
3311            (if mismatch (setq blinkpos nil))
3312            (if blinkpos
3313                (progn
3314                 (goto-char blinkpos)
3315                 (if (pos-visible-in-window-p)
3316                     (and blink-matching-paren-on-screen
3317                          (progn
3318                            (auto-show-make-point-visible)
3319                            (sit-for blink-matching-delay)))
3320                   (goto-char blinkpos)
3321                   (lmessage 'command "Matches %s"
3322                     ;; Show what precedes the open in its line, if anything.
3323                     (if (save-excursion
3324                           (skip-chars-backward " \t")
3325                           (not (bolp)))
3326                         (buffer-substring (progn (beginning-of-line) (point))
3327                                           (1+ blinkpos))
3328                       ;; Show what follows the open in its line, if anything.
3329                       (if (save-excursion
3330                             (forward-char 1)
3331                             (skip-chars-forward " \t")
3332                             (not (eolp)))
3333                           (buffer-substring blinkpos
3334                                             (progn (end-of-line) (point)))
3335                         ;; Otherwise show the previous nonblank line,
3336                         ;; if there is one.
3337                         (if (save-excursion
3338                               (skip-chars-backward "\n \t")
3339                               (not (bobp)))
3340                             (concat
3341                              (buffer-substring (progn
3342                                                  (skip-chars-backward "\n \t")
3343                                                  (beginning-of-line)
3344                                                  (point))
3345                                                (progn (end-of-line)
3346                                                       (skip-chars-backward " \t")
3347                                                       (point)))
3348                              ;; Replace the newline and other whitespace with `...'.
3349                              "..."
3350                              (buffer-substring blinkpos (1+ blinkpos)))
3351                           ;; There is nothing to show except the char itself.
3352                           (buffer-substring blinkpos (1+ blinkpos))))))))
3353              (cond (mismatch
3354                     (display-message 'no-log "Mismatched parentheses"))
3355                    ((not blink-matching-paren-distance)
3356                     (display-message 'no-log "Unmatched parenthesis"))))))))
3357
3358 ;Turned off because it makes dbx bomb out.
3359 (setq blink-paren-function 'blink-matching-open)
3360 \f
3361 (eval-when-compile (defvar myhelp))     ; suppress compiler warning
3362
3363 ;; XEmacs: Some functions moved to cmdloop.el:
3364 ;; keyboard-quit
3365 ;; buffer-quit-function
3366 ;; keyboard-escape-quit
3367
3368 (defun assoc-ignore-case (key alist)
3369   "Like `assoc', but assumes KEY is a string and ignores case when comparing."
3370   (setq key (downcase key))
3371   (let (element)
3372     (while (and alist (not element))
3373       (if (equal key (downcase (car (car alist))))
3374           (setq element (car alist)))
3375       (setq alist (cdr alist)))
3376     element))
3377
3378 \f
3379 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3380 ;;                          mail composition code                        ;;
3381 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3382
3383 (defcustom mail-user-agent 'sendmail-user-agent
3384   "*Your preference for a mail composition package.
3385 Various Emacs Lisp packages (e.g. reporter) require you to compose an
3386 outgoing email message.  This variable lets you specify which
3387 mail-sending package you prefer.
3388
3389 Valid values include:
3390
3391     sendmail-user-agent -- use the default Emacs Mail package
3392     mh-e-user-agent     -- use the Emacs interface to the MH mail system
3393     message-user-agent  -- use the GNUS mail sending package
3394
3395 Additional valid symbols may be available; check with the author of
3396 your package for details."
3397   :type '(radio (function-item :tag "Default Emacs mail"
3398                                :format "%t\n"
3399                                sendmail-user-agent)
3400                 (function-item :tag "Gnus mail sending package"
3401                                :format "%t\n"
3402                                message-user-agent)
3403                 (function :tag "Other"))
3404   :group 'mail)
3405
3406 (defun define-mail-user-agent (symbol composefunc sendfunc
3407                                       &optional abortfunc hookvar)
3408   "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3409
3410 SYMBOL can be any Lisp symbol.  Its function definition and/or
3411 value as a variable do not matter for this usage; we use only certain
3412 properties on its property list, to encode the rest of the arguments.
3413
3414 COMPOSEFUNC is program callable function that composes an outgoing
3415 mail message buffer.  This function should set up the basics of the
3416 buffer without requiring user interaction.  It should populate the
3417 standard mail headers, leaving the `to:' and `subject:' headers blank
3418 by default.
3419
3420 COMPOSEFUNC should accept several optional arguments--the same
3421 arguments that `compose-mail' takes.  See that function's documentation.
3422
3423 SENDFUNC is the command a user would run to send the message.
3424
3425 Optional ABORTFUNC is the command a user would run to abort the
3426 message.  For mail packages that don't have a separate abort function,
3427 this can be `kill-buffer' (the equivalent of omitting this argument).
3428
3429 Optional HOOKVAR is a hook variable that gets run before the message
3430 is actually sent.  Callers that use the `mail-user-agent' may
3431 install a hook function temporarily on this hook variable.
3432 If HOOKVAR is nil, `mail-send-hook' is used.
3433
3434 The properties used on SYMBOL are `composefunc', `sendfunc',
3435 `abortfunc', and `hookvar'."
3436   (put symbol 'composefunc composefunc)
3437   (put symbol 'sendfunc sendfunc)
3438   (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3439   (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3440
3441 (define-mail-user-agent 'sendmail-user-agent
3442   'sendmail-user-agent-compose 'mail-send-and-exit)
3443
3444 (define-mail-user-agent 'message-user-agent
3445   'message-mail 'message-send-and-exit
3446   'message-kill-buffer 'message-send-hook)
3447
3448 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3449                                               switch-function yank-action
3450                                               send-actions)
3451   (if switch-function
3452       (let ((special-display-buffer-names nil)
3453             (special-display-regexps nil)
3454             (same-window-buffer-names nil)
3455             (same-window-regexps nil))
3456         (funcall switch-function "*mail*")))
3457   (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
3458         (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers))))
3459     (or (mail continue to subject in-reply-to cc yank-action send-actions)
3460         continue
3461         (error "Message aborted"))
3462     (save-excursion
3463       (goto-char (point-min))
3464       (search-forward mail-header-separator)
3465       (beginning-of-line)
3466       (while other-headers
3467         (if (not (member (car (car other-headers)) '("in-reply-to" "cc")))
3468             (insert (car (car other-headers)) ": "
3469                     (cdr (car other-headers)) "\n"))
3470         (setq other-headers (cdr other-headers)))
3471       t)))
3472
3473 (define-mail-user-agent 'mh-e-user-agent
3474   'mh-user-agent-compose 'mh-send-letter 'mh-fully-kill-draft
3475   'mh-before-send-letter-hook)
3476
3477 (defun compose-mail (&optional to subject other-headers continue
3478                                switch-function yank-action send-actions)
3479   "Start composing a mail message to send.
3480 This uses the user's chosen mail composition package
3481 as selected with the variable `mail-user-agent'.
3482 The optional arguments TO and SUBJECT specify recipients
3483 and the initial Subject field, respectively.
3484
3485 OTHER-HEADERS is an alist specifying additional
3486 header fields.  Elements look like (HEADER . VALUE) where both
3487 HEADER and VALUE are strings.
3488
3489 CONTINUE, if non-nil, says to continue editing a message already
3490 being composed.
3491
3492 SWITCH-FUNCTION, if non-nil, is a function to use to
3493 switch to and display the buffer used for mail composition.
3494
3495 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3496 to insert the raw text of the message being replied to.
3497 It has the form (FUNCTION . ARGS).  The user agent will apply
3498 FUNCTION to ARGS, to insert the raw text of the original message.
3499 \(The user agent will also run `mail-citation-hook', *after* the
3500 original text has been inserted in this way.)
3501
3502 SEND-ACTIONS is a list of actions to call when the message is sent.
3503 Each action has the form (FUNCTION . ARGS)."
3504   (interactive
3505    (list nil nil nil current-prefix-arg))
3506   (let ((function (get mail-user-agent 'composefunc)))
3507     (funcall function to subject other-headers continue
3508              switch-function yank-action send-actions)))
3509
3510 (defun compose-mail-other-window (&optional to subject other-headers continue
3511                                             yank-action send-actions)
3512   "Like \\[compose-mail], but edit the outgoing message in another window."
3513   (interactive
3514    (list nil nil nil current-prefix-arg))
3515   (compose-mail to subject other-headers continue
3516                 'switch-to-buffer-other-window yank-action send-actions))
3517
3518
3519 (defun compose-mail-other-frame (&optional to subject other-headers continue
3520                                             yank-action send-actions)
3521   "Like \\[compose-mail], but edit the outgoing message in another frame."
3522   (interactive
3523    (list nil nil nil current-prefix-arg))
3524   (compose-mail to subject other-headers continue
3525                 'switch-to-buffer-other-frame yank-action send-actions))
3526
3527 \f
3528 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3529 ;;                             set variable                              ;;
3530 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3531
3532 (defun set-variable (var val)
3533   "Set VARIABLE to VALUE.  VALUE is a Lisp object.
3534 When using this interactively, supply a Lisp expression for VALUE.
3535 If you want VALUE to be a string, you must surround it with doublequotes.
3536 If VARIABLE is a specifier, VALUE is added to it as an instantiator in
3537 the 'global locale with nil tag set (see `set-specifier').
3538
3539 If VARIABLE has a `variable-interactive' property, that is used as if
3540 it were the arg to `interactive' (which see) to interactively read the value."
3541   (interactive
3542    (let* ((var (read-variable "Set variable: "))
3543           ;; #### - yucky code replication here.  This should use something
3544           ;; from help.el or hyper-apropos.el
3545           (minibuffer-help-form
3546            '(funcall myhelp))
3547           (myhelp
3548            #'(lambda ()
3549               (with-output-to-temp-buffer "*Help*"
3550                 (prin1 var)
3551                 (princ "\nDocumentation:\n")
3552                 (princ (substring (documentation-property var 'variable-documentation)
3553                                   1))
3554                 (if (boundp var)
3555                     (let ((print-length 20))
3556                       (princ "\n\nCurrent value: ")
3557                       (prin1 (symbol-value var))))
3558                 (save-excursion
3559                   (set-buffer standard-output)
3560                   (help-mode))
3561                 nil))))
3562      (list var
3563            (let ((prop (get var 'variable-interactive)))
3564              (if prop
3565                  ;; Use VAR's `variable-interactive' property
3566                  ;; as an interactive spec for prompting.
3567                  (call-interactively (list 'lambda '(arg)
3568                                            (list 'interactive prop)
3569                                            'arg))
3570                (eval-minibuffer (format "Set %s to value: " var)))))))
3571   (if (and (boundp var) (specifierp (symbol-value var)))
3572       (set-specifier (symbol-value var) val)
3573     (set var val)))
3574
3575 \f
3576 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3577 ;;                           case changing code                          ;;
3578 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3579
3580 ;; A bunch of stuff was moved elsewhere:
3581 ;; completion-list-mode-map
3582 ;; completion-reference-buffer
3583 ;; completion-base-size
3584 ;; delete-completion-window
3585 ;; previous-completion
3586 ;; next-completion
3587 ;; choose-completion
3588 ;; choose-completion-delete-max-match
3589 ;; choose-completion-string
3590 ;; completion-list-mode
3591 ;; completion-fixup-function
3592 ;; completion-setup-function
3593 ;; switch-to-completions
3594 ;; event stuffs
3595 ;; keypad stuffs
3596
3597 ;; The rest of this file is not in Lisp in FSF
3598 (defun capitalize-region-or-word (arg)
3599   "Capitalize the selected region or the following word (or ARG words)."
3600   (interactive "p")
3601   (if (region-active-p)
3602       (capitalize-region (region-beginning) (region-end))
3603     (capitalize-word arg)))
3604
3605 (defun upcase-region-or-word (arg)
3606   "Upcase the selected region or the following word (or ARG words)."
3607   (interactive "p")
3608   (if (region-active-p)
3609       (upcase-region (region-beginning) (region-end))
3610     (upcase-word arg)))
3611
3612 (defun downcase-region-or-word (arg)
3613   "Downcase the selected region or the following word (or ARG words)."
3614   (interactive "p")
3615   (if (region-active-p)
3616       (downcase-region (region-beginning) (region-end))
3617     (downcase-word arg)))
3618
3619 ;; #### not localized
3620 (defvar uncapitalized-title-words
3621   '("the" "a" "an" "in" "of" "for" "to" "and" "but" "at" "on" "as" "by"))
3622
3623 (defvar uncapitalized-title-word-regexp
3624   (concat "[ \t]*\\(" (mapconcat #'identity uncapitalized-title-words "\\|")
3625           "\\)\\>"))
3626
3627 (defun capitalize-string-as-title (string)
3628   "Capitalize the words in the string, except for small words (as in titles).
3629 The words not capitalized are specified in `uncapitalized-title-words'."
3630   (let ((buffer (get-buffer-create " *capitalize-string-as-title*")))
3631     (unwind-protect
3632         (progn
3633           (insert-string string buffer)
3634           (capitalize-region-as-title 1 (point-max buffer) buffer)
3635           (buffer-string buffer))
3636       (kill-buffer buffer))))
3637
3638 (defun capitalize-region-as-title (b e &optional buffer)
3639   "Capitalize the words in the region, except for small words (as in titles).
3640 The words not capitalized are specified in `uncapitalized-title-words'."
3641   (interactive "r")
3642   (save-excursion
3643     (and buffer
3644          (set-buffer buffer))
3645     (save-restriction
3646       (narrow-to-region b e)
3647       (goto-char (point-min))
3648       (let ((first t))
3649         (while (< (point) (point-max))
3650           (if (or first
3651                   (not (looking-at uncapitalized-title-word-regexp)))
3652               (capitalize-word 1)
3653             (forward-word 1))
3654           (setq first nil))))))
3655
3656 \f
3657 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3658 ;;                          zmacs active region code                     ;;
3659 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3660
3661 ;; Most of the zmacs code is now in elisp.  The only thing left in C
3662 ;; are the variables zmacs-regions, zmacs-region-active-p and
3663 ;; zmacs-region-stays plus the function zmacs_update_region which
3664 ;; simply calls the lisp level zmacs-update-region.  It must remain
3665 ;; for convenience, since it is called by core C code.
3666
3667 ;; XEmacs
3668 (defun activate-region ()
3669   "Activate the region, if `zmacs-regions' is true.
3670 Setting `zmacs-regions' to true causes LISPM-style active regions to be used.
3671 This function has no effect if `zmacs-regions' is false."
3672   (interactive)
3673   (and zmacs-regions (zmacs-activate-region)))
3674
3675 ;; XEmacs
3676 (defsubst region-exists-p ()
3677   "Return t if the region exists.
3678 If active regions are in use (i.e. `zmacs-regions' is true), this means that
3679  the region is active.  Otherwise, this means that the user has pushed
3680  a mark in this buffer at some point in the past.
3681 The functions `region-beginning' and `region-end' can be used to find the
3682  limits of the region."
3683   (not (null (mark))))
3684
3685 ;; XEmacs
3686 (defun region-active-p ()
3687   "Return non-nil if the region is active.
3688 If `zmacs-regions' is true, this is equivalent to `region-exists-p'.
3689 Otherwise, this function always returns false."
3690   (and zmacs-regions zmacs-region-extent))
3691
3692 (defvar zmacs-activate-region-hook nil
3693   "Function or functions called when the region becomes active;
3694 see the variable `zmacs-regions'.")
3695
3696 (defvar zmacs-deactivate-region-hook nil
3697   "Function or functions called when the region becomes inactive;
3698 see the variable `zmacs-regions'.")
3699
3700 (defvar zmacs-update-region-hook nil
3701   "Function or functions called when the active region changes.
3702 This is called after each command that sets `zmacs-region-stays' to t.
3703 See the variable `zmacs-regions'.")
3704
3705 (defvar zmacs-region-extent nil
3706   "The extent of the zmacs region; don't use this.")
3707
3708 (defvar zmacs-region-rectangular-p nil
3709   "Whether the zmacs region is a rectangle; don't use this.")
3710
3711 (defun zmacs-make-extent-for-region (region)
3712   ;; Given a region, this makes an extent in the buffer which holds that
3713   ;; region, for highlighting purposes.  If the region isn't associated
3714   ;; with a buffer, this does nothing.
3715   (let ((buffer nil)
3716         (valid (and (extentp zmacs-region-extent)
3717                     (extent-object zmacs-region-extent)
3718                     (buffer-live-p (extent-object zmacs-region-extent))))
3719         start end)
3720     (cond ((consp region)
3721            (setq start (min (car region) (cdr region))
3722                  end (max (car region) (cdr region))
3723                  valid (and valid
3724                             (eq (marker-buffer (car region))
3725                                 (extent-object zmacs-region-extent)))
3726                  buffer (marker-buffer (car region))))
3727           (t
3728            (signal 'error (list "Invalid region" region))))
3729
3730     (if valid
3731         nil
3732       ;; The condition case is in case any of the extents are dead or
3733       ;; otherwise incapacitated.
3734       (condition-case ()
3735           (if (listp zmacs-region-extent)
3736               (mapc 'delete-extent zmacs-region-extent)
3737             (delete-extent zmacs-region-extent))
3738         (error nil)))
3739
3740     (if valid
3741         (set-extent-endpoints zmacs-region-extent start end)
3742       (setq zmacs-region-extent (make-extent start end buffer))
3743
3744       ;; Make the extent be closed on the right, which means that if
3745       ;; characters are inserted exactly at the end of the extent, the
3746       ;; extent will grow to cover them.  This is important for shell
3747       ;; buffers - suppose one makes a region, and one end is at point-max.
3748       ;; If the shell produces output, that marker will remain at point-max
3749       ;; (its position will increase).  So it's important that the extent
3750       ;; exhibit the same behavior, lest the region covered by the extent
3751       ;; (the visual indication), and the region between point and mark
3752       ;; (the actual region value) become different!
3753       (set-extent-property zmacs-region-extent 'end-open nil)
3754
3755       ;; use same priority as mouse-highlighting so that conflicts between
3756       ;; the region extent and a mouse-highlighted extent are resolved by
3757       ;; the usual size-and-endpoint-comparison method.
3758       (set-extent-priority zmacs-region-extent mouse-highlight-priority)
3759       (set-extent-face zmacs-region-extent 'zmacs-region)
3760
3761       ;; #### It might be better to actually break
3762       ;; default-mouse-track-next-move-rect out of mouse.el so that we
3763       ;; can use its logic here.
3764       (cond
3765        (zmacs-region-rectangular-p
3766         (setq zmacs-region-extent (list zmacs-region-extent))
3767         (default-mouse-track-next-move-rect start end zmacs-region-extent)
3768         ))
3769
3770       zmacs-region-extent)))
3771
3772 (defun zmacs-region-buffer ()
3773   "Return the buffer containing the zmacs region, or nil."
3774   ;; #### this is horrible and kludgy!  This stuff needs to be rethought.
3775   (and zmacs-regions zmacs-region-active-p
3776        (or (marker-buffer (mark-marker t))
3777            (and (extent-live-p zmacs-region-extent)
3778                 (buffer-live-p (extent-object zmacs-region-extent))
3779                 (extent-object zmacs-region-extent)))))
3780
3781 (defun zmacs-activate-region ()
3782   "Make the region between `point' and `mark' be active (highlighted),
3783 if `zmacs-regions' is true.  Only a very small number of commands
3784 should ever do this.  Calling this function will call the hook
3785 `zmacs-activate-region-hook', if the region was previously inactive.
3786 Calling this function ensures that the region stays active after the
3787 current command terminates, even if `zmacs-region-stays' is not set.
3788 Returns t if the region was activated (i.e. if `zmacs-regions' if t)."
3789   (if (not zmacs-regions)
3790       nil
3791     (setq zmacs-region-active-p t
3792           zmacs-region-stays t
3793           zmacs-region-rectangular-p (and (boundp 'mouse-track-rectangle-p)
3794                                           mouse-track-rectangle-p))
3795     (if (marker-buffer (mark-marker t))
3796         (zmacs-make-extent-for-region (cons (point-marker t) (mark-marker t))))
3797     (run-hooks 'zmacs-activate-region-hook)
3798     t))
3799
3800 (defun zmacs-deactivate-region ()
3801   "Make the region between `point' and `mark' no longer be active,
3802 if `zmacs-regions' is true.  You shouldn't need to call this; the
3803 command loop calls it when appropriate.  Calling this function will
3804 call the hook `zmacs-deactivate-region-hook', if the region was
3805 previously active.  Returns t if the region had been active, nil
3806 otherwise."
3807   (if (not zmacs-region-active-p)
3808       nil
3809     (setq zmacs-region-active-p nil
3810           zmacs-region-stays nil
3811           zmacs-region-rectangular-p nil)
3812     (if zmacs-region-extent
3813         (let ((inhibit-quit t))
3814           (if (listp zmacs-region-extent)
3815               (mapc 'delete-extent zmacs-region-extent)
3816             (delete-extent zmacs-region-extent))
3817           (setq zmacs-region-extent nil)))
3818     (run-hooks 'zmacs-deactivate-region-hook)
3819     t))
3820
3821 (defun zmacs-update-region ()
3822   "Update the highlighted region between `point' and `mark'.
3823 You shouldn't need to call this; the command loop calls it
3824 when appropriate.  Calling this function will call the hook
3825 `zmacs-update-region-hook', if the region is active."
3826   (when zmacs-region-active-p
3827     (when (marker-buffer (mark-marker t))
3828       (zmacs-make-extent-for-region (cons (point-marker t)
3829                                           (mark-marker t))))
3830     (run-hooks 'zmacs-update-region-hook)))
3831
3832 \f
3833 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3834 ;;                           message logging code                        ;;
3835 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3836
3837 ;;; #### Should this be moved to a separate file, for clarity?
3838 ;;; -hniksic
3839
3840 ;;; The `message-stack' is an alist of labels with messages; the first
3841 ;;; message in this list is always in the echo area.  A call to
3842 ;;; `display-message' inserts a label/message pair at the head of the
3843 ;;; list, and removes any other pairs with that label.  Calling
3844 ;;; `clear-message' causes any pair with matching label to be removed,
3845 ;;; and this may cause the displayed message to change or vanish.  If
3846 ;;; the label arg is nil, the entire message stack is cleared.
3847 ;;;
3848 ;;; Message/error filtering will be a little tricker to implement than
3849 ;;; logging, since messages can be built up incrementally
3850 ;;; using clear-message followed by repeated calls to append-message
3851 ;;; (this happens with error messages).  For messages which aren't
3852 ;;; created this way, filtering could be implemented at display-message
3853 ;;; very easily.
3854 ;;;
3855 ;;; Bits of the logging code are borrowed from log-messages.el by
3856 ;;; Robert Potter (rpotter@grip.cis.upenn.edu).
3857
3858 ;; need this to terminate the currently-displayed message
3859 ;; ("Loading simple ...")
3860 (when (and
3861        (not (fboundp 'display-message))
3862        (not (featurep 'debug)))
3863   (send-string-to-terminal "\n"))
3864
3865 (defvar message-stack nil
3866   "An alist of label/string pairs representing active echo-area messages.
3867 The first element in the list is currently displayed in the echo area.
3868 Do not modify this directly--use the `message' or
3869 `display-message'/`clear-message' functions.")
3870
3871 (defvar remove-message-hook 'log-message
3872   "A function or list of functions to be called when a message is removed
3873 from the echo area at the bottom of the frame.  The label of the removed
3874 message is passed as the first argument, and the text of the message
3875 as the second argument.")
3876
3877 (defcustom log-message-max-size 50000
3878   "Maximum size of the \" *Message-Log*\" buffer.  See `log-message'."
3879   :type 'integer
3880   :group 'log-message)
3881 (make-compatible-variable 'message-log-max 'log-message-max-size)
3882
3883 ;; We used to reject quite a lot of stuff here, but it was a bad idea,
3884 ;; for two reasons:
3885 ;;
3886 ;; a) In most circumstances, you *want* to see the message in the log.
3887 ;;    The explicitly non-loggable messages should be marked as such by
3888 ;;    the issuer.  Gratuitous non-displaying of random regexps made
3889 ;;    debugging harder, too (because various reasonable debugging
3890 ;;    messages would get eaten).
3891 ;;
3892 ;; b) It slowed things down.  Yes, visibly.
3893 ;;
3894 ;; So, I left only a few of the really useless ones on this kill-list.
3895 ;;
3896 ;;                                            --hniksic
3897 (defcustom log-message-ignore-regexps
3898   '(;; Note: adding entries to this list slows down messaging
3899     ;; significantly.  Wherever possible, use message labels.
3900
3901     ;; Often-seen messages
3902     "\\`\\'"                            ; empty message
3903     "\\`\\(Beginning\\|End\\) of buffer\\'"
3904     ;;"^Quit$"
3905     ;; completions
3906     ;; Many packages print this -- impossible to categorize
3907     ;;"^Making completion list"
3908     ;; Gnus
3909     ;; "^No news is no news$"
3910     ;; "^No more\\( unread\\)? newsgroups$"
3911     ;; "^Opening [^ ]+ server\\.\\.\\."
3912     ;; "^[^:]+: Reading incoming mail"
3913     ;; "^Getting mail from "
3914     ;; "^\\(Generating Summary\\|Sorting threads\\|Making sparse threads\\|Scoring\\|Checking new news\\|Expiring articles\\|Sending\\)\\.\\.\\."
3915     ;; "^\\(Fetching headers for\\|Retrieving newsgroup\\|Reading active file\\)"
3916     ;; "^No more\\( unread\\)? articles"
3917     ;; "^Deleting article "
3918     ;; W3
3919     ;; "^Parsed [0-9]+ of [0-9]+ ([0-9]+%)"
3920     )
3921   "List of regular expressions matching messages which shouldn't be logged.
3922 See `log-message'.
3923
3924 Ideally, packages which generate messages which might need to be ignored
3925 should label them with 'progress, 'prompt, or 'no-log, so they can be
3926 filtered by the log-message-ignore-labels."
3927   :type '(repeat regexp)
3928   :group 'log-message)
3929
3930 (defcustom log-message-ignore-labels
3931   '(help-echo command progress prompt no-log garbage-collecting auto-saving)
3932   "List of symbols indicating labels of messages which shouldn't be logged.
3933 See `display-message' for some common labels.  See also `log-message'."
3934   :type '(repeat (symbol :tag "Label"))
3935   :group 'log-message)
3936
3937 ;;Subsumed by view-lossage
3938 ;; Not really, I'm adding it back by popular demand. -slb
3939 (defun show-message-log ()
3940   "Show the \" *Message-Log*\" buffer, which contains old messages and errors."
3941   (interactive)
3942   (pop-to-buffer (get-buffer-create " *Message-Log*")))
3943
3944 (defvar log-message-filter-function 'log-message-filter
3945   "Value must be a function of two arguments: a symbol (label) and
3946 a string (message).  It should return non-nil to indicate a message
3947 should be logged.  Possible values include 'log-message-filter and
3948 'log-message-filter-errors-only.")
3949
3950 (defun log-message-filter (label message)
3951   "Default value of `log-message-filter-function'.
3952 Messages whose text matches one of the `log-message-ignore-regexps'
3953 or whose label appears in `log-message-ignore-labels' are not saved."
3954   (let ((r  log-message-ignore-regexps)
3955         (ok (not (memq label log-message-ignore-labels))))
3956     (save-match-data
3957       (while (and r ok)
3958         (when (string-match (car r) message)
3959           (setq ok nil))
3960         (setq r (cdr r))))
3961     ok))
3962
3963 (defun log-message-filter-errors-only (label message)
3964   "For use as the `log-message-filter-function'.  Only logs error messages."
3965   (eq label 'error))
3966
3967 (defun log-message (label message)
3968   "Stuff a copy of the message into the \" *Message-Log*\" buffer,
3969 if it satisfies the `log-message-filter-function'.
3970
3971 For use on `remove-message-hook'."
3972   (when (and (not noninteractive)
3973              (funcall log-message-filter-function label message))
3974     ;; Use save-excursion rather than save-current-buffer because we
3975     ;; change the value of point.
3976     (save-excursion
3977       (set-buffer (get-buffer-create " *Message-Log*"))
3978       (goto-char (point-max))
3979       ;(insert (concat (upcase (symbol-name label)) ": "  message "\n"))
3980       (let (extent)
3981         ;; Mark multiline message with an extent, which `view-lossage'
3982         ;; will recognize.
3983         (when (string-match "\n" message)
3984           (setq extent (make-extent (point) (point)))
3985           (set-extent-properties extent '(end-open nil message-multiline t)))
3986         (insert message "\n")
3987         (when extent
3988           (set-extent-property extent 'end-open t)))
3989       (when (> (point-max) (max log-message-max-size (point-min)))
3990         ;; Trim log to ~90% of max size.
3991         (goto-char (max (- (point-max)
3992                            (truncate (* 0.9 log-message-max-size)))
3993                         (point-min)))
3994         (forward-line 1)
3995         (delete-region (point-min) (point))))))
3996
3997 (defun message-displayed-p (&optional return-string frame)
3998   "Return a non-nil value if a message is presently displayed in the\n\
3999 minibuffer's echo area.  If optional argument RETURN-STRING is non-nil,\n\
4000 return a string containing the message, otherwise just return t."
4001   ;; by definition, a message is displayed if the echo area buffer is
4002   ;; non-empty (see also echo_area_active()).  It had better also
4003   ;; be the case that message-stack is nil exactly when the echo area
4004   ;; is non-empty.
4005   (let ((buffer (get-buffer " *Echo Area*")))
4006     (and (< (point-min buffer) (point-max buffer))
4007          (if return-string
4008              (buffer-substring nil nil buffer)
4009            t))))
4010
4011 ;;; Returns the string which remains in the echo area, or nil if none.
4012 ;;; If label is nil, the whole message stack is cleared.
4013 (defun clear-message (&optional label frame stdout-p no-restore)
4014   "Remove any message with the given LABEL from the message-stack,
4015 erasing it from the echo area if it's currently displayed there.
4016 If a message remains at the head of the message-stack and NO-RESTORE
4017 is nil, it will be displayed.  The string which remains in the echo
4018 area will be returned, or nil if the message-stack is now empty.
4019 If LABEL is nil, the entire message-stack is cleared.
4020
4021 Unless you need the return value or you need to specify a label,
4022 you should just use (message nil)."
4023   (or frame (setq frame (selected-frame)))
4024   (let ((clear-stream (and message-stack (eq 'stream (frame-type frame)))))
4025     (remove-message label frame)
4026     (let ((inhibit-read-only t)
4027           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
4028       (erase-buffer " *Echo Area*"))
4029     (if clear-stream
4030         (send-string-to-terminal ?\n stdout-p))
4031     (if no-restore
4032         nil                     ; just preparing to put another msg up
4033       (if message-stack
4034           (let ((oldmsg (cdr (car message-stack))))
4035             (raw-append-message oldmsg frame stdout-p)
4036             oldmsg)
4037         ;; #### Should we (redisplay-echo-area) here?  Messes some
4038         ;; things up.
4039         nil))))
4040
4041 (defun remove-message (&optional label frame)
4042   ;; If label is nil, we want to remove all matching messages.
4043   ;; Must reverse the stack first to log them in the right order.
4044   (let ((log nil))
4045     (while (and message-stack
4046                 (or (null label)        ; null label means clear whole stack
4047                     (eq label (car (car message-stack)))))
4048       (push (car message-stack) log)
4049       (setq message-stack (cdr message-stack)))
4050     (let ((s  message-stack))
4051       (while (cdr s)
4052         (let ((msg (car (cdr s))))
4053           (if (eq label (car msg))
4054               (progn
4055                 (push msg log)
4056                 (setcdr s (cdr (cdr s))))
4057             (setq s (cdr s))))))
4058     ;; (possibly) log each removed message
4059     (while log
4060       (condition-case e
4061           (run-hook-with-args 'remove-message-hook
4062                               (car (car log)) (cdr (car log)))
4063         (error (setq remove-message-hook nil)
4064                (lwarn 'message-log 'warning
4065                  "Error caught in `remove-message-hook': %s"
4066                  (error-message-string e))
4067                (let ((inhibit-read-only t))
4068                  (erase-buffer " *Echo Area*"))
4069                (signal (car e) (cdr e))))
4070       (setq log (cdr log)))))
4071
4072 (defun append-message (label message &optional frame stdout-p)
4073   (or frame (setq frame (selected-frame)))
4074   ;; Add a new entry to the message-stack, or modify an existing one
4075   (let ((top (car message-stack)))
4076     (if (eq label (car top))
4077         (setcdr top (concat (cdr top) message))
4078       (push (cons label message) message-stack)))
4079   (raw-append-message message frame stdout-p))
4080
4081 ;; Really append the message to the echo area.  no fiddling with
4082 ;; message-stack.
4083 (defun raw-append-message (message &optional frame stdout-p)
4084   (unless (equal message "")
4085     (let ((inhibit-read-only t)
4086           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
4087       (insert-string message " *Echo Area*")
4088       ;; Conditionalizing on the device type in this way is not that clean,
4089       ;; but neither is having a device method, as I originally implemented
4090       ;; it: all non-stream devices behave in the same way.  Perhaps
4091       ;; the cleanest way is to make the concept of a "redisplayable"
4092       ;; device, which stream devices are not.  Look into this more if
4093       ;; we ever create another non-redisplayable device type (e.g.
4094       ;; processes?  printers?).
4095
4096       ;; Don't redisplay the echo area if we are executing a macro.
4097       (if (not executing-kbd-macro)
4098           (if (eq 'stream (frame-type frame))
4099               (send-string-to-terminal message stdout-p (frame-device frame))
4100             (redisplay-echo-area))))))
4101
4102 (defun display-message (label message &optional frame stdout-p)
4103   "Print a one-line message at the bottom of the frame.  First argument
4104 LABEL is an identifier for this message.  MESSAGE is the string to display.
4105 Use `clear-message' to remove a labelled message.
4106
4107 Here are some standard labels (those marked with `*' are not logged
4108 by default--see the `log-message-ignore-labels' variable):
4109     message       default label used by the `message' function
4110     error         default label used for reporting errors
4111   * progress      progress indicators like \"Converting... 45%\"
4112   * prompt        prompt-like messages like \"I-search: foo\"
4113   * command       helper command messages like \"Mark set\"
4114   * no-log        messages that should never be logged"
4115   (clear-message label frame stdout-p t)
4116   (append-message label message frame stdout-p))
4117
4118 (defun current-message (&optional frame)
4119   "Return the current message in the echo area, or nil.
4120 The FRAME argument is currently unused."
4121   (cdr (car message-stack)))
4122
4123 ;;; may eventually be frame-dependent
4124 (defun current-message-label (&optional frame)
4125   (car (car message-stack)))
4126
4127 (defun message (fmt &rest args)
4128   "Print a one-line message at the bottom of the frame.
4129 The arguments are the same as to `format'.
4130
4131 If the only argument is nil, clear any existing message; let the
4132 minibuffer contents show."
4133   ;; questionable junk in the C code
4134   ;; (if (framep default-minibuffer-frame)
4135   ;;     (make-frame-visible default-minibuffer-frame))
4136   (if (and (null fmt) (null args))
4137       (prog1 nil
4138         (clear-message nil))
4139     (let ((str (apply 'format fmt args)))
4140       (display-message 'message str)
4141       str)))
4142
4143 (defun lmessage (label fmt &rest args)
4144   "Print a one-line message at the bottom of the frame.
4145 First argument LABEL is an identifier for this message.  The rest of the
4146 arguments are the same as to `format'.
4147
4148 See `display-message' for a list of standard labels."
4149   (if (and (null fmt) (null args))
4150       (prog1 nil
4151         (clear-message label nil))
4152     (let ((str (apply 'format fmt args)))
4153       (display-message label str)
4154       str)))
4155
4156 \f
4157 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4158 ;;                              warning code                             ;;
4159 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4160
4161 (defcustom log-warning-minimum-level 'info
4162   "Minimum level of warnings that should be logged.
4163 The warnings in levels below this are completely ignored, as if they never
4164 happened.
4165
4166 The recognized warning levels, in decreasing order of priority, are
4167 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
4168 'debug.
4169
4170 See also `display-warning-minimum-level'.
4171
4172 You can also control which warnings are displayed on a class-by-class
4173 basis.  See `display-warning-suppressed-classes' and
4174 `log-warning-suppressed-classes'."
4175   :type '(choice (const emergency) (const alert) (const critical)
4176                  (const error) (const warning) (const notice)
4177                  (const info) (const debug))
4178   :group 'warnings)
4179
4180 (defcustom display-warning-minimum-level 'info
4181   "Minimum level of warnings that should be displayed.
4182 The warnings in levels below this will be generated, but not
4183 displayed.
4184
4185 The recognized warning levels, in decreasing order of priority, are
4186 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
4187 'debug.
4188
4189 See also `log-warning-minimum-level'.
4190
4191 You can also control which warnings are displayed on a class-by-class
4192 basis.  See `display-warning-suppressed-classes' and
4193 `log-warning-suppressed-classes'."
4194   :type '(choice (const emergency) (const alert) (const critical)
4195                  (const error) (const warning) (const notice)
4196                  (const info) (const debug))
4197   :group 'warnings)
4198
4199 (defvar log-warning-suppressed-classes nil
4200   "List of classes of warnings that shouldn't be logged or displayed.
4201 If any of the CLASS symbols associated with a warning is the same as
4202 any of the symbols listed here, the warning will be completely ignored,
4203 as it they never happened.
4204
4205 NOTE: In most circumstances, you should *not* set this variable.
4206 Set `display-warning-suppressed-classes' instead.  That way the suppressed
4207 warnings are not displayed but are still unobtrusively logged.
4208
4209 See also `log-warning-minimum-level' and `display-warning-minimum-level'.")
4210
4211 (defcustom display-warning-suppressed-classes nil
4212   "List of classes of warnings that shouldn't be displayed.
4213 If any of the CLASS symbols associated with a warning is the same as
4214 any of the symbols listed here, the warning will not be displayed.
4215 The warning will still logged in the *Warnings* buffer (unless also
4216 contained in `log-warning-suppressed-classes'), but the buffer will
4217 not be automatically popped up.
4218
4219 See also `log-warning-minimum-level' and `display-warning-minimum-level'."
4220   :type '(repeat symbol)
4221   :group 'warnings)
4222
4223 (defvar warning-count 0
4224   "Count of the number of warning messages displayed so far.")
4225
4226 (defconst warning-level-alist '((emergency . 8)
4227                                 (alert . 7)
4228                                 (critical . 6)
4229                                 (error . 5)
4230                                 (warning . 4)
4231                                 (notice . 3)
4232                                 (info . 2)
4233                                 (debug . 1)))
4234
4235 (defun warning-level-p (level)
4236   "Non-nil if LEVEL specifies a warning level."
4237   (and (symbolp level) (assq level warning-level-alist)))
4238
4239 ;; If you're interested in rewriting this function, be aware that it
4240 ;; could be called at arbitrary points in a Lisp program (when a
4241 ;; built-in function wants to issue a warning, it will call out to
4242 ;; this function the next time some Lisp code is evaluated).  Therefore,
4243 ;; this function *must* not permanently modify any global variables
4244 ;; (e.g. the current buffer) except those that specifically apply
4245 ;; to the warning system.
4246
4247 (defvar before-init-deferred-warnings nil)
4248
4249 (defun after-init-display-warnings ()
4250   "Display warnings deferred till after the init file is run.
4251 Warnings that occur before then are deferred so that warning
4252 suppression in the .emacs file will be honored."
4253   (while before-init-deferred-warnings
4254     (apply 'display-warning (car before-init-deferred-warnings))
4255     (setq before-init-deferred-warnings
4256           (cdr before-init-deferred-warnings))))
4257
4258 (add-hook 'after-init-hook 'after-init-display-warnings)
4259
4260 (defun display-warning (class message &optional level)
4261   "Display a warning message.
4262 CLASS should be a symbol describing what sort of warning this is, such
4263 as `resource' or `key-mapping'.  A list of such symbols is also
4264 accepted. (Individual classes can be suppressed; see
4265 `display-warning-suppressed-classes'.)  Optional argument LEVEL can
4266 be used to specify a priority for the warning, other than default priority
4267 `warning'. (See `display-warning-minimum-level').  The message is
4268 inserted into the *Warnings* buffer, which is made visible at appropriate
4269 times."
4270   (or level (setq level 'warning))
4271   (or (listp class) (setq class (list class)))
4272   (check-argument-type 'warning-level-p level)
4273   (if (and (not (featurep 'infodock))
4274            (not init-file-loaded))
4275       (push (list class message level) before-init-deferred-warnings)
4276     (catch 'ignored
4277       (let ((display-p t)
4278             (level-num (cdr (assq level warning-level-alist))))
4279         (if (< level-num (cdr (assq log-warning-minimum-level
4280                                     warning-level-alist)))
4281             (throw 'ignored nil))
4282         (if (intersection class log-warning-suppressed-classes)
4283             (throw 'ignored nil))
4284
4285         (if (< level-num (cdr (assq display-warning-minimum-level
4286                                     warning-level-alist)))
4287             (setq display-p nil))
4288         (if (and display-p
4289                  (intersection class display-warning-suppressed-classes))
4290             (setq display-p nil))
4291         (let ((buffer (get-buffer-create "*Warnings*")))
4292           (when display-p
4293             ;; The C code looks at display-warning-tick to determine
4294             ;; when it should call `display-warning-buffer'.  Change it
4295             ;; to get the C code's attention.
4296             (incf display-warning-tick))
4297           (with-current-buffer buffer
4298             (goto-char (point-max))
4299             (incf warning-count)
4300             (princ (format "(%d) (%s/%s) "
4301                            warning-count
4302                            (mapconcat 'symbol-name class ",")
4303                            level)
4304                    buffer)
4305             (princ message buffer)
4306             (terpri buffer)
4307             (terpri buffer)))))))
4308
4309 (defun warn (&rest args)
4310   "Display a warning message.
4311 The message is constructed by passing all args to `format'.  The message
4312 is placed in the *Warnings* buffer, which will be popped up at the next
4313 redisplay.  The class of the warning is `warning'.  See also
4314 `display-warning'."
4315   (display-warning 'warning (apply 'format args)))
4316
4317 (defun lwarn (class level &rest args)
4318   "Display a labeled warning message.
4319 CLASS should be a symbol describing what sort of warning this is, such
4320 as `resource' or `key-mapping'.  A list of such symbols is also
4321 accepted. (Individual classes can be suppressed; see
4322 `display-warning-suppressed-classes'.)  If non-nil, LEVEL can be used
4323 to specify a priority for the warning, other than default priority
4324 `warning'. (See `display-warning-minimum-level').  The message is
4325 inserted into the *Warnings* buffer, which is made visible at appropriate
4326 times.
4327
4328 The rest of the arguments are passed to `format'."
4329   (display-warning class (apply 'format args)
4330                    (or level 'warning)))
4331
4332 (defvar warning-marker nil)
4333
4334 ;; When this function is called by the C code, all non-local exits are
4335 ;; trapped and C-g is inhibited; therefore, it would be a very, very
4336 ;; bad idea for this function to get into an infinite loop.
4337
4338 (defun display-warning-buffer ()
4339   "Make the buffer that contains the warnings be visible.
4340 The C code calls this periodically, right before redisplay."
4341   (let ((buffer (get-buffer-create "*Warnings*")))
4342     (when (or (not warning-marker)
4343               (not (eq (marker-buffer warning-marker) buffer)))
4344       (setq warning-marker (make-marker))
4345       (set-marker warning-marker 1 buffer))
4346     (if temp-buffer-show-function
4347         (let ((show-buffer (get-buffer-create "*Warnings-Show*")))
4348           (save-excursion
4349             (set-buffer show-buffer)
4350             (setq buffer-read-only nil)
4351             (erase-buffer))
4352           (save-excursion
4353             (set-buffer buffer)
4354             (copy-to-buffer show-buffer
4355                             (marker-position warning-marker)
4356                             (point-max)))
4357           (funcall temp-buffer-show-function show-buffer))
4358       (set-window-start (display-buffer buffer) warning-marker))
4359     (set-marker warning-marker (point-max buffer) buffer)))
4360
4361 \f
4362 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4363 ;;                                misc junk                              ;;
4364 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4365
4366 (defun emacs-name ()
4367   "Return the printable name of this instance of Emacs."
4368   (cond ((featurep 'infodock) "InfoDock")
4369         ((featurep 'xemacs) "XEmacs")
4370         (t "Emacs")))
4371           
4372 ;;; simple.el ends here