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