import xemacs-21.2.37
[chise/xemacs-chise.git.1] / lisp / fill.el
1 ;;; fill.el --- fill commands for XEmacs.
2
3 ;; Copyright (C) 1985, 86, 92, 94, 95, 1997 Free Software Foundation, Inc.
4
5 ;; Maintainer: XEmacs Development Team
6 ;; Keywords: wp, dumped
7
8 ;; This file is part of XEmacs.
9
10 ;; XEmacs is free software; you can redistribute it and/or modify it
11 ;; under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; XEmacs is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
22 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23 ;; 02111-1307, USA.
24
25 ;;; Synched up with: FSF 19.34.
26
27 ;;; Commentary:
28
29 ;; This file is dumped with XEmacs.
30
31 ;; All the commands for filling text.  These are documented in the XEmacs
32 ;; Reference Manual.
33
34 ;; 97/3/14 Jareth Hein (jhod@po.iijnet.or.jp) added functions for kinsoku (asian text
35 ;; line break processing)
36 ;; 97/06/11 Steve Baur (steve@xemacs.org) converted broken
37 ;;  following-char/preceding-char calls to char-after/char-before.
38
39 ;;; Code:
40
41 (defgroup fill nil
42   "Indenting and filling text."
43   :group 'editing)
44
45 (defcustom fill-individual-varying-indent nil
46   "*Controls criterion for a new paragraph in `fill-individual-paragraphs'.
47 Non-nil means changing indent doesn't end a paragraph.
48 That mode can handle paragraphs with extra indentation on the first line,
49 but it requires separator lines between paragraphs.
50 A value of nil means that any change in indentation starts a new paragraph."
51   :type 'boolean
52   :group 'fill)
53
54 (defcustom sentence-end-double-space t
55   "*Non-nil means a single space does not end a sentence.
56 This variable applies only to filling, not motion commands.  To
57 change the behavior of motion commands, see `sentence-end'."
58   :type 'boolean
59   :group 'fill)
60
61 (defcustom colon-double-space nil
62   "*Non-nil means put two spaces after a colon when filling."
63   :type 'boolean
64   :group 'fill)
65
66 (defvar fill-paragraph-function nil
67   "Mode-specific function to fill a paragraph, or nil if there is none.
68 If the function returns nil, then `fill-paragraph' does its normal work.")
69
70 (defun set-fill-prefix ()
71   "Set the fill prefix to the current line up to point.
72 Filling expects lines to start with the fill prefix and
73 reinserts the fill prefix in each resulting line."
74   (interactive)
75   (setq fill-prefix (buffer-substring
76                      (save-excursion (move-to-left-margin) (point))
77                      (point)))
78   (if (equal fill-prefix "")
79       (setq fill-prefix nil))
80   (if fill-prefix
81       (message "fill-prefix: \"%s\"" fill-prefix)
82     (message "fill-prefix cancelled")))
83
84 (defcustom adaptive-fill-mode t
85   "*Non-nil means determine a paragraph's fill prefix from its text."
86   :type 'boolean
87   :group 'fill)
88
89 ;; #### - this is still weak.  Yeah, there's filladapt, but this should
90 ;; still be better...  --Stig
91 (defcustom adaptive-fill-regexp "[ \t]*\\([#;>*]+ +\\)?"
92   "*Regexp to match text at start of line that constitutes indentation.
93 If Adaptive Fill mode is enabled, whatever text matches this pattern
94 on the second line of a paragraph is used as the standard indentation
95 for the paragraph.  If the paragraph has just one line, the indentation
96 is taken from that line."
97   :type 'regexp
98   :group 'fill)
99
100 (defcustom adaptive-fill-function nil
101   "*Function to call to choose a fill prefix for a paragraph.
102 This function is used when `adaptive-fill-regexp' does not match."
103   :type 'function
104   :group 'fill)
105
106 ;; Added for kinsoku processing. Use this instead of
107 ;; (skip-chars-backward "^ \t\n")
108 ;; (skip-chars-backward "^ \n" linebeg)
109 (defun fill-move-backward-to-break-point (regexp &optional lim)
110   (let ((opoint (point)))
111     ;; 93.8.23 by kawamoto@ics.es.osaka-u.ac.jp
112     ;;  case of first 'word' being longer than fill-column
113     (if (not (re-search-backward regexp lim 'move))
114         nil
115       ;; we have skipped backward SPC or WAN (word-across-newline).  So move point forward again.
116       (forward-char)
117       (if (< opoint (point))
118           (forward-char -1)))))
119
120 ;; Added for kinsoku processing. Use instead of
121 ;; (re-search-forward "[ \t]" opoint t)
122 ;; (skip-chars-forward "^ \n")
123 ;; (skip-chars-forward "^ \n")
124 (defun fill-move-forward-to-break-point (regexp &optional lim)
125   (let ((opoint (point)))
126     (if (not (re-search-forward regexp lim 'move))
127         nil
128       (forward-char -1)
129       (if (< (point) opoint)
130           (forward-char))))
131   (if (featurep 'mule) (kinsoku-process-extend)))
132
133 (defun fill-end-of-sentence-p ()
134   (save-excursion
135     (skip-chars-backward " ]})\"'")
136     (memq (char-before (point)) '(?. ?? ?!))))
137
138 (defun current-fill-column ()
139   "Return the fill-column to use for this line.
140 The fill-column to use for a buffer is stored in the variable `fill-column',
141 but can be locally modified by the `right-margin' text property, which is
142 subtracted from `fill-column'.
143
144 The fill column to use for a line is the first column at which the column
145 number equals or exceeds the local fill-column - right-margin difference."
146   (save-excursion
147     (if fill-column
148         (let* ((here (progn (beginning-of-line) (point)))
149                (here-col 0)
150                (eol (progn (end-of-line) (point)))
151                margin fill-col change col)
152           ;; Look separately at each region of line with a different right-margin.
153           (while (and (setq margin (get-text-property here 'right-margin)
154                             fill-col (- fill-column (or margin 0))
155                             change (text-property-not-all
156                                     here eol 'right-margin margin))
157                       (progn (goto-char (1- change))
158                              (setq col (current-column))
159                              (< col fill-col)))
160             (setq here change
161                   here-col col))
162           (max here-col fill-col)))))
163
164 (defun canonically-space-region (start end)
165   "Remove extra spaces between words in region.
166 Leave one space between words, two at end of sentences or after colons
167 \(depending on values of `sentence-end-double-space' and `colon-double-space').
168 Remove indentation from each line."
169   (interactive "r")
170   ;;;### 97/3/14 jhod: Do I have to add anything here for kinsoku?
171   (save-excursion
172     (goto-char start)
173     ;; XEmacs - (ENE/stig from fa-extras.el): Skip the start of a comment.
174     (and comment-start-skip
175          (looking-at comment-start-skip)
176          (goto-char (match-end 0)))
177     ;; Nuke tabs; they get screwed up in a fill.
178     ;; This is quick, but loses when a tab follows the end of a sentence.
179     ;; Actually, it is difficult to tell that from "Mr.\tSmith".
180     ;; Blame the typist.
181     (subst-char-in-region start end ?\t ?\ )
182     (while (and (< (point) end)
183                 (re-search-forward "   *" end t))
184       (delete-region
185        (+ (match-beginning 0)
186           ;; Determine number of spaces to leave:
187           (save-excursion
188             (skip-chars-backward " ]})\"'")
189             (cond ((and sentence-end-double-space
190                         (memq (char-before (point)) '(?. ?? ?!)))  2)
191                   ((and colon-double-space
192                         (eq (char-before (point)) ?:))  2)
193                   ((char-equal (char-before (point)) ?\n)  0)
194                   (t 1))))
195        (match-end 0)))
196     ;; Make sure sentences ending at end of line get an extra space.
197     ;; loses on split abbrevs ("Mr.\nSmith")
198     (goto-char start)
199     (while (and (< (point) end)
200                 (re-search-forward "[.?!][])}\"']*$" end t))
201       ;; We insert before markers in case a caller such as
202       ;; do-auto-fill has done a save-excursion with point at the end
203       ;; of the line and wants it to stay at the end of the line.
204       (insert ? ))))
205 ;; XEmacs: we don't have this function.
206 ;; (insert-before-markers-and-inherit ? ))))
207
208 ;; XEmacs -- added DONT-SKIP-FIRST.  Port of older code changes by Stig.
209 ;; #### probably this junk is broken -- do-auto-fill doesn't actually use
210 ;; it.  If so, it should be removed.
211
212 (defun fill-context-prefix (from to &optional first-line-regexp
213                                  dont-skip-first)
214   "Compute a fill prefix from the text between FROM and TO.
215 This uses the variables `adaptive-fill-prefix' and `adaptive-fill-function'.
216 If FIRST-LINE-REGEXP is non-nil, then when taking a prefix from the
217 first line, insist it must match FIRST-LINE-REGEXP."
218   (save-excursion
219     (goto-char from)
220     (if (eolp) (forward-line 1))
221     ;; Move to the second line unless there is just one.
222     (let ((firstline (point))
223           ;; Non-nil if we are on the second line.
224           at-second
225           result)
226       ;; XEmacs change
227       (if (not dont-skip-first)
228           (forward-line 1))
229       (cond ((>= (point) to)
230              (goto-char firstline))
231             ((/= (point) from)
232              (setq at-second t)))
233       (move-to-left-margin)
234       ;; XEmacs change
235       (let ((start (point))
236             ; jhod: no longer used?
237             ;(eol (save-excursion (end-of-line) (point)))
238             )
239         (setq result
240               (if (or dont-skip-first (not (looking-at paragraph-start)))
241                   (cond ((and adaptive-fill-regexp (looking-at adaptive-fill-regexp))
242                          (buffer-substring-no-properties start (match-end 0)))
243                         (adaptive-fill-function (funcall adaptive-fill-function)))))
244         (and result
245              (or at-second
246                  (null first-line-regexp)
247                  (string-match first-line-regexp result))
248              result)))))
249
250 ;; XEmacs (stig) - this is pulled out of fill-region-as-paragraph so that it
251 ;; can also be called from do-auto-fill
252 ;; #### But it's not used there.  Chuck pulled it out because it broke things.
253 (defun maybe-adapt-fill-prefix (&optional from to dont-skip-first)
254   (if (and adaptive-fill-mode
255            (or (null fill-prefix) (string= fill-prefix "")))
256       (setq fill-prefix (fill-context-prefix from to nil dont-skip-first))))
257
258 (defun fill-region-as-paragraph (from to &optional justify
259                                       nosqueeze squeeze-after)
260   "Fill the region as one paragraph.
261 It removes any paragraph breaks in the region and extra newlines at the end,
262 indents and fills lines between the margins given by the
263 `current-left-margin' and `current-fill-column' functions.
264 It leaves point at the beginning of the line following the paragraph.
265
266 Normally performs justification according to the `current-justification'
267 function, but with a prefix arg, does full justification instead.
268
269 From a program, optional third arg JUSTIFY can specify any type of
270 justification.  Fourth arg NOSQUEEZE non-nil means not to make spaces
271 between words canonical before filling.  Fifth arg SQUEEZE-AFTER, if non-nil,
272 means don't canonicalize spaces before that position.
273
274 If `sentence-end-double-space' is non-nil, then period followed by one
275 space does not end a sentence, so don't break a line there."
276   (interactive
277    (progn
278      ;; XEmacs addition:
279      (barf-if-buffer-read-only nil (region-beginning) (region-end))
280      (list (region-beginning) (region-end)
281            (if current-prefix-arg 'full))))
282   ;; Arrange for undoing the fill to restore point.
283   (if (and buffer-undo-list (not (eq buffer-undo-list t)))
284       (setq buffer-undo-list (cons (point) buffer-undo-list)))
285
286   ;; Make sure "to" is the endpoint.
287   (goto-char (min from to))
288   (setq to   (max from to))
289   ;; Ignore blank lines at beginning of region.
290   (skip-chars-forward " \t\n")
291
292   (let ((from-plus-indent (point))
293         (oneleft nil))
294
295     (beginning-of-line)
296     (setq from (point))
297
298     ;; Delete all but one soft newline at end of region.
299     ;; And leave TO before that one.
300     (goto-char to)
301     (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
302       (if (and oneleft
303                (not (and use-hard-newlines
304                          (get-text-property (1- (point)) 'hard))))
305           (delete-backward-char 1)
306         (backward-char 1)
307         (setq oneleft t)))
308     (setq to (point))
309
310     ;; If there was no newline, and there is text in the paragraph, then
311     ;; create a newline.
312     (if (and (not oneleft) (> to from-plus-indent))
313         (newline))
314     (goto-char from-plus-indent))
315
316   (if (not (> to (point)))
317       nil ; There is no paragraph, only whitespace: exit now.
318
319     (or justify (setq justify (current-justification)))
320
321     ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
322     (let ((fill-prefix fill-prefix))
323       ;; Figure out how this paragraph is indented, if desired.
324       ;; XEmacs: move some code here to a separate function.
325       (maybe-adapt-fill-prefix from to t)
326
327       (save-restriction
328         (goto-char from)
329         (beginning-of-line)
330         (narrow-to-region (point) to)
331
332         (if (not justify)           ; filling disabled: just check indentation
333             (progn
334               (goto-char from)
335               (while (not (eobp))
336                 (if (and (not (eolp))
337                          (< (current-indentation) (current-left-margin)))
338                     (indent-to-left-margin))
339                 (forward-line 1)))
340
341           (if use-hard-newlines
342               (remove-text-properties from (point-max) '(hard nil)))
343           ;; Make sure first line is indented (at least) to left margin...
344           (if (or (memq justify '(right center))
345                   (< (current-indentation) (current-left-margin)))
346               (indent-to-left-margin))
347           ;; Delete the fill prefix from every line except the first.
348           ;; The first line may not even have a fill prefix.
349           (goto-char from)
350           (let ((fpre (and fill-prefix (not (equal fill-prefix ""))
351                            (concat "[ \t]*"
352                                    (regexp-quote fill-prefix)
353                                    "[ \t]*"))))
354             (and fpre
355                  (progn
356                    (if (>= (+ (current-left-margin) (length fill-prefix))
357                            (current-fill-column))
358                        (error "fill-prefix too long for specified width"))
359                    (goto-char from)
360                    (forward-line 1)
361                    (while (not (eobp))
362                      (if (looking-at fpre)
363                          (delete-region (point) (match-end 0)))
364                      (forward-line 1))
365                    (goto-char from)
366                    (if (looking-at fpre)
367                        (goto-char (match-end 0)))
368                    (setq from (point)))))
369           ;; Remove indentation from lines other than the first.
370           (beginning-of-line 2)
371           (indent-region (point) (point-max) 0)
372           (goto-char from)
373
374           ;; FROM, and point, are now before the text to fill,
375           ;; but after any fill prefix on the first line.
376
377           ;; Make sure sentences ending at end of line get an extra space.
378           ;; loses on split abbrevs ("Mr.\nSmith")
379           (while (re-search-forward "[.?!][])}\"']*$" nil t)
380             ;; XEmacs change (no insert-and-inherit)
381             (or (eobp) (insert ?\  ?\ )))
382           (goto-char from)
383           (skip-chars-forward " \t")
384           ;; Then change all newlines to spaces.
385           ;;; 97/3/14 jhod: Kinsoku change
386           ;; Spacing is not necessary for characters of no word-separator.
387           ;; The regexp word-across-newline is used for this check.
388           (defvar word-across-newline)
389           (if (not (and (featurep 'mule)
390                         (stringp word-across-newline)))
391               (subst-char-in-region from (point-max) ?\n ?\ )
392             ;;
393             ;; WAN     +NL+WAN       --> WAN            + WAN
394             ;; not(WAN)+NL+WAN       --> not(WAN)       + WAN
395             ;; WAN     +NL+not(WAN)  --> WAN            + not(WAN)
396             ;; SPC     +NL+not(WAN)  --> SPC            + not(WAN)
397             ;; not(WAN)+NL+not(WAN)  --> not(WAN) + SPC + not(WAN)
398             ;;
399             (goto-char from)
400             (end-of-line)
401             (while (not (eobp))
402               ;; Insert SPC only when point is between nonWAN.  Insert
403               ;; before deleting to preserve marker if possible.
404               (if (or (prog2            ; check following char.
405                           (forward-char)        ; skip newline
406                           (or (eobp)
407                               (looking-at word-across-newline))
408                         (forward-char -1))
409                       (prog2            ; check previous char.
410                           (forward-char -1)
411                           (or (eq (char-after (point)) ?\ )
412                               (looking-at word-across-newline))
413                         (forward-char)))
414                   nil
415                 (insert ?\ ))
416               (delete-char 1)           ; delete newline
417               (end-of-line)))
418           ;; end patch
419           (goto-char from)
420           (skip-chars-forward " \t")
421           (if (and nosqueeze (not (eq justify 'full)))
422               nil
423             (canonically-space-region (or squeeze-after (point)) (point-max))
424             (goto-char (point-max))
425             (delete-horizontal-space)
426             ;; XEmacs change (no insert-and-inherit)
427             (insert " "))
428           (goto-char (point-min))
429
430           ;; This is the actual filling loop.
431           (let ((prefixcol 0) linebeg
432                 (re-break-point (if (featurep 'mule)
433                                     (concat "[ \n\t]\\|" word-across-newline
434                                             ".\\|." word-across-newline)
435                                   "[ \n\t]")))
436             (while (not (eobp))
437               (setq linebeg (point))
438               (move-to-column (1+ (current-fill-column)))
439               (if (eobp)
440                   (or nosqueeze (delete-horizontal-space))
441                 ;; Move back to start of word.
442                 ;; 97/3/14 jhod: Kinsoku
443                 ;(skip-chars-backward "^ \n" linebeg)
444                 (fill-move-backward-to-break-point re-break-point linebeg)
445                 ;; end patch
446                 ;; Don't break after a period followed by just one space.
447                 ;; Move back to the previous place to break.
448                 ;; The reason is that if a period ends up at the end of a line,
449                 ;; further fills will assume it ends a sentence.
450                 ;; If we now know it does not end a sentence,
451                 ;; avoid putting it at the end of the line.
452                 (if sentence-end-double-space
453                     (while (and (> (point) (+ linebeg 2))
454                                 (eq (char-before (point)) ?\ )
455                                 (not (eq (char-after (point)) ?\ ))
456                                 (eq (char-after (- (point) 2)) ?\.))
457                       (forward-char -2)
458                       ;; 97/3/14 jhod: Kinsoku
459                       ;(skip-chars-backward "^ \n" linebeg)))
460                       (fill-move-backward-to-break-point re-break-point linebeg)))
461                 (if (featurep 'mule) (kinsoku-process))
462                 ;end patch
463
464                 ;; If the left margin and fill prefix by themselves
465                 ;; pass the fill-column. or if they are zero
466                 ;; but we have no room for even one word,
467                 ;; keep at least one word anyway.
468                 ;; This handles ALL BUT the first line of the paragraph.
469                 (if (if (zerop prefixcol)
470                         (save-excursion
471                           (skip-chars-backward " \t" linebeg)
472                           (bolp))
473                       (>= prefixcol (current-column)))
474                     ;; Ok, skip at least one word.
475                     ;; Meanwhile, don't stop at a period followed by one space.
476                     (let ((first t))
477                       (move-to-column prefixcol)
478                       (while (and (not (eobp))
479                                   (or first
480                                       (and (not (bobp))
481                                            sentence-end-double-space
482                                            (save-excursion (forward-char -1)
483                                                            (and (looking-at "\\. ")
484                                                                 (not (looking-at "\\.  ")))))))
485                         (skip-chars-forward " \t")
486                         ;; 94/3/14 jhod: Kinsoku
487                         ;(skip-chars-forward "^ \n\t")
488                         (fill-move-forward-to-break-point re-break-point)
489                         ;; end patch
490                         (setq first nil)))
491                   ;; Normally, move back over the single space between the words.
492                   (if (eq (char-before (point)) ?\ )
493                       (forward-char -1)))
494                 ;; If the left margin and fill prefix by themselves
495                 ;; pass the fill-column, keep at least one word.
496                 ;; This handles the first line of the paragraph.
497                 (if (and (zerop prefixcol)
498                          (let ((fill-point (point)) nchars)
499                            (save-excursion
500                              (move-to-left-margin)
501                              (setq nchars (- fill-point (point)))
502                              (or (< nchars 0)
503                                  (and fill-prefix
504                                       (< nchars (length fill-prefix))
505                                       (string= (buffer-substring (point) fill-point)
506                                                (substring fill-prefix 0 nchars)))))))
507                     ;; Ok, skip at least one word.  But
508                     ;; don't stop at a period followed by just one space.
509                     (let ((first t))
510                       (while (and (not (eobp))
511                                   (or first
512                                       (and (not (bobp))
513                                            sentence-end-double-space
514                                            (save-excursion (forward-char -1)
515                                                            (and (looking-at "\\. ")
516                                                                 (not (looking-at "\\.  ")))))))
517                         (skip-chars-forward " \t")
518                         ;; 97/3/14 jhod: Kinsoku
519                         ;(skip-chars-forward "^ \t\n")
520                         (fill-move-forward-to-break-point re-break-point)
521                         ;; end patch
522                         (setq first nil))))
523                 ;; Check again to see if we got to the end of the paragraph.
524                 (if (save-excursion (skip-chars-forward " \t") (eobp))
525                     (or nosqueeze (delete-horizontal-space))
526                   ;; Replace whitespace here with one newline, then indent to left
527                   ;; margin.
528                   (skip-chars-backward " \t")
529                   ;; 97/3/14 jhod: More kinsoku stuff
530                   (if (featurep 'mule)
531                       ;; WAN means chars which match word-across-newline.
532                       ;; (0)     | SPC + SPC* <EOB>     --> NL
533                       ;; (1) WAN | SPC + SPC*           --> WAN + SPC + NL
534                       ;; (2)     | SPC + SPC* + WAN     --> SPC + NL  + WAN
535                       ;; (3) '.' | SPC + nonSPC         --> '.' + SPC + NL + nonSPC
536                       ;; (4) '.' | SPC + SPC            --> '.' + NL
537                       ;; (5)     | SPC*                 --> NL
538                       (let ((start (point))     ; 92.6.30 by K.Handa
539                             (ch (char-after (point))))
540                         (if (and (= ch ? )
541                                  (progn         ; not case (0) -- 92.6.30 by K.Handa
542                                    (skip-chars-forward " \t")
543                                    (not (eobp)))
544                                  (or
545                                   (progn        ; case (1)
546                                     (goto-char start)
547                                     (forward-char -1)
548                                     (looking-at word-across-newline))
549                                   (progn        ; case (2)
550                                     (goto-char start)
551                                     (skip-chars-forward " \t")
552                                     (and (not (eobp))
553                                          (looking-at word-across-newline)
554                                          ;; never leave space after the end of sentence
555                                          (not (fill-end-of-sentence-p))))
556                                   (progn        ; case (3)
557                                     (goto-char (1+ start))
558                                     (and (not (eobp))
559                                          (not (eq (char-after (point)) ? ))
560                                          (fill-end-of-sentence-p)))))
561                             ;; We should keep one SPACE before NEWLINE. (1),(2),(3)
562                             (goto-char (1+ start))
563                           ;; We should delete all SPACES around break point. (4),(5)
564                           (goto-char start))))
565                   ;; end of patch
566                   (insert ?\n)
567                   ;; Give newline the properties of the space(s) it replaces
568                   (set-text-properties (1- (point)) (point)
569                                        (text-properties-at (point)))
570                   (indent-to-left-margin)
571                   ;; Insert the fill prefix after indentation.
572                   ;; Set prefixcol so whitespace in the prefix won't get lost.
573                   (and fill-prefix (not (equal fill-prefix ""))
574                        (progn
575                          (insert fill-prefix)
576                          (setq prefixcol (current-column))))))
577               ;; Justify the line just ended, if desired.
578               (if justify
579                   (if (save-excursion (skip-chars-forward " \t") (eobp))
580                       (progn
581                         (delete-horizontal-space)
582                         (justify-current-line justify t t))
583                     (forward-line -1)
584                     (justify-current-line justify nil t)
585                     (forward-line 1))))))
586         ;; Leave point after final newline.
587         (goto-char (point-max)))
588     (forward-char 1))))
589
590 (defun fill-paragraph (arg)
591   "Fill paragraph at or after point.  Prefix arg means justify as well.
592 If `sentence-end-double-space' is non-nil, then period followed by one
593 space does not end a sentence, so don't break a line there.
594
595 If `fill-paragraph-function' is non-nil, we call it (passing our
596 argument to it), and if it returns non-nil, we simply return its value."
597   (interactive (list (if current-prefix-arg 'full)))
598   (or (and fill-paragraph-function
599            (let ((function fill-paragraph-function)
600                  fill-paragraph-function)
601              (funcall function arg)))
602       (let ((before (point)))
603         (save-excursion
604           (forward-paragraph)
605           (or (bolp) (newline 1))
606           (let ((end (point))
607                 (start (progn (backward-paragraph) (point))))
608             (goto-char before)
609             (if use-hard-newlines
610                 ;; Can't use fill-region-as-paragraph, since this paragraph may
611                 ;; still contain hard newlines.  See fill-region.
612                 (fill-region start end arg)
613               (fill-region-as-paragraph start end arg)))))))
614
615 (defun fill-region (from to &optional justify nosqueeze to-eop)
616   "Fill each of the paragraphs in the region.
617 Prefix arg (non-nil third arg, if called from program) means justify as well.
618
619 Noninteractively, fourth arg NOSQUEEZE non-nil means to leave
620 whitespace other than line breaks untouched, and fifth arg TO-EOP
621 non-nil means to keep filling to the end of the paragraph (or next
622 hard newline, if `use-hard-newlines' is on).
623
624 If `sentence-end-double-space' is non-nil, then period followed by one
625 space does not end a sentence, so don't break a line there."
626   (interactive
627    (progn
628      ;; XEmacs addition:
629      (barf-if-buffer-read-only nil (region-beginning) (region-end))
630      (list (region-beginning) (region-end)
631            (if current-prefix-arg 'full))))
632   (let (end start)
633     (save-restriction
634       (goto-char (max from to))
635       (if to-eop
636           (progn (skip-chars-backward "\n")
637                  (forward-paragraph)))
638       (setq end (point))
639       (goto-char (setq start (min from to)))
640       (beginning-of-line)
641       (narrow-to-region (point) end)
642       (while (not (eobp))
643         (let ((initial (point))
644               end)
645           ;; If using hard newlines, break at every one for filling
646           ;; purposes rather than using paragraph breaks.
647           (if use-hard-newlines
648               (progn
649                 (while (and (setq end (text-property-any (point) (point-max)
650                                                          'hard t))
651                             (not (eq ?\n (char-after end)))
652                             (not (= end (point-max))))
653                   (goto-char (1+ end)))
654                 (setq end (if end (min (point-max) (1+ end)) (point-max)))
655                 (goto-char initial))
656             (forward-paragraph 1)
657             (setq end (point))
658             (forward-paragraph -1))
659           (if (< (point) start)
660               (goto-char start))
661           (if (>= (point) initial)
662               (fill-region-as-paragraph (point) end justify nosqueeze)
663             (goto-char end)))))))
664
665 ;; XEmacs addition: from Tim Bradshaw <tfb@edinburgh.ac.uk>
666 (defun fill-paragraph-or-region (arg)
667   "Fill the current region, if it's active; otherwise, fill the paragraph.
668 See `fill-paragraph' and `fill-region' for more information."
669   (interactive "*P")
670   (if (region-active-p)
671       (fill-region (point) (mark) arg)
672     (fill-paragraph arg)))
673
674 \f
675 (defconst default-justification 'left
676   "*Method of justifying text not otherwise specified.
677 Possible values are `left', `right', `full', `center', or `none'.
678 The requested kind of justification is done whenever lines are filled.
679 The `justification' text-property  can locally override this variable.
680 This variable automatically becomes buffer-local when set in any fashion.")
681 (make-variable-buffer-local 'default-justification)
682
683 (defun current-justification ()
684   "How should we justify this line?
685 This returns the value of the text-property `justification',
686 or the variable `default-justification' if there is no text-property.
687 However, it returns nil rather than `none' to mean \"don't justify\"."
688   (let ((j (or (get-text-property
689                 ;; Make sure we're looking at paragraph body.
690                 (save-excursion (skip-chars-forward " \t")
691                                 (if (and (eobp) (not (bobp)))
692                                     (1- (point)) (point)))
693                 'justification)
694                default-justification)))
695     (if (eq 'none j)
696         nil
697       j)))
698
699 (defun set-justification (begin end value &optional whole-par)
700   "Set the region's justification style.
701 The kind of justification to use is prompted for.
702 If the mark is not active, this command operates on the current paragraph.
703 If the mark is active, the region is used.  However, if the beginning and end
704 of the region are not at paragraph breaks, they are moved to the beginning and
705 end of the paragraphs they are in.
706 If `use-hard-newlines' is true, all hard newlines are taken to be paragraph
707 breaks.
708
709 When calling from a program, operates just on region between BEGIN and END,
710 unless optional fourth arg WHOLE-PAR is non-nil.  In that case bounds are
711 extended to include entire paragraphs as in the interactive command."
712   ;; XEmacs change (was mark-active)
713   (interactive (list (if (region-active-p) (region-beginning) (point))
714                      (if (region-active-p) (region-end) (point))
715                      (let ((s (completing-read
716                                "Set justification to: "
717                                '(("left") ("right") ("full")
718                                  ("center") ("none"))
719                                nil t)))
720                        (if (equal s "") (error ""))
721                        (intern s))
722                      t))
723   (save-excursion
724     (save-restriction
725       (if whole-par
726           (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
727                 (paragraph-ignore-fill-prefix (if use-hard-newlines t
728                                                 paragraph-ignore-fill-prefix)))
729             (goto-char begin)
730             (while (and (bolp) (not (eobp))) (forward-char 1))
731             (backward-paragraph)
732             (setq begin (point))
733             (goto-char end)
734             (skip-chars-backward " \t\n" begin)
735             (forward-paragraph)
736             (setq end (point))))
737
738       (narrow-to-region (point-min) end)
739       (unjustify-region begin (point-max))
740       (put-text-property begin (point-max) 'justification value)
741       (fill-region begin (point-max) nil t))))
742
743 (defun set-justification-none (b e)
744   "Disable automatic filling for paragraphs in the region.
745 If the mark is not active, this applies to the current paragraph."
746   ;; XEmacs change (was mark-active)
747   (interactive (list (if (region-active-p) (region-beginning) (point))
748                      (if (region-active-p) (region-end) (point))))
749   (set-justification b e 'none t))
750
751 (defun set-justification-left (b e)
752   "Make paragraphs in the region left-justified.
753 This is usually the default, but see the variable `default-justification'.
754 If the mark is not active, this applies to the current paragraph."
755   ;; XEmacs change (was mark-active)
756   (interactive (list (if (region-active-p) (region-beginning) (point))
757                      (if (region-active-p) (region-end) (point))))
758   (set-justification b e 'left t))
759
760 (defun set-justification-right (b e)
761   "Make paragraphs in the region right-justified:
762 Flush at the right margin and ragged on the left.
763 If the mark is not active, this applies to the current paragraph."
764   ;; XEmacs change (was mark-active)
765   (interactive (list (if (region-active-p) (region-beginning) (point))
766                      (if (region-active-p) (region-end) (point))))
767   (set-justification b e 'right t))
768
769 (defun set-justification-full (b e)
770   "Make paragraphs in the region fully justified:
771 This makes lines flush on both margins by inserting spaces between words.
772 If the mark is not active, this applies to the current paragraph."
773   ;; XEmacs change (was mark-active)
774   (interactive (list (if (region-active-p) (region-beginning) (point))
775                      (if (region-active-p) (region-end) (point))))
776   (set-justification b e 'full t))
777
778 (defun set-justification-center (b e)
779   "Make paragraphs in the region centered.
780 If the mark is not active, this applies to the current paragraph."
781   ;; XEmacs change (was mark-active)
782   (interactive (list (if (region-active-p) (region-beginning) (point))
783                      (if (region-active-p) (region-end) (point))))
784   (set-justification b e 'center t))
785
786 ;; 97/3/14 jhod: This functions are added for Kinsoku support
787 (defun find-space-insertable-point ()
788  "Search backward for a permissible point for inserting justification spaces."
789  (if (boundp 'space-insertable)
790      (if (re-search-backward space-insertable nil t)
791          (progn (forward-char 1)
792                 t)
793        nil)
794    (search-backward " " nil t)))
795
796 ;; A line has up to six parts:
797 ;;
798 ;;           >>>                    hello.
799 ;; [Indent-1][FP][    Indent-2     ][text][trailing whitespace][newline]
800 ;;
801 ;; "Indent-1" is the left-margin indentation; normally it ends at column
802 ;;     given by the `current-left-margin' function.
803 ;; "FP" is the fill-prefix.  It can be any string, including whitespace.
804 ;; "Indent-2" is added to justify a line if the `current-justification' is
805 ;;     `center' or `right'.  In `left' and `full' justification regions, any
806 ;;     whitespace there is part of the line's text, and should not be changed.
807 ;; Trailing whitespace is not counted as part of the line length when
808 ;; center- or right-justifying.
809 ;;
810 ;; All parts of the line are optional, although the final newline can
811 ;;     only be missing on the last line of the buffer.
812
813 (defun justify-current-line (&optional how eop nosqueeze)
814   "Do some kind of justification on this line.
815 Normally does full justification: adds spaces to the line to make it end at
816 the column given by `current-fill-column'.
817 Optional first argument HOW specifies alternate type of justification:
818 it can be `left', `right', `full', `center', or `none'.
819 If HOW is t, will justify however the `current-justification' function says to.
820 If HOW is nil or missing, full justification is done by default.
821 Second arg EOP non-nil means that this is the last line of the paragraph, so
822 it will not be stretched by full justification.
823 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
824 otherwise it is made canonical."
825   (interactive)
826   (if (eq t how) (setq how (or (current-justification) 'none))
827     (if (null how) (setq how 'full)
828       (or (memq how '(none left right center))
829           (setq how 'full))))
830   (or (memq how '(none left))  ; No action required for these.
831       (let ((fc (current-fill-column))
832             (pos (point-marker))
833             fp-end                      ; point at end of fill prefix
834             start                               ; point at beginning of line's text
835             end                         ; point at end of line's text
836             indent                      ; column of `start'
837             endcol                      ; column of `end'
838             ncols)                      ; new indent point or offset
839         (end-of-line)
840         ;; Check if this is the last line of the paragraph.
841         (if (and use-hard-newlines (null eop)
842                  (get-text-property (point) 'hard))
843             (setq eop t))
844         (skip-chars-backward " \t")
845         ;; Quick exit if it appears to be properly justified already
846         ;; or there is no text.
847         (if (or (bolp)
848                 (and (memq how '(full right))
849                      (= (current-column) fc)))
850             nil
851           (setq end (point))
852           (beginning-of-line)
853           (skip-chars-forward " \t")
854           ;; Skip over fill-prefix.
855           (if (and fill-prefix
856                    (not (string-equal fill-prefix ""))
857                    (equal fill-prefix
858                           (buffer-substring
859                            (point) (min (point-max) (+ (length fill-prefix)
860                                                        (point))))))
861               (forward-char (length fill-prefix))
862             (if (and adaptive-fill-mode
863                      (looking-at adaptive-fill-regexp))
864                 (goto-char (match-end 0))))
865           (setq fp-end (point))
866           (skip-chars-forward " \t")
867           ;; This is beginning of the line's text.
868           (setq indent (current-column))
869           (setq start (point))
870           (goto-char end)
871           (setq endcol (current-column))
872
873           ;; HOW can't be null or left--we would have exited already
874           (cond ((eq 'right how)
875                  (setq ncols (- fc endcol))
876                  (if (< ncols 0)
877                      ;; Need to remove some indentation
878                      (delete-region
879                       (progn (goto-char fp-end)
880                              (if (< (current-column) (+ indent ncols))
881                                  (move-to-column (+ indent ncols) t))
882                              (point))
883                       (progn (move-to-column indent) (point)))
884                    ;; Need to add some
885                    (goto-char start)
886                    (indent-to (+ indent ncols))
887                    ;; If point was at beginning of text, keep it there.
888                    (if (= start pos)
889                        (move-marker pos (point)))))
890
891                 ((eq 'center how)
892                  ;; Figure out how much indentation is needed
893                  (setq ncols (+ (current-left-margin)
894                                 (/ (- fc (current-left-margin) ;avail. space
895                                       (- endcol indent)) ;text width
896                                    2)))
897                  (if (< ncols indent)
898                      ;; Have too much indentation - remove some
899                      (delete-region
900                       (progn (goto-char fp-end)
901                              (if (< (current-column) ncols)
902                                  (move-to-column ncols t))
903                              (point))
904                       (progn (move-to-column indent) (point)))
905                    ;; Have too little - add some
906                    (goto-char start)
907                    (indent-to ncols)
908                    ;; If point was at beginning of text, keep it there.
909                    (if (= start pos)
910                        (move-marker pos (point)))))
911
912                 ((eq 'full how)
913                  ;; Insert extra spaces between words to justify line
914                  (save-restriction
915                    (narrow-to-region start end)
916                    (or nosqueeze
917                        (canonically-space-region start end))
918                    (goto-char (point-max))
919                    (setq ncols (- fc endcol))
920                    ;; Ncols is number of additional spaces needed
921                    (if (> ncols 0)
922                        (if (and (not eop)
923                                 ;; 97/3/14 jhod: Kinsoku
924                                 (find-space-insertable-point)) ;(search-backward " " nil t))
925                            (while (> ncols 0)
926                              (let ((nmove (+ 3 (random 3))))
927                                (while (> nmove 0)
928                                  (or (find-space-insertable-point) ;(search-backward " " nil t)
929                                      (progn
930                                        (goto-char (point-max))
931                                        (find-space-insertable-point))) ;(search-backward " ")))
932                                  (skip-chars-backward " ")
933                                  (setq nmove (1- nmove))))
934                              ;; XEmacs change
935                              (insert " ")
936                              (skip-chars-backward " ")
937                              (setq ncols (1- ncols)))))))
938                 (t (error "Unknown justification value"))))
939         (goto-char pos)
940         (move-marker pos nil)))
941   nil)
942
943 (defun unjustify-current-line ()
944   "Remove justification whitespace from current line.
945 If the line is centered or right-justified, this function removes any
946 indentation past the left margin.  If the line is full-justified, it removes
947 extra spaces between words.  It does nothing in other justification modes."
948   (let ((justify (current-justification)))
949     (cond ((eq 'left justify) nil)
950           ((eq  nil  justify) nil)
951           ((eq 'full justify)           ; full justify: remove extra spaces
952            (beginning-of-line-text)
953            (canonically-space-region
954             (point) (save-excursion (end-of-line) (point))))
955           ((memq justify '(center right))
956            (save-excursion
957              (move-to-left-margin nil t)
958              ;; Position ourselves after any fill-prefix.
959              (if (and fill-prefix
960                       (not (string-equal fill-prefix ""))
961                       (equal fill-prefix
962                              (buffer-substring
963                               (point) (min (point-max) (+ (length fill-prefix)
964                                                           (point))))))
965                  (forward-char (length fill-prefix)))
966              (delete-region (point) (progn (skip-chars-forward " \t")
967                                            (point))))))))
968
969 (defun unjustify-region (&optional begin end)
970   "Remove justification whitespace from region.
971 For centered or right-justified regions, this function removes any indentation
972 past the left margin from each line.  For full-justified lines, it removes
973 extra spaces between words.  It does nothing in other justification modes.
974 Arguments BEGIN and END are optional; default is the whole buffer."
975   (save-excursion
976     (save-restriction
977       (if end (narrow-to-region (point-min) end))
978       (goto-char (or begin (point-min)))
979       (while (not (eobp))
980         (unjustify-current-line)
981         (forward-line 1)))))
982
983 \f
984 (defun fill-nonuniform-paragraphs (min max &optional justifyp mailp)
985   "Fill paragraphs within the region, allowing varying indentation within each.
986 This command divides the region into \"paragraphs\",
987 only at paragraph-separator lines, then fills each paragraph
988 using as the fill prefix the smallest indentation of any line
989 in the paragraph.
990
991 When calling from a program, pass range to fill as first two arguments.
992
993 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
994 JUSTIFY to justify paragraphs (prefix arg),
995 MAIL-FLAG for a mail message, i. e. don't fill header lines."
996   (interactive (list (region-beginning) (region-end)
997                      (if current-prefix-arg 'full)))
998   (let ((fill-individual-varying-indent t))
999     (fill-individual-paragraphs min max justifyp mailp)))
1000
1001 (defun fill-individual-paragraphs (min max &optional justify mailp)
1002   "Fill paragraphs of uniform indentation within the region.
1003 This command divides the region into \"paragraphs\",
1004 treating every change in indentation level as a paragraph boundary,
1005 then fills each paragraph using its indentation level as the fill prefix.
1006
1007 When calling from a program, pass range to fill as first two arguments.
1008
1009 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1010 JUSTIFY to justify paragraphs (prefix arg),
1011 MAIL-FLAG for a mail message, i. e. don't fill header lines."
1012   (interactive (list (region-beginning) (region-end)
1013                      (if current-prefix-arg 'full)))
1014   (save-restriction
1015     (save-excursion
1016       (goto-char min)
1017       (beginning-of-line)
1018       (narrow-to-region (point) max)
1019       (if mailp
1020           (while (and (not (eobp))
1021                       (or (looking-at "[ \t]*[^ \t\n]+:")
1022                           (looking-at "[ \t]*$")))
1023             (if (looking-at "[ \t]*[^ \t\n]+:")
1024                 (search-forward "\n\n" nil 'move)
1025                 (forward-line 1))))
1026       (narrow-to-region (point) max)
1027       ;; Loop over paragraphs.
1028       (while (progn (skip-chars-forward " \t\n") (not (eobp)))
1029         (move-to-left-margin)
1030         (let ((start (point))
1031               fill-prefix fill-prefix-regexp)
1032           ;; Find end of paragraph, and compute the smallest fill-prefix
1033           ;; that fits all the lines in this paragraph.
1034           (while (progn
1035                    ;; Update the fill-prefix on the first line
1036                    ;; and whenever the prefix good so far is too long.
1037                    (if (not (and fill-prefix
1038                                  (looking-at fill-prefix-regexp)))
1039                        (setq fill-prefix
1040                              (if (and adaptive-fill-mode adaptive-fill-regexp
1041                                       (looking-at adaptive-fill-regexp))
1042                                  (match-string 0)
1043                                (buffer-substring
1044                                 (point)
1045                                 (save-excursion (skip-chars-forward " \t")
1046                                                 (point))))
1047                              fill-prefix-regexp (regexp-quote fill-prefix)))
1048                    (forward-line 1)
1049                    (if (bolp)
1050                        ;; If forward-line went past a newline
1051                        ;; move further to the left margin.
1052                        (move-to-left-margin))
1053                    ;; Now stop the loop if end of paragraph.
1054                    (and (not (eobp))
1055                         (if fill-individual-varying-indent
1056                             ;; If this line is a separator line, with or
1057                             ;; without prefix, end the paragraph.
1058                             (and
1059                              (not (looking-at paragraph-separate))
1060                              (save-excursion
1061                                (not (and (looking-at fill-prefix-regexp)
1062                                          ;; XEmacs change
1063                                          (progn
1064                                            (forward-char (length fill-prefix))
1065                                            (looking-at paragraph-separate))))))
1066                             ;; If this line has more or less indent
1067                             ;; than the fill prefix wants, end the paragraph.
1068                             (and (looking-at fill-prefix-regexp)
1069                                  (save-excursion
1070                                    (not
1071                                     (progn
1072                                       (forward-char (length fill-prefix))
1073                                       (or (looking-at paragraph-separate)
1074                                           (looking-at paragraph-start))))))))))
1075           ;; Fill this paragraph, but don't add a newline at the end.
1076           (let ((had-newline (bolp)))
1077             (fill-region-as-paragraph start (point) justify)
1078             (or had-newline (delete-char -1))))))))
1079
1080 ;;; fill.el ends here