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