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