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