*** empty log message ***
[emacs.git] / lisp / textmodes / fill.el
blobcce52b0d60bf6044d0da78247e4651d1540ce7cd
1 ;;; fill.el --- fill commands for Emacs
3 ;; Copyright (C) 1985,86,92,94,95,96,97,1999,2001,2002
4 ;; Free Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Keywords: wp
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;; All the commands for filling text. These are documented in the Emacs
29 ;; manual.
31 ;;; Code:
33 (defcustom fill-individual-varying-indent nil
34 "*Controls criterion for a new paragraph in `fill-individual-paragraphs'.
35 Non-nil means changing indent doesn't end a paragraph.
36 That mode can handle paragraphs with extra indentation on the first line,
37 but it requires separator lines between paragraphs.
38 A value of nil means that any change in indentation starts a new paragraph."
39 :type 'boolean
40 :group 'fill)
42 (defcustom colon-double-space nil
43 "*Non-nil means put two spaces after a colon when filling."
44 :type 'boolean
45 :group 'fill)
47 (defvar fill-paragraph-function nil
48 "Mode-specific function to fill a paragraph, or nil if there is none.
49 If the function returns nil, then `fill-paragraph' does its normal work.")
51 (defvar fill-paragraph-handle-comment t
52 "If non-nil, paragraph filling will try to pay attention to comments.")
54 (defvar enable-kinsoku t
55 "*Non-nil means enable \"kinsoku\" processing on filling paragraph.
56 Kinsoku processing is designed to prevent certain characters from being
57 placed at the beginning or end of a line by filling.
58 See the documentation of `kinsoku' for more information.")
60 (defun set-fill-prefix ()
61 "Set the fill prefix to the current line up to point.
62 Filling expects lines to start with the fill prefix and
63 reinserts the fill prefix in each resulting line."
64 (interactive)
65 (let ((left-margin-pos (save-excursion (move-to-left-margin) (point))))
66 (if (> (point) left-margin-pos)
67 (progn
68 (setq fill-prefix (buffer-substring left-margin-pos (point)))
69 (if (equal fill-prefix "")
70 (setq fill-prefix nil)))
71 (setq fill-prefix nil)))
72 (if fill-prefix
73 (message "fill-prefix: \"%s\"" fill-prefix)
74 (message "fill-prefix cancelled")))
76 (defcustom adaptive-fill-mode t
77 "*Non-nil means determine a paragraph's fill prefix from its text."
78 :type 'boolean
79 :group 'fill)
81 (defcustom adaptive-fill-regexp
82 ;; Added `!' for doxygen comments starting with `//!' or `/*!'.
83 ;; Added `%' for TeX comments.
84 (purecopy "[ \t]*\\([-!|#%;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*")
85 "*Regexp to match text at start of line that constitutes indentation.
86 If Adaptive Fill mode is enabled, a prefix matching this pattern
87 on the first and second lines of a paragraph is used as the
88 standard indentation for the whole paragraph.
90 If the paragraph has just one line, the indentation is taken from that
91 line, but in that case `adaptive-fill-first-line-regexp' also plays
92 a role."
93 :type 'regexp
94 :group 'fill)
96 (defcustom adaptive-fill-first-line-regexp "\\`[ \t]*\\'"
97 "*Regexp specifying whether to set fill prefix from a one-line paragraph.
98 When a paragraph has just one line, then after `adaptive-fill-regexp'
99 finds the prefix at the beginning of the line, if it doesn't
100 match this regexp, it is replaced with whitespace.
102 By default, this regexp matches sequences of just spaces and tabs.
104 However, we never use a prefix from a one-line paragraph
105 if it would act as a paragraph-starter on the second line."
106 :type 'regexp
107 :group 'fill)
109 (defcustom adaptive-fill-function nil
110 "*Function to call to choose a fill prefix for a paragraph, or nil.
111 This function is used when `adaptive-fill-regexp' does not match."
112 :type '(choice (const nil) function)
113 :group 'fill)
115 (defvar fill-indent-according-to-mode nil ;Screws up CC-mode's filling tricks.
116 "Whether or not filling should try to use the major mode's indentation.")
118 (defun current-fill-column ()
119 "Return the fill-column to use for this line.
120 The fill-column to use for a buffer is stored in the variable `fill-column',
121 but can be locally modified by the `right-margin' text property, which is
122 subtracted from `fill-column'.
124 The fill column to use for a line is the first column at which the column
125 number equals or exceeds the local fill-column - right-margin difference."
126 (save-excursion
127 (if fill-column
128 (let* ((here (progn (beginning-of-line) (point)))
129 (here-col 0)
130 (eol (progn (end-of-line) (point)))
131 margin fill-col change col)
132 ;; Look separately at each region of line with a different
133 ;; right-margin.
134 (while (and (setq margin (get-text-property here 'right-margin)
135 fill-col (- fill-column (or margin 0))
136 change (text-property-not-all
137 here eol 'right-margin margin))
138 (progn (goto-char (1- change))
139 (setq col (current-column))
140 (< col fill-col)))
141 (setq here change
142 here-col col))
143 (max here-col fill-col)))))
145 (defun canonically-space-region (beg end)
146 "Remove extra spaces between words in region.
147 Leave one space between words, two at end of sentences or after colons
148 \(depending on values of `sentence-end-double-space', `colon-double-space',
149 and `sentence-end-without-period').
150 Remove indentation from each line."
151 (interactive "*r")
152 (let ((end-spc-re (concat "\\(" sentence-end "\\) *\\| +")))
153 (save-excursion
154 (goto-char beg)
155 ;; Nuke tabs; they get screwed up in a fill.
156 ;; This is quick, but loses when a tab follows the end of a sentence.
157 ;; Actually, it is difficult to tell that from "Mr.\tSmith".
158 ;; Blame the typist.
159 (subst-char-in-region beg end ?\t ?\ )
160 (while (and (< (point) end)
161 (re-search-forward end-spc-re end t))
162 (delete-region
163 (cond
164 ;; `sentence-end' matched and did not match all spaces.
165 ;; I.e. it only matched the number of spaces it needs: drop the rest.
166 ((and (match-end 1) (> (match-end 0) (match-end 1))) (match-end 1))
167 ;; `sentence-end' matched but with nothing left. Either that means
168 ;; nothing should be removed, or it means it's the "old-style"
169 ;; sentence-end which matches all it can. Keep only 2 spaces.
170 ;; We probably don't even need to check `sentence-end-double-space'.
171 ((match-end 1)
172 (min (match-end 0)
173 (+ (if sentence-end-double-space 2 1)
174 (save-excursion (goto-char (match-end 0))
175 (skip-chars-backward " ")
176 (point)))))
177 (t ;; It's not an end of sentence.
178 (+ (match-beginning 0)
179 ;; Determine number of spaces to leave:
180 (save-excursion
181 (skip-chars-backward " ]})\"'")
182 (cond ((and sentence-end-double-space
183 (or (memq (preceding-char) '(?. ?? ?!))
184 (and sentence-end-without-period
185 (= (char-syntax (preceding-char)) ?w)))) 2)
186 ((and colon-double-space
187 (= (preceding-char) ?:)) 2)
188 ((char-equal (preceding-char) ?\n) 0)
189 (t 1))))))
190 (match-end 0))))))
192 (defun fill-common-string-prefix (s1 s2)
193 "Return the longest common prefix of strings S1 and S2, or nil if none."
194 (let ((cmp (compare-strings s1 nil nil s2 nil nil)))
195 (if (eq cmp t)
197 (setq cmp (1- (abs cmp)))
198 (unless (zerop cmp)
199 (substring s1 0 cmp)))))
201 (defun fill-context-prefix (from to &optional first-line-regexp)
202 "Compute a fill prefix from the text between FROM and TO.
203 This uses the variables `adaptive-fill-regexp' and `adaptive-fill-function'
204 and `adaptive-fill-first-line-regexp'. `paragraph-start' also plays a role;
205 we reject a prefix based on a one-line paragraph if that prefix would
206 act as a paragraph-separator."
207 (or first-line-regexp
208 (setq first-line-regexp adaptive-fill-first-line-regexp))
209 (save-excursion
210 (goto-char from)
211 (if (eolp) (forward-line 1))
212 ;; Move to the second line unless there is just one.
213 (move-to-left-margin)
214 (let ((firstline (point))
215 first-line-prefix
216 ;; Non-nil if we are on the second line.
217 second-line-prefix
218 start)
219 (setq start (point))
220 (setq first-line-prefix
221 ;; We don't need to consider `paragraph-start' here since it
222 ;; will be explicitly checked later on.
223 ;; Also setting first-line-prefix to nil prevents
224 ;; second-line-prefix from being used.
225 (cond ;; ((looking-at paragraph-start) nil)
226 ((and adaptive-fill-regexp (looking-at adaptive-fill-regexp))
227 (match-string-no-properties 0))
228 (adaptive-fill-function (funcall adaptive-fill-function))))
229 (forward-line 1)
230 (if (< (point) to)
231 (progn
232 (move-to-left-margin)
233 (setq start (point))
234 (setq second-line-prefix
235 (cond ((looking-at paragraph-start) nil) ;Can it happen ? -stef
236 ((and adaptive-fill-regexp
237 (looking-at adaptive-fill-regexp))
238 (buffer-substring-no-properties start (match-end 0)))
239 (adaptive-fill-function
240 (funcall adaptive-fill-function))))
241 ;; If we get a fill prefix from the second line,
242 ;; make sure it or something compatible is on the first line too.
243 (when second-line-prefix
244 (unless first-line-prefix (setq first-line-prefix ""))
245 ;; If the non-whitespace chars match the first line,
246 ;; just use it (this subsumes the 2 checks used previously).
247 ;; Used when first line is `/* ...' and second-line is
248 ;; ` * ...'.
249 (let ((tmp second-line-prefix)
250 (re "\\`"))
251 (while (string-match "\\`[ \t]*\\([^ \t]+\\)" tmp)
252 (setq re (concat re ".*" (regexp-quote (match-string 1 tmp))))
253 (setq tmp (substring tmp (match-end 0))))
254 ;; (assert (string-match "\\`[ \t]*\\'" tmp))
256 (if (string-match re first-line-prefix)
257 second-line-prefix
259 ;; Use the longest common substring of both prefixes,
260 ;; if there is one.
261 (fill-common-string-prefix first-line-prefix
262 second-line-prefix)))))
263 ;; If we get a fill prefix from a one-line paragraph,
264 ;; maybe change it to whitespace,
265 ;; and check that it isn't a paragraph starter.
266 (if first-line-prefix
267 (let ((result
268 ;; If first-line-prefix comes from the first line,
269 ;; see if it seems reasonable to use for all lines.
270 ;; If not, replace it with whitespace.
271 (if (or (and first-line-regexp
272 (string-match first-line-regexp
273 first-line-prefix))
274 (and comment-start-skip
275 (string-match comment-start-skip
276 first-line-prefix)))
277 first-line-prefix
278 (make-string (string-width first-line-prefix) ?\ ))))
279 ;; But either way, reject it if it indicates the start
280 ;; of a paragraph when text follows it.
281 (if (not (eq 0 (string-match paragraph-start
282 (concat result "a"))))
283 result)))))))
285 (defun fill-single-word-nobreak-p ()
286 "Don't break a line after the first or before the last word of a sentence."
287 (or (looking-at "[ \t]*\\sw+[ \t]*[.?!:][ \t]*$")
288 (save-excursion
289 (skip-chars-backward " \t")
290 (and (/= (skip-syntax-backward "w") 0)
291 (/= (skip-chars-backward " \t") 0)
292 (/= (skip-chars-backward ".?!:") 0)))))
294 (defun fill-french-nobreak-p ()
295 "Return nil if French style allows breaking the line at point.
296 This is used in `fill-nobreak-predicate' to prevent breaking lines just
297 after an opening paren or just before a closing paren or a punctuation
298 mark such as `?' or `:'. It is common in French writing to put a space
299 at such places, which would normally allow breaking the line at those
300 places."
301 (or (looking-at "[ \t]*[])}»?!;:-]")
302 (save-excursion
303 (skip-chars-backward " \t")
304 (unless (bolp)
305 (backward-char 1)
306 (or (looking-at "[([{«]")
307 ;; Don't cut right after a single-letter word.
308 (and (memq (preceding-char) '(?\t ?\ ))
309 (eq (char-syntax (following-char)) ?w)))))))
311 (defcustom fill-nobreak-predicate nil
312 "List of predicates for recognizing places not to break a line.
313 The predicates are called with no arguments, with point at the place to
314 be tested. If it returns t, fill commands do not break the line there."
315 :group 'fill
316 :type 'hook
317 :options '(fill-french-nobreak-p fill-single-word-nobreak-p))
319 (defcustom fill-nobreak-invisible nil
320 "Non-nil means that fill command do not break lines in invisible text."
321 :type 'boolean
322 :group 'fill)
324 (defun fill-nobreak-p ()
325 "Return nil if breaking the line at point is allowed.
326 Can be customized with the variables `fill-nobreak-predicate'
327 and `fill-nobreak-invisible'."
329 (and fill-nobreak-invisible (line-move-invisible (point)))
330 (unless (bolp)
332 ;; Don't break after a period followed by just one space.
333 ;; Move back to the previous place to break.
334 ;; The reason is that if a period ends up at the end of a
335 ;; line, further fills will assume it ends a sentence.
336 ;; If we now know it does not end a sentence, avoid putting
337 ;; it at the end of the line.
338 (and sentence-end-double-space
339 (save-excursion
340 (skip-chars-backward ". ")
341 (looking-at "\\. \\([^ ]\\|$\\)")))
342 ;; Another approach to the same problem.
343 (save-excursion
344 (skip-chars-backward ". ")
345 (and (looking-at "\\.")
346 (not (looking-at sentence-end))))
347 ;; Don't split a line if the rest would look like a new paragraph.
348 (unless use-hard-newlines
349 (save-excursion
350 (skip-chars-forward " \t") (looking-at paragraph-start)))
351 (run-hook-with-args-until-success 'fill-nobreak-predicate)))))
353 ;; Put `fill-find-break-point-function' property to charsets which
354 ;; require special functions to find line breaking point.
355 (dolist (pair '((katakana-jisx0201 . kinsoku)
356 (chinese-gb2312 . kinsoku)
357 (japanese-jisx0208 . kinsoku)
358 (japanese-jisx0212 . kinsoku)
359 (chinese-big5-1 . kinsoku)
360 (chinese-big5-2 . kinsoku)))
361 (put-charset-property (car pair) 'fill-find-break-point-function (cdr pair)))
363 (defun fill-find-break-point (limit)
364 "Move point to a proper line breaking position of the current line.
365 Don't move back past the buffer position LIMIT.
367 This function is called when we are going to break the current line
368 after or before a non-ascii character. If the charset of the
369 character has the property `fill-find-break-point-function', this
370 function calls the property value as a function with one arg LINEBEG.
371 If the charset has no such property, do nothing."
372 (let* ((ch (following-char))
373 (charset (char-charset ch))
374 func)
375 (if (eq charset 'ascii)
376 (setq ch (preceding-char)
377 charset (char-charset ch)))
378 (if (charsetp charset)
379 (setq func
380 (get-charset-property charset 'fill-find-break-point-function)))
381 (if (and func (fboundp func))
382 (funcall func limit))))
384 (defun fill-delete-prefix (from to prefix)
385 "Delete the fill prefix from every line except the first.
386 The first line may not even have a fill prefix.
387 Point is moved to just past the fill prefix on the first line."
388 (let ((fpre (if (and prefix (not (string-match "\\`[ \t]*\\'" prefix)))
389 (concat "[ \t]*\\("
390 (replace-regexp-in-string
391 "[ \t]+" "[ \t]*"
392 (regexp-quote prefix))
393 "\\)?[ \t]*")
394 "[ \t]*")))
395 (goto-char from)
396 (if (>= (+ (current-left-margin) (length prefix))
397 (current-fill-column))
398 (error "fill-prefix too long for specified width"))
399 (forward-line 1)
400 (while (< (point) to)
401 (if (looking-at fpre)
402 (delete-region (point) (match-end 0)))
403 (forward-line 1))
404 (goto-char from)
405 (if (looking-at fpre)
406 (goto-char (match-end 0)))
407 (setq from (point))))
409 (defun fill-delete-newlines (from to justify nosqueeze squeeze-after)
410 (goto-char from)
411 ;; Make sure sentences ending at end of line get an extra space.
412 ;; loses on split abbrevs ("Mr.\nSmith")
413 (let ((eol-double-space-re
414 (cond
415 ((not colon-double-space) (concat sentence-end "$"))
416 ;; Try to add the : inside the `sentence-end' regexp.
417 ((string-match "\\[[^][]*\\(\\.\\)[^][]*\\]" sentence-end)
418 (concat (replace-match ".:" nil nil sentence-end 1) "$"))
419 ;; Can't find the right spot to insert the colon.
420 (t "[.?!:][])}\"']*$"))))
421 (while (re-search-forward eol-double-space-re to t)
422 (or (>= (point) to) (memq (char-before) '(?\t ?\ ))
423 (insert-and-inherit ?\ ))))
425 (goto-char from)
426 (if enable-multibyte-characters
427 ;; Delete unnecessay newlines surrounded by words. The
428 ;; character category `|' means that we can break a line
429 ;; at the character. And, charset property
430 ;; `nospace-between-words' tells how to concatenate
431 ;; words. If the value is non-nil, never put spaces
432 ;; between words, thus delete a newline between them.
433 ;; If the value is nil, delete a newline only when a
434 ;; character preceding a newline has text property
435 ;; `nospace-between-words'.
436 (while (search-forward "\n" to t)
437 (let ((prev (char-before (match-beginning 0)))
438 (next (following-char)))
439 (if (and (or (aref (char-category-set next) ?|)
440 (aref (char-category-set prev) ?|))
441 (or (get-charset-property (char-charset prev)
442 'nospace-between-words)
443 (get-text-property (1- (match-beginning 0))
444 'nospace-between-words)))
445 (delete-char -1)))))
447 (goto-char from)
448 (skip-chars-forward " \t")
449 ;; Then change all newlines to spaces.
450 (subst-char-in-region from to ?\n ?\ )
451 (if (and nosqueeze (not (eq justify 'full)))
453 (canonically-space-region (or squeeze-after (point)) to))
454 (goto-char from))
456 (defun fill-move-to-break-point (linebeg)
457 "Move to the position where the line should be broken.
458 The break position will be always after LINEBEG and generally before point."
459 ;; If the fill column is before linebeg, move to linebeg.
460 (if (> linebeg (point)) (goto-char linebeg))
461 ;; Move back to the point where we can break the line
462 ;; at. We break the line between word or after/before
463 ;; the character which has character category `|'. We
464 ;; search space, \c| followed by a character, or \c|
465 ;; following a character. If not found, place
466 ;; the point at linebeg.
467 (while
468 (when (re-search-backward "[ \t]\\|\\c|.\\|.\\c|" linebeg 0)
469 ;; In case of space, we place the point at next to
470 ;; the point where the break occurs actually,
471 ;; because we don't want to change the following
472 ;; logic of original Emacs. In case of \c|, the
473 ;; point is at the place where the break occurs.
474 (forward-char 1)
475 (when (fill-nobreak-p) (skip-chars-backward " \t" linebeg))))
477 ;; Move back over the single space between the words.
478 (skip-chars-backward " \t")
480 ;; If the left margin and fill prefix by themselves
481 ;; pass the fill-column. or if they are zero
482 ;; but we have no room for even one word,
483 ;; keep at least one word or a character which has
484 ;; category `|' anyway.
485 (if (>= linebeg (point))
486 ;; Ok, skip at least one word or one \c| character.
487 ;; Meanwhile, don't stop at a period followed by one space.
488 (let ((to (line-end-position))
489 (fill-nobreak-predicate nil) ;to break sooner.
490 (first t))
491 (goto-char linebeg)
492 (while (and (< (point) to) (or first (fill-nobreak-p)))
493 ;; Find a breakable point while ignoring the
494 ;; following spaces.
495 (skip-chars-forward " \t")
496 (if (looking-at "\\c|")
497 (forward-char 1)
498 (let ((pos (save-excursion
499 (skip-chars-forward "^ \n\t")
500 (point))))
501 (if (re-search-forward "\\c|" pos t)
502 (forward-char -1)
503 (goto-char pos))))
504 (setq first nil)))
506 (if enable-multibyte-characters
507 ;; If we are going to break the line after or
508 ;; before a non-ascii character, we may have to
509 ;; run a special function for the charset of the
510 ;; character to find the correct break point.
511 (if (not (and (eq (charset-after (1- (point))) 'ascii)
512 (eq (charset-after (point)) 'ascii)))
513 ;; Make sure we take SOMETHING after the fill prefix if any.
514 (fill-find-break-point linebeg)))))
516 (defun fill-newline ()
517 ;; Replace whitespace here with one newline, then
518 ;; indent to left margin.
519 (skip-chars-backward " \t")
520 (if (and (= (following-char) ?\ )
521 (or (aref (char-category-set (preceding-char)) ?|)
522 (looking-at "[ \t]+\\c|")))
523 ;; We need one space at end of line so that
524 ;; further filling won't delete it. NOTE: We
525 ;; intentionally leave this one space to
526 ;; distinguish the case that user wants to put
527 ;; space between \c| characters.
528 (forward-char 1))
529 (insert ?\n)
530 ;; Give newline the properties of the space(s) it replaces
531 (set-text-properties (1- (point)) (point)
532 (text-properties-at (point)))
533 ;; If we don't want breaks in invisible text, don't insert
534 ;; an invisible newline.
535 (if fill-nobreak-invisible
536 (remove-text-properties (1- (point)) (point)
537 '(invisible t)))
538 (if (or fill-prefix
539 (not fill-indent-according-to-mode))
540 (fill-indent-to-left-margin)
541 (indent-according-to-mode))
542 ;; Insert the fill prefix after indentation.
543 (and fill-prefix (not (equal fill-prefix ""))
544 ;; Markers that were after the whitespace are now at point: insert
545 ;; before them so they don't get stuck before the prefix.
546 (insert-before-markers-and-inherit fill-prefix)))
548 (defun fill-indent-to-left-margin ()
549 "Indent current line to the column given by `current-left-margin'."
550 (let ((beg (point)))
551 (indent-line-to (current-left-margin))
552 (put-text-property beg (point) 'face 'default)))
554 (defun fill-region-as-paragraph (from to &optional justify
555 nosqueeze squeeze-after)
556 "Fill the region as one paragraph.
557 It removes any paragraph breaks in the region and extra newlines at the end,
558 indents and fills lines between the margins given by the
559 `current-left-margin' and `current-fill-column' functions.
560 \(In most cases, the variable `fill-column' controls the width.)
561 It leaves point at the beginning of the line following the paragraph.
563 Normally performs justification according to the `current-justification'
564 function, but with a prefix arg, does full justification instead.
566 From a program, optional third arg JUSTIFY can specify any type of
567 justification. Fourth arg NOSQUEEZE non-nil means not to make spaces
568 between words canonical before filling. Fifth arg SQUEEZE-AFTER, if non-nil,
569 means don't canonicalize spaces before that position.
571 Return the `fill-prefix' used for filling.
573 If `sentence-end-double-space' is non-nil, then period followed by one
574 space does not end a sentence, so don't break a line there."
575 (interactive (progn
576 (barf-if-buffer-read-only)
577 (list (region-beginning) (region-end)
578 (if current-prefix-arg 'full))))
579 (unless (memq justify '(t nil none full center left right))
580 (setq justify 'full))
582 ;; Make sure "to" is the endpoint.
583 (goto-char (min from to))
584 (setq to (max from to))
585 ;; Ignore blank lines at beginning of region.
586 (skip-chars-forward " \t\n")
588 (let ((from-plus-indent (point))
589 (oneleft nil))
591 (beginning-of-line)
592 (setq from (point))
594 ;; Delete all but one soft newline at end of region.
595 ;; And leave TO before that one.
596 (goto-char to)
597 (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
598 (if (and oneleft
599 (not (and use-hard-newlines
600 (get-text-property (1- (point)) 'hard))))
601 (delete-backward-char 1)
602 (backward-char 1)
603 (setq oneleft t)))
604 (setq to (copy-marker (point) t))
605 ;; ;; If there was no newline, and there is text in the paragraph, then
606 ;; ;; create a newline.
607 ;; (if (and (not oneleft) (> to from-plus-indent))
608 ;; (newline))
609 (goto-char from-plus-indent))
611 (if (not (> to (point)))
612 nil ;; There is no paragraph, only whitespace: exit now.
614 (or justify (setq justify (current-justification)))
616 ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
617 (let ((fill-prefix fill-prefix))
618 ;; Figure out how this paragraph is indented, if desired.
619 (when (and adaptive-fill-mode
620 (or (null fill-prefix) (string= fill-prefix "")))
621 (setq fill-prefix (fill-context-prefix from to))
622 ;; Ignore a white-space only fill-prefix
623 ;; if we indent-according-to-mode.
624 (when (and fill-prefix fill-indent-according-to-mode
625 (string-match "\\`[ \t]*\\'" fill-prefix))
626 (setq fill-prefix nil)))
628 (goto-char from)
629 (beginning-of-line)
631 (if (not justify) ; filling disabled: just check indentation
632 (progn
633 (goto-char from)
634 (while (< (point) to)
635 (if (and (not (eolp))
636 (< (current-indentation) (current-left-margin)))
637 (fill-indent-to-left-margin))
638 (forward-line 1)))
640 (if use-hard-newlines
641 (remove-list-of-text-properties from to '(hard)))
642 ;; Make sure first line is indented (at least) to left margin...
643 (if (or (memq justify '(right center))
644 (< (current-indentation) (current-left-margin)))
645 (fill-indent-to-left-margin))
646 ;; Delete the fill-prefix from every line.
647 (fill-delete-prefix from to fill-prefix)
648 (setq from (point))
650 ;; FROM, and point, are now before the text to fill,
651 ;; but after any fill prefix on the first line.
653 (fill-delete-newlines from to justify nosqueeze squeeze-after)
655 ;; This is the actual filling loop.
656 (goto-char from)
657 (let (linebeg)
658 (while (< (point) to)
659 (setq linebeg (point))
660 (move-to-column (1+ (current-fill-column)))
661 (if (when (< (point) to)
662 ;; Find the position where we'll break the line.
663 (fill-move-to-break-point linebeg)
664 ;; Check again to see if we got to the end of
665 ;; the paragraph.
666 (skip-chars-forward " \t")
667 (< (point) to))
668 ;; Found a place to cut.
669 (progn
670 (fill-newline)
671 (when justify
672 ;; Justify the line just ended, if desired.
673 (save-excursion
674 (forward-line -1)
675 (justify-current-line justify nil t))))
677 (goto-char to)
678 ;; Justify this last line, if desired.
679 (if justify (justify-current-line justify t t))))))
680 ;; Leave point after final newline.
681 (goto-char to)
682 (unless (eobp) (forward-char 1))
683 ;; Return the fill-prefix we used
684 fill-prefix)))
686 (defsubst skip-line-prefix (prefix)
687 "If point is inside the string PREFIX at the beginning of line, move past it."
688 (when (and prefix
689 (< (- (point) (line-beginning-position)) (length prefix))
690 (save-excursion
691 (beginning-of-line)
692 (looking-at (regexp-quote prefix))))
693 (goto-char (match-end 0))))
695 (defun fill-paragraph (arg)
696 "Fill paragraph at or after point. Prefix ARG means justify as well.
697 If `sentence-end-double-space' is non-nil, then period followed by one
698 space does not end a sentence, so don't break a line there.
699 the variable `fill-column' controls the width for filling.
701 If `fill-paragraph-function' is non-nil, we call it (passing our
702 argument to it), and if it returns non-nil, we simply return its value.
704 If `fill-paragraph-function' is nil, return the `fill-prefix' used for filling."
705 (interactive (progn
706 (barf-if-buffer-read-only)
707 (list (if current-prefix-arg 'full))))
708 ;; First try fill-paragraph-function.
709 (or (and fill-paragraph-function
710 (let ((function fill-paragraph-function)
711 ;; If fill-paragraph-function is set, it probably takes care
712 ;; of comments and stuff. If not, it will have to set
713 ;; fill-paragraph-handle-comment back to t explicitly or
714 ;; return nil.
715 (fill-paragraph-handle-comment nil)
716 fill-paragraph-function)
717 (funcall function arg)))
718 ;; Then try our syntax-aware filling code.
719 (and fill-paragraph-handle-comment
720 ;; Our code only handles \n-terminated comments right now.
721 comment-start comment-start-skip (equal comment-end "")
722 (let ((fill-paragraph-handle-comment nil))
723 (fill-comment-paragraph arg)))
724 ;; If it all fails, default to the good ol' text paragraph filling.
725 (let ((before (point))
726 (paragraph-start paragraph-start)
727 ;; Fill prefix used for filling the paragraph.
728 fill-pfx)
729 ;; Try to prevent code sections and comment sections from being
730 ;; filled together.
731 (when (and fill-paragraph-handle-comment comment-start-skip)
732 (setq paragraph-start
733 (concat paragraph-start "\\|[ \t]*\\(?:"
734 comment-start-skip "\\)")))
735 (save-excursion
736 ;; To make sure the return value of forward-paragraph is meaningful,
737 ;; we have to start from the beginning of line, otherwise skipping
738 ;; past the last few chars of a paragraph-separator would count as
739 ;; a paragraph (and not skipping any chars at EOB would not count
740 ;; as a paragraph even if it is).
741 (move-to-left-margin)
742 (if (not (zerop (forward-paragraph)))
743 ;; There's no paragraph at or after point: give up.
744 (setq fill-pfx "")
745 (let ((end (point))
746 (beg (progn (backward-paragraph) (point))))
747 (goto-char before)
748 (setq fill-pfx
749 (if use-hard-newlines
750 ;; Can't use fill-region-as-paragraph, since this
751 ;; paragraph may still contain hard newlines. See
752 ;; fill-region.
753 (fill-region beg end arg)
754 (fill-region-as-paragraph beg end arg))))))
755 ;; See if point ended up inside the fill-prefix, and if so, move
756 ;; past it.
757 (skip-line-prefix fill-pfx)
758 fill-pfx)))
760 (defun fill-comment-paragraph (&optional justify)
761 "Fill current comment.
762 If we're not in a comment, just return nil so that the caller
763 can take care of filling. JUSTIFY is used as in `fill-paragraph'."
764 (comment-normalize-vars)
765 (let (has-code-and-comment ; Non-nil if it contains code and a comment.
766 comin comstart)
767 ;; Figure out what kind of comment we are looking at.
768 (save-excursion
769 (beginning-of-line)
770 (when (setq comstart (comment-search-forward (line-end-position) t))
771 (setq comin (point))
772 (goto-char comstart) (skip-chars-backward " \t")
773 (setq has-code-and-comment (not (bolp)))))
775 (if (not comstart)
776 ;; Return nil, so the normal filling will take place.
779 ;; Narrow to include only the comment, and then fill the region.
780 (let* ((fill-prefix fill-prefix)
781 (comment-re (concat "[ \t]*\\(?:" comment-start-skip "\\)"))
782 (comment-fill-prefix ; Compute a fill prefix.
783 (save-excursion
784 (goto-char comstart)
785 (if has-code-and-comment
786 (concat (make-string (/ (current-column) tab-width) ?\t)
787 (make-string (% (current-column) tab-width) ?\ )
788 (buffer-substring (point) comin))
789 (buffer-substring (line-beginning-position) comin))))
790 beg end)
791 (save-excursion
792 (save-restriction
793 (beginning-of-line)
794 (narrow-to-region
795 ;; Find the first line we should include in the region to fill.
796 (if has-code-and-comment
797 (line-beginning-position)
798 (save-excursion
799 (while (and (zerop (forward-line -1))
800 (looking-at comment-re)))
801 ;; We may have gone too far. Go forward again.
802 (line-beginning-position
803 (if (looking-at (concat ".*\\(?:" comment-start-skip "\\)"))
804 1 2))))
805 ;; Find the beginning of the first line past the region to fill.
806 (save-excursion
807 (while (progn (forward-line 1)
808 (looking-at comment-re)))
809 (point)))
810 ;; Obey paragraph starters and boundaries within comments.
811 (let* ((paragraph-separate
812 ;; Use the default values since they correspond to
813 ;; the values to use for plain text.
814 (concat paragraph-separate "\\|[ \t]*\\(?:"
815 comment-start-skip "\\)\\(?:"
816 (default-value 'paragraph-separate) "\\)"))
817 (paragraph-start
818 (concat paragraph-start "\\|[ \t]*\\(?:"
819 comment-start-skip "\\)\\(?:"
820 (default-value 'paragraph-start) "\\)"))
821 (paragraph-ignore-fill-prefix nil)
822 (fill-prefix comment-fill-prefix)
823 (after-line (if has-code-and-comment
824 (line-beginning-position 2))))
825 (setq end (progn (forward-paragraph) (point)))
826 ;; If this comment starts on a line with code,
827 ;; include that line in the filling.
828 (setq beg (progn (backward-paragraph)
829 (if (eq (point) after-line)
830 (forward-line -1))
831 (point)))))
833 ;; Find the fill-prefix to use.
834 (cond
835 (fill-prefix) ; Use the user-provided fill prefix.
836 ((and adaptive-fill-mode ; Try adaptive fill mode.
837 (setq fill-prefix (fill-context-prefix beg end))
838 (string-match comment-start-skip fill-prefix)))
840 (setq fill-prefix comment-fill-prefix)))
842 ;; Don't fill with narrowing.
844 (fill-region-as-paragraph
845 beg end justify nil
846 ;; Don't canonicalize spaces within the code just before
847 ;; the comment.
848 (save-excursion
849 (goto-char beg)
850 (if (looking-at fill-prefix)
852 (re-search-forward comment-start-skip))))
853 ;; Make sure we don't return nil.
854 t))))))
856 (defun fill-region (from to &optional justify nosqueeze to-eop)
857 "Fill each of the paragraphs in the region.
858 A prefix arg means justify as well.
859 Ordinarily the variable `fill-column' controls the width.
861 Noninteractively, the third argument JUSTIFY specifies which
862 kind of justification to do: `full', `left', `right', `center',
863 or `none' (equivalent to nil). t means handle each paragraph
864 as specified by its text properties.
866 The fourth arg NOSQUEEZE non-nil means to leave
867 whitespace other than line breaks untouched, and fifth arg TO-EOP
868 non-nil means to keep filling to the end of the paragraph (or next
869 hard newline, if `use-hard-newlines' is on).
871 Return the fill-prefix used for filling the last paragraph.
873 If `sentence-end-double-space' is non-nil, then period followed by one
874 space does not end a sentence, so don't break a line there."
875 (interactive (progn
876 (barf-if-buffer-read-only)
877 (list (region-beginning) (region-end)
878 (if current-prefix-arg 'full))))
879 (unless (memq justify '(t nil none full center left right))
880 (setq justify 'full))
881 (let (max beg fill-pfx)
882 (goto-char (max from to))
883 (when to-eop
884 (skip-chars-backward "\n")
885 (forward-paragraph))
886 (setq max (copy-marker (point) t))
887 (goto-char (setq beg (min from to)))
888 (beginning-of-line)
889 (while (< (point) max)
890 (let ((initial (point))
891 end)
892 ;; If using hard newlines, break at every one for filling
893 ;; purposes rather than using paragraph breaks.
894 (if use-hard-newlines
895 (progn
896 (while (and (setq end (text-property-any (point) max
897 'hard t))
898 (not (= ?\n (char-after end)))
899 (not (>= end max)))
900 (goto-char (1+ end)))
901 (setq end (if end (min max (1+ end)) max))
902 (goto-char initial))
903 (forward-paragraph 1)
904 (setq end (min max (point)))
905 (forward-paragraph -1))
906 (if (< (point) beg)
907 (goto-char beg))
908 (if (>= (point) initial)
909 (setq fill-pfx
910 (fill-region-as-paragraph (point) end justify nosqueeze))
911 (goto-char end))))
912 fill-pfx))
915 (defcustom default-justification 'left
916 "*Method of justifying text not otherwise specified.
917 Possible values are `left', `right', `full', `center', or `none'.
918 The requested kind of justification is done whenever lines are filled.
919 The `justification' text-property can locally override this variable."
920 :type '(choice (const left)
921 (const right)
922 (const full)
923 (const center)
924 (const none))
925 :group 'fill)
926 (make-variable-buffer-local 'default-justification)
928 (defun current-justification ()
929 "How should we justify this line?
930 This returns the value of the text-property `justification',
931 or the variable `default-justification' if there is no text-property.
932 However, it returns nil rather than `none' to mean \"don't justify\"."
933 (let ((j (or (get-text-property
934 ;; Make sure we're looking at paragraph body.
935 (save-excursion (skip-chars-forward " \t")
936 (if (and (eobp) (not (bobp)))
937 (1- (point)) (point)))
938 'justification)
939 default-justification)))
940 (if (eq 'none j)
942 j)))
944 (defun set-justification (begin end style &optional whole-par)
945 "Set the region's justification style to STYLE.
946 This commands prompts for the kind of justification to use.
947 If the mark is not active, this command operates on the current paragraph.
948 If the mark is active, it operates on the region. However, if the
949 beginning and end of the region are not at paragraph breaks, they are
950 moved to the beginning and end \(respectively) of the paragraphs they
951 are in.
953 If `use-hard-newlines' is true, all hard newlines are taken to be paragraph
954 breaks.
956 When calling from a program, operates just on region between BEGIN and END,
957 unless optional fourth arg WHOLE-PAR is non-nil. In that case bounds are
958 extended to include entire paragraphs as in the interactive command."
959 (interactive (list (if mark-active (region-beginning) (point))
960 (if mark-active (region-end) (point))
961 (let ((s (completing-read
962 "Set justification to: "
963 '(("left") ("right") ("full")
964 ("center") ("none"))
965 nil t)))
966 (if (equal s "") (error ""))
967 (intern s))
969 (save-excursion
970 (save-restriction
971 (if whole-par
972 (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
973 (paragraph-ignore-fill-prefix (if use-hard-newlines t
974 paragraph-ignore-fill-prefix)))
975 (goto-char begin)
976 (while (and (bolp) (not (eobp))) (forward-char 1))
977 (backward-paragraph)
978 (setq begin (point))
979 (goto-char end)
980 (skip-chars-backward " \t\n" begin)
981 (forward-paragraph)
982 (setq end (point))))
984 (narrow-to-region (point-min) end)
985 (unjustify-region begin (point-max))
986 (put-text-property begin (point-max) 'justification style)
987 (fill-region begin (point-max) nil t))))
989 (defun set-justification-none (b e)
990 "Disable automatic filling for paragraphs in the region.
991 If the mark is not active, this applies to the current paragraph."
992 (interactive (list (if mark-active (region-beginning) (point))
993 (if mark-active (region-end) (point))))
994 (set-justification b e 'none t))
996 (defun set-justification-left (b e)
997 "Make paragraphs in the region left-justified.
998 This means they are flush at the left margin and ragged on the right.
999 This is usually the default, but see the variable `default-justification'.
1000 If the mark is not active, this applies to the current paragraph."
1001 (interactive (list (if mark-active (region-beginning) (point))
1002 (if mark-active (region-end) (point))))
1003 (set-justification b e 'left t))
1005 (defun set-justification-right (b e)
1006 "Make paragraphs in the region right-justified.
1007 This means they are flush at the right margin and ragged on the left.
1008 If the mark is not active, this applies to the current paragraph."
1009 (interactive (list (if mark-active (region-beginning) (point))
1010 (if mark-active (region-end) (point))))
1011 (set-justification b e 'right t))
1013 (defun set-justification-full (b e)
1014 "Make paragraphs in the region fully justified.
1015 This makes lines flush on both margins by inserting spaces between words.
1016 If the mark is not active, this applies to the current paragraph."
1017 (interactive (list (if mark-active (region-beginning) (point))
1018 (if mark-active (region-end) (point))))
1019 (set-justification b e 'full t))
1021 (defun set-justification-center (b e)
1022 "Make paragraphs in the region centered.
1023 If the mark is not active, this applies to the current paragraph."
1024 (interactive (list (if mark-active (region-beginning) (point))
1025 (if mark-active (region-end) (point))))
1026 (set-justification b e 'center t))
1028 ;; A line has up to six parts:
1030 ;; >>> hello.
1031 ;; [Indent-1][FP][ Indent-2 ][text][trailing whitespace][newline]
1033 ;; "Indent-1" is the left-margin indentation; normally it ends at column
1034 ;; given by the `current-left-margin' function.
1035 ;; "FP" is the fill-prefix. It can be any string, including whitespace.
1036 ;; "Indent-2" is added to justify a line if the `current-justification' is
1037 ;; `center' or `right'. In `left' and `full' justification regions, any
1038 ;; whitespace there is part of the line's text, and should not be changed.
1039 ;; Trailing whitespace is not counted as part of the line length when
1040 ;; center- or right-justifying.
1042 ;; All parts of the line are optional, although the final newline can
1043 ;; only be missing on the last line of the buffer.
1045 (defun justify-current-line (&optional how eop nosqueeze)
1046 "Do some kind of justification on this line.
1047 Normally does full justification: adds spaces to the line to make it end at
1048 the column given by `current-fill-column'.
1049 Optional first argument HOW specifies alternate type of justification:
1050 it can be `left', `right', `full', `center', or `none'.
1051 If HOW is t, will justify however the `current-justification' function says to.
1052 If HOW is nil or missing, full justification is done by default.
1053 Second arg EOP non-nil means that this is the last line of the paragraph, so
1054 it will not be stretched by full justification.
1055 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
1056 otherwise it is made canonical."
1057 (interactive "*")
1058 (if (eq t how) (setq how (or (current-justification) 'none))
1059 (if (null how) (setq how 'full)
1060 (or (memq how '(none left right center))
1061 (setq how 'full))))
1062 (or (memq how '(none left)) ; No action required for these.
1063 (let ((fc (current-fill-column))
1064 (pos (point-marker))
1065 fp-end ; point at end of fill prefix
1066 beg ; point at beginning of line's text
1067 end ; point at end of line's text
1068 indent ; column of `beg'
1069 endcol ; column of `end'
1070 ncols ; new indent point or offset
1071 (nspaces 0) ; number of spaces between words
1072 ; in line (not space characters)
1073 fracspace ; fractional amount of space to be
1074 ; added between each words
1075 (curr-fracspace 0) ; current fractional space amount
1076 count)
1077 (end-of-line)
1078 ;; Check if this is the last line of the paragraph.
1079 (if (and use-hard-newlines (null eop)
1080 (get-text-property (point) 'hard))
1081 (setq eop t))
1082 (skip-chars-backward " \t")
1083 ;; Quick exit if it appears to be properly justified already
1084 ;; or there is no text.
1085 (if (or (bolp)
1086 (and (memq how '(full right))
1087 (= (current-column) fc)))
1089 (setq end (point))
1090 (beginning-of-line)
1091 (skip-chars-forward " \t")
1092 ;; Skip over fill-prefix.
1093 (if (and fill-prefix
1094 (not (string-equal fill-prefix ""))
1095 (equal fill-prefix
1096 (buffer-substring
1097 (point) (min (point-max) (+ (length fill-prefix)
1098 (point))))))
1099 (forward-char (length fill-prefix))
1100 (if (and adaptive-fill-mode
1101 (looking-at adaptive-fill-regexp))
1102 (goto-char (match-end 0))))
1103 (setq fp-end (point))
1104 (skip-chars-forward " \t")
1105 ;; This is beginning of the line's text.
1106 (setq indent (current-column))
1107 (setq beg (point))
1108 (goto-char end)
1109 (setq endcol (current-column))
1111 ;; HOW can't be null or left--we would have exited already
1112 (cond ((eq 'right how)
1113 (setq ncols (- fc endcol))
1114 (if (< ncols 0)
1115 ;; Need to remove some indentation
1116 (delete-region
1117 (progn (goto-char fp-end)
1118 (if (< (current-column) (+ indent ncols))
1119 (move-to-column (+ indent ncols) t))
1120 (point))
1121 (progn (move-to-column indent) (point)))
1122 ;; Need to add some
1123 (goto-char beg)
1124 (indent-to (+ indent ncols))
1125 ;; If point was at beginning of text, keep it there.
1126 (if (= beg pos)
1127 (move-marker pos (point)))))
1129 ((eq 'center how)
1130 ;; Figure out how much indentation is needed
1131 (setq ncols (+ (current-left-margin)
1132 (/ (- fc (current-left-margin) ;avail. space
1133 (- endcol indent)) ;text width
1134 2)))
1135 (if (< ncols indent)
1136 ;; Have too much indentation - remove some
1137 (delete-region
1138 (progn (goto-char fp-end)
1139 (if (< (current-column) ncols)
1140 (move-to-column ncols t))
1141 (point))
1142 (progn (move-to-column indent) (point)))
1143 ;; Have too little - add some
1144 (goto-char beg)
1145 (indent-to ncols)
1146 ;; If point was at beginning of text, keep it there.
1147 (if (= beg pos)
1148 (move-marker pos (point)))))
1150 ((eq 'full how)
1151 ;; Insert extra spaces between words to justify line
1152 (save-restriction
1153 (narrow-to-region beg end)
1154 (or nosqueeze
1155 (canonically-space-region beg end))
1156 (goto-char (point-max))
1157 ;; count word spaces in line
1158 (while (search-backward " " nil t)
1159 (setq nspaces (1+ nspaces))
1160 (skip-chars-backward " "))
1161 (setq ncols (- fc endcol))
1162 ;; Ncols is number of additional space chars needed
1163 (if (and (> ncols 0) (> nspaces 0) (not eop))
1164 (progn
1165 (setq curr-fracspace (+ ncols (/ (1+ nspaces) 2))
1166 count nspaces)
1167 (while (> count 0)
1168 (skip-chars-forward " ")
1169 (insert-and-inherit
1170 (make-string (/ curr-fracspace nspaces) ?\ ))
1171 (search-forward " " nil t)
1172 (setq count (1- count)
1173 curr-fracspace
1174 (+ (% curr-fracspace nspaces) ncols)))))))
1175 (t (error "Unknown justification value"))))
1176 (goto-char pos)
1177 (move-marker pos nil)))
1178 nil)
1180 (defun unjustify-current-line ()
1181 "Remove justification whitespace from current line.
1182 If the line is centered or right-justified, this function removes any
1183 indentation past the left margin. If the line is full-justified, it removes
1184 extra spaces between words. It does nothing in other justification modes."
1185 (let ((justify (current-justification)))
1186 (cond ((eq 'left justify) nil)
1187 ((eq nil justify) nil)
1188 ((eq 'full justify) ; full justify: remove extra spaces
1189 (beginning-of-line-text)
1190 (canonically-space-region (point) (line-end-position)))
1191 ((memq justify '(center right))
1192 (save-excursion
1193 (move-to-left-margin nil t)
1194 ;; Position ourselves after any fill-prefix.
1195 (if (and fill-prefix
1196 (not (string-equal fill-prefix ""))
1197 (equal fill-prefix
1198 (buffer-substring
1199 (point) (min (point-max) (+ (length fill-prefix)
1200 (point))))))
1201 (forward-char (length fill-prefix)))
1202 (delete-region (point) (progn (skip-chars-forward " \t")
1203 (point))))))))
1205 (defun unjustify-region (&optional begin end)
1206 "Remove justification whitespace from region.
1207 For centered or right-justified regions, this function removes any indentation
1208 past the left margin from each line. For full-justified lines, it removes
1209 extra spaces between words. It does nothing in other justification modes.
1210 Arguments BEGIN and END are optional; default is the whole buffer."
1211 (save-excursion
1212 (save-restriction
1213 (if end (narrow-to-region (point-min) end))
1214 (goto-char (or begin (point-min)))
1215 (while (not (eobp))
1216 (unjustify-current-line)
1217 (forward-line 1)))))
1220 (defun fill-nonuniform-paragraphs (min max &optional justifyp citation-regexp)
1221 "Fill paragraphs within the region, allowing varying indentation within each.
1222 This command divides the region into \"paragraphs\",
1223 only at paragraph-separator lines, then fills each paragraph
1224 using as the fill prefix the smallest indentation of any line
1225 in the paragraph.
1227 When calling from a program, pass range to fill as first two arguments.
1229 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1230 JUSTIFY to justify paragraphs (prefix arg),
1231 When filling a mail message, pass a regexp for CITATION-REGEXP
1232 which will match the prefix of a line which is a citation marker
1233 plus whitespace, but no other kind of prefix.
1234 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1235 (interactive (progn
1236 (barf-if-buffer-read-only)
1237 (list (region-beginning) (region-end)
1238 (if current-prefix-arg 'full))))
1239 (let ((fill-individual-varying-indent t))
1240 (fill-individual-paragraphs min max justifyp citation-regexp)))
1242 (defun fill-individual-paragraphs (min max &optional justify citation-regexp)
1243 "Fill paragraphs of uniform indentation within the region.
1244 This command divides the region into \"paragraphs\",
1245 treating every change in indentation level or prefix as a paragraph boundary,
1246 then fills each paragraph using its indentation level as the fill prefix.
1248 There is one special case where a change in indentation does not start
1249 a new paragraph. This is for text of this form:
1251 foo> This line with extra indentation starts
1252 foo> a paragraph that continues on more lines.
1254 These lines are filled together.
1256 When calling from a program, pass the range to fill
1257 as the first two arguments.
1259 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1260 JUSTIFY to justify paragraphs (prefix arg),
1261 When filling a mail message, pass a regexp for CITATION-REGEXP
1262 which will match the prefix of a line which is a citation marker
1263 plus whitespace, but no other kind of prefix.
1264 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1265 (interactive (progn
1266 (barf-if-buffer-read-only)
1267 (list (region-beginning) (region-end)
1268 (if current-prefix-arg 'full))))
1269 (save-restriction
1270 (save-excursion
1271 (goto-char min)
1272 (beginning-of-line)
1273 (narrow-to-region (point) max)
1274 (if citation-regexp
1275 (while (and (not (eobp))
1276 (or (looking-at "[ \t]*[^ \t\n]+:")
1277 (looking-at "[ \t]*$")))
1278 (if (looking-at "[ \t]*[^ \t\n]+:")
1279 (search-forward "\n\n" nil 'move)
1280 (forward-line 1))))
1281 (narrow-to-region (point) max)
1282 ;; Loop over paragraphs.
1283 (while (let ((here (point)))
1284 ;; Skip over all paragraph-separating lines
1285 ;; so as to not include them in any paragraph.
1286 (while (and (not (eobp))
1287 (progn (move-to-left-margin)
1288 (and (not (eobp))
1289 (looking-at paragraph-separate))))
1290 (forward-line 1))
1291 (skip-chars-forward " \t\n") (not (eobp)))
1292 (move-to-left-margin)
1293 (let ((start (point))
1294 fill-prefix fill-prefix-regexp)
1295 ;; Find end of paragraph, and compute the smallest fill-prefix
1296 ;; that fits all the lines in this paragraph.
1297 (while (progn
1298 ;; Update the fill-prefix on the first line
1299 ;; and whenever the prefix good so far is too long.
1300 (if (not (and fill-prefix
1301 (looking-at fill-prefix-regexp)))
1302 (setq fill-prefix
1303 (fill-individual-paragraphs-prefix
1304 citation-regexp)
1305 fill-prefix-regexp (regexp-quote fill-prefix)))
1306 (forward-line 1)
1307 (if (bolp)
1308 ;; If forward-line went past a newline,
1309 ;; move further to the left margin.
1310 (move-to-left-margin))
1311 ;; Now stop the loop if end of paragraph.
1312 (and (not (eobp))
1313 (if fill-individual-varying-indent
1314 ;; If this line is a separator line, with or
1315 ;; without prefix, end the paragraph.
1316 (and
1317 (not (looking-at paragraph-separate))
1318 (save-excursion
1319 (not (and (looking-at fill-prefix-regexp)
1320 (progn (forward-char
1321 (length fill-prefix))
1322 (looking-at
1323 paragraph-separate))))))
1324 ;; If this line has more or less indent
1325 ;; than the fill prefix wants, end the paragraph.
1326 (and (looking-at fill-prefix-regexp)
1327 ;; If fill prefix is shorter than a new
1328 ;; fill prefix computed here, end paragraph.
1329 (let ((this-line-fill-prefix
1330 (fill-individual-paragraphs-prefix
1331 citation-regexp)))
1332 (>= (length fill-prefix)
1333 (length this-line-fill-prefix)))
1334 (save-excursion
1335 (not (progn (forward-char
1336 (length fill-prefix))
1337 (or (looking-at "[ \t]")
1338 (looking-at paragraph-separate)
1339 (looking-at paragraph-start)))))
1340 (not (and (equal fill-prefix "")
1341 citation-regexp
1342 (looking-at citation-regexp))))))))
1343 ;; Fill this paragraph, but don't add a newline at the end.
1344 (let ((had-newline (bolp)))
1345 (fill-region-as-paragraph start (point) justify)
1346 (if (and (bolp) (not had-newline))
1347 (delete-char -1))))))))
1348 (defun fill-individual-paragraphs-prefix (citation-regexp)
1349 (let* ((adaptive-fill-first-line-regexp ".*")
1350 (just-one-line-prefix
1351 ;; Accept any prefix rather than just the ones matched by
1352 ;; adaptive-fill-first-line-regexp.
1353 (fill-context-prefix (point) (line-beginning-position 2)))
1354 (two-lines-prefix
1355 (fill-context-prefix (point) (line-beginning-position 3))))
1356 (if (not just-one-line-prefix)
1357 (buffer-substring
1358 (point) (save-excursion (skip-chars-forward " \t") (point)))
1359 ;; See if the citation part of JUST-ONE-LINE-PREFIX
1360 ;; is the same as that of TWO-LINES-PREFIX,
1361 ;; except perhaps with longer whitespace.
1362 (if (and just-one-line-prefix two-lines-prefix
1363 (let* ((one-line-citation-part
1364 (fill-individual-paragraphs-citation
1365 just-one-line-prefix citation-regexp))
1366 (two-lines-citation-part
1367 (fill-individual-paragraphs-citation
1368 two-lines-prefix citation-regexp))
1369 (adjusted-two-lines-citation-part
1370 (substring two-lines-citation-part 0
1371 (string-match "[ \t]*\\'"
1372 two-lines-citation-part))))
1373 (and
1374 (string-match (concat "\\`"
1375 (regexp-quote
1376 adjusted-two-lines-citation-part)
1377 "[ \t]*\\'")
1378 one-line-citation-part)
1379 (>= (string-width one-line-citation-part)
1380 (string-width two-lines-citation-part)))))
1381 two-lines-prefix
1382 just-one-line-prefix))))
1384 (defun fill-individual-paragraphs-citation (string citation-regexp)
1385 (if citation-regexp
1386 (if (string-match citation-regexp string)
1387 (match-string 0 string)
1389 string))
1391 ;;; fill.el ends here