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