(fill-region-as-paragraph): Fix previous change.
[bpt/emacs.git] / lisp / textmodes / fill.el
1 ;;; fill.el --- fill commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 92, 94, 95, 96, 97, 1999 Free Software Foundation, Inc.
4
5 ;; Keywords: wp
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; All the commands for filling text. These are documented in the Emacs
27 ;; manual.
28
29 ;;; Code:
30
31 (defcustom fill-individual-varying-indent nil
32 "*Controls criterion for a new paragraph in `fill-individual-paragraphs'.
33 Non-nil means changing indent doesn't end a paragraph.
34 That mode can handle paragraphs with extra indentation on the first line,
35 but it requires separator lines between paragraphs.
36 A value of nil means that any change in indentation starts a new paragraph."
37 :type 'boolean
38 :group 'fill)
39
40 (defcustom sentence-end-double-space t
41 "*Non-nil means a single space does not end a sentence.
42
43 If you change this, you should also change `sentence-end'.
44 See Info node `Sentences'."
45 :type 'boolean
46 :group 'fill)
47
48 (defcustom colon-double-space nil
49 "*Non-nil means put two spaces after a colon when filling."
50 :type 'boolean
51 :group 'fill)
52
53 (defcustom sentence-end-without-period nil
54 "*Non-nil means a sentence will end without period.
55 For example, Thai text ends with double space but without period."
56 :type 'boolean
57 :group 'fill)
58
59 (defvar fill-paragraph-function nil
60 "Mode-specific function to fill a paragraph, or nil if there is none.
61 If the function returns nil, then `fill-paragraph' does its normal work.")
62
63 (defvar enable-kinsoku t
64 "*Non-nil means enable \"kinsoku\" processing on filling paragraph.
65 Kinsoku processing is designed to prevent certain characters from being
66 placed at the beginning or end of a line by filling.
67 See the documentation of `kinsoku' for more information.")
68
69 (defun set-fill-prefix ()
70 "Set the fill prefix to the current line up to point.
71 Filling expects lines to start with the fill prefix and
72 reinserts the fill prefix in each resulting line."
73 (interactive)
74 (setq fill-prefix (buffer-substring
75 (save-excursion (move-to-left-margin) (point))
76 (point)))
77 (if (equal fill-prefix "")
78 (setq fill-prefix nil))
79 (if fill-prefix
80 (message "fill-prefix: \"%s\"" fill-prefix)
81 (message "fill-prefix cancelled")))
82
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)
87
88 (defcustom adaptive-fill-regexp "[ \t]*\\([-|#;>*]+ *\\|(?[0-9]+[.)] *\\)*"
89 "*Regexp to match text at start of line that constitutes indentation.
90 If Adaptive Fill mode is enabled, a prefix matching this pattern
91 on the first and second lines of a paragraph is used as the
92 standard indentation for the whole paragraph.
93
94 If the paragraph has just one line, the indentation is taken from that
95 line, but in that case `adaptive-fill-first-line-regexp' also plays
96 a role."
97 :type 'regexp
98 :group 'fill)
99
100 (defcustom adaptive-fill-first-line-regexp "\\`[ \t]*\\'"
101 "*Regexp specifying whether to set fill prefix from a one-line paragraph.
102 When a paragraph has just one line, then after `adaptive-fill-regexp'
103 finds the prefix at the beginning of the line, if it doesn't
104 match this regexp, it is replaced with whitespace.
105
106 By default, this regexp matches sequences of just spaces and tabs.
107
108 However, we never use a prefix from a one-line paragraph
109 if it would act as a paragraph-starter on the second line."
110 :type 'regexp
111 :group 'fill)
112
113 (defcustom adaptive-fill-function nil
114 "*Function to call to choose a fill prefix for a paragraph.
115 This function is used when `adaptive-fill-regexp' does not match."
116 :type 'function
117 :group 'fill)
118
119 (defun current-fill-column ()
120 "Return the fill-column to use for this line.
121 The fill-column to use for a buffer is stored in the variable `fill-column',
122 but can be locally modified by the `right-margin' text property, which is
123 subtracted from `fill-column'.
124
125 The fill column to use for a line is the first column at which the column
126 number equals or exceeds the local fill-column - right-margin difference."
127 (save-excursion
128 (if fill-column
129 (let* ((here (progn (beginning-of-line) (point)))
130 (here-col 0)
131 (eol (progn (end-of-line) (point)))
132 margin fill-col change col)
133 ;; Look separately at each region of line with a different right-margin.
134 (while (and (setq margin (get-text-property here 'right-margin)
135 fill-col (- fill-column (or margin 0))
136 change (text-property-not-all
137 here eol 'right-margin margin))
138 (progn (goto-char (1- change))
139 (setq col (current-column))
140 (< col fill-col)))
141 (setq here change
142 here-col col))
143 (max here-col fill-col)))))
144
145 (defun canonically-space-region (beg end)
146 "Remove extra spaces between words in region.
147 Leave one space between words, two at end of sentences or after colons
148 \(depending on values of `sentence-end-double-space', `colon-double-space',
149 and `sentence-end-without-period').
150 Remove indentation from each line."
151 (interactive "*r")
152 (save-excursion
153 (goto-char beg)
154 ;; Nuke tabs; they get screwed up in a fill.
155 ;; This is quick, but loses when a tab follows the end of a sentence.
156 ;; Actually, it is difficult to tell that from "Mr.\tSmith".
157 ;; Blame the typist.
158 (subst-char-in-region beg end ?\t ?\ )
159 (while (and (< (point) end)
160 (re-search-forward " *" end t))
161 (delete-region
162 (+ (match-beginning 0)
163 ;; Determine number of spaces to leave:
164 (save-excursion
165 (skip-chars-backward " ]})\"'")
166 (cond ((and sentence-end-double-space
167 (or (memq (preceding-char) '(?. ?? ?!))
168 (and sentence-end-without-period
169 (= (char-syntax (preceding-char)) ?w)))) 2)
170 ((and colon-double-space
171 (= (preceding-char) ?:)) 2)
172 ((char-equal (preceding-char) ?\n) 0)
173 (t 1))))
174 (match-end 0)))
175 ;; Make sure sentences ending at end of line get an extra space.
176 ;; loses on split abbrevs ("Mr.\nSmith")
177 (goto-char beg)
178 (while (and (< (point) end)
179 (re-search-forward "[.?!][])}\"']*$" end t))
180 ;; We insert before markers in case a caller such as
181 ;; do-auto-fill has done a save-excursion with point at the end
182 ;; of the line and wants it to stay at the end of the line.
183 (insert-before-markers-and-inherit ? ))))
184
185 (defun fill-context-prefix (from to &optional first-line-regexp)
186 "Compute a fill prefix from the text between FROM and TO.
187 This uses the variables `adaptive-fill-prefix' and `adaptive-fill-function'
188 and `adaptive-fill-first-line-regexp'. `paragraph-start' also plays a role;
189 we reject a prefix based on a one-line paragraph if that prefix would
190 act as a paragraph-separator."
191 (or first-line-regexp
192 (setq first-line-regexp adaptive-fill-first-line-regexp))
193 (save-excursion
194 (goto-char from)
195 (if (eolp) (forward-line 1))
196 ;; Move to the second line unless there is just one.
197 (let ((firstline (point))
198 first-line-prefix
199 ;; Non-nil if we are on the second line.
200 at-second
201 second-line-prefix
202 start)
203 (move-to-left-margin)
204 (setq start (point))
205 (setq first-line-prefix
206 (cond ((looking-at paragraph-start) nil)
207 ((and adaptive-fill-regexp (looking-at adaptive-fill-regexp))
208 (buffer-substring-no-properties start (match-end 0)))
209 (adaptive-fill-function (funcall adaptive-fill-function))))
210 (forward-line 1)
211 (if (>= (point) to)
212 (goto-char firstline)
213 (setq at-second t)
214 (move-to-left-margin)
215 (setq start (point))
216 (setq second-line-prefix
217 (cond ((looking-at paragraph-start) nil)
218 ((and adaptive-fill-regexp (looking-at adaptive-fill-regexp))
219 (buffer-substring-no-properties start (match-end 0)))
220 (adaptive-fill-function (funcall adaptive-fill-function)))))
221 (if at-second
222 ;; If we get a fill prefix from the second line,
223 ;; make sure it or something compatible is on the first line too.
224 (and second-line-prefix first-line-prefix
225 ;; If the first line has the second line prefix too, use it.
226 (if (or (string-match (concat "\\`"
227 (regexp-quote second-line-prefix)
228 "\\(\\'\\|[ \t]\\)")
229 first-line-prefix)
230 ;; If the second line prefix is whitespace, use it.
231 (string-match "\\`[ \t]+\\'" second-line-prefix))
232 second-line-prefix
233 ;; If the second line has the first line prefix,
234 ;; plus whitespace, use the part that the first line shares.
235 (if (string-match (concat "\\`"
236 (regexp-quote first-line-prefix)
237 "[ \t]*\\'")
238 second-line-prefix)
239 first-line-prefix)))
240 ;; If we get a fill prefix from a one-line paragraph,
241 ;; maybe change it to whitespace,
242 ;; and check that it isn't a paragraph starter.
243 (if first-line-prefix
244 (let ((result
245 ;; If first-line-prefix comes from the first line,
246 ;; see if it seems reasonable to use for all lines.
247 ;; If not, replace it with whitespace.
248 (if (or (and first-line-regexp
249 (string-match first-line-regexp
250 first-line-prefix))
251 (and comment-start-skip
252 (string-match comment-start-skip
253 first-line-prefix)))
254 first-line-prefix
255 (make-string (string-width first-line-prefix) ?\ ))))
256 ;; But either way, reject it if it indicates the start
257 ;; of a paragraph when text follows it.
258 (if (not (eq 0 (string-match paragraph-start
259 (concat result "a"))))
260 result)))))))
261
262 (defvar fill-nobreak-predicate nil
263 "If non-nil, a predicate for recognizing places not to break a line.
264 The predicate is called with no arguments, with point at the place
265 to be tested. If it returns t, fill commands do not break the line there.")
266
267 ;; Put `fill-find-break-point-function' property to charsets which
268 ;; require special functions to find line breaking point.
269 (let ((alist '((katakana-jisx0201 . kinsoku)
270 (chinese-gb2312 . kinsoku)
271 (japanese-jisx0208 . kinsoku)
272 (japanese-jisx0212 . kinsoku)
273 (chinese-big5-1 . kinsoku)
274 (chinese-big5-2 . kinsoku))))
275 (while alist
276 (put-charset-property (car (car alist)) 'fill-find-break-point-function
277 (cdr (car alist)))
278 (setq alist (cdr alist))))
279
280 (defun fill-find-break-point (limit)
281 "Move point to a proper line breaking position of the current line.
282 Don't move back past the buffer position LIMIT.
283
284 This function is called when we are going to break the current line
285 after or before a non-ascii character. If the charset of the
286 character has the property `fill-find-break-point-function', this
287 function calls the property value as a function with one arg LINEBEG.
288 If the charset has no such property, do nothing."
289 (let* ((ch (following-char))
290 (charset (char-charset ch))
291 func)
292 (if (eq charset 'ascii)
293 (setq ch (preceding-char)
294 charset (char-charset ch)))
295 (if (eq charset 'ascii)
296 nil
297 (if (eq charset 'composition)
298 (setq charset (char-charset (composite-char-component ch 0)))))
299 (setq func (get-charset-property charset 'fill-find-break-point-function))
300 (if (and func (fboundp func))
301 (funcall func limit))))
302
303 (defun fill-region-as-paragraph (from to &optional justify
304 nosqueeze squeeze-after)
305 "Fill the region as one paragraph.
306 It removes any paragraph breaks in the region and extra newlines at the end,
307 indents and fills lines between the margins given by the
308 `current-left-margin' and `current-fill-column' functions.
309 \(In most cases, the variable `fill-column' controls the width.)
310 It leaves point at the beginning of the line following the paragraph.
311
312 Normally performs justification according to the `current-justification'
313 function, but with a prefix arg, does full justification instead.
314
315 From a program, optional third arg JUSTIFY can specify any type of
316 justification. Fourth arg NOSQUEEZE non-nil means not to make spaces
317 between words canonical before filling. Fifth arg SQUEEZE-AFTER, if non-nil,
318 means don't canonicalize spaces before that position.
319
320 If `sentence-end-double-space' is non-nil, then period followed by one
321 space does not end a sentence, so don't break a line there."
322 (interactive (progn
323 (barf-if-buffer-read-only)
324 (list (region-beginning) (region-end)
325 (if current-prefix-arg 'full))))
326 (unless (memq justify '(t nil none full center left right))
327 (setq justify 'full))
328 ;; Arrange for undoing the fill to restore point.
329 (if (and buffer-undo-list (not (eq buffer-undo-list t)))
330 (setq buffer-undo-list (cons (point) buffer-undo-list)))
331
332 ;; Make sure "to" is the endpoint.
333 (goto-char (min from to))
334 (setq to (max from to))
335 ;; Ignore blank lines at beginning of region.
336 (skip-chars-forward " \t\n")
337
338 (let ((from-plus-indent (point))
339 (oneleft nil))
340
341 (beginning-of-line)
342 (setq from (point))
343
344 ;; Delete all but one soft newline at end of region.
345 ;; And leave TO before that one.
346 (goto-char to)
347 (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
348 (if (and oneleft
349 (not (and use-hard-newlines
350 (get-text-property (1- (point)) 'hard))))
351 (delete-backward-char 1)
352 (backward-char 1)
353 (setq oneleft t)))
354 (setq to (point))
355 ;;; ;; If there was no newline, and there is text in the paragraph, then
356 ;;; ;; create a newline.
357 ;;; (if (and (not oneleft) (> to from-plus-indent))
358 ;;; (newline))
359 (goto-char from-plus-indent))
360
361 (if (not (> to (point)))
362 nil ; There is no paragraph, only whitespace: exit now.
363
364 (or justify (setq justify (current-justification)))
365
366 ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
367 (let ((fill-prefix fill-prefix))
368 ;; Figure out how this paragraph is indented, if desired.
369 (if (and adaptive-fill-mode
370 (or (null fill-prefix) (string= fill-prefix "")))
371 (setq fill-prefix (fill-context-prefix from to)))
372
373 (save-restriction
374 (goto-char from)
375 (beginning-of-line)
376 (narrow-to-region (point) to)
377
378 (if (not justify) ; filling disabled: just check indentation
379 (progn
380 (goto-char from)
381 (while (not (eobp))
382 (if (and (not (eolp))
383 (< (current-indentation) (current-left-margin)))
384 (indent-to-left-margin))
385 (forward-line 1)))
386
387 (if use-hard-newlines
388 (remove-text-properties from (point-max) '(hard nil)))
389 ;; Make sure first line is indented (at least) to left margin...
390 (if (or (memq justify '(right center))
391 (< (current-indentation) (current-left-margin)))
392 (indent-to-left-margin))
393 ;; Delete the fill prefix from every line except the first.
394 ;; The first line may not even have a fill prefix.
395 (goto-char from)
396 (let ((fpre (and fill-prefix (not (equal fill-prefix ""))
397 (concat "[ \t]*"
398 (regexp-quote fill-prefix)
399 "[ \t]*"))))
400 (and fpre
401 (progn
402 (if (>= (+ (current-left-margin) (length fill-prefix))
403 (current-fill-column))
404 (error "fill-prefix too long for specified width"))
405 (goto-char from)
406 (forward-line 1)
407 (while (not (eobp))
408 (if (looking-at fpre)
409 (delete-region (point) (match-end 0)))
410 (forward-line 1))
411 (goto-char from)
412 (if (looking-at fpre)
413 (goto-char (match-end 0)))
414 (setq from (point)))))
415 ;; Remove indentation from lines other than the first.
416 (beginning-of-line 2)
417 (indent-region (point) (point-max) 0)
418 (goto-char from)
419
420 ;; FROM, and point, are now before the text to fill,
421 ;; but after any fill prefix on the first line.
422
423 ;; Make sure sentences ending at end of line get an extra space.
424 ;; loses on split abbrevs ("Mr.\nSmith")
425 (while (re-search-forward "[.?!][])}\"']*$" nil t)
426 (or (eobp) (insert-and-inherit ?\ )))
427
428 (goto-char from)
429 (if enable-multibyte-characters
430 ;; Delete unnecessay newlines surrounded by words. The
431 ;; character category `|' means that we can break a line
432 ;; at the character. And, charset property
433 ;; `nospace-between-words' tells how to concatenate
434 ;; words. If the value is non-nil, never put spaces
435 ;; between words, thus delete a newline between them.
436 ;; If the value is nil, delete a newline only when a
437 ;; character preceding a newline has text property
438 ;; `nospace-between-words'.
439 (while (search-forward "\n" nil t)
440 (let ((prev (char-before (match-beginning 0)))
441 (next (following-char)))
442 (if (cmpcharp prev)
443 (setq prev (composite-char-component prev 0)))
444 (if (cmpcharp next)
445 (setq next (composite-char-component next 0)))
446 (if (and (or (aref (char-category-set next) ?|)
447 (aref (char-category-set prev) ?|))
448 (or (get-charset-property (char-charset prev)
449 'nospace-between-words)
450 (get-text-property (1- (match-beginning 0))
451 'nospace-between-words)))
452 (delete-char -1)))))
453
454 (goto-char from)
455 (skip-chars-forward " \t")
456 ;; Then change all newlines to spaces.
457 (subst-char-in-region from (point-max) ?\n ?\ )
458 (if (and nosqueeze (not (eq justify 'full)))
459 nil
460 (canonically-space-region (or squeeze-after (point)) (point-max))
461 (goto-char (point-max))
462 (delete-horizontal-space)
463 (insert-and-inherit " "))
464 (goto-char (point-min))
465
466 ;; This is the actual filling loop.
467 (let ((prefixcol 0) linebeg)
468 (while (not (eobp))
469 (setq linebeg (point))
470 (move-to-column (1+ (current-fill-column)))
471 (if (eobp)
472 (or nosqueeze (delete-horizontal-space))
473 ;; Move back to the point where we can break the line
474 ;; at. We break the line between word or after/before
475 ;; the character which has character category `|'. We
476 ;; search space, \c| followed by a character, or \c|
477 ;; following a character. If not found, place
478 ;; the point at linebeg.
479 (if (re-search-backward " \\|\\c|.\\|.\\c|" linebeg 0)
480 ;; In case of space, we place the point at next to
481 ;; the point where the break occurs acutually,
482 ;; because we don't want to change the following
483 ;; logic of original Emacs. In case of \c|, the
484 ;; point is at the place where the break occurs.
485 (forward-char 1))
486 ;; Don't break after a period followed by just one space.
487 ;; Move back to the previous place to break.
488 ;; The reason is that if a period ends up at the end of a line,
489 ;; further fills will assume it ends a sentence.
490 ;; If we now know it does not end a sentence,
491 ;; avoid putting it at the end of the line.
492 (while (or (and sentence-end-double-space
493 (> (point) (+ linebeg 2))
494 (eq (preceding-char) ?\ )
495 (not (eq (following-char) ?\ ))
496 (eq (char-after (- (point) 2)) ?\.)
497 (progn (forward-char -2) t))
498 (and fill-nobreak-predicate
499 (funcall fill-nobreak-predicate)
500 (goto-char (match-beginning 0))))
501 (if (re-search-backward " \\|\\c|.\\|.\\c|" linebeg 0)
502 (forward-char 1)))
503 ;; If the left margin and fill prefix by themselves
504 ;; pass the fill-column. or if they are zero
505 ;; but we have no room for even one word,
506 ;; keep at least one word or a character which has
507 ;; category `|'anyway .
508 ;; This handles ALL BUT the first line of the paragraph.
509 (if (if (zerop prefixcol)
510 (save-excursion
511 (skip-chars-backward " \t" linebeg)
512 (bolp))
513 (>= prefixcol (current-column)))
514 ;; Ok, skip at least one word or one \c| character.
515 ;; Meanwhile, don't stop at a period followed by one space.
516 (let ((first t))
517 (move-to-column prefixcol)
518 (while (and (not (eobp))
519 (or first
520 (and (not (bobp))
521 sentence-end-double-space
522 (save-excursion (forward-char -1)
523 (and (looking-at "\\. ")
524 (not (looking-at "\\. ")))))
525 (and fill-nobreak-predicate
526 (funcall fill-nobreak-predicate))))
527 ;; Find a breakable point while ignoring the
528 ;; following spaces.
529 (skip-chars-forward " \t")
530 (if (looking-at "\\c|")
531 (forward-char 1)
532 (let ((pos (save-excursion
533 (skip-chars-forward "^ \n\t")
534 (point))))
535 (if (re-search-forward "\\c|" pos t)
536 (forward-char -1)
537 (goto-char pos))))
538 (setq first nil)))
539 ;; Normally, move back over the single space between the words.
540 (if (= (preceding-char) ?\ ) (forward-char -1))
541
542 (if enable-multibyte-characters
543 ;; If we are going to break the line after or
544 ;; before a non-ascii character, we may have to
545 ;; run a special function for the charset of the
546 ;; character to find the correct break point.
547 (if (not (and (eq (charset-after (1- (point))) 'ascii)
548 (eq (charset-after (point)) 'ascii)))
549 (fill-find-break-point
550 (+ linebeg
551 (current-left-margin)
552 (if fill-prefix (length fill-prefix) 0))))))
553
554 ;; If the left margin and fill prefix by themselves
555 ;; pass the fill-column, keep at least one word.
556 ;; This handles the first line of the paragraph.
557 (if (and (zerop prefixcol)
558 (let ((fill-point (point)) nchars)
559 (save-excursion
560 (move-to-left-margin)
561 (setq nchars (- fill-point (point)))
562 (or (< nchars 0)
563 (and fill-prefix
564 (< nchars (length fill-prefix))
565 (string= (buffer-substring (point) fill-point)
566 (substring fill-prefix 0 nchars)))))))
567 ;; Ok, skip at least one word. But
568 ;; don't stop at a period followed by just one space.
569 (let ((first t))
570 (while (and (not (eobp))
571 (or first
572 (and (not (bobp))
573 sentence-end-double-space
574 (save-excursion (forward-char -1)
575 (and (looking-at "\\. ")
576 (not (looking-at "\\. ")))))
577 (and fill-nobreak-predicate
578 (funcall fill-nobreak-predicate))))
579 ;; Find a breakable point while ignoring the
580 ;; following spaces.
581 (skip-chars-forward " \t")
582 (if (looking-at "\\c|")
583 (forward-char 1)
584 (let ((pos (save-excursion
585 (skip-chars-forward "^ \n\t")
586 (point))))
587 (if (re-search-forward "\\c|" pos t)
588 (forward-char -1)
589 (goto-char pos))))
590 (setq first nil))))
591 ;; Check again to see if we got to the end of the paragraph.
592 (if (save-excursion (skip-chars-forward " \t") (eobp))
593 (or nosqueeze (delete-horizontal-space))
594 ;; Replace whitespace here with one newline, then indent to left
595 ;; margin.
596 (skip-chars-backward " \t")
597 (if (and (= (following-char) ?\ )
598 (or (aref (char-category-set (preceding-char)) ?|)
599 (looking-at "[ \t]+\\c|")))
600 ;; We need one space at end of line so that
601 ;; further filling won't delete it. NOTE: We
602 ;; intentionally leave this one space to
603 ;; distingush the case that user wants to put
604 ;; space between \c| characters.
605 (forward-char 1))
606 (insert ?\n)
607 ;; Give newline the properties of the space(s) it replaces
608 (set-text-properties (1- (point)) (point)
609 (text-properties-at (point)))
610 (indent-to-left-margin)
611 ;; Insert the fill prefix after indentation.
612 ;; Set prefixcol so whitespace in the prefix won't get lost.
613 (and fill-prefix (not (equal fill-prefix ""))
614 (progn
615 (insert-and-inherit fill-prefix)
616 (setq prefixcol (current-column))))))
617 ;; Justify the line just ended, if desired.
618 (if justify
619 (if (save-excursion (skip-chars-forward " \t") (eobp))
620 (progn
621 (delete-horizontal-space)
622 (justify-current-line justify t t))
623 (forward-line -1)
624 (justify-current-line justify nil t)
625 (forward-line 1))))))
626 ;; Leave point after final newline.
627 (goto-char (point-max)))
628 (unless (eobp)
629 (forward-char 1)))))
630
631 (defun fill-paragraph (arg)
632 "Fill paragraph at or after point. Prefix arg means justify as well.
633 If `sentence-end-double-space' is non-nil, then period followed by one
634 space does not end a sentence, so don't break a line there.
635 the variable `fill-column' controls the width for filling.
636
637 If `fill-paragraph-function' is non-nil, we call it (passing our
638 argument to it), and if it returns non-nil, we simply return its value."
639 (interactive (progn
640 (barf-if-buffer-read-only)
641 (list (if current-prefix-arg 'full))))
642 (or (and fill-paragraph-function
643 (let ((function fill-paragraph-function)
644 fill-paragraph-function)
645 (funcall function arg)))
646 (let ((before (point))
647 ;; If fill-paragraph is called recursively,
648 ;; don't give fill-paragraph-function a second chance.
649 fill-paragraph-function)
650 (save-excursion
651 (forward-paragraph)
652 (or (bolp) (newline 1))
653 (let ((end (point))
654 (beg (progn (backward-paragraph) (point))))
655 (goto-char before)
656 (if use-hard-newlines
657 ;; Can't use fill-region-as-paragraph, since this paragraph may
658 ;; still contain hard newlines. See fill-region.
659 (fill-region beg end arg)
660 (fill-region-as-paragraph beg end arg)))))))
661
662 (defun fill-region (from to &optional justify nosqueeze to-eop)
663 "Fill each of the paragraphs in the region.
664 A prefix arg means justify as well.
665 Ordinarily the variable `fill-column' controls the width.
666
667 Noninteractively, the third argument JUSTIFY specifies which
668 kind of justification to do: `full', `left', `right', `center',
669 or `none' (equivalent to nil). t means handle each paragraph
670 as specified by its text properties.
671
672 The fourth arg NOSQUEEZE non-nil means to leave
673 whitespace other than line breaks untouched, and fifth arg TO-EOP
674 non-nil means to keep filling to the end of the paragraph (or next
675 hard newline, if `use-hard-newlines' is on).
676
677 If `sentence-end-double-space' is non-nil, then period followed by one
678 space does not end a sentence, so don't break a line there."
679 (interactive (progn
680 (barf-if-buffer-read-only)
681 (list (region-beginning) (region-end)
682 (if current-prefix-arg 'full))))
683 (unless (memq justify '(t nil none full center left right))
684 (setq justify 'full))
685 (let (end beg)
686 (save-restriction
687 (goto-char (max from to))
688 (if to-eop
689 (progn (skip-chars-backward "\n")
690 (forward-paragraph)))
691 (setq end (point))
692 (goto-char (setq beg (min from to)))
693 (beginning-of-line)
694 (narrow-to-region (point) end)
695 (while (not (eobp))
696 (let ((initial (point))
697 end)
698 ;; If using hard newlines, break at every one for filling
699 ;; purposes rather than using paragraph breaks.
700 (if use-hard-newlines
701 (progn
702 (while (and (setq end (text-property-any (point) (point-max)
703 'hard t))
704 (not (= ?\n (char-after end)))
705 (not (= end (point-max))))
706 (goto-char (1+ end)))
707 (setq end (if end (min (point-max) (1+ end)) (point-max)))
708 (goto-char initial))
709 (forward-paragraph 1)
710 (setq end (point))
711 (forward-paragraph -1))
712 (if (< (point) beg)
713 (goto-char beg))
714 (if (>= (point) initial)
715 (fill-region-as-paragraph (point) end justify nosqueeze)
716 (goto-char end)))))))
717
718 \f
719 (defcustom default-justification 'left
720 "*Method of justifying text not otherwise specified.
721 Possible values are `left', `right', `full', `center', or `none'.
722 The requested kind of justification is done whenever lines are filled.
723 The `justification' text-property can locally override this variable.
724 This variable automatically becomes buffer-local when set in any fashion."
725 :type '(choice (const left)
726 (const right)
727 (const full)
728 (const center)
729 (const none))
730 :group 'fill)
731 (make-variable-buffer-local 'default-justification)
732
733 (defun current-justification ()
734 "How should we justify this line?
735 This returns the value of the text-property `justification',
736 or the variable `default-justification' if there is no text-property.
737 However, it returns nil rather than `none' to mean \"don't justify\"."
738 (let ((j (or (get-text-property
739 ;; Make sure we're looking at paragraph body.
740 (save-excursion (skip-chars-forward " \t")
741 (if (and (eobp) (not (bobp)))
742 (1- (point)) (point)))
743 'justification)
744 default-justification)))
745 (if (eq 'none j)
746 nil
747 j)))
748
749 (defun set-justification (begin end value &optional whole-par)
750 "Set the region's justification style.
751 The kind of justification to use is prompted for.
752 If the mark is not active, this command operates on the current paragraph.
753 If the mark is active, the region is used. However, if the beginning and end
754 of the region are not at paragraph breaks, they are moved to the beginning and
755 end of the paragraphs they are in.
756 If `use-hard-newlines' is true, all hard newlines are taken to be paragraph
757 breaks.
758
759 When calling from a program, operates just on region between BEGIN and END,
760 unless optional fourth arg WHOLE-PAR is non-nil. In that case bounds are
761 extended to include entire paragraphs as in the interactive command."
762 (interactive (list (if mark-active (region-beginning) (point))
763 (if mark-active (region-end) (point))
764 (let ((s (completing-read
765 "Set justification to: "
766 '(("left") ("right") ("full")
767 ("center") ("none"))
768 nil t)))
769 (if (equal s "") (error ""))
770 (intern s))
771 t))
772 (save-excursion
773 (save-restriction
774 (if whole-par
775 (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
776 (paragraph-ignore-fill-prefix (if use-hard-newlines t
777 paragraph-ignore-fill-prefix)))
778 (goto-char begin)
779 (while (and (bolp) (not (eobp))) (forward-char 1))
780 (backward-paragraph)
781 (setq begin (point))
782 (goto-char end)
783 (skip-chars-backward " \t\n" begin)
784 (forward-paragraph)
785 (setq end (point))))
786
787 (narrow-to-region (point-min) end)
788 (unjustify-region begin (point-max))
789 (put-text-property begin (point-max) 'justification value)
790 (fill-region begin (point-max) nil t))))
791
792 (defun set-justification-none (b e)
793 "Disable automatic filling for paragraphs in the region.
794 If the mark is not active, this applies to the current paragraph."
795 (interactive (list (if mark-active (region-beginning) (point))
796 (if mark-active (region-end) (point))))
797 (set-justification b e 'none t))
798
799 (defun set-justification-left (b e)
800 "Make paragraphs in the region left-justified.
801 This is usually the default, but see the variable `default-justification'.
802 If the mark is not active, this applies to the current paragraph."
803 (interactive (list (if mark-active (region-beginning) (point))
804 (if mark-active (region-end) (point))))
805 (set-justification b e 'left t))
806
807 (defun set-justification-right (b e)
808 "Make paragraphs in the region right-justified:
809 Flush at the right margin and ragged on the left.
810 If the mark is not active, this applies to the current paragraph."
811 (interactive (list (if mark-active (region-beginning) (point))
812 (if mark-active (region-end) (point))))
813 (set-justification b e 'right t))
814
815 (defun set-justification-full (b e)
816 "Make paragraphs in the region fully justified:
817 This makes lines flush on both margins by inserting spaces between words.
818 If the mark is not active, this applies to the current paragraph."
819 (interactive (list (if mark-active (region-beginning) (point))
820 (if mark-active (region-end) (point))))
821 (set-justification b e 'full t))
822
823 (defun set-justification-center (b e)
824 "Make paragraphs in the region centered.
825 If the mark is not active, this applies to the current paragraph."
826 (interactive (list (if mark-active (region-beginning) (point))
827 (if mark-active (region-end) (point))))
828 (set-justification b e 'center t))
829
830 ;; A line has up to six parts:
831 ;;
832 ;; >>> hello.
833 ;; [Indent-1][FP][ Indent-2 ][text][trailing whitespace][newline]
834 ;;
835 ;; "Indent-1" is the left-margin indentation; normally it ends at column
836 ;; given by the `current-left-margin' function.
837 ;; "FP" is the fill-prefix. It can be any string, including whitespace.
838 ;; "Indent-2" is added to justify a line if the `current-justification' is
839 ;; `center' or `right'. In `left' and `full' justification regions, any
840 ;; whitespace there is part of the line's text, and should not be changed.
841 ;; Trailing whitespace is not counted as part of the line length when
842 ;; center- or right-justifying.
843 ;;
844 ;; All parts of the line are optional, although the final newline can
845 ;; only be missing on the last line of the buffer.
846
847 (defun justify-current-line (&optional how eop nosqueeze)
848 "Do some kind of justification on this line.
849 Normally does full justification: adds spaces to the line to make it end at
850 the column given by `current-fill-column'.
851 Optional first argument HOW specifies alternate type of justification:
852 it can be `left', `right', `full', `center', or `none'.
853 If HOW is t, will justify however the `current-justification' function says to.
854 If HOW is nil or missing, full justification is done by default.
855 Second arg EOP non-nil means that this is the last line of the paragraph, so
856 it will not be stretched by full justification.
857 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
858 otherwise it is made canonical."
859 (interactive "*")
860 (if (eq t how) (setq how (or (current-justification) 'none))
861 (if (null how) (setq how 'full)
862 (or (memq how '(none left right center))
863 (setq how 'full))))
864 (or (memq how '(none left)) ; No action required for these.
865 (let ((fc (current-fill-column))
866 (pos (point-marker))
867 fp-end ; point at end of fill prefix
868 beg ; point at beginning of line's text
869 end ; point at end of line's text
870 indent ; column of `beg'
871 endcol ; column of `end'
872 ncols ; new indent point or offset
873 (nspaces 0) ; number of spaces between words
874 ; in line (not space characters)
875 fracspace ; fractional amount of space to be
876 ; added between each words
877 (curr-fracspace 0) ; current fractional space amount
878 count)
879 (end-of-line)
880 ;; Check if this is the last line of the paragraph.
881 (if (and use-hard-newlines (null eop)
882 (get-text-property (point) 'hard))
883 (setq eop t))
884 (skip-chars-backward " \t")
885 ;; Quick exit if it appears to be properly justified already
886 ;; or there is no text.
887 (if (or (bolp)
888 (and (memq how '(full right))
889 (= (current-column) fc)))
890 nil
891 (setq end (point))
892 (beginning-of-line)
893 (skip-chars-forward " \t")
894 ;; Skip over fill-prefix.
895 (if (and fill-prefix
896 (not (string-equal fill-prefix ""))
897 (equal fill-prefix
898 (buffer-substring
899 (point) (min (point-max) (+ (length fill-prefix)
900 (point))))))
901 (forward-char (length fill-prefix))
902 (if (and adaptive-fill-mode
903 (looking-at adaptive-fill-regexp))
904 (goto-char (match-end 0))))
905 (setq fp-end (point))
906 (skip-chars-forward " \t")
907 ;; This is beginning of the line's text.
908 (setq indent (current-column))
909 (setq beg (point))
910 (goto-char end)
911 (setq endcol (current-column))
912
913 ;; HOW can't be null or left--we would have exited already
914 (cond ((eq 'right how)
915 (setq ncols (- fc endcol))
916 (if (< ncols 0)
917 ;; Need to remove some indentation
918 (delete-region
919 (progn (goto-char fp-end)
920 (if (< (current-column) (+ indent ncols))
921 (move-to-column (+ indent ncols) t))
922 (point))
923 (progn (move-to-column indent) (point)))
924 ;; Need to add some
925 (goto-char beg)
926 (indent-to (+ indent ncols))
927 ;; If point was at beginning of text, keep it there.
928 (if (= beg pos)
929 (move-marker pos (point)))))
930
931 ((eq 'center how)
932 ;; Figure out how much indentation is needed
933 (setq ncols (+ (current-left-margin)
934 (/ (- fc (current-left-margin) ;avail. space
935 (- endcol indent)) ;text width
936 2)))
937 (if (< ncols indent)
938 ;; Have too much indentation - remove some
939 (delete-region
940 (progn (goto-char fp-end)
941 (if (< (current-column) ncols)
942 (move-to-column ncols t))
943 (point))
944 (progn (move-to-column indent) (point)))
945 ;; Have too little - add some
946 (goto-char beg)
947 (indent-to ncols)
948 ;; If point was at beginning of text, keep it there.
949 (if (= beg pos)
950 (move-marker pos (point)))))
951
952 ((eq 'full how)
953 ;; Insert extra spaces between words to justify line
954 (save-restriction
955 (narrow-to-region beg end)
956 (or nosqueeze
957 (canonically-space-region beg end))
958 (goto-char (point-max))
959 ;; count word spaces in line
960 (while (search-backward " " nil t)
961 (setq nspaces (1+ nspaces))
962 (skip-chars-backward " "))
963 (setq ncols (- fc endcol))
964 ;; Ncols is number of additional space chars needed
965 (if (and (> ncols 0) (> nspaces 0) (not eop))
966 (progn
967 (setq curr-fracspace (+ ncols (/ (1+ nspaces) 2))
968 count nspaces)
969 (while (> count 0)
970 (skip-chars-forward " ")
971 (insert-and-inherit
972 (make-string (/ curr-fracspace nspaces) ?\ ))
973 (search-forward " " nil t)
974 (setq count (1- count)
975 curr-fracspace
976 (+ (% curr-fracspace nspaces) ncols)))))))
977 (t (error "Unknown justification value"))))
978 (goto-char pos)
979 (move-marker pos nil)))
980 nil)
981
982 (defun unjustify-current-line ()
983 "Remove justification whitespace from current line.
984 If the line is centered or right-justified, this function removes any
985 indentation past the left margin. If the line is full-justified, it removes
986 extra spaces between words. It does nothing in other justification modes."
987 (let ((justify (current-justification)))
988 (cond ((eq 'left justify) nil)
989 ((eq nil justify) nil)
990 ((eq 'full justify) ; full justify: remove extra spaces
991 (beginning-of-line-text)
992 (canonically-space-region
993 (point) (save-excursion (end-of-line) (point))))
994 ((memq justify '(center right))
995 (save-excursion
996 (move-to-left-margin nil t)
997 ;; Position ourselves after any fill-prefix.
998 (if (and fill-prefix
999 (not (string-equal fill-prefix ""))
1000 (equal fill-prefix
1001 (buffer-substring
1002 (point) (min (point-max) (+ (length fill-prefix)
1003 (point))))))
1004 (forward-char (length fill-prefix)))
1005 (delete-region (point) (progn (skip-chars-forward " \t")
1006 (point))))))))
1007
1008 (defun unjustify-region (&optional begin end)
1009 "Remove justification whitespace from region.
1010 For centered or right-justified regions, this function removes any indentation
1011 past the left margin from each line. For full-justified lines, it removes
1012 extra spaces between words. It does nothing in other justification modes.
1013 Arguments BEGIN and END are optional; default is the whole buffer."
1014 (save-excursion
1015 (save-restriction
1016 (if end (narrow-to-region (point-min) end))
1017 (goto-char (or begin (point-min)))
1018 (while (not (eobp))
1019 (unjustify-current-line)
1020 (forward-line 1)))))
1021
1022 \f
1023 (defun fill-nonuniform-paragraphs (min max &optional justifyp citation-regexp)
1024 "Fill paragraphs within the region, allowing varying indentation within each.
1025 This command divides the region into \"paragraphs\",
1026 only at paragraph-separator lines, then fills each paragraph
1027 using as the fill prefix the smallest indentation of any line
1028 in the paragraph.
1029
1030 When calling from a program, pass range to fill as first two arguments.
1031
1032 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1033 JUSTIFY to justify paragraphs (prefix arg),
1034 When filling a mail message, pass a regexp for CITATION-REGEXP
1035 which will match the prefix of a line which is a citation marker
1036 plus whitespace, but no other kind of prefix.
1037 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1038 (interactive (progn
1039 (barf-if-buffer-read-only)
1040 (list (region-beginning) (region-end)
1041 (if current-prefix-arg 'full))))
1042 (let ((fill-individual-varying-indent t))
1043 (fill-individual-paragraphs min max justifyp citation-regexp)))
1044
1045 (defun fill-individual-paragraphs (min max &optional justify citation-regexp)
1046 "Fill paragraphs of uniform indentation within the region.
1047 This command divides the region into \"paragraphs\",
1048 treating every change in indentation level or prefix as a paragraph boundary,
1049 then fills each paragraph using its indentation level as the fill prefix.
1050
1051 There is one special case where a change in indentation does not start
1052 a new paragraph. This is for text of this form:
1053
1054 foo> This line with extra indentation starts
1055 foo> a paragraph that continues on more lines.
1056
1057 These lines are filled together.
1058
1059 When calling from a program, pass the range to fill
1060 as the first two arguments.
1061
1062 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1063 JUSTIFY to justify paragraphs (prefix arg),
1064 When filling a mail message, pass a regexp for CITATION-REGEXP
1065 which will match the prefix of a line which is a citation marker
1066 plus whitespace, but no other kind of prefix.
1067 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1068 (interactive (progn
1069 (barf-if-buffer-read-only)
1070 (list (region-beginning) (region-end)
1071 (if current-prefix-arg 'full))))
1072 (save-restriction
1073 (save-excursion
1074 (goto-char min)
1075 (beginning-of-line)
1076 (narrow-to-region (point) max)
1077 (if citation-regexp
1078 (while (and (not (eobp))
1079 (or (looking-at "[ \t]*[^ \t\n]+:")
1080 (looking-at "[ \t]*$")))
1081 (if (looking-at "[ \t]*[^ \t\n]+:")
1082 (search-forward "\n\n" nil 'move)
1083 (forward-line 1))))
1084 (narrow-to-region (point) max)
1085 ;; Loop over paragraphs.
1086 (while (let ((here (point)))
1087 ;; Skip over all paragraph-separating lines
1088 ;; so as to not include them in any paragraph.
1089 (while (and (not (eobp))
1090 (progn (move-to-left-margin)
1091 (and (not (eobp))
1092 (looking-at paragraph-separate))))
1093 (forward-line 1))
1094 (skip-chars-forward " \t\n") (not (eobp)))
1095 (move-to-left-margin)
1096 (let ((start (point))
1097 fill-prefix fill-prefix-regexp)
1098 ;; Find end of paragraph, and compute the smallest fill-prefix
1099 ;; that fits all the lines in this paragraph.
1100 (while (progn
1101 ;; Update the fill-prefix on the first line
1102 ;; and whenever the prefix good so far is too long.
1103 (if (not (and fill-prefix
1104 (looking-at fill-prefix-regexp)))
1105 (setq fill-prefix
1106 (fill-individual-paragraphs-prefix citation-regexp)
1107 fill-prefix-regexp (regexp-quote fill-prefix)))
1108 (forward-line 1)
1109 (if (bolp)
1110 ;; If forward-line went past a newline,
1111 ;; move further to the left margin.
1112 (move-to-left-margin))
1113 ;; Now stop the loop if end of paragraph.
1114 (and (not (eobp))
1115 (if fill-individual-varying-indent
1116 ;; If this line is a separator line, with or
1117 ;; without prefix, end the paragraph.
1118 (and
1119 (not (looking-at paragraph-separate))
1120 (save-excursion
1121 (not (and (looking-at fill-prefix-regexp)
1122 (progn (forward-char (length fill-prefix))
1123 (looking-at paragraph-separate))))))
1124 ;; If this line has more or less indent
1125 ;; than the fill prefix wants, end the paragraph.
1126 (and (looking-at fill-prefix-regexp)
1127 (save-excursion
1128 (not (progn (forward-char (length fill-prefix))
1129 (or (looking-at "[ \t]")
1130 (looking-at paragraph-separate)
1131 (looking-at paragraph-start))))))))))
1132 ;; Fill this paragraph, but don't add a newline at the end.
1133 (let ((had-newline (bolp)))
1134 (fill-region-as-paragraph start (point) justify)
1135 (if (and (bolp) (not had-newline))
1136 (delete-char -1))))))))
1137
1138 (defun fill-individual-paragraphs-prefix (citation-regexp)
1139 (or (let ((adaptive-fill-first-line-regexp "")
1140 just-one-line-prefix
1141 two-lines-prefix
1142 one-line-citation-part
1143 two-lines-citation-part
1144 adjusted-two-lines-citation-part)
1145 (setq just-one-line-prefix
1146 (fill-context-prefix
1147 (point)
1148 (save-excursion (forward-line 1)
1149 (point))))
1150 (setq two-lines-prefix
1151 (fill-context-prefix
1152 (point)
1153 (save-excursion (forward-line 2)
1154 (point))))
1155 (when just-one-line-prefix
1156 (setq one-line-citation-part
1157 (if citation-regexp
1158 (fill-individual-paragraphs-citation just-one-line-prefix
1159 citation-regexp)
1160 just-one-line-prefix)))
1161 (when two-lines-prefix
1162 (setq two-lines-citation-part
1163 (if citation-regexp
1164 (fill-individual-paragraphs-citation two-lines-prefix
1165 citation-regexp)
1166 just-one-line-prefix))
1167 (or two-lines-citation-part (setq two-lines-citation-part ""))
1168 (setq adjusted-two-lines-citation-part
1169 (substring two-lines-citation-part 0
1170 (string-match "[ \t]*\\'"
1171 two-lines-citation-part))))
1172 ;; See if the citation part of JUST-ONE-LINE-PREFIX
1173 ;; is the same as that of TWO-LINES-PREFIX,
1174 ;; except perhaps with longer whitespace.
1175 (if (and just-one-line-prefix
1176 two-lines-prefix
1177 (string-match (concat "\\`"
1178 (regexp-quote adjusted-two-lines-citation-part)
1179 "[ \t]*\\'")
1180 one-line-citation-part)
1181 (>= (string-width one-line-citation-part)
1182 (string-width two-lines-citation-part)))
1183 two-lines-prefix
1184 just-one-line-prefix))
1185 (buffer-substring
1186 (point)
1187 (save-excursion (skip-chars-forward " \t")
1188 (point)))))
1189
1190 (defun fill-individual-paragraphs-citation (string citation-regexp)
1191 (string-match citation-regexp
1192 string)
1193 (match-string 0 string))
1194
1195 ;;; fill.el ends here