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