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