XEmacs 21.2-b1
[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@altair.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 (purecopy "[ \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 (beg 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 beg)
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 beg 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 beg)
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       (if (>= (point) to)
230           (goto-char firstline)
231         (setq at-second t))
232       (move-to-left-margin)
233       ;; XEmacs change
234       (let ((start (point))
235             ; jhod: no longer used?
236             ;(eol (save-excursion (end-of-line) (point)))
237             )
238         (setq result
239               (if (not (looking-at paragraph-start))
240                   (cond ((and adaptive-fill-regexp (looking-at adaptive-fill-regexp))
241                          (buffer-substring-no-properties start (match-end 0)))
242                         (adaptive-fill-function (funcall adaptive-fill-function)))))
243         (and result
244              (or at-second
245                  (null first-line-regexp)
246                  (string-match first-line-regexp result))
247              result)))))
248
249 ;; XEmacs (stig) - this is pulled out of fill-region-as-paragraph so that it
250 ;; can also be called from do-auto-fill
251 ;; #### But it's not used there.  Chuck pulled it out because it broke things.
252 (defun maybe-adapt-fill-prefix (&optional from to dont-skip-first)
253   (if (and adaptive-fill-mode
254            (or (null fill-prefix) (string= fill-prefix "")))
255       (setq fill-prefix (fill-context-prefix from to nil dont-skip-first))))
256
257 (defun fill-region-as-paragraph (from to &optional justify
258                                       nosqueeze squeeze-after)
259   "Fill the region as one paragraph.
260 It removes any paragraph breaks in the region and extra newlines at the end,
261 indents and fills lines between the margins given by the
262 `current-left-margin' and `current-fill-column' functions.
263 It leaves point at the beginning of the line following the paragraph.
264
265 Normally performs justification according to the `current-justification'
266 function, but with a prefix arg, does full justification instead.
267
268 From a program, optional third arg JUSTIFY can specify any type of
269 justification.  Fourth arg NOSQUEEZE non-nil means not to make spaces
270 between words canonical before filling.  Fifth arg SQUEEZE-AFTER, if non-nil,
271 means don't canonicalize spaces before that position.
272
273 If `sentence-end-double-space' is non-nil, then period followed by one
274 space does not end a sentence, so don't break a line there."
275   (interactive
276    (progn
277      ;; XEmacs addition:
278      (barf-if-buffer-read-only nil (region-beginning) (region-end))
279      (list (region-beginning) (region-end)
280            (if current-prefix-arg 'full))))
281   ;; Arrange for undoing the fill to restore point.
282   (if (and buffer-undo-list (not (eq buffer-undo-list t)))
283       (setq buffer-undo-list (cons (point) buffer-undo-list)))
284
285   ;; Make sure "to" is the endpoint.
286   (goto-char (min from to))
287   (setq to   (max from to))
288   ;; Ignore blank lines at beginning of region.
289   (skip-chars-forward " \t\n")
290
291   (let ((from-plus-indent (point))
292         (oneleft nil))
293
294     (beginning-of-line)
295     (setq from (point))
296   
297     ;; Delete all but one soft newline at end of region.
298     ;; And leave TO before that one.
299     (goto-char to)
300     (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
301       (if (and oneleft
302                (not (and use-hard-newlines
303                          (get-text-property (1- (point)) 'hard))))
304           (delete-backward-char 1)
305         (backward-char 1)
306         (setq oneleft t)))
307     (setq to (point))
308
309     ;; If there was no newline, and there is text in the paragraph, then
310     ;; create a newline.
311     (if (and (not oneleft) (> to from-plus-indent))
312         (newline))
313     (goto-char from-plus-indent))
314
315   (if (not (> to (point)))
316       nil ; There is no paragraph, only whitespace: exit now.
317
318     (or justify (setq justify (current-justification)))
319
320     ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
321     (let ((fill-prefix fill-prefix))
322       ;; Figure out how this paragraph is indented, if desired.
323       ;; XEmacs: move some code here to a separate function.
324       (maybe-adapt-fill-prefix from to t)
325
326       (save-restriction
327         (goto-char from)
328         (beginning-of-line)
329         (narrow-to-region (point) to)
330
331         (if (not justify)           ; filling disabled: just check indentation
332             (progn
333               (goto-char from)
334               (while (not (eobp))
335                 (if (and (not (eolp))
336                          (< (current-indentation) (current-left-margin)))
337                     (indent-to-left-margin))
338                 (forward-line 1)))
339
340           (if use-hard-newlines
341               (remove-text-properties from (point-max) '(hard nil)))
342           ;; Make sure first line is indented (at least) to left margin...
343           (if (or (memq justify '(right center))
344                   (< (current-indentation) (current-left-margin)))
345               (indent-to-left-margin))
346           ;; Delete the fill prefix from every line except the first.
347           ;; The first line may not even have a fill prefix.
348           (goto-char from)
349           (let ((fpre (and fill-prefix (not (equal fill-prefix ""))
350                            (concat "[ \t]*"
351                                    (regexp-quote fill-prefix)
352                                    "[ \t]*"))))
353             (and fpre
354                  (progn
355                    (if (>= (+ (current-left-margin) (length fill-prefix))
356                            (current-fill-column))
357                        (error "fill-prefix too long for specified width"))
358                    (goto-char from)
359                    (forward-line 1)
360                    (while (not (eobp))
361                      (if (looking-at fpre)
362                          (delete-region (point) (match-end 0)))
363                      (forward-line 1))
364                    (goto-char from)
365                    (if (looking-at fpre)
366                        (goto-char (match-end 0)))
367                    (setq from (point)))))
368           ;; Remove indentation from lines other than the first.
369           (beginning-of-line 2)
370           (indent-region (point) (point-max) 0)
371           (goto-char from)
372
373           ;; FROM, and point, are now before the text to fill,
374           ;; but after any fill prefix on the first line.
375
376           ;; Make sure sentences ending at end of line get an extra space.
377           ;; loses on split abbrevs ("Mr.\nSmith")
378           (while (re-search-forward "[.?!][])}\"']*$" nil t)
379             ;; XEmacs change (no insert-and-inherit)
380             (or (eobp) (insert ?\  ?\ )))
381           (goto-char from)
382           (skip-chars-forward " \t")
383           ;; Then change all newlines to spaces.
384           ;;; 97/3/14 jhod: Kinsoku change
385           ;; Spacing is not necessary for charcters of no word-separater.
386           ;; The regexp word-across-newline is used for this check.
387           (if (not (and (featurep 'mule)
388                         (stringp word-across-newline)))
389               (subst-char-in-region from (point-max) ?\n ?\ )
390             ;;
391             ;; WAN     +NL+WAN       --> WAN            + WAN
392             ;; not(WAN)+NL+WAN       --> not(WAN)       + WAN
393             ;; WAN     +NL+not(WAN)  --> WAN            + not(WAN)
394             ;; SPC     +NL+not(WAN)  --> SPC            + not(WAN)
395             ;; not(WAN)+NL+not(WAN)  --> not(WAN) + SPC + not(WAN)
396             ;;
397             (goto-char from)
398             (end-of-line)
399             (while (not (eobp))
400               ;; Insert SPC only when point is between nonWAN.  Insert
401               ;; before deleting to preserve marker if possible.
402               (if (or (prog2            ; check following char.
403                           (forward-char)        ; skip newline
404                           (or (eobp)
405                               (looking-at word-across-newline))
406                         (forward-char -1))
407                       (prog2            ; check previous char.
408                           (forward-char -1)
409                           (or (eq (char-after (point)) ?\ )
410                               (looking-at word-across-newline))
411                         (forward-char)))
412                   nil
413                 (insert ?\ ))
414               (delete-char 1)           ; delete newline
415               (end-of-line)))
416           ;; end patch
417           (goto-char from)
418           (skip-chars-forward " \t")
419           (if (and nosqueeze (not (eq justify 'full)))
420               nil
421             (canonically-space-region (or squeeze-after (point)) (point-max))
422             (goto-char (point-max))
423             (delete-horizontal-space)
424             ;; XEmacs change (no insert-and-inherit)
425             (insert " "))
426           (goto-char (point-min))
427
428           ;; This is the actual filling loop.
429           (let ((prefixcol 0) linebeg
430                 (re-break-point (if (featurep 'mule)
431                                     (concat "[ \n\t]\\|" word-across-newline)
432                                   "[ \n\t]")))
433             (while (not (eobp))
434               (setq linebeg (point))
435               (move-to-column (1+ (current-fill-column)))
436               (if (eobp)
437                   (or nosqueeze (delete-horizontal-space))
438                 ;; Move back to start of word.
439                 ;; 97/3/14 jhod: Kinsoku
440                 ;(skip-chars-backward "^ \n" linebeg)
441                 (fill-move-backward-to-break-point re-break-point linebeg)
442                 ;; end patch
443                 ;; Don't break after a period followed by just one space.
444                 ;; Move back to the previous place to break.
445                 ;; The reason is that if a period ends up at the end of a line,
446                 ;; further fills will assume it ends a sentence.
447                 ;; If we now know it does not end a sentence,
448                 ;; avoid putting it at the end of the line.
449                 (if sentence-end-double-space
450                     (while (and (> (point) (+ linebeg 2))
451                                 (eq (char-before (point)) ?\ )
452                                 (not (eq (char-after (point)) ?\ ))
453                                 (eq (char-after (- (point) 2)) ?\.))
454                       (forward-char -2)
455                       ;; 97/3/14 jhod: Kinsoku
456                       ;(skip-chars-backward "^ \n" linebeg)))
457                       (fill-move-backward-to-break-point re-break-point linebeg)))
458                 (if (featurep 'mule) (kinsoku-process))
459                 ;end patch
460
461                 ;; If the left margin and fill prefix by themselves
462                 ;; pass the fill-column. or if they are zero
463                 ;; but we have no room for even one word,
464                 ;; keep at least one word anyway.
465                 ;; This handles ALL BUT the first line of the paragraph.
466                 (if (if (zerop prefixcol)
467                         (save-excursion
468                           (skip-chars-backward " \t" linebeg)
469                           (bolp))
470                       (>= prefixcol (current-column)))
471                     ;; Ok, skip at least one word.
472                     ;; Meanwhile, don't stop at a period followed by one space.
473                     (let ((first t))
474                       (move-to-column prefixcol)
475                       (while (and (not (eobp))
476                                   (or first
477                                       (and (not (bobp))
478                                            sentence-end-double-space
479                                            (save-excursion (forward-char -1)
480                                                            (and (looking-at "\\. ")
481                                                                 (not (looking-at "\\.  ")))))))
482                         (skip-chars-forward " \t")
483                         ;; 94/3/14 jhod: Kinsoku
484                         ;(skip-chars-forward "^ \n\t")
485                         (fill-move-forward-to-break-point re-break-point)
486                         ;; end patch
487                         (setq first nil)))
488                   ;; Normally, move back over the single space between the words.
489                   (if (eq (char-before (point)) ?\ )
490                       (forward-char -1)))
491                 ;; If the left margin and fill prefix by themselves
492                 ;; pass the fill-column, keep at least one word.
493                 ;; This handles the first line of the paragraph.
494                 (if (and (zerop prefixcol)
495                          (let ((fill-point (point)) nchars)
496                            (save-excursion
497                              (move-to-left-margin)
498                              (setq nchars (- fill-point (point)))
499                              (or (< nchars 0)
500                                  (and fill-prefix
501                                       (< nchars (length fill-prefix))
502                                       (string= (buffer-substring (point) fill-point)
503                                                (substring fill-prefix 0 nchars)))))))
504                     ;; Ok, skip at least one word.  But
505                     ;; don't stop at a period followed by just one space.
506                     (let ((first t))
507                       (while (and (not (eobp))
508                                   (or first
509                                       (and (not (bobp))
510                                            sentence-end-double-space
511                                            (save-excursion (forward-char -1)
512                                                            (and (looking-at "\\. ")
513                                                                 (not (looking-at "\\.  ")))))))
514                         (skip-chars-forward " \t")
515                         ;; 97/3/14 jhod: Kinsoku
516                         ;(skip-chars-forward "^ \t\n")
517                         (fill-move-forward-to-break-point re-break-point)
518                         ;; end patch
519                         (setq first nil))))
520                 ;; Check again to see if we got to the end of the paragraph.
521                 (if (save-excursion (skip-chars-forward " \t") (eobp))
522                     (or nosqueeze (delete-horizontal-space))
523                   ;; Replace whitespace here with one newline, then indent to left
524                   ;; margin.
525                   (skip-chars-backward " \t")
526                   ;; 97/3/14 jhod: More kinsoku stuff
527                   (if (featurep 'mule)
528                       ;; WAN means chars which match word-across-newline.
529                       ;; (0)     | SPC + SPC* <EOB>     --> NL
530                       ;; (1) WAN | SPC + SPC*           --> WAN + SPC + NL
531                       ;; (2)     | SPC + SPC* + WAN     --> SPC + NL  + WAN
532                       ;; (3) '.' | SPC + nonSPC         --> '.' + SPC + NL + nonSPC
533                       ;; (4) '.' | SPC + SPC            --> '.' + NL
534                       ;; (5)     | SPC*                 --> NL
535                       (let ((start (point))     ; 92.6.30 by K.Handa
536                             (ch (char-after (point))))
537                         (if (and (= ch ? )
538                                  (progn         ; not case (0) -- 92.6.30 by K.Handa
539                                    (skip-chars-forward " \t")
540                                    (not (eobp)))
541                                  (or
542                                   (progn        ; case (1)
543                                     (goto-char start)
544                                     (forward-char -1)
545                                     (looking-at word-across-newline))
546                                   (progn        ; case (2)
547                                     (goto-char start)
548                                     (skip-chars-forward " \t")
549                                     (and (not (eobp))
550                                          (looking-at word-across-newline)
551                                          ;; never leave space after the end of sentence
552                                          (not (fill-end-of-sentence-p))))
553                                   (progn        ; case (3)
554                                     (goto-char (1+ start))
555                                     (and (not (eobp))
556                                          (not (eq (char-after (point)) ? ))
557                                          (fill-end-of-sentence-p)))))
558                             ;; We should keep one SPACE before NEWLINE. (1),(2),(3)
559                             (goto-char (1+ start))
560                           ;; We should delete all SPACES around break point. (4),(5)
561                           (goto-char start))))
562                   ;; end of patch
563                   (insert ?\n)
564                   ;; Give newline the properties of the space(s) it replaces
565                   (set-text-properties (1- (point)) (point)
566                                        (text-properties-at (point)))
567                   (indent-to-left-margin)
568                   ;; Insert the fill prefix after indentation.
569                   ;; Set prefixcol so whitespace in the prefix won't get lost.
570                   (and fill-prefix (not (equal fill-prefix ""))
571                        (progn
572                          (insert fill-prefix)
573                          (setq prefixcol (current-column))))))
574               ;; Justify the line just ended, if desired.
575               (if justify
576                   (if (save-excursion (skip-chars-forward " \t") (eobp))
577                       (progn
578                         (delete-horizontal-space)
579                         (justify-current-line justify t t))
580                     (forward-line -1)
581                     (justify-current-line justify nil t)
582                     (forward-line 1))))))
583         ;; Leave point after final newline.
584         (goto-char (point-max)))
585     (forward-char 1))))
586
587 (defun fill-paragraph (arg)
588   "Fill paragraph at or after point.  Prefix arg means justify as well.
589 If `sentence-end-double-space' is non-nil, then period followed by one
590 space does not end a sentence, so don't break a line there.
591
592 If `fill-paragraph-function' is non-nil, we call it (passing our
593 argument to it), and if it returns non-nil, we simply return its value."
594   (interactive (list (if current-prefix-arg 'full)))
595   (or (and fill-paragraph-function
596            (let ((function fill-paragraph-function)
597                  fill-paragraph-function)
598              (funcall function arg)))
599       (let ((before (point)))
600         (save-excursion
601           (forward-paragraph)
602           (or (bolp) (newline 1))
603           (let ((end (point))
604                 (beg (progn (backward-paragraph) (point))))
605             (goto-char before)
606             (if use-hard-newlines
607                 ;; Can't use fill-region-as-paragraph, since this paragraph may
608                 ;; still contain hard newlines.  See fill-region.
609                 (fill-region beg end arg)
610               (fill-region-as-paragraph beg end arg)))))))
611
612 (defun fill-region (from to &optional justify nosqueeze to-eop)
613   "Fill each of the paragraphs in the region.
614 Prefix arg (non-nil third arg, if called from program) means justify as well.
615
616 Noninteractively, fourth arg NOSQUEEZE non-nil means to leave
617 whitespace other than line breaks untouched, and fifth arg TO-EOP
618 non-nil means to keep filling to the end of the paragraph (or next
619 hard newline, if `use-hard-newlines' is on).
620
621 If `sentence-end-double-space' is non-nil, then period followed by one
622 space does not end a sentence, so don't break a line there."
623   (interactive
624    (progn
625      ;; XEmacs addition:
626      (barf-if-buffer-read-only nil (region-beginning) (region-end))
627      (list (region-beginning) (region-end)
628            (if current-prefix-arg 'full))))
629   (let (end beg)
630     (save-restriction
631       (goto-char (max from to))
632       (if to-eop
633           (progn (skip-chars-backward "\n")
634                  (forward-paragraph)))
635       (setq end (point))
636       (goto-char (setq beg (min from to)))
637       (beginning-of-line)
638       (narrow-to-region (point) end)
639       (while (not (eobp))
640         (let ((initial (point))
641               end)
642           ;; If using hard newlines, break at every one for filling
643           ;; purposes rather than using paragraph breaks. 
644           (if use-hard-newlines
645               (progn 
646                 (while (and (setq end (text-property-any (point) (point-max)
647                                                          'hard t))
648                             (not (eq ?\n (char-after end)))
649                             (not (= end (point-max))))
650                   (goto-char (1+ end)))
651                 (setq end (if end (min (point-max) (1+ end)) (point-max)))
652                 (goto-char initial))
653             (forward-paragraph 1)
654             (setq end (point))
655             (forward-paragraph -1))
656           (if (< (point) beg)
657               (goto-char beg))
658           (if (>= (point) initial)
659               (fill-region-as-paragraph (point) end justify nosqueeze)
660             (goto-char end)))))))
661
662 ;; XEmacs addition: from Tim Bradshaw <tfb@edinburgh.ac.uk>
663 (defun fill-paragraph-or-region (arg)
664   "Fill the current region, if it's active; otherwise, fill the paragraph.
665 See `fill-paragraph' and `fill-region' for more information."
666   (interactive "*P")
667   (if (region-active-p)
668       (fill-region (point) (mark) arg)
669     (fill-paragraph arg)))
670
671 \f  
672 (defconst default-justification 'left
673   "*Method of justifying text not otherwise specified.
674 Possible values are `left', `right', `full', `center', or `none'.
675 The requested kind of justification is done whenever lines are filled.
676 The `justification' text-property  can locally override this variable.
677 This variable automatically becomes buffer-local when set in any fashion.")
678 (make-variable-buffer-local 'default-justification)
679
680 (defun current-justification ()
681   "How should we justify this line?
682 This returns the value of the text-property `justification',
683 or the variable `default-justification' if there is no text-property.
684 However, it returns nil rather than `none' to mean \"don't justify\"."
685   (let ((j (or (get-text-property 
686                 ;; Make sure we're looking at paragraph body.
687                 (save-excursion (skip-chars-forward " \t") 
688                                 (if (and (eobp) (not (bobp)))
689                                     (1- (point)) (point)))
690                 'justification)
691                default-justification)))
692     (if (eq 'none j)
693         nil
694       j)))
695
696 (defun set-justification (begin end value &optional whole-par)
697   "Set the region's justification style.
698 The kind of justification to use is prompted for.
699 If the mark is not active, this command operates on the current paragraph.
700 If the mark is active, the region is used.  However, if the beginning and end
701 of the region are not at paragraph breaks, they are moved to the beginning and
702 end of the paragraphs they are in.
703 If `use-hard-newlines' is true, all hard newlines are taken to be paragraph
704 breaks.
705
706 When calling from a program, operates just on region between BEGIN and END,
707 unless optional fourth arg WHOLE-PAR is non-nil.  In that case bounds are
708 extended to include entire paragraphs as in the interactive command."
709   ;; XEmacs change (was mark-active)
710   (interactive (list (if (region-active-p) (region-beginning) (point))
711                      (if (region-active-p) (region-end) (point))
712                      (let ((s (completing-read
713                                "Set justification to: "
714                                '(("left") ("right") ("full")
715                                  ("center") ("none"))
716                                nil t)))
717                        (if (equal s "") (error ""))
718                        (intern s))
719                      t))
720   (save-excursion
721     (save-restriction
722       (if whole-par
723           (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
724                 (paragraph-ignore-fill-prefix (if use-hard-newlines t 
725                                                 paragraph-ignore-fill-prefix)))
726             (goto-char begin)
727             (while (and (bolp) (not (eobp))) (forward-char 1))
728             (backward-paragraph)
729             (setq begin (point))
730             (goto-char end)
731             (skip-chars-backward " \t\n" begin)
732             (forward-paragraph)
733             (setq end (point))))
734
735       (narrow-to-region (point-min) end)
736       (unjustify-region begin (point-max))
737       (put-text-property begin (point-max) 'justification value)
738       (fill-region begin (point-max) nil t))))
739
740 (defun set-justification-none (b e)
741   "Disable automatic filling for paragraphs in the region.
742 If the mark is not active, this applies to the current paragraph."
743   ;; XEmacs change (was mark-active)
744   (interactive (list (if (region-active-p) (region-beginning) (point))
745                      (if (region-active-p) (region-end) (point))))
746   (set-justification b e 'none t))
747
748 (defun set-justification-left (b e)
749   "Make paragraphs in the region left-justified.
750 This is usually the default, but see the variable `default-justification'.
751 If the mark is not active, this applies to the current paragraph."
752   ;; XEmacs change (was mark-active)
753   (interactive (list (if (region-active-p) (region-beginning) (point))
754                      (if (region-active-p) (region-end) (point))))
755   (set-justification b e 'left t))
756
757 (defun set-justification-right (b e)
758   "Make paragraphs in the region right-justified:
759 Flush at the right margin and ragged on the left.
760 If the mark is not active, this applies to the current paragraph."
761   ;; XEmacs change (was mark-active)
762   (interactive (list (if (region-active-p) (region-beginning) (point))
763                      (if (region-active-p) (region-end) (point))))
764   (set-justification b e 'right t))
765
766 (defun set-justification-full (b e)
767   "Make paragraphs in the region fully justified:
768 This makes lines flush on both margins by inserting spaces between words.
769 If the mark is not active, this applies to the current paragraph."
770   ;; XEmacs change (was mark-active)
771   (interactive (list (if (region-active-p) (region-beginning) (point))
772                      (if (region-active-p) (region-end) (point))))
773   (set-justification b e 'full t))
774
775 (defun set-justification-center (b e)
776   "Make paragraphs in the region centered.
777 If the mark is not active, this applies to the current paragraph."
778   ;; XEmacs change (was mark-active)
779   (interactive (list (if (region-active-p) (region-beginning) (point))
780                      (if (region-active-p) (region-end) (point))))
781   (set-justification b e 'center t))
782
783 ;; 97/3/14 jhod: This functions are added for Kinsoku support
784 (defun find-space-insertable-point ()
785  "Search backward for a permissable point for inserting justification spaces"
786  (if (boundp 'space-insertable)
787      (if (re-search-backward space-insertable nil t)
788          (progn (forward-char 1)
789                 t)
790        nil)
791    (search-backward " " nil t)))
792
793 ;; A line has up to six parts:
794 ;;
795 ;;           >>>                    hello.                     
796 ;; [Indent-1][FP][    Indent-2     ][text][trailing whitespace][newline]
797 ;;
798 ;; "Indent-1" is the left-margin indentation; normally it ends at column
799 ;;     given by the `current-left-margin' function.
800 ;; "FP" is the fill-prefix.  It can be any string, including whitespace.
801 ;; "Indent-2" is added to justify a line if the `current-justification' is
802 ;;     `center' or `right'.  In `left' and `full' justification regions, any
803 ;;     whitespace there is part of the line's text, and should not be changed.
804 ;; Trailing whitespace is not counted as part of the line length when
805 ;; center- or right-justifying.
806 ;;
807 ;; All parts of the line are optional, although the final newline can 
808 ;;     only be missing on the last line of the buffer.
809
810 (defun justify-current-line (&optional how eop nosqueeze)
811   "Do some kind of justification on this line.
812 Normally does full justification: adds spaces to the line to make it end at
813 the column given by `current-fill-column'.
814 Optional first argument HOW specifies alternate type of justification:
815 it can be `left', `right', `full', `center', or `none'.  
816 If HOW is t, will justify however the `current-justification' function says to.
817 If HOW is nil or missing, full justification is done by default.
818 Second arg EOP non-nil means that this is the last line of the paragraph, so
819 it will not be stretched by full justification.
820 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
821 otherwise it is made canonical."
822   (interactive)
823   (if (eq t how) (setq how (or (current-justification) 'none))
824     (if (null how) (setq how 'full)
825       (or (memq how '(none left right center))
826           (setq how 'full))))
827   (or (memq how '(none left))  ; No action required for these.
828       (let ((fc (current-fill-column))
829             (pos (point-marker))
830             fp-end                      ; point at end of fill prefix
831             beg                         ; point at beginning of line's text
832             end                         ; point at end of line's text
833             indent                      ; column of `beg'
834             endcol                      ; column of `end'
835             ncols)                      ; new indent point or offset
836         (end-of-line)
837         ;; Check if this is the last line of the paragraph.
838         (if (and use-hard-newlines (null eop) 
839                  (get-text-property (point) 'hard))
840             (setq eop t))
841         (skip-chars-backward " \t")
842         ;; Quick exit if it appears to be properly justified already
843         ;; or there is no text.
844         (if (or (bolp)
845                 (and (memq how '(full right))
846                      (= (current-column) fc)))
847             nil
848           (setq end (point))
849           (beginning-of-line)
850           (skip-chars-forward " \t")
851           ;; Skip over fill-prefix.
852           (if (and fill-prefix 
853                    (not (string-equal fill-prefix ""))
854                    (equal fill-prefix
855                           (buffer-substring 
856                            (point) (min (point-max) (+ (length fill-prefix)
857                                                        (point))))))
858               (forward-char (length fill-prefix))
859             (if (and adaptive-fill-mode 
860                      (looking-at adaptive-fill-regexp))
861                 (goto-char (match-end 0))))
862           (setq fp-end (point))
863           (skip-chars-forward " \t")
864           ;; This is beginning of the line's text.
865           (setq indent (current-column))
866           (setq beg (point))
867           (goto-char end)
868           (setq endcol (current-column))
869
870           ;; HOW can't be null or left--we would have exited already
871           (cond ((eq 'right how) 
872                  (setq ncols (- fc endcol))
873                  (if (< ncols 0)
874                      ;; Need to remove some indentation
875                      (delete-region 
876                       (progn (goto-char fp-end)
877                              (if (< (current-column) (+ indent ncols))
878                                  (move-to-column (+ indent ncols) t))
879                              (point))
880                       (progn (move-to-column indent) (point)))
881                    ;; Need to add some
882                    (goto-char beg)
883                    (indent-to (+ indent ncols))
884                    ;; If point was at beginning of text, keep it there.
885                    (if (= beg pos) 
886                        (move-marker pos (point)))))
887
888                 ((eq 'center how)
889                  ;; Figure out how much indentation is needed
890                  (setq ncols (+ (current-left-margin)
891                                 (/ (- fc (current-left-margin) ;avail. space
892                                       (- endcol indent)) ;text width
893                                    2)))
894                  (if (< ncols indent)
895                      ;; Have too much indentation - remove some
896                      (delete-region
897                       (progn (goto-char fp-end)
898                              (if (< (current-column) ncols)
899                                  (move-to-column ncols t))
900                              (point))
901                       (progn (move-to-column indent) (point)))
902                    ;; Have too little - add some
903                    (goto-char beg)
904                    (indent-to ncols)
905                    ;; If point was at beginning of text, keep it there.
906                    (if (= beg pos)
907                        (move-marker pos (point)))))
908
909                 ((eq 'full how)
910                  ;; Insert extra spaces between words to justify line
911                  (save-restriction
912                    (narrow-to-region beg end)
913                    (or nosqueeze
914                        (canonically-space-region beg end))
915                    (goto-char (point-max))
916                    (setq ncols (- fc endcol))
917                    ;; Ncols is number of additional spaces needed
918                    (if (> ncols 0)
919                        (if (and (not eop)
920                                 ;; 97/3/14 jhod: Kinsoku
921                                 (find-space-insertable-point)) ;(search-backward " " nil t))
922                            (while (> ncols 0)
923                              (let ((nmove (+ 3 (random 3))))
924                                (while (> nmove 0)
925                                  (or (find-space-insertable-point) ;(search-backward " " nil t)
926                                      (progn
927                                        (goto-char (point-max))
928                                        (find-space-insertable-point))) ;(search-backward " ")))
929                                  (skip-chars-backward " ")
930                                  (setq nmove (1- nmove))))
931                              ;; XEmacs change
932                              (insert " ")
933                              (skip-chars-backward " ")
934                              (setq ncols (1- ncols)))))))
935                 (t (error "Unknown justification value"))))
936         (goto-char pos)
937         (move-marker pos nil)))
938   nil)
939
940 (defun unjustify-current-line ()
941   "Remove justification whitespace from current line.
942 If the line is centered or right-justified, this function removes any
943 indentation past the left margin.  If the line is full-justified, it removes
944 extra spaces between words.  It does nothing in other justification modes."
945   (let ((justify (current-justification)))
946     (cond ((eq 'left justify) nil)
947           ((eq  nil  justify) nil)
948           ((eq 'full justify)           ; full justify: remove extra spaces
949            (beginning-of-line-text)
950            (canonically-space-region
951             (point) (save-excursion (end-of-line) (point))))
952           ((memq justify '(center right))
953            (save-excursion
954              (move-to-left-margin nil t)
955              ;; Position ourselves after any fill-prefix.
956              (if (and fill-prefix 
957                       (not (string-equal fill-prefix ""))
958                       (equal fill-prefix
959                              (buffer-substring 
960                               (point) (min (point-max) (+ (length fill-prefix)
961                                                           (point))))))
962                  (forward-char (length fill-prefix)))
963              (delete-region (point) (progn (skip-chars-forward " \t")
964                                            (point))))))))
965
966 (defun unjustify-region (&optional begin end)
967   "Remove justification whitespace from region.
968 For centered or right-justified regions, this function removes any indentation
969 past the left margin from each line.  For full-justified lines, it removes 
970 extra spaces between words.  It does nothing in other justification modes.
971 Arguments BEGIN and END are optional; default is the whole buffer."
972   (save-excursion
973     (save-restriction
974       (if end (narrow-to-region (point-min) end))
975       (goto-char (or begin (point-min)))
976       (while (not (eobp))
977         (unjustify-current-line)
978         (forward-line 1)))))
979
980 \f
981 (defun fill-nonuniform-paragraphs (min max &optional justifyp mailp)
982   "Fill paragraphs within the region, allowing varying indentation within each.
983 This command divides the region into \"paragraphs\",
984 only at paragraph-separator lines, then fills each paragraph
985 using as the fill prefix the smallest indentation of any line
986 in the paragraph.
987
988 When calling from a program, pass range to fill as first two arguments.
989
990 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
991 JUSTIFY to justify paragraphs (prefix arg),
992 MAIL-FLAG for a mail message, i. e. don't fill header lines."
993   (interactive (list (region-beginning) (region-end)
994                      (if current-prefix-arg 'full)))
995   (let ((fill-individual-varying-indent t))
996     (fill-individual-paragraphs min max justifyp mailp)))
997
998 (defun fill-individual-paragraphs (min max &optional justify mailp)
999   "Fill paragraphs of uniform indentation within the region.
1000 This command divides the region into \"paragraphs\",
1001 treating every change in indentation level as a paragraph boundary,
1002 then fills each paragraph using its indentation level as the fill prefix.
1003
1004 When calling from a program, pass range to fill as first two arguments.
1005
1006 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1007 JUSTIFY to justify paragraphs (prefix arg),
1008 MAIL-FLAG for a mail message, i. e. don't fill header lines."
1009   (interactive (list (region-beginning) (region-end)
1010                      (if current-prefix-arg 'full)))
1011   (save-restriction
1012     (save-excursion
1013       (goto-char min)
1014       (beginning-of-line)
1015       (narrow-to-region (point) max)
1016       (if mailp 
1017           (while (and (not (eobp))
1018                       (or (looking-at "[ \t]*[^ \t\n]+:")
1019                           (looking-at "[ \t]*$")))
1020             (if (looking-at "[ \t]*[^ \t\n]+:")
1021                 (search-forward "\n\n" nil 'move)
1022                 (forward-line 1))))
1023       (narrow-to-region (point) max)
1024       ;; Loop over paragraphs.
1025       (while (progn (skip-chars-forward " \t\n") (not (eobp)))
1026         (move-to-left-margin)
1027         (let ((start (point))
1028               fill-prefix fill-prefix-regexp)
1029           ;; Find end of paragraph, and compute the smallest fill-prefix
1030           ;; that fits all the lines in this paragraph.
1031           (while (progn
1032                    ;; Update the fill-prefix on the first line
1033                    ;; and whenever the prefix good so far is too long.
1034                    (if (not (and fill-prefix
1035                                  (looking-at fill-prefix-regexp)))
1036                        (setq fill-prefix
1037                              (if (and adaptive-fill-mode adaptive-fill-regexp
1038                                       (looking-at adaptive-fill-regexp))
1039                                  (match-string 0)
1040                                (buffer-substring 
1041                                 (point)
1042                                 (save-excursion (skip-chars-forward " \t")
1043                                                 (point))))
1044                              fill-prefix-regexp (regexp-quote fill-prefix)))
1045                    (forward-line 1)
1046                    (if (bolp)
1047                        ;; If forward-line went past a newline
1048                        ;; move further to the left margin.
1049                        (move-to-left-margin))
1050                    ;; Now stop the loop if end of paragraph.
1051                    (and (not (eobp))
1052                         (if fill-individual-varying-indent
1053                             ;; If this line is a separator line, with or
1054                             ;; without prefix, end the paragraph.
1055                             (and 
1056                              (not (looking-at paragraph-separate))
1057                              (save-excursion
1058                                (not (and (looking-at fill-prefix-regexp)
1059                                          ;; XEmacs change
1060                                          (progn
1061                                            (forward-char (length fill-prefix))
1062                                            (looking-at paragraph-separate))))))
1063                             ;; If this line has more or less indent
1064                             ;; than the fill prefix wants, end the paragraph.
1065                             (and (looking-at fill-prefix-regexp)
1066                                  (save-excursion
1067                                    (not
1068                                     (progn
1069                                       (forward-char (length fill-prefix))
1070                                       (or (looking-at paragraph-separate)
1071                                           (looking-at paragraph-start))))))))))
1072           ;; Fill this paragraph, but don't add a newline at the end.
1073           (let ((had-newline (bolp)))
1074             (fill-region-as-paragraph start (point) justify)
1075             (or had-newline (delete-char -1))))))))
1076
1077 ;;; fill.el ends here