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