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