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