Merge from emacs--devo--0
[bpt/emacs.git] / 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 (defvar fill-find-break-point-function-table (make-char-table nil)
373 "Char-table of special functions to find line breaking point.")
374
375 (defvar fill-nospace-between-words-table (make-char-table nil)
376 "Char-table of characters that don't use space between words.")
377
378 (progn
379 ;; Register `kinsoku' for scripts HAN, KANA, BOPOMPFO, and CJK-MISS.
380 ;; Also tell that they don't use space between words.
381 (map-char-table
382 #'(lambda (key val)
383 (when (memq val '(han kana bopomofo cjk-misc))
384 (set-char-table-range fill-find-break-point-function-table
385 key 'kinsoku)
386 (set-char-table-range fill-nospace-between-words-table
387 key t)))
388 char-script-table)
389 ;; Do the same thing also for full width characters and half
390 ;; width kana variants.
391 (set-char-table-range fill-find-break-point-function-table
392 '(#xFF01 . #xFFE6) 'kinsoku)
393 (set-char-table-range fill-nospace-between-words-table
394 '(#xFF01 . #xFFE6) 'kinsoku))
395
396 (defun fill-find-break-point (limit)
397 "Move point to a proper line breaking position of the current line.
398 Don't move back past the buffer position LIMIT.
399
400 This function is called when we are going to break the current line
401 after or before a non-ASCII character. If the charset of the
402 character has the property `fill-find-break-point-function', this
403 function calls the property value as a function with one arg LINEBEG.
404 If the charset has no such property, do nothing."
405 (let ((func (or
406 (aref fill-find-break-point-function-table (following-char))
407 (aref fill-find-break-point-function-table (preceding-char)))))
408 (if (and func (fboundp func))
409 (funcall func limit))))
410
411 (defun fill-delete-prefix (from to prefix)
412 "Delete the fill prefix from every line except the first.
413 The first line may not even have a fill prefix.
414 Point is moved to just past the fill prefix on the first line."
415 (let ((fpre (if (and prefix (not (string-match "\\`[ \t]*\\'" prefix)))
416 (concat "[ \t]*\\("
417 (replace-regexp-in-string
418 "[ \t]+" "[ \t]*"
419 (regexp-quote prefix))
420 "\\)?[ \t]*")
421 "[ \t]*")))
422 (goto-char from)
423 ;; Why signal an error here? The problem needs to be caught elsewhere.
424 ;; (if (>= (+ (current-left-margin) (length prefix))
425 ;; (current-fill-column))
426 ;; (error "fill-prefix too long for specified width"))
427 (forward-line 1)
428 (while (< (point) to)
429 (if (looking-at fpre)
430 (delete-region (point) (match-end 0)))
431 (forward-line 1))
432 (goto-char from)
433 (if (looking-at fpre)
434 (goto-char (match-end 0)))
435 (point)))
436
437 ;; The `fill-space' property carries the string with which a newline
438 ;; should be replaced when unbreaking a line (in fill-delete-newlines).
439 ;; It is added to newline characters by fill-newline when the default
440 ;; behavior of fill-delete-newlines is not what we want.
441 (add-to-list 'text-property-default-nonsticky '(fill-space . t))
442
443 (defun fill-delete-newlines (from to justify nosqueeze squeeze-after)
444 (goto-char from)
445 ;; Make sure sentences ending at end of line get an extra space.
446 ;; loses on split abbrevs ("Mr.\nSmith")
447 (let ((eol-double-space-re
448 (cond
449 ((not colon-double-space) (concat (sentence-end) "$"))
450 ;; Try to add the : inside the `sentence-end' regexp.
451 ((string-match "\\[[^][]*\\(\\.\\)[^][]*\\]" (sentence-end))
452 (concat (replace-match ".:" nil nil (sentence-end) 1) "$"))
453 ;; Can't find the right spot to insert the colon.
454 (t "[.?!:][])}\"']*$")))
455 (sentence-end-without-space-list
456 (string-to-list sentence-end-without-space)))
457 (while (re-search-forward eol-double-space-re to t)
458 (or (>= (point) to) (memq (char-before) '(?\t ?\s))
459 (memq (char-after (match-beginning 0))
460 sentence-end-without-space-list)
461 (insert-and-inherit ?\s))))
462
463 (goto-char from)
464 (if enable-multibyte-characters
465 ;; Delete unnecessay newlines surrounded by words. The
466 ;; character category `|' means that we can break a line at the
467 ;; character. And, char-table
468 ;; `fill-nospace-between-words-table' tells how to concatenate
469 ;; words. If a character has non-nil value in the table, never
470 ;; put spaces between words, thus delete a newline between them.
471 ;; Otherwise, delete a newline only when a character preceding a
472 ;; newline has non-nil value in that table.
473 (while (search-forward "\n" to t)
474 (if (get-text-property (match-beginning 0) 'fill-space)
475 (replace-match (get-text-property (match-beginning 0) 'fill-space))
476 (let ((prev (char-before (match-beginning 0)))
477 (next (following-char)))
478 (if (and (or (aref (char-category-set next) ?|)
479 (aref (char-category-set prev) ?|))
480 (or (aref fill-nospace-between-words-table next)
481 (aref fill-nospace-between-words-table prev)))
482 (delete-char -1))))))
483
484 (goto-char from)
485 (skip-chars-forward " \t")
486 ;; Then change all newlines to spaces.
487 (subst-char-in-region from to ?\n ?\s)
488 (if (and nosqueeze (not (eq justify 'full)))
489 nil
490 (canonically-space-region (or squeeze-after (point)) to)
491 ;; Remove trailing whitespace.
492 ;; Maybe canonically-space-region should do that.
493 (goto-char to) (delete-char (- (skip-chars-backward " \t"))))
494 (goto-char from))
495
496 (defun fill-move-to-break-point (linebeg)
497 "Move to the position where the line should be broken.
498 The break position will be always after LINEBEG and generally before point."
499 ;; If the fill column is before linebeg, move to linebeg.
500 (if (> linebeg (point)) (goto-char linebeg))
501 ;; Move back to the point where we can break the line
502 ;; at. We break the line between word or after/before
503 ;; the character which has character category `|'. We
504 ;; search space, \c| followed by a character, or \c|
505 ;; following a character. If not found, place
506 ;; the point at linebeg.
507 (while
508 (when (re-search-backward "[ \t]\\|\\c|.\\|.\\c|" linebeg 0)
509 ;; In case of space, we place the point at next to
510 ;; the point where the break occurs actually,
511 ;; because we don't want to change the following
512 ;; logic of original Emacs. In case of \c|, the
513 ;; point is at the place where the break occurs.
514 (forward-char 1)
515 (when (fill-nobreak-p) (skip-chars-backward " \t" linebeg))))
516
517 ;; Move back over the single space between the words.
518 (skip-chars-backward " \t")
519
520 ;; If the left margin and fill prefix by themselves
521 ;; pass the fill-column. or if they are zero
522 ;; but we have no room for even one word,
523 ;; keep at least one word or a character which has
524 ;; category `|' anyway.
525 (if (>= linebeg (point))
526 ;; Ok, skip at least one word or one \c| character.
527 ;; Meanwhile, don't stop at a period followed by one space.
528 (let ((to (line-end-position))
529 (fill-nobreak-predicate nil) ;to break sooner.
530 (first t))
531 (goto-char linebeg)
532 (while (and (< (point) to) (or first (fill-nobreak-p)))
533 ;; Find a breakable point while ignoring the
534 ;; following spaces.
535 (skip-chars-forward " \t")
536 (if (looking-at "\\c|")
537 (forward-char 1)
538 (let ((pos (save-excursion
539 (skip-chars-forward "^ \n\t")
540 (point))))
541 (if (re-search-forward "\\c|" pos t)
542 (forward-char -1)
543 (goto-char pos))))
544 (setq first nil)))
545
546 (if enable-multibyte-characters
547 ;; If we are going to break the line after or
548 ;; before a non-ascii character, we may have to
549 ;; run a special function for the charset of the
550 ;; character to find the correct break point.
551 (if (not (and (eq (charset-after (1- (point))) 'ascii)
552 (eq (charset-after (point)) 'ascii)))
553 ;; Make sure we take SOMETHING after the fill prefix if any.
554 (fill-find-break-point linebeg)))))
555
556 ;; Like text-properties-at but don't include `composition' property.
557 (defun fill-text-properties-at (pos)
558 (let ((l (text-properties-at pos))
559 prop-list)
560 (while l
561 (unless (eq (car l) 'composition)
562 (setq prop-list
563 (cons (car l) (cons (cadr l) prop-list))))
564 (setq l (cddr l)))
565 prop-list))
566
567 (defun fill-newline ()
568 ;; Replace whitespace here with one newline, then
569 ;; indent to left margin.
570 (skip-chars-backward " \t")
571 (insert ?\n)
572 ;; Give newline the properties of the space(s) it replaces
573 (set-text-properties (1- (point)) (point)
574 (fill-text-properties-at (point)))
575 (and (looking-at "\\( [ \t]*\\)\\(\\c|\\)?")
576 (or (aref (char-category-set (or (char-before (1- (point))) ?\000)) ?|)
577 (match-end 2))
578 ;; When refilling later on, this newline would normally not be replaced
579 ;; by a space, so we need to mark it specially to re-install the space
580 ;; when we unfill.
581 (put-text-property (1- (point)) (point) 'fill-space (match-string 1)))
582 ;; If we don't want breaks in invisible text, don't insert
583 ;; an invisible newline.
584 (if fill-nobreak-invisible
585 (remove-text-properties (1- (point)) (point)
586 '(invisible t)))
587 (if (or fill-prefix
588 (not fill-indent-according-to-mode))
589 (fill-indent-to-left-margin)
590 (indent-according-to-mode))
591 ;; Insert the fill prefix after indentation.
592 (and fill-prefix (not (equal fill-prefix ""))
593 ;; Markers that were after the whitespace are now at point: insert
594 ;; before them so they don't get stuck before the prefix.
595 (insert-before-markers-and-inherit fill-prefix)))
596
597 (defun fill-indent-to-left-margin ()
598 "Indent current line to the column given by `current-left-margin'."
599 (let ((beg (point)))
600 (indent-line-to (current-left-margin))
601 (put-text-property beg (point) 'face 'default)))
602
603 (defun fill-region-as-paragraph (from to &optional justify
604 nosqueeze squeeze-after)
605 "Fill the region as one paragraph.
606 It removes any paragraph breaks in the region and extra newlines at the end,
607 indents and fills lines between the margins given by the
608 `current-left-margin' and `current-fill-column' functions.
609 \(In most cases, the variable `fill-column' controls the width.)
610 It leaves point at the beginning of the line following the paragraph.
611
612 Normally performs justification according to the `current-justification'
613 function, but with a prefix arg, does full justification instead.
614
615 From a program, optional third arg JUSTIFY can specify any type of
616 justification. Fourth arg NOSQUEEZE non-nil means not to make spaces
617 between words canonical before filling. Fifth arg SQUEEZE-AFTER, if non-nil,
618 means don't canonicalize spaces before that position.
619
620 Return the `fill-prefix' used for filling.
621
622 If `sentence-end-double-space' is non-nil, then period followed by one
623 space does not end a sentence, so don't break a line there."
624 (interactive (progn
625 (barf-if-buffer-read-only)
626 (list (region-beginning) (region-end)
627 (if current-prefix-arg 'full))))
628 (unless (memq justify '(t nil none full center left right))
629 (setq justify 'full))
630
631 ;; Make sure "to" is the endpoint.
632 (goto-char (min from to))
633 (setq to (max from to))
634 ;; Ignore blank lines at beginning of region.
635 (skip-chars-forward " \t\n")
636
637 (let ((from-plus-indent (point))
638 (oneleft nil))
639
640 (beginning-of-line)
641 ;; We used to round up to whole line, but that prevents us from
642 ;; correctly handling filling of mixed code-and-comment where we do want
643 ;; to fill the comment but not the code. So only use (point) if it's
644 ;; further than `from', which means that `from' is followed by some
645 ;; number of empty lines.
646 (setq from (max (point) from))
647
648 ;; Delete all but one soft newline at end of region.
649 ;; And leave TO before that one.
650 (goto-char to)
651 (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
652 (if (and oneleft
653 (not (and use-hard-newlines
654 (get-text-property (1- (point)) 'hard))))
655 (delete-backward-char 1)
656 (backward-char 1)
657 (setq oneleft t)))
658 (setq to (copy-marker (point) t))
659 ;; ;; If there was no newline, and there is text in the paragraph, then
660 ;; ;; create a newline.
661 ;; (if (and (not oneleft) (> to from-plus-indent))
662 ;; (newline))
663 (goto-char from-plus-indent))
664
665 (if (not (> to (point)))
666 nil ;; There is no paragraph, only whitespace: exit now.
667
668 (or justify (setq justify (current-justification)))
669
670 ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
671 (let ((fill-prefix fill-prefix))
672 ;; Figure out how this paragraph is indented, if desired.
673 (when (and adaptive-fill-mode
674 (or (null fill-prefix) (string= fill-prefix "")))
675 (setq fill-prefix (fill-context-prefix from to))
676 ;; Ignore a white-space only fill-prefix
677 ;; if we indent-according-to-mode.
678 (when (and fill-prefix fill-indent-according-to-mode
679 (string-match "\\`[ \t]*\\'" fill-prefix))
680 (setq fill-prefix nil)))
681
682 (goto-char from)
683 (beginning-of-line)
684
685 (if (not justify) ; filling disabled: just check indentation
686 (progn
687 (goto-char from)
688 (while (< (point) to)
689 (if (and (not (eolp))
690 (< (current-indentation) (current-left-margin)))
691 (fill-indent-to-left-margin))
692 (forward-line 1)))
693
694 (if use-hard-newlines
695 (remove-list-of-text-properties from to '(hard)))
696 ;; Make sure first line is indented (at least) to left margin...
697 (if (or (memq justify '(right center))
698 (< (current-indentation) (current-left-margin)))
699 (fill-indent-to-left-margin))
700 ;; Delete the fill-prefix from every line.
701 (fill-delete-prefix from to fill-prefix)
702 (setq from (point))
703
704 ;; FROM, and point, are now before the text to fill,
705 ;; but after any fill prefix on the first line.
706
707 (fill-delete-newlines from to justify nosqueeze squeeze-after)
708
709 ;; This is the actual filling loop.
710 (goto-char from)
711 (let (linebeg)
712 (while (< (point) to)
713 (setq linebeg (point))
714 (move-to-column (current-fill-column))
715 (if (when (< (point) to)
716 ;; Find the position where we'll break the line.
717 (forward-char 1) ;Use an immediately following space, if any.
718 (fill-move-to-break-point linebeg)
719 ;; Check again to see if we got to the end of
720 ;; the paragraph.
721 (skip-chars-forward " \t")
722 (< (point) to))
723 ;; Found a place to cut.
724 (progn
725 (fill-newline)
726 (when justify
727 ;; Justify the line just ended, if desired.
728 (save-excursion
729 (forward-line -1)
730 (justify-current-line justify nil t))))
731
732 (goto-char to)
733 ;; Justify this last line, if desired.
734 (if justify (justify-current-line justify t t))))))
735 ;; Leave point after final newline.
736 (goto-char to)
737 (unless (eobp) (forward-char 1))
738 ;; Return the fill-prefix we used
739 fill-prefix)))
740
741 (defsubst skip-line-prefix (prefix)
742 "If point is inside the string PREFIX at the beginning of line, move past it."
743 (when (and prefix
744 (< (- (point) (line-beginning-position)) (length prefix))
745 (save-excursion
746 (beginning-of-line)
747 (looking-at (regexp-quote prefix))))
748 (goto-char (match-end 0))))
749
750 (defun fill-minibuffer-function (arg)
751 "Fill a paragraph in the minibuffer, ignoring the prompt."
752 (save-restriction
753 (narrow-to-region (minibuffer-prompt-end) (point-max))
754 (fill-paragraph arg)))
755
756 (defun fill-paragraph (arg)
757 "Fill paragraph at or after point. Prefix ARG means justify as well.
758 If `sentence-end-double-space' is non-nil, then period followed by one
759 space does not end a sentence, so don't break a line there.
760 the variable `fill-column' controls the width for filling.
761
762 If `fill-paragraph-function' is non-nil, we call it (passing our
763 argument to it), and if it returns non-nil, we simply return its value.
764
765 If `fill-paragraph-function' is nil, return the `fill-prefix' used for filling."
766 (interactive (progn
767 (barf-if-buffer-read-only)
768 (list (if current-prefix-arg 'full))))
769 ;; First try fill-paragraph-function.
770 (or (and (not (eq fill-paragraph-function t))
771 (or fill-paragraph-function
772 (and (minibufferp (current-buffer))
773 (= 1 (point-min))))
774 (let ((function (or fill-paragraph-function
775 ;; In the minibuffer, don't count the width
776 ;; of the prompt.
777 'fill-minibuffer-function))
778 ;; If fill-paragraph-function is set, it probably takes care
779 ;; of comments and stuff. If not, it will have to set
780 ;; fill-paragraph-handle-comment back to t explicitly or
781 ;; return nil.
782 (fill-paragraph-handle-comment nil)
783 (fill-paragraph-function t))
784 (funcall function arg)))
785 ;; Then try our syntax-aware filling code.
786 (and fill-paragraph-handle-comment
787 ;; Our code only handles \n-terminated comments right now.
788 comment-start (equal comment-end "")
789 (let ((fill-paragraph-handle-comment nil))
790 (fill-comment-paragraph arg)))
791 ;; If it all fails, default to the good ol' text paragraph filling.
792 (let ((before (point))
793 (paragraph-start paragraph-start)
794 ;; Fill prefix used for filling the paragraph.
795 fill-pfx)
796 ;; Try to prevent code sections and comment sections from being
797 ;; filled together.
798 (when (and fill-paragraph-handle-comment comment-start-skip)
799 (setq paragraph-start
800 (concat paragraph-start "\\|[ \t]*\\(?:"
801 comment-start-skip "\\)")))
802 (save-excursion
803 ;; To make sure the return value of forward-paragraph is meaningful,
804 ;; we have to start from the beginning of line, otherwise skipping
805 ;; past the last few chars of a paragraph-separator would count as
806 ;; a paragraph (and not skipping any chars at EOB would not count
807 ;; as a paragraph even if it is).
808 (move-to-left-margin)
809 (if (not (zerop (forward-paragraph)))
810 ;; There's no paragraph at or after point: give up.
811 (setq fill-pfx "")
812 (let ((end (point))
813 (beg (progn (backward-paragraph) (point))))
814 (goto-char before)
815 (setq fill-pfx
816 (if use-hard-newlines
817 ;; Can't use fill-region-as-paragraph, since this
818 ;; paragraph may still contain hard newlines. See
819 ;; fill-region.
820 (fill-region beg end arg)
821 (fill-region-as-paragraph beg end arg))))))
822 fill-pfx)))
823
824 (defun fill-comment-paragraph (&optional justify)
825 "Fill current comment.
826 If we're not in a comment, just return nil so that the caller
827 can take care of filling. JUSTIFY is used as in `fill-paragraph'."
828 (comment-normalize-vars)
829 (let (has-code-and-comment ; Non-nil if it contains code and a comment.
830 comin comstart)
831 ;; Figure out what kind of comment we are looking at.
832 (save-excursion
833 (beginning-of-line)
834 (when (setq comstart (comment-search-forward (line-end-position) t))
835 (setq comin (point))
836 (goto-char comstart) (skip-chars-backward " \t")
837 (setq has-code-and-comment (not (bolp)))))
838
839 (if (not comstart)
840 ;; Return nil, so the normal filling will take place.
841 nil
842
843 ;; Narrow to include only the comment, and then fill the region.
844 (let* ((fill-prefix fill-prefix)
845 (commark
846 (comment-string-strip (buffer-substring comstart comin) nil t))
847 (comment-re
848 ;; A regexp more specialized than comment-start-skip, that only
849 ;; matches the current commark rather than any valid commark.
850 ;;
851 ;; The specialized regexp only works for "normal" comment
852 ;; syntax, not for Texinfo's "@c" (which can't be immediately
853 ;; followed by word-chars) or Fortran's "C" (which needs to be
854 ;; at bol), so check that comment-start-skip indeed allows the
855 ;; commark to appear in the middle of the line and followed by
856 ;; word chars. The choice of "\0" and "a" is mostly arbitrary.
857 (if (string-match comment-start-skip (concat "\0" commark "a"))
858 (concat "[ \t]*" (regexp-quote commark)
859 ;; Make sure we only match comments that
860 ;; use the exact same comment marker.
861 "[^" (substring commark -1) "]")
862 (concat "[ \t]*\\(?:" comment-start-skip "\\)")))
863 (comment-fill-prefix ; Compute a fill prefix.
864 (save-excursion
865 (goto-char comstart)
866 (if has-code-and-comment
867 (concat
868 (if (not indent-tabs-mode)
869 (make-string (current-column) ?\s)
870 (concat
871 (make-string (/ (current-column) tab-width) ?\t)
872 (make-string (% (current-column) tab-width) ?\s)))
873 (buffer-substring (point) comin))
874 (buffer-substring (line-beginning-position) comin))))
875 beg end)
876 (save-excursion
877 (save-restriction
878 (beginning-of-line)
879 (narrow-to-region
880 ;; Find the first line we should include in the region to fill.
881 (if has-code-and-comment
882 (line-beginning-position)
883 (save-excursion
884 (while (and (zerop (forward-line -1))
885 (looking-at comment-re)))
886 ;; We may have gone too far. Go forward again.
887 (line-beginning-position
888 (if (progn
889 (goto-char
890 (or (comment-search-forward (line-end-position) t)
891 (point)))
892 (looking-at comment-re))
893 (progn (setq comstart (point)) 1)
894 (progn (setq comstart (point)) 2)))))
895 ;; Find the beginning of the first line past the region to fill.
896 (save-excursion
897 (while (progn (forward-line 1)
898 (looking-at comment-re)))
899 (point)))
900 ;; Obey paragraph starters and boundaries within comments.
901 (let* ((paragraph-separate
902 ;; Use the default values since they correspond to
903 ;; the values to use for plain text.
904 (concat paragraph-separate "\\|[ \t]*\\(?:"
905 comment-start-skip "\\)\\(?:"
906 (default-value 'paragraph-separate) "\\)"))
907 (paragraph-start
908 (concat paragraph-start "\\|[ \t]*\\(?:"
909 comment-start-skip "\\)\\(?:"
910 (default-value 'paragraph-start) "\\)"))
911 ;; We used to rely on fill-prefix to break paragraph at
912 ;; comment-starter changes, but it did not work for the
913 ;; first line (mixed comment&code).
914 ;; We now use comment-re instead to "manually" make sure
915 ;; we treat comment-marker changes as paragraph boundaries.
916 ;; (paragraph-ignore-fill-prefix nil)
917 ;; (fill-prefix comment-fill-prefix)
918 (after-line (if has-code-and-comment
919 (line-beginning-position 2))))
920 (setq end (progn (forward-paragraph) (point)))
921 ;; If this comment starts on a line with code,
922 ;; include that line in the filling.
923 (setq beg (progn (backward-paragraph)
924 (if (eq (point) after-line)
925 (forward-line -1))
926 (point)))))
927
928 ;; Find the fill-prefix to use.
929 (cond
930 (fill-prefix) ; Use the user-provided fill prefix.
931 ((and adaptive-fill-mode ; Try adaptive fill mode.
932 (setq fill-prefix (fill-context-prefix beg end))
933 (string-match comment-start-skip fill-prefix)))
934 (t
935 (setq fill-prefix comment-fill-prefix)))
936
937 ;; Don't fill with narrowing.
938 (or
939 (fill-region-as-paragraph
940 (max comstart beg) end justify nil
941 ;; Don't canonicalize spaces within the code just before
942 ;; the comment.
943 (save-excursion
944 (goto-char beg)
945 (if (looking-at fill-prefix)
946 nil
947 (re-search-forward comment-start-skip))))
948 ;; Make sure we don't return nil.
949 t))))))
950
951 (defun fill-region (from to &optional justify nosqueeze to-eop)
952 "Fill each of the paragraphs in the region.
953 A prefix arg means justify as well.
954 Ordinarily the variable `fill-column' controls the width.
955
956 Noninteractively, the third argument JUSTIFY specifies which
957 kind of justification to do: `full', `left', `right', `center',
958 or `none' (equivalent to nil). A value of t means handle each
959 paragraph as specified by its text properties.
960
961 The fourth arg NOSQUEEZE non-nil means to leave whitespace other
962 than line breaks untouched, and fifth arg TO-EOP non-nil means
963 to keep filling to the end of the paragraph (or next hard newline,
964 if variable `use-hard-newlines' is on).
965
966 Return the fill-prefix used for filling the last paragraph.
967
968 If `sentence-end-double-space' is non-nil, then period followed by one
969 space does not end a sentence, so don't break a line there."
970 (interactive (progn
971 (barf-if-buffer-read-only)
972 (list (region-beginning) (region-end)
973 (if current-prefix-arg 'full))))
974 (unless (memq justify '(t nil none full center left right))
975 (setq justify 'full))
976 (let (max beg fill-pfx)
977 (goto-char (max from to))
978 (when to-eop
979 (skip-chars-backward "\n")
980 (forward-paragraph))
981 (setq max (copy-marker (point) t))
982 (goto-char (setq beg (min from to)))
983 (beginning-of-line)
984 (while (< (point) max)
985 (let ((initial (point))
986 end)
987 ;; If using hard newlines, break at every one for filling
988 ;; purposes rather than using paragraph breaks.
989 (if use-hard-newlines
990 (progn
991 (while (and (setq end (text-property-any (point) max
992 'hard t))
993 (not (= ?\n (char-after end)))
994 (not (>= end max)))
995 (goto-char (1+ end)))
996 (setq end (if end (min max (1+ end)) max))
997 (goto-char initial))
998 (forward-paragraph 1)
999 (setq end (min max (point)))
1000 (forward-paragraph -1))
1001 (if (< (point) beg)
1002 (goto-char beg))
1003 (if (>= (point) initial)
1004 (setq fill-pfx
1005 (fill-region-as-paragraph (point) end justify nosqueeze))
1006 (goto-char end))))
1007 fill-pfx))
1008
1009 \f
1010 (defcustom default-justification 'left
1011 "*Method of justifying text not otherwise specified.
1012 Possible values are `left', `right', `full', `center', or `none'.
1013 The requested kind of justification is done whenever lines are filled.
1014 The `justification' text-property can locally override this variable."
1015 :type '(choice (const left)
1016 (const right)
1017 (const full)
1018 (const center)
1019 (const none))
1020 :group 'fill)
1021 (make-variable-buffer-local 'default-justification)
1022
1023 (defun current-justification ()
1024 "How should we justify this line?
1025 This returns the value of the text-property `justification',
1026 or the variable `default-justification' if there is no text-property.
1027 However, it returns nil rather than `none' to mean \"don't justify\"."
1028 (let ((j (or (get-text-property
1029 ;; Make sure we're looking at paragraph body.
1030 (save-excursion (skip-chars-forward " \t")
1031 (if (and (eobp) (not (bobp)))
1032 (1- (point)) (point)))
1033 'justification)
1034 default-justification)))
1035 (if (eq 'none j)
1036 nil
1037 j)))
1038
1039 (defun set-justification (begin end style &optional whole-par)
1040 "Set the region's justification style to STYLE.
1041 This commands prompts for the kind of justification to use.
1042 If the mark is not active, this command operates on the current paragraph.
1043 If the mark is active, it operates on the region. However, if the
1044 beginning and end of the region are not at paragraph breaks, they are
1045 moved to the beginning and end \(respectively) of the paragraphs they
1046 are in.
1047
1048 If variable `use-hard-newlines' is true, all hard newlines are
1049 taken to be paragraph breaks.
1050
1051 When calling from a program, operates just on region between BEGIN and END,
1052 unless optional fourth arg WHOLE-PAR is non-nil. In that case bounds are
1053 extended to include entire paragraphs as in the interactive command."
1054 (interactive (list (if mark-active (region-beginning) (point))
1055 (if mark-active (region-end) (point))
1056 (let ((s (completing-read
1057 "Set justification to: "
1058 '(("left") ("right") ("full")
1059 ("center") ("none"))
1060 nil t)))
1061 (if (equal s "") (error ""))
1062 (intern s))
1063 t))
1064 (save-excursion
1065 (save-restriction
1066 (if whole-par
1067 (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
1068 (paragraph-ignore-fill-prefix (if use-hard-newlines t
1069 paragraph-ignore-fill-prefix)))
1070 (goto-char begin)
1071 (while (and (bolp) (not (eobp))) (forward-char 1))
1072 (backward-paragraph)
1073 (setq begin (point))
1074 (goto-char end)
1075 (skip-chars-backward " \t\n" begin)
1076 (forward-paragraph)
1077 (setq end (point))))
1078
1079 (narrow-to-region (point-min) end)
1080 (unjustify-region begin (point-max))
1081 (put-text-property begin (point-max) 'justification style)
1082 (fill-region begin (point-max) nil t))))
1083
1084 (defun set-justification-none (b e)
1085 "Disable automatic filling for paragraphs in the region.
1086 If the mark is not active, this applies to the current paragraph."
1087 (interactive (list (if mark-active (region-beginning) (point))
1088 (if mark-active (region-end) (point))))
1089 (set-justification b e 'none t))
1090
1091 (defun set-justification-left (b e)
1092 "Make paragraphs in the region left-justified.
1093 This means they are flush at the left margin and ragged on the right.
1094 This is usually the default, but see the variable `default-justification'.
1095 If the mark is not active, this applies to the current paragraph."
1096 (interactive (list (if mark-active (region-beginning) (point))
1097 (if mark-active (region-end) (point))))
1098 (set-justification b e 'left t))
1099
1100 (defun set-justification-right (b e)
1101 "Make paragraphs in the region right-justified.
1102 This means they are flush at the right margin and ragged on the left.
1103 If the mark is not active, this applies to the current paragraph."
1104 (interactive (list (if mark-active (region-beginning) (point))
1105 (if mark-active (region-end) (point))))
1106 (set-justification b e 'right t))
1107
1108 (defun set-justification-full (b e)
1109 "Make paragraphs in the region fully justified.
1110 This makes lines flush on both margins by inserting spaces between words.
1111 If the mark is not active, this applies to the current paragraph."
1112 (interactive (list (if mark-active (region-beginning) (point))
1113 (if mark-active (region-end) (point))))
1114 (set-justification b e 'full t))
1115
1116 (defun set-justification-center (b e)
1117 "Make paragraphs in the region centered.
1118 If the mark is not active, this applies to the current paragraph."
1119 (interactive (list (if mark-active (region-beginning) (point))
1120 (if mark-active (region-end) (point))))
1121 (set-justification b e 'center t))
1122
1123 ;; A line has up to six parts:
1124 ;;
1125 ;; >>> hello.
1126 ;; [Indent-1][FP][ Indent-2 ][text][trailing whitespace][newline]
1127 ;;
1128 ;; "Indent-1" is the left-margin indentation; normally it ends at column
1129 ;; given by the `current-left-margin' function.
1130 ;; "FP" is the fill-prefix. It can be any string, including whitespace.
1131 ;; "Indent-2" is added to justify a line if the `current-justification' is
1132 ;; `center' or `right'. In `left' and `full' justification regions, any
1133 ;; whitespace there is part of the line's text, and should not be changed.
1134 ;; Trailing whitespace is not counted as part of the line length when
1135 ;; center- or right-justifying.
1136 ;;
1137 ;; All parts of the line are optional, although the final newline can
1138 ;; only be missing on the last line of the buffer.
1139
1140 (defun justify-current-line (&optional how eop nosqueeze)
1141 "Do some kind of justification on this line.
1142 Normally does full justification: adds spaces to the line to make it end at
1143 the column given by `current-fill-column'.
1144 Optional first argument HOW specifies alternate type of justification:
1145 it can be `left', `right', `full', `center', or `none'.
1146 If HOW is t, will justify however the `current-justification' function says to.
1147 If HOW is nil or missing, full justification is done by default.
1148 Second arg EOP non-nil means that this is the last line of the paragraph, so
1149 it will not be stretched by full justification.
1150 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
1151 otherwise it is made canonical."
1152 (interactive "*")
1153 (if (eq t how) (setq how (or (current-justification) 'none))
1154 (if (null how) (setq how 'full)
1155 (or (memq how '(none left right center))
1156 (setq how 'full))))
1157 (or (memq how '(none left)) ; No action required for these.
1158 (let ((fc (current-fill-column))
1159 (pos (point-marker))
1160 fp-end ; point at end of fill prefix
1161 beg ; point at beginning of line's text
1162 end ; point at end of line's text
1163 indent ; column of `beg'
1164 endcol ; column of `end'
1165 ncols ; new indent point or offset
1166 (nspaces 0) ; number of spaces between words
1167 ; in line (not space characters)
1168 (curr-fracspace 0) ; current fractional space amount
1169 count)
1170 (end-of-line)
1171 ;; Check if this is the last line of the paragraph.
1172 (if (and use-hard-newlines (null eop)
1173 (get-text-property (point) 'hard))
1174 (setq eop t))
1175 (skip-chars-backward " \t")
1176 ;; Quick exit if it appears to be properly justified already
1177 ;; or there is no text.
1178 (if (or (bolp)
1179 (and (memq how '(full right))
1180 (= (current-column) fc)))
1181 nil
1182 (setq end (point))
1183 (beginning-of-line)
1184 (skip-chars-forward " \t")
1185 ;; Skip over fill-prefix.
1186 (if (and fill-prefix
1187 (not (string-equal fill-prefix ""))
1188 (equal fill-prefix
1189 (buffer-substring
1190 (point) (min (point-max) (+ (length fill-prefix)
1191 (point))))))
1192 (forward-char (length fill-prefix))
1193 (if (and adaptive-fill-mode
1194 (looking-at adaptive-fill-regexp))
1195 (goto-char (match-end 0))))
1196 (setq fp-end (point))
1197 (skip-chars-forward " \t")
1198 ;; This is beginning of the line's text.
1199 (setq indent (current-column))
1200 (setq beg (point))
1201 (goto-char end)
1202 (setq endcol (current-column))
1203
1204 ;; HOW can't be null or left--we would have exited already
1205 (cond ((eq 'right how)
1206 (setq ncols (- fc endcol))
1207 (if (< ncols 0)
1208 ;; Need to remove some indentation
1209 (delete-region
1210 (progn (goto-char fp-end)
1211 (if (< (current-column) (+ indent ncols))
1212 (move-to-column (+ indent ncols) t))
1213 (point))
1214 (progn (move-to-column indent) (point)))
1215 ;; Need to add some
1216 (goto-char beg)
1217 (indent-to (+ indent ncols))
1218 ;; If point was at beginning of text, keep it there.
1219 (if (= beg pos)
1220 (move-marker pos (point)))))
1221
1222 ((eq 'center how)
1223 ;; Figure out how much indentation is needed
1224 (setq ncols (+ (current-left-margin)
1225 (/ (- fc (current-left-margin) ;avail. space
1226 (- endcol indent)) ;text width
1227 2)))
1228 (if (< ncols indent)
1229 ;; Have too much indentation - remove some
1230 (delete-region
1231 (progn (goto-char fp-end)
1232 (if (< (current-column) ncols)
1233 (move-to-column ncols t))
1234 (point))
1235 (progn (move-to-column indent) (point)))
1236 ;; Have too little - add some
1237 (goto-char beg)
1238 (indent-to ncols)
1239 ;; If point was at beginning of text, keep it there.
1240 (if (= beg pos)
1241 (move-marker pos (point)))))
1242
1243 ((eq 'full how)
1244 ;; Insert extra spaces between words to justify line
1245 (save-restriction
1246 (narrow-to-region beg end)
1247 (or nosqueeze
1248 (canonically-space-region beg end))
1249 (goto-char (point-max))
1250 ;; count word spaces in line
1251 (while (search-backward " " nil t)
1252 (setq nspaces (1+ nspaces))
1253 (skip-chars-backward " "))
1254 (setq ncols (- fc endcol))
1255 ;; Ncols is number of additional space chars needed
1256 (if (and (> ncols 0) (> nspaces 0) (not eop))
1257 (progn
1258 (setq curr-fracspace (+ ncols (/ (1+ nspaces) 2))
1259 count nspaces)
1260 (while (> count 0)
1261 (skip-chars-forward " ")
1262 (insert-and-inherit
1263 (make-string (/ curr-fracspace nspaces) ?\s))
1264 (search-forward " " nil t)
1265 (setq count (1- count)
1266 curr-fracspace
1267 (+ (% curr-fracspace nspaces) ncols)))))))
1268 (t (error "Unknown justification value"))))
1269 (goto-char pos)
1270 (move-marker pos nil)))
1271 nil)
1272
1273 (defun unjustify-current-line ()
1274 "Remove justification whitespace from current line.
1275 If the line is centered or right-justified, this function removes any
1276 indentation past the left margin. If the line is full-justified, it removes
1277 extra spaces between words. It does nothing in other justification modes."
1278 (let ((justify (current-justification)))
1279 (cond ((eq 'left justify) nil)
1280 ((eq nil justify) nil)
1281 ((eq 'full justify) ; full justify: remove extra spaces
1282 (beginning-of-line-text)
1283 (canonically-space-region (point) (line-end-position)))
1284 ((memq justify '(center right))
1285 (save-excursion
1286 (move-to-left-margin nil t)
1287 ;; Position ourselves after any fill-prefix.
1288 (if (and fill-prefix
1289 (not (string-equal fill-prefix ""))
1290 (equal fill-prefix
1291 (buffer-substring
1292 (point) (min (point-max) (+ (length fill-prefix)
1293 (point))))))
1294 (forward-char (length fill-prefix)))
1295 (delete-region (point) (progn (skip-chars-forward " \t")
1296 (point))))))))
1297
1298 (defun unjustify-region (&optional begin end)
1299 "Remove justification whitespace from region.
1300 For centered or right-justified regions, this function removes any indentation
1301 past the left margin from each line. For full-justified lines, it removes
1302 extra spaces between words. It does nothing in other justification modes.
1303 Arguments BEGIN and END are optional; default is the whole buffer."
1304 (save-excursion
1305 (save-restriction
1306 (if end (narrow-to-region (point-min) end))
1307 (goto-char (or begin (point-min)))
1308 (while (not (eobp))
1309 (unjustify-current-line)
1310 (forward-line 1)))))
1311
1312 \f
1313 (defun fill-nonuniform-paragraphs (min max &optional justifyp citation-regexp)
1314 "Fill paragraphs within the region, allowing varying indentation within each.
1315 This command divides the region into \"paragraphs\",
1316 only at paragraph-separator lines, then fills each paragraph
1317 using as the fill prefix the smallest indentation of any line
1318 in the paragraph.
1319
1320 When calling from a program, pass range to fill as first two arguments.
1321
1322 Optional third and fourth arguments JUSTIFYP and CITATION-REGEXP:
1323 JUSTIFYP to justify paragraphs (prefix arg).
1324 When filling a mail message, pass a regexp for CITATION-REGEXP
1325 which will match the prefix of a line which is a citation marker
1326 plus whitespace, but no other kind of prefix.
1327 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1328 (interactive (progn
1329 (barf-if-buffer-read-only)
1330 (list (region-beginning) (region-end)
1331 (if current-prefix-arg 'full))))
1332 (let ((fill-individual-varying-indent t))
1333 (fill-individual-paragraphs min max justifyp citation-regexp)))
1334
1335 (defun fill-individual-paragraphs (min max &optional justify citation-regexp)
1336 "Fill paragraphs of uniform indentation within the region.
1337 This command divides the region into \"paragraphs\",
1338 treating every change in indentation level or prefix as a paragraph boundary,
1339 then fills each paragraph using its indentation level as the fill prefix.
1340
1341 There is one special case where a change in indentation does not start
1342 a new paragraph. This is for text of this form:
1343
1344 foo> This line with extra indentation starts
1345 foo> a paragraph that continues on more lines.
1346
1347 These lines are filled together.
1348
1349 When calling from a program, pass the range to fill
1350 as the first two arguments.
1351
1352 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1353 JUSTIFY to justify paragraphs (prefix arg),
1354 When filling a mail message, pass a regexp for CITATION-REGEXP
1355 which will match the prefix of a line which is a citation marker
1356 plus whitespace, but no other kind of prefix.
1357 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1358 (interactive (progn
1359 (barf-if-buffer-read-only)
1360 (list (region-beginning) (region-end)
1361 (if current-prefix-arg 'full))))
1362 (save-restriction
1363 (save-excursion
1364 (goto-char min)
1365 (beginning-of-line)
1366 (narrow-to-region (point) max)
1367 (if citation-regexp
1368 (while (and (not (eobp))
1369 (or (looking-at "[ \t]*[^ \t\n]+:")
1370 (looking-at "[ \t]*$")))
1371 (if (looking-at "[ \t]*[^ \t\n]+:")
1372 (search-forward "\n\n" nil 'move)
1373 (forward-line 1))))
1374 (narrow-to-region (point) max)
1375 ;; Loop over paragraphs.
1376 (while (progn
1377 ;; Skip over all paragraph-separating lines
1378 ;; so as to not include them in any paragraph.
1379 (while (and (not (eobp))
1380 (progn (move-to-left-margin)
1381 (and (not (eobp))
1382 (looking-at paragraph-separate))))
1383 (forward-line 1))
1384 (skip-chars-forward " \t\n") (not (eobp)))
1385 (move-to-left-margin)
1386 (let ((start (point))
1387 fill-prefix fill-prefix-regexp)
1388 ;; Find end of paragraph, and compute the smallest fill-prefix
1389 ;; that fits all the lines in this paragraph.
1390 (while (progn
1391 ;; Update the fill-prefix on the first line
1392 ;; and whenever the prefix good so far is too long.
1393 (if (not (and fill-prefix
1394 (looking-at fill-prefix-regexp)))
1395 (setq fill-prefix
1396 (fill-individual-paragraphs-prefix
1397 citation-regexp)
1398 fill-prefix-regexp (regexp-quote fill-prefix)))
1399 (forward-line 1)
1400 (if (bolp)
1401 ;; If forward-line went past a newline,
1402 ;; move further to the left margin.
1403 (move-to-left-margin))
1404 ;; Now stop the loop if end of paragraph.
1405 (and (not (eobp))
1406 (if fill-individual-varying-indent
1407 ;; If this line is a separator line, with or
1408 ;; without prefix, end the paragraph.
1409 (and
1410 (not (looking-at paragraph-separate))
1411 (save-excursion
1412 (not (and (looking-at fill-prefix-regexp)
1413 (progn (forward-char
1414 (length fill-prefix))
1415 (looking-at
1416 paragraph-separate))))))
1417 ;; If this line has more or less indent
1418 ;; than the fill prefix wants, end the paragraph.
1419 (and (looking-at fill-prefix-regexp)
1420 ;; If fill prefix is shorter than a new
1421 ;; fill prefix computed here, end paragraph.
1422 (let ((this-line-fill-prefix
1423 (fill-individual-paragraphs-prefix
1424 citation-regexp)))
1425 (>= (length fill-prefix)
1426 (length this-line-fill-prefix)))
1427 (save-excursion
1428 (not (progn (forward-char
1429 (length fill-prefix))
1430 (or (looking-at "[ \t]")
1431 (looking-at paragraph-separate)
1432 (looking-at paragraph-start)))))
1433 (not (and (equal fill-prefix "")
1434 citation-regexp
1435 (looking-at citation-regexp))))))))
1436 ;; Fill this paragraph, but don't add a newline at the end.
1437 (let ((had-newline (bolp)))
1438 (fill-region-as-paragraph start (point) justify)
1439 (if (and (bolp) (not had-newline))
1440 (delete-char -1))))))))
1441 (defun fill-individual-paragraphs-prefix (citation-regexp)
1442 (let* ((adaptive-fill-first-line-regexp ".*")
1443 (just-one-line-prefix
1444 ;; Accept any prefix rather than just the ones matched by
1445 ;; adaptive-fill-first-line-regexp.
1446 (fill-context-prefix (point) (line-beginning-position 2)))
1447 (two-lines-prefix
1448 (fill-context-prefix (point) (line-beginning-position 3))))
1449 (if (not just-one-line-prefix)
1450 (buffer-substring
1451 (point) (save-excursion (skip-chars-forward " \t") (point)))
1452 ;; See if the citation part of JUST-ONE-LINE-PREFIX
1453 ;; is the same as that of TWO-LINES-PREFIX,
1454 ;; except perhaps with longer whitespace.
1455 (if (and just-one-line-prefix two-lines-prefix
1456 (let* ((one-line-citation-part
1457 (fill-individual-paragraphs-citation
1458 just-one-line-prefix citation-regexp))
1459 (two-lines-citation-part
1460 (fill-individual-paragraphs-citation
1461 two-lines-prefix citation-regexp))
1462 (adjusted-two-lines-citation-part
1463 (substring two-lines-citation-part 0
1464 (string-match "[ \t]*\\'"
1465 two-lines-citation-part))))
1466 (and
1467 (string-match (concat "\\`"
1468 (regexp-quote
1469 adjusted-two-lines-citation-part)
1470 "[ \t]*\\'")
1471 one-line-citation-part)
1472 (>= (string-width one-line-citation-part)
1473 (string-width two-lines-citation-part)))))
1474 two-lines-prefix
1475 just-one-line-prefix))))
1476
1477 (defun fill-individual-paragraphs-citation (string citation-regexp)
1478 (if citation-regexp
1479 (if (string-match citation-regexp string)
1480 (match-string 0 string)
1481 "")
1482 string))
1483
1484 ;; arch-tag: 727ad455-1161-4fa9-8df5-0f74b179216d
1485 ;;; fill.el ends here