(set-justification): New function.
[emacs.git] / lisp / textmodes / fill.el
blob336236d88223663245f397edb1360673a0efaec1
1 ;;; fill.el --- fill commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1992, 1994 Free Software Foundation, Inc.
5 ;; Keywords: wp
7 ;; This file is part of GNU Emacs.
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.
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.
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
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23 ;;; Commentary:
25 ;; All the commands for filling text. These are documented in the Emacs
26 ;; manual.
28 ;;; Code:
30 (defconst fill-individual-varying-indent nil
31 "*Controls criterion for a new paragraph in `fill-individual-paragraphs'.
32 Non-nil means changing indent doesn't end a paragraph.
33 That mode can handle paragraphs with extra indentation on the first line,
34 but it requires separator lines between paragraphs.
35 A value of nil means that any change in indentation starts a new paragraph.")
37 (defconst sentence-end-double-space t
38 "*Non-nil means a single space does not end a sentence.")
40 (defun set-fill-prefix ()
41 "Set the fill prefix to the current line up to point.
42 Filling expects lines to start with the fill prefix and
43 reinserts the fill prefix in each resulting line."
44 (interactive)
45 (setq fill-prefix (buffer-substring
46 (save-excursion (beginning-of-line) (point))
47 (point)))
48 (if (equal fill-prefix "")
49 (setq fill-prefix nil))
50 (if fill-prefix
51 (message "fill-prefix: \"%s\"" fill-prefix)
52 (message "fill-prefix cancelled")))
54 (defconst adaptive-fill-mode t
55 "*Non-nil means determine a paragraph's fill prefix from its text.")
57 (defconst adaptive-fill-regexp "[ \t]*\\([>*] +\\)?"
58 "*Regexp to match text at start of line that constitutes indentation.
59 If Adaptive Fill mode is enabled, whatever text matches this pattern
60 on the second line of a paragraph is used as the standard indentation
61 for the paragraph.")
63 (defun current-fill-column ()
64 "Return the fill-column to use for this line.
65 The fill-column to use for a buffer is stored in the variable `fill-column',
66 but can be locally modified by the `right-margin' text property, which is
67 subtracted from `fill-column'.
69 The fill column to use for a line is the first column at which the column
70 number equals or exceeds the local fill-column - right-margin difference."
71 (save-excursion
72 (let* ((here (progn (beginning-of-line) (point)))
73 (here-col 0)
74 (eol (progn (end-of-line) (point)))
75 margin fill-col change col)
76 ;; Look separately at each region of line with a different right-margin
77 (while (and (setq margin (get-text-property here 'right-margin)
78 fill-col (- fill-column (or margin 0))
79 change (text-property-not-all here eol
80 'right-margin margin))
81 (progn (goto-char (1- change))
82 (setq col (current-column))
83 (< col fill-col)))
84 (setq here change
85 here-col col))
86 (max here-col fill-col))))
88 (defun canonically-space-region (beg end)
89 "Remove extra spaces between words in region.
90 Puts one space between words in region; two between sentences.
91 Remove indenation from each line."
92 (interactive "r")
93 (save-excursion
94 (goto-char beg)
95 ;; Nuke tabs; they get screwed up in a fill.
96 ;; This is quick, but loses when a tab follows the end of a sentence.
97 ;; Actually, it is difficult to tell that from "Mr.\tSmith".
98 ;; Blame the typist.
99 (subst-char-in-region beg end ?\t ?\ )
100 (while (and (< (point) end)
101 (re-search-forward " *" end t))
102 (delete-region
103 (+ (match-beginning 0)
104 ;; Determine number of spaces to leave:
105 (save-excursion
106 (skip-chars-backward " ]})\"'")
107 (cond ((and sentence-end-double-space
108 (memq (preceding-char) '(?. ?? ?!))) 2)
109 ((char-equal (preceding-char) ?\n) 0)
110 (t 1))))
111 (match-end 0)))
112 ;; Make sure sentences ending at end of line get an extra space.
113 ;; loses on split abbrevs ("Mr.\nSmith")
114 (goto-char beg)
115 (while (and (< (point) end)
116 (re-search-forward "[.?!][])}\"']*$" end t))
117 (insert-and-inherit ? ))))
119 (defun fill-region-as-paragraph (from to &optional justify nosqueeze)
120 "Fill region as one paragraph: break lines to fit `fill-column'.
121 This removes any paragraph breaks in the region.
122 It performs justification according to the `justification' text-property,
123 but a prefix arg can be used to override this and request full justification.
125 Optional fourth arg NOSQUEEZE non-nil means to leave whitespace other than line
126 breaks untouched. Normally it is made canonical before filling.
128 If `sentence-end-double-space' is non-nil, then period followed by one
129 space does not end a sentence, so don't break a line there."
130 (interactive "r\nP")
131 ;; Arrange for undoing the fill to restore point.
132 (if (and buffer-undo-list (not (eq buffer-undo-list t)))
133 (setq buffer-undo-list (cons (point) buffer-undo-list)))
134 (or justify (setq justify (justification)))
136 ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
137 (let ((fill-prefix fill-prefix))
138 ;; Figure out how this paragraph is indented, if desired.
139 (if (and adaptive-fill-mode
140 (or (null fill-prefix) (string= fill-prefix "")))
141 (save-excursion
142 (goto-char (min from to))
143 (if (eolp) (forward-line 1))
144 (forward-line 1)
145 (move-to-left-margin)
146 (if (< (point) (max from to))
147 (let ((start (point)))
148 (re-search-forward adaptive-fill-regexp)
149 (setq fill-prefix (buffer-substring start (point)))
150 (set-text-properties 0 (length fill-prefix) nil fill-prefix))
151 (goto-char (min from to))
152 (if (eolp) (forward-line 1))
153 ;; If paragraph has only one line, don't assume in general
154 ;; that additional lines would have the same starting
155 ;; decoration. Assume no indentation.
158 (if (not justify) ; filling disabled: just check indentation
159 (progn
160 (goto-char (min from to))
161 (setq to (max from to))
162 (while (< (point) to)
163 (if (not (eolp))
164 (if (< (current-indentation) (left-margin))
165 (indent-to-left-margin)))
166 (forward-line 1)))
168 (save-restriction
169 (let (beg)
170 (goto-char (min from to))
171 (skip-chars-forward "\n")
172 (setq beg (point))
173 (goto-char (max from to))
174 (skip-chars-backward "\n")
175 (setq to (point)
176 from beg)
177 (goto-char from)
178 (beginning-of-line)
179 (narrow-to-region (point) to))
180 (if use-hard-newlines
181 (remove-text-properties from to '(hard nil)))
182 ;; Make sure first line is indented (at least) to left margin...
183 (if (or (memq justify '(right center))
184 (< (current-indentation) (left-margin)))
185 (indent-to-left-margin))
186 ;; and remove indentation from other lines.
187 (beginning-of-line 2)
188 (indent-region (point) (point-max) 0)
189 ;; Delete the fill prefix from every line except the first.
190 ;; The first line may not even have a fill prefix.
191 (goto-char from)
192 (let ((fpre (and fill-prefix (not (equal fill-prefix ""))
193 (concat "[ \t]*"
194 (regexp-quote fill-prefix)))))
195 (and fpre
196 (progn
197 (if (>= (+ (left-margin) (length fill-prefix))
198 (current-fill-column))
199 (error "fill-prefix too long for specified width"))
200 (goto-char from)
201 (forward-line 1)
202 (while (not (eobp))
203 (if (looking-at fpre)
204 (delete-region (point) (match-end 0)))
205 (forward-line 1))
206 (goto-char from)
207 (and (looking-at fpre) (goto-char (match-end 0)))
208 (setq from (point)))))
209 ;; "from" is now before the text to fill,
210 ;; but after any fill prefix on the first line.
212 ;; Make sure sentences ending at end of line get an extra space.
213 ;; loses on split abbrevs ("Mr.\nSmith")
214 (while (re-search-forward "[.?!][])}\"']*$" nil t)
215 (insert-and-inherit ? ))
216 (goto-char from)
217 (skip-chars-forward " \t")
218 ;; Then change all newlines to spaces.
219 (subst-char-in-region from (point-max) ?\n ?\ )
220 (if (and nosqueeze (not (eq justify 'full)))
222 (canonically-space-region (point) (point-max))
223 (goto-char (point-max))
224 (delete-horizontal-space)
225 (insert-and-inherit " "))
226 (goto-char (point-min))
228 ;; This is the actual filling loop.
229 (let ((prefixcol 0) linebeg)
230 (while (not (eobp))
231 (setq linebeg (point))
232 (move-to-column (1+ (current-fill-column)))
233 (if (eobp)
234 (or nosqueeze (delete-horizontal-space))
235 ;; Move back to start of word.
236 (skip-chars-backward "^ \n" linebeg)
237 ;; Don't break after a period followed by just one space.
238 ;; Move back to the previous place to break.
239 ;; The reason is that if a period ends up at the end of a line,
240 ;; further fills will assume it ends a sentence.
241 ;; If we now know it does not end a sentence,
242 ;; avoid putting it at the end of the line.
243 (if sentence-end-double-space
244 (while (and (> (point) (+ linebeg 2))
245 (eq (preceding-char) ?\ )
246 (not (eq (following-char) ?\ ))
247 (eq (char-after (- (point) 2)) ?\.))
248 (forward-char -2)
249 (skip-chars-backward "^ \n" linebeg)))
250 (if (if (zerop prefixcol)
251 (save-excursion
252 (skip-chars-backward " " linebeg)
253 (bolp))
254 (>= prefixcol (current-column)))
255 ;; Keep at least one word even if fill prefix exceeds margin.
256 ;; This handles all but the first line of the paragraph.
257 ;; Meanwhile, don't stop at a period followed by one space.
258 (let ((first t))
259 (move-to-column prefixcol)
260 (while (and (not (eobp))
261 (or first
262 (and (not (bobp))
263 sentence-end-double-space
264 (save-excursion (forward-char -1)
265 (and (looking-at "\\. ")
266 (not (looking-at "\\. ")))))))
267 (skip-chars-forward " ")
268 (skip-chars-forward "^ \n")
269 (setq first nil)))
270 ;; Normally, move back over the single space between the words.
271 (forward-char -1))
272 (if (and fill-prefix (zerop prefixcol)
273 (< (- (point) (point-min)) (length fill-prefix))
274 (string= (buffer-substring (point-min) (point))
275 (substring fill-prefix 0 (- (point) (point-min)))))
276 ;; Keep at least one word even if fill prefix exceeds margin.
277 ;; This handles the first line of the paragraph.
278 ;; Don't stop at a period followed by just one space.
279 (let ((first t))
280 (while (and (not (eobp))
281 (or first
282 (and (not (bobp))
283 sentence-end-double-space
284 (save-excursion (forward-char -1)
285 (and (looking-at "\\. ")
286 (not (looking-at "\\. ")))))))
287 (skip-chars-forward " ")
288 (skip-chars-forward "^ \n")
289 (setq first nil))))
290 ;; Replace whitespace here with one newline, then indent to left
291 ;; margin.
292 (skip-chars-backward " ")
293 (insert ?\n)
294 ;; Give newline the properties of the space(s) it replaces
295 (set-text-properties (1- (point)) (point)
296 (text-properties-at (point)))
297 (indent-to-left-margin)
298 ;; Insert the fill prefix after indentation.
299 ;; Set prefixcol so whitespace in the prefix won't get lost.
300 (and fill-prefix (not (equal fill-prefix ""))
301 (progn
302 (insert-and-inherit fill-prefix)
303 (setq prefixcol (current-column)))))
304 ;; Justify the line just ended, if desired.
305 (if justify
306 (if (eobp)
307 (justify-current-line justify t t)
308 (forward-line -1)
309 (justify-current-line justify nil t)
310 (forward-line 1)))))))))
312 (defun fill-paragraph (arg)
313 "Fill paragraph at or after point. Prefix arg means justify as well.
314 If `sentence-end-double-space' is non-nil, then period followed by one
315 space does not end a sentence, so don't break a line there."
316 (interactive "P")
317 (let ((before (point)))
318 (save-excursion
319 (forward-paragraph)
320 (or (bolp) (newline 1))
321 (let ((end (point))
322 (beg (progn (backward-paragraph) (point))))
323 (goto-char before)
324 (if use-hard-newlines
325 ;; Can't use fill-region-as-paragraph, since this paragraph may
326 ;; still contain hard newlines. See fill-region.
327 (fill-region beg end arg)
328 (fill-region-as-paragraph beg end arg))))))
330 (defun fill-region (from to &optional justify nosqueeze to-eop)
331 "Fill each of the paragraphs in the region.
332 Prefix arg (non-nil third arg, if called from program) means justify as well.
334 Noninteractively, fourth arg NOSQUEEZE non-nil means to leave
335 whitespace other than line breaks untouched, and fifth arg TO-EOP
336 non-nil means to keep filling to the end of the paragraph (or next
337 hard newline, if `use-hard-newlines' is on).
339 If `sentence-end-double-space' is non-nil, then period followed by one
340 space does not end a sentence, so don't break a line there."
341 (interactive "r\nP")
342 ;; If using hard newlines, break at every one for filling purposes rather
343 ;; than breaking at normal paragraph breaks.
344 (let ((paragraph-start (if use-hard-newlines "^" paragraph-start))
345 end beg)
346 (save-restriction
347 (goto-char (max from to))
348 (if to-eop
349 (progn (skip-chars-backward "\n")
350 (forward-paragraph)))
351 (setq end (point))
352 (goto-char (setq beg (min from to)))
353 (beginning-of-line)
354 (narrow-to-region (point) end)
355 (while (not (eobp))
356 (let ((initial (point))
357 (end (progn
358 (forward-paragraph 1) (point))))
359 (forward-paragraph -1)
360 (if (< (point) beg)
361 (goto-char beg))
362 (if (>= (point) initial)
363 (fill-region-as-paragraph (point) end justify nosqueeze)
364 (goto-char end)))))))
367 (defconst default-justification 'left
368 "*Method of justifying text not otherwise specified.
369 Possible values are `left', `right', `full', `center', or `none'.
370 The requested kind of justification is done whenever lines are filled.
371 The `justification' text-property can locally override this variable.
372 This variable automatically becomes buffer-local when set in any fashion.")
373 (make-variable-buffer-local 'default-justification)
375 (defun justification ()
376 "How should we justify this line?
377 This returns the value of the text-property `justification',
378 or the variable `default-justification' if there is no text-property.
379 However, it returns nil rather than `none' to mean \"don't justify\"."
380 (let ((j (or (get-text-property
381 ;; Make sure we're looking at paragraph body.
382 (save-excursion (skip-chars-forward " \t") (point))
383 'justification)
384 default-justification)))
385 (if (eq 'none j)
387 j)))
389 (defun set-justification (begin end value)
390 "Set the region's justification style.
391 If the mark is not active, this operates on the current line.
392 In interactive use, if the BEGIN and END points are
393 not at line breaks, they are moved outward to the next line break.
394 If `use-hard-newlines' is true, they are moved to the next hard line breaks.
395 Noninteractively, the values of BEGIN, END and VALUE are not modified."
396 (interactive (list (if mark-active (region-beginning) (point))
397 (if mark-active (region-end) (point))
398 (let ((s (completing-read
399 "Set justification to: "
400 '(("left") ("right") ("full") ("center")
401 ("none"))
402 nil t)))
403 (if (equal s "")
404 (error "")
405 (intern s)))))
406 (let* ((paragraph-start (if use-hard-newlines "^" paragraph-start)))
407 (save-excursion
408 (goto-char begin)
409 (while (bolp) (forward-char 1))
410 (backward-paragraph)
411 (setq begin (point))
413 (goto-char end)
414 (skip-chars-backward " \t\n" begin)
415 (forward-paragraph)
416 (setq end (point))
417 (set-mark begin)
418 (goto-char end)
419 (y-or-n-p "set-just")))
420 (put-text-property begin end 'justification value)
421 (fill-region begin end nil t))
423 (defun set-justification-none (b e)
424 "Disable automatic filling for paragraphs in the region.
425 If the mark is not active, this applies to the current paragraph."
426 (interactive "r")
427 (set-justification b e 'none))
429 (defun set-justification-left (b e)
430 "Make paragraphs in the region left-justified.
431 This is usually the default, but see `enriched-default-justification'.
432 If the mark is not active, this applies to the current paragraph."
433 (interactive "r")
434 (set-justification b e 'left))
436 (defun set-justification-right (b e)
437 "Make paragraphs in the region right-justified:
438 Flush at the right margin and ragged on the left.
439 If the mark is not active, this applies to the current paragraph."
440 (interactive "r")
441 (set-justification b e 'right))
443 (defun set-justification-full (b e)
444 "Make paragraphs in the region fully justified:
445 Flush on both margins.
446 If the mark is not active, this applies to the current paragraph."
447 (interactive "r")
448 (set-justification b e 'both))
450 (defun set-justification-center (b e)
451 "Make paragraphs in the region centered.
452 If the mark is not active, this applies to the current paragraph."
453 (interactive "r")
454 (set-justification b e 'center))
456 (defun justify-current-line (&optional how eop nosqueeze)
457 "Add spaces to line point is in, so it ends at `fill-column'.
458 Optional first argument HOW specifies alternate type of justification:
459 it can be `left', `right', `full', `center', or `none'.
460 If HOW is t, will justify however the `justification' function says.
461 Any other value, including nil, is taken to mean `full'.
462 Second arg EOP non-nil means that this is the last line of the paragraph, so
463 it will not be stretched by full justification.
464 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
465 otherwise it is made canonical."
466 (interactive (list 'full nil nil))
467 (if (eq t how) (setq how (or (justification) 'none)))
468 (save-excursion
469 (save-restriction
470 (let ((fc (current-fill-column))
471 ncols beg indent end)
472 (end-of-line)
473 (if (and use-hard-newlines (null eop)
474 (get-text-property (point) 'hard))
475 (setq eop t))
476 (skip-chars-backward " \t")
477 (if (= (current-column) fc)
478 nil ;; Quick exit if it appears to be properly justified already.
479 (setq end (point))
480 (beginning-of-line)
481 (skip-chars-forward " \t")
482 (if (and fill-prefix
483 (equal fill-prefix
484 (buffer-substring (point)
485 (+ (point) (length fill-prefix)))))
486 (forward-char (length fill-prefix)))
487 (setq indent (current-column))
488 (setq beg (point))
489 (goto-char end)
490 (cond ((or (eq 'none how) (eq 'left how))
491 nil)
492 ((eq 'right how)
493 (setq ncols (- (+ indent (current-fill-column))
494 (current-column)))
495 (if (> ncols 0)
496 (indent-line-to ncols)))
497 ((eq 'center how)
498 (setq ncols
499 (/ (- (+ indent (current-fill-column)) (current-column))
501 (if (>= ncols 0)
502 (indent-line-to ncols)
503 (message "Line to long to center")))
504 (t ;; full
505 (narrow-to-region beg end)
506 (or nosqueeze
507 (canonically-space-region beg end))
508 (goto-char (point-max))
509 (setq ncols (- (current-fill-column) indent (current-column)))
510 (if (< ncols 0)
511 (message "Line to long to justify")
512 (if (and (not eop)
513 (search-backward " " nil t))
514 (while (> ncols 0)
515 (let ((nmove (+ 3 (random 3))))
516 (while (> nmove 0)
517 (or (search-backward " " nil t)
518 (progn
519 (goto-char (point-max))
520 (search-backward " ")))
521 (skip-chars-backward " ")
522 (setq nmove (1- nmove))))
523 (insert-and-inherit " ")
524 (skip-chars-backward " ")
525 (setq ncols (1- ncols)))))))))))
526 nil)
529 (defun fill-nonuniform-paragraphs (min max &optional justifyp mailp)
530 "Fill paragraphs within the region, allowing varying indentation within each.
531 This command divides the region into \"paragraphs\",
532 only at paragraph-separator lines, then fills each paragraph
533 using as the fill prefix the smallest indentation of any line
534 in the paragraph.
536 When calling from a program, pass range to fill as first two arguments.
538 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
539 JUSTIFY to justify paragraphs (prefix arg),
540 MAIL-FLAG for a mail message, i. e. don't fill header lines."
541 (interactive "r\nP")
542 (let ((fill-individual-varying-indent t))
543 (fill-individual-paragraphs min max justifyp mailp)))
545 (defun fill-individual-paragraphs (min max &optional justify mailp)
546 "Fill paragraphs of uniform indentation within the region.
547 This command divides the region into \"paragraphs\",
548 treating every change in indentation level as a paragraph boundary,
549 then fills each paragraph using its indentation level as the fill prefix.
551 When calling from a program, pass range to fill as first two arguments.
553 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
554 JUSTIFY to justify paragraphs (prefix arg),
555 MAIL-FLAG for a mail message, i. e. don't fill header lines."
556 (interactive "r\nP")
557 (save-restriction
558 (save-excursion
559 (goto-char min)
560 (beginning-of-line)
561 (narrow-to-region (point) max)
562 (if mailp
563 (while (and (not (eobp))
564 (or (looking-at "[ \t]*[^ \t\n]*:")
565 (looking-at "[ \t]*$")))
566 (if (looking-at "[ \t]*[^ \t\n]*:")
567 (search-forward "\n\n" nil 'move)
568 (forward-line 1))))
569 (narrow-to-region (point) max)
570 ;; Loop over paragraphs.
571 (while (progn (skip-chars-forward " \t\n") (not (eobp)))
572 (beginning-of-line)
573 (let ((start (point))
574 fill-prefix fill-prefix-regexp)
575 ;; Find end of paragraph, and compute the smallest fill-prefix
576 ;; that fits all the lines in this paragraph.
577 (while (progn
578 ;; Update the fill-prefix on the first line
579 ;; and whenever the prefix good so far is too long.
580 (if (not (and fill-prefix
581 (looking-at fill-prefix-regexp)))
582 (setq fill-prefix
583 (buffer-substring (point)
584 (save-excursion (skip-chars-forward " \t") (point)))
585 fill-prefix-regexp
586 (regexp-quote fill-prefix)))
587 (forward-line 1)
588 ;; Now stop the loop if end of paragraph.
589 (and (not (eobp))
590 (if fill-individual-varying-indent
591 ;; If this line is a separator line, with or
592 ;; without prefix, end the paragraph.
593 (and
594 (not (looking-at paragraph-separate))
595 (save-excursion
596 (not (and (looking-at fill-prefix-regexp)
597 (progn (forward-char (length fill-prefix))
598 (looking-at paragraph-separate))))))
599 ;; If this line has more or less indent
600 ;; than the fill prefix wants, end the paragraph.
601 (and (looking-at fill-prefix-regexp)
602 (save-excursion
603 (not (progn (forward-char (length fill-prefix))
604 (or (looking-at paragraph-separate)
605 (looking-at paragraph-start))))))))))
606 ;; Fill this paragraph, but don't add a newline at the end.
607 (let ((had-newline (bolp)))
608 (fill-region-as-paragraph start (point) justify)
609 (or had-newline (delete-char -1))))))))
611 ;;; fill.el ends here