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