(org-up-heading-all): Fixed bug with
[bpt/emacs.git] / lisp / textmodes / fill.el
1 ;;; fill.el --- fill commands for Emacs -*- coding: iso-2022-7bit -*-
2
3 ;; Copyright (C) 1985,86,92,94,95,96,97,1999,2001,02,03,2004
4 ;; Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Keywords: wp
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
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.
25
26 ;;; Commentary:
27
28 ;; All the commands for filling text. These are documented in the Emacs
29 ;; manual.
30
31 ;;; Code:
32
33 (defgroup fill nil
34 "Indenting and filling text."
35 :link '(custom-manual "(emacs)Filling")
36 :group 'editing)
37
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)
46
47 (defcustom colon-double-space nil
48 "*Non-nil means put two spaces after a colon when filling."
49 :type 'boolean
50 :group 'fill)
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
56 (defvar fill-paragraph-handle-comment t
57 "Non-nil means paragraph filling will try to pay attention to comments.")
58
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)
65
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")))
81
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)
86
87 (defcustom adaptive-fill-regexp
88 ;; Added `!' for doxygen comments starting with `//!' or `/*!'.
89 ;; Added `%' for TeX comments.
90 (purecopy "[ \t]*\\([-!|#%;>*\e,A7\e$,1s"s#sC\e$,2"F\e(B]+[ \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.
95
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)
101
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.
107
108 By default, this regexp matches sequences of just spaces and tabs.
109
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)
114
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)
120
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.")
123
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'.
129
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)))))
150
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))))))
197
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)
202 s1
203 (setq cmp (1- (abs cmp)))
204 (unless (zerop cmp)
205 (substring s1 0 cmp)))))
206
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))
261
262 (if (string-match re first-line-prefix)
263 second-line-prefix
264
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)))))))
290
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)))))
299
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]*[])}\e,A;\e,b;\e(B?!;:-]")
308 (save-excursion
309 (skip-chars-backward " \t")
310 (unless (bolp)
311 (backward-char 1)
312 (or (looking-at "[([{\e,A+\e,b+\e(B]")
313 ;; Don't cut right after a single-letter word.
314 (and (memq (preceding-char) '(?\t ?\ ))
315 (eq (char-syntax (following-char)) ?w)))))))
316
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))
324
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)
329
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'."
334 (or
335 (and fill-nobreak-invisible (line-move-invisible (point)))
336 (unless (bolp)
337 (or
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")
357 ;; If this break point is at the end of the line,
358 ;; which can occur for auto-fill, don't consider the newline
359 ;; which follows as a reason to return t.
360 (and (not (eolp))
361 (looking-at paragraph-start))))
362 (run-hook-with-args-until-success 'fill-nobreak-predicate)))))
363
364 ;; Put `fill-find-break-point-function' property to charsets which
365 ;; require special functions to find line breaking point.
366 (dolist (pair '((katakana-jisx0201 . kinsoku)
367 (chinese-gb2312 . kinsoku)
368 (japanese-jisx0208 . kinsoku)
369 (japanese-jisx0212 . kinsoku)
370 (chinese-big5-1 . kinsoku)
371 (chinese-big5-2 . kinsoku)))
372 (put-charset-property (car pair) 'fill-find-break-point-function (cdr pair)))
373
374 (defun fill-find-break-point (limit)
375 "Move point to a proper line breaking position of the current line.
376 Don't move back past the buffer position LIMIT.
377
378 This function is called when we are going to break the current line
379 after or before a non-ASCII character. If the charset of the
380 character has the property `fill-find-break-point-function', this
381 function calls the property value as a function with one arg LINEBEG.
382 If the charset has no such property, do nothing."
383 (let* ((ch (following-char))
384 (charset (char-charset ch))
385 func)
386 (if (eq charset 'ascii)
387 (setq ch (preceding-char)
388 charset (char-charset ch)))
389 (if (charsetp charset)
390 (setq func
391 (get-charset-property charset 'fill-find-break-point-function)))
392 (if (and func (fboundp func))
393 (funcall func limit))))
394
395 (defun fill-delete-prefix (from to prefix)
396 "Delete the fill prefix from every line except the first.
397 The first line may not even have a fill prefix.
398 Point is moved to just past the fill prefix on the first line."
399 (let ((fpre (if (and prefix (not (string-match "\\`[ \t]*\\'" prefix)))
400 (concat "[ \t]*\\("
401 (replace-regexp-in-string
402 "[ \t]+" "[ \t]*"
403 (regexp-quote prefix))
404 "\\)?[ \t]*")
405 "[ \t]*")))
406 (goto-char from)
407 (if (>= (+ (current-left-margin) (length prefix))
408 (current-fill-column))
409 (error "fill-prefix too long for specified width"))
410 (forward-line 1)
411 (while (< (point) to)
412 (if (looking-at fpre)
413 (delete-region (point) (match-end 0)))
414 (forward-line 1))
415 (goto-char from)
416 (if (looking-at fpre)
417 (goto-char (match-end 0)))
418 (setq from (point))))
419
420 ;; The `fill-space' property carries the string with which a newline
421 ;; should be replaced when unbreaking a line (in fill-delete-newlines).
422 ;; It is added to newline characters by fill-newline when the default
423 ;; behavior of fill-delete-newlines is not what we want.
424 (add-to-list 'text-property-default-nonsticky '(fill-space . t))
425
426 (defun fill-delete-newlines (from to justify nosqueeze squeeze-after)
427 (goto-char from)
428 ;; Make sure sentences ending at end of line get an extra space.
429 ;; loses on split abbrevs ("Mr.\nSmith")
430 (let ((eol-double-space-re
431 (cond
432 ((not colon-double-space) (concat (sentence-end) "$"))
433 ;; Try to add the : inside the `sentence-end' regexp.
434 ((string-match "\\[[^][]*\\(\\.\\)[^][]*\\]" (sentence-end))
435 (concat (replace-match ".:" nil nil (sentence-end) 1) "$"))
436 ;; Can't find the right spot to insert the colon.
437 (t "[.?!:][])}\"']*$")))
438 (sentence-end-without-space-list
439 (string-to-list sentence-end-without-space)))
440 (while (re-search-forward eol-double-space-re to t)
441 (or (>= (point) to) (memq (char-before) '(?\t ?\ ))
442 (memq (char-after (match-beginning 0))
443 sentence-end-without-space-list)
444 (insert-and-inherit ?\ ))))
445
446 (goto-char from)
447 (if enable-multibyte-characters
448 ;; Delete unnecessay newlines surrounded by words. The
449 ;; character category `|' means that we can break a line
450 ;; at the character. And, charset property
451 ;; `nospace-between-words' tells how to concatenate
452 ;; words. If the value is non-nil, never put spaces
453 ;; between words, thus delete a newline between them.
454 ;; If the value is nil, delete a newline only when a
455 ;; character preceding a newline has text property
456 ;; `nospace-between-words'.
457 (while (search-forward "\n" to t)
458 (if (get-text-property (match-beginning 0) 'fill-space)
459 (replace-match (get-text-property (match-beginning 0) 'fill-space))
460 (let ((prev (char-before (match-beginning 0)))
461 (next (following-char)))
462 (if (and (or (aref (char-category-set next) ?|)
463 (aref (char-category-set prev) ?|))
464 (or (get-charset-property (char-charset prev)
465 'nospace-between-words)
466 (get-text-property (1- (match-beginning 0))
467 'nospace-between-words)))
468 (delete-char -1))))))
469
470 (goto-char from)
471 (skip-chars-forward " \t")
472 ;; Then change all newlines to spaces.
473 (subst-char-in-region from to ?\n ?\ )
474 (if (and nosqueeze (not (eq justify 'full)))
475 nil
476 (canonically-space-region (or squeeze-after (point)) to)
477 ;; Remove trailing whitespace.
478 ;; Maybe canonically-space-region should do that.
479 (goto-char to) (delete-char (- (skip-chars-backward " \t"))))
480 (goto-char from))
481
482 (defun fill-move-to-break-point (linebeg)
483 "Move to the position where the line should be broken.
484 The break position will be always after LINEBEG and generally before point."
485 ;; If the fill column is before linebeg, move to linebeg.
486 (if (> linebeg (point)) (goto-char linebeg))
487 ;; Move back to the point where we can break the line
488 ;; at. We break the line between word or after/before
489 ;; the character which has character category `|'. We
490 ;; search space, \c| followed by a character, or \c|
491 ;; following a character. If not found, place
492 ;; the point at linebeg.
493 (while
494 (when (re-search-backward "[ \t]\\|\\c|.\\|.\\c|" linebeg 0)
495 ;; In case of space, we place the point at next to
496 ;; the point where the break occurs actually,
497 ;; because we don't want to change the following
498 ;; logic of original Emacs. In case of \c|, the
499 ;; point is at the place where the break occurs.
500 (forward-char 1)
501 (when (fill-nobreak-p) (skip-chars-backward " \t" linebeg))))
502
503 ;; Move back over the single space between the words.
504 (skip-chars-backward " \t")
505
506 ;; If the left margin and fill prefix by themselves
507 ;; pass the fill-column. or if they are zero
508 ;; but we have no room for even one word,
509 ;; keep at least one word or a character which has
510 ;; category `|' anyway.
511 (if (>= linebeg (point))
512 ;; Ok, skip at least one word or one \c| character.
513 ;; Meanwhile, don't stop at a period followed by one space.
514 (let ((to (line-end-position))
515 (fill-nobreak-predicate nil) ;to break sooner.
516 (first t))
517 (goto-char linebeg)
518 (while (and (< (point) to) (or first (fill-nobreak-p)))
519 ;; Find a breakable point while ignoring the
520 ;; following spaces.
521 (skip-chars-forward " \t")
522 (if (looking-at "\\c|")
523 (forward-char 1)
524 (let ((pos (save-excursion
525 (skip-chars-forward "^ \n\t")
526 (point))))
527 (if (re-search-forward "\\c|" pos t)
528 (forward-char -1)
529 (goto-char pos))))
530 (setq first nil)))
531
532 (if enable-multibyte-characters
533 ;; If we are going to break the line after or
534 ;; before a non-ascii character, we may have to
535 ;; run a special function for the charset of the
536 ;; character to find the correct break point.
537 (if (not (and (eq (charset-after (1- (point))) 'ascii)
538 (eq (charset-after (point)) 'ascii)))
539 ;; Make sure we take SOMETHING after the fill prefix if any.
540 (fill-find-break-point linebeg)))))
541
542 ;; Like text-properties-at but don't include `composition' property.
543 (defun fill-text-properties-at (pos)
544 (let ((l (text-properties-at pos))
545 prop-list)
546 (while l
547 (unless (eq (car l) 'composition)
548 (setq prop-list
549 (cons (car l) (cons (cadr l) prop-list))))
550 (setq l (cddr l)))
551 prop-list))
552
553 (defun fill-newline ()
554 ;; Replace whitespace here with one newline, then
555 ;; indent to left margin.
556 (skip-chars-backward " \t")
557 (insert ?\n)
558 ;; Give newline the properties of the space(s) it replaces
559 (set-text-properties (1- (point)) (point)
560 (fill-text-properties-at (point)))
561 (and (looking-at "\\( [ \t]*\\)\\(\\c|\\)?")
562 (or (aref (char-category-set (or (char-before (1- (point))) ?\000)) ?|)
563 (match-end 2))
564 ;; When refilling later on, this newline would normally not be replaced
565 ;; by a space, so we need to mark it specially to re-install the space
566 ;; when we unfill.
567 (put-text-property (1- (point)) (point) 'fill-space (match-string 1)))
568 ;; If we don't want breaks in invisible text, don't insert
569 ;; an invisible newline.
570 (if fill-nobreak-invisible
571 (remove-text-properties (1- (point)) (point)
572 '(invisible t)))
573 (if (or fill-prefix
574 (not fill-indent-according-to-mode))
575 (fill-indent-to-left-margin)
576 (indent-according-to-mode))
577 ;; Insert the fill prefix after indentation.
578 (and fill-prefix (not (equal fill-prefix ""))
579 ;; Markers that were after the whitespace are now at point: insert
580 ;; before them so they don't get stuck before the prefix.
581 (insert-before-markers-and-inherit fill-prefix)))
582
583 (defun fill-indent-to-left-margin ()
584 "Indent current line to the column given by `current-left-margin'."
585 (let ((beg (point)))
586 (indent-line-to (current-left-margin))
587 (put-text-property beg (point) 'face 'default)))
588
589 (defun fill-region-as-paragraph (from to &optional justify
590 nosqueeze squeeze-after)
591 "Fill the region as one paragraph.
592 It removes any paragraph breaks in the region and extra newlines at the end,
593 indents and fills lines between the margins given by the
594 `current-left-margin' and `current-fill-column' functions.
595 \(In most cases, the variable `fill-column' controls the width.)
596 It leaves point at the beginning of the line following the paragraph.
597
598 Normally performs justification according to the `current-justification'
599 function, but with a prefix arg, does full justification instead.
600
601 From a program, optional third arg JUSTIFY can specify any type of
602 justification. Fourth arg NOSQUEEZE non-nil means not to make spaces
603 between words canonical before filling. Fifth arg SQUEEZE-AFTER, if non-nil,
604 means don't canonicalize spaces before that position.
605
606 Return the `fill-prefix' used for filling.
607
608 If `sentence-end-double-space' is non-nil, then period followed by one
609 space does not end a sentence, so don't break a line there."
610 (interactive (progn
611 (barf-if-buffer-read-only)
612 (list (region-beginning) (region-end)
613 (if current-prefix-arg 'full))))
614 (unless (memq justify '(t nil none full center left right))
615 (setq justify 'full))
616
617 ;; Make sure "to" is the endpoint.
618 (goto-char (min from to))
619 (setq to (max from to))
620 ;; Ignore blank lines at beginning of region.
621 (skip-chars-forward " \t\n")
622
623 (let ((from-plus-indent (point))
624 (oneleft nil))
625
626 (beginning-of-line)
627 (setq from (point))
628
629 ;; Delete all but one soft newline at end of region.
630 ;; And leave TO before that one.
631 (goto-char to)
632 (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
633 (if (and oneleft
634 (not (and use-hard-newlines
635 (get-text-property (1- (point)) 'hard))))
636 (delete-backward-char 1)
637 (backward-char 1)
638 (setq oneleft t)))
639 (setq to (copy-marker (point) t))
640 ;; ;; If there was no newline, and there is text in the paragraph, then
641 ;; ;; create a newline.
642 ;; (if (and (not oneleft) (> to from-plus-indent))
643 ;; (newline))
644 (goto-char from-plus-indent))
645
646 (if (not (> to (point)))
647 nil ;; There is no paragraph, only whitespace: exit now.
648
649 (or justify (setq justify (current-justification)))
650
651 ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
652 (let ((fill-prefix fill-prefix))
653 ;; Figure out how this paragraph is indented, if desired.
654 (when (and adaptive-fill-mode
655 (or (null fill-prefix) (string= fill-prefix "")))
656 (setq fill-prefix (fill-context-prefix from to))
657 ;; Ignore a white-space only fill-prefix
658 ;; if we indent-according-to-mode.
659 (when (and fill-prefix fill-indent-according-to-mode
660 (string-match "\\`[ \t]*\\'" fill-prefix))
661 (setq fill-prefix nil)))
662
663 (goto-char from)
664 (beginning-of-line)
665
666 (if (not justify) ; filling disabled: just check indentation
667 (progn
668 (goto-char from)
669 (while (< (point) to)
670 (if (and (not (eolp))
671 (< (current-indentation) (current-left-margin)))
672 (fill-indent-to-left-margin))
673 (forward-line 1)))
674
675 (if use-hard-newlines
676 (remove-list-of-text-properties from to '(hard)))
677 ;; Make sure first line is indented (at least) to left margin...
678 (if (or (memq justify '(right center))
679 (< (current-indentation) (current-left-margin)))
680 (fill-indent-to-left-margin))
681 ;; Delete the fill-prefix from every line.
682 (fill-delete-prefix from to fill-prefix)
683 (setq from (point))
684
685 ;; FROM, and point, are now before the text to fill,
686 ;; but after any fill prefix on the first line.
687
688 (fill-delete-newlines from to justify nosqueeze squeeze-after)
689
690 ;; This is the actual filling loop.
691 (goto-char from)
692 (let (linebeg)
693 (while (< (point) to)
694 (setq linebeg (point))
695 (move-to-column (current-fill-column))
696 (if (when (< (point) to)
697 ;; Find the position where we'll break the line.
698 (forward-char 1) ;Use an immediately following space, if any.
699 (fill-move-to-break-point linebeg)
700 ;; Check again to see if we got to the end of
701 ;; the paragraph.
702 (skip-chars-forward " \t")
703 (< (point) to))
704 ;; Found a place to cut.
705 (progn
706 (fill-newline)
707 (when justify
708 ;; Justify the line just ended, if desired.
709 (save-excursion
710 (forward-line -1)
711 (justify-current-line justify nil t))))
712
713 (goto-char to)
714 ;; Justify this last line, if desired.
715 (if justify (justify-current-line justify t t))))))
716 ;; Leave point after final newline.
717 (goto-char to)
718 (unless (eobp) (forward-char 1))
719 ;; Return the fill-prefix we used
720 fill-prefix)))
721
722 (defsubst skip-line-prefix (prefix)
723 "If point is inside the string PREFIX at the beginning of line, move past it."
724 (when (and prefix
725 (< (- (point) (line-beginning-position)) (length prefix))
726 (save-excursion
727 (beginning-of-line)
728 (looking-at (regexp-quote prefix))))
729 (goto-char (match-end 0))))
730
731 (defun fill-paragraph (arg)
732 "Fill paragraph at or after point. Prefix ARG means justify as well.
733 If `sentence-end-double-space' is non-nil, then period followed by one
734 space does not end a sentence, so don't break a line there.
735 the variable `fill-column' controls the width for filling.
736
737 If `fill-paragraph-function' is non-nil, we call it (passing our
738 argument to it), and if it returns non-nil, we simply return its value.
739
740 If `fill-paragraph-function' is nil, return the `fill-prefix' used for filling."
741 (interactive (progn
742 (barf-if-buffer-read-only)
743 (list (if current-prefix-arg 'full))))
744 ;; First try fill-paragraph-function.
745 (or (and fill-paragraph-function
746 (let ((function fill-paragraph-function)
747 ;; If fill-paragraph-function is set, it probably takes care
748 ;; of comments and stuff. If not, it will have to set
749 ;; fill-paragraph-handle-comment back to t explicitly or
750 ;; return nil.
751 (fill-paragraph-handle-comment nil)
752 fill-paragraph-function)
753 (funcall function arg)))
754 ;; Then try our syntax-aware filling code.
755 (and fill-paragraph-handle-comment
756 ;; Our code only handles \n-terminated comments right now.
757 comment-start (equal comment-end "")
758 (let ((fill-paragraph-handle-comment nil))
759 (fill-comment-paragraph arg)))
760 ;; If it all fails, default to the good ol' text paragraph filling.
761 (let ((before (point))
762 (paragraph-start paragraph-start)
763 ;; Fill prefix used for filling the paragraph.
764 fill-pfx)
765 ;; Try to prevent code sections and comment sections from being
766 ;; filled together.
767 (when (and fill-paragraph-handle-comment comment-start-skip)
768 (setq paragraph-start
769 (concat paragraph-start "\\|[ \t]*\\(?:"
770 comment-start-skip "\\)")))
771 (save-excursion
772 ;; To make sure the return value of forward-paragraph is meaningful,
773 ;; we have to start from the beginning of line, otherwise skipping
774 ;; past the last few chars of a paragraph-separator would count as
775 ;; a paragraph (and not skipping any chars at EOB would not count
776 ;; as a paragraph even if it is).
777 (move-to-left-margin)
778 (if (not (zerop (forward-paragraph)))
779 ;; There's no paragraph at or after point: give up.
780 (setq fill-pfx "")
781 (let ((end (point))
782 (beg (progn (backward-paragraph) (point))))
783 (goto-char before)
784 (setq fill-pfx
785 (if use-hard-newlines
786 ;; Can't use fill-region-as-paragraph, since this
787 ;; paragraph may still contain hard newlines. See
788 ;; fill-region.
789 (fill-region beg end arg)
790 (fill-region-as-paragraph beg end arg))))))
791 fill-pfx)))
792
793 (defun fill-comment-paragraph (&optional justify)
794 "Fill current comment.
795 If we're not in a comment, just return nil so that the caller
796 can take care of filling. JUSTIFY is used as in `fill-paragraph'."
797 (comment-normalize-vars)
798 (let (has-code-and-comment ; Non-nil if it contains code and a comment.
799 comin comstart)
800 ;; Figure out what kind of comment we are looking at.
801 (save-excursion
802 (beginning-of-line)
803 (when (setq comstart (comment-search-forward (line-end-position) t))
804 (setq comin (point))
805 (goto-char comstart) (skip-chars-backward " \t")
806 (setq has-code-and-comment (not (bolp)))))
807
808 (if (not comstart)
809 ;; Return nil, so the normal filling will take place.
810 nil
811
812 ;; Narrow to include only the comment, and then fill the region.
813 (let* ((fill-prefix fill-prefix)
814 (commark
815 (comment-string-strip (buffer-substring comstart comin) nil t))
816 (comment-re
817 (if (string-match comment-start-skip (concat commark "a"))
818 (concat "[ \t]*" (regexp-quote commark)
819 ;; Make sure we only match comments that use
820 ;; the exact same comment marker.
821 "[^" (substring commark -1) "]")
822 ;; If the commark needs to be followed by some special
823 ;; set of characters (like @c in TeXinfo), we can't
824 ;; rely just on `commark'.
825 (concat "[ \t]*\\(?:" comment-start-skip "\\)")))
826 (comment-fill-prefix ; Compute a fill prefix.
827 (save-excursion
828 (goto-char comstart)
829 (if has-code-and-comment
830 (concat
831 (if (not indent-tabs-mode)
832 (make-string (current-column) ?\ )
833 (concat
834 (make-string (/ (current-column) tab-width) ?\t)
835 (make-string (% (current-column) tab-width) ?\ )))
836 (buffer-substring (point) comin))
837 (buffer-substring (line-beginning-position) comin))))
838 beg end)
839 (save-excursion
840 (save-restriction
841 (beginning-of-line)
842 (narrow-to-region
843 ;; Find the first line we should include in the region to fill.
844 (if has-code-and-comment
845 (line-beginning-position)
846 (save-excursion
847 (while (and (zerop (forward-line -1))
848 (looking-at comment-re)))
849 ;; We may have gone too far. Go forward again.
850 (line-beginning-position
851 (if (progn
852 (goto-char
853 (or (comment-search-forward (line-end-position) t)
854 (point)))
855 (looking-at comment-re))
856 1 2))))
857 ;; Find the beginning of the first line past the region to fill.
858 (save-excursion
859 (while (progn (forward-line 1)
860 (looking-at comment-re)))
861 (point)))
862 ;; Obey paragraph starters and boundaries within comments.
863 (let* ((paragraph-separate
864 ;; Use the default values since they correspond to
865 ;; the values to use for plain text.
866 (concat paragraph-separate "\\|[ \t]*\\(?:"
867 comment-start-skip "\\)\\(?:"
868 (default-value 'paragraph-separate) "\\)"))
869 (paragraph-start
870 (concat paragraph-start "\\|[ \t]*\\(?:"
871 comment-start-skip "\\)\\(?:"
872 (default-value 'paragraph-start) "\\)"))
873 ;; We used to reply on fill-prefix to break paragraph at
874 ;; comment-starter changes, but it did not work for the
875 ;; first line (mixed comment&code).
876 ;; We now use comment-re instead to "manually" make sure
877 ;; we treat comment-marker changes as paragraph boundaries.
878 ;; (paragraph-ignore-fill-prefix nil)
879 ;; (fill-prefix comment-fill-prefix)
880 (after-line (if has-code-and-comment
881 (line-beginning-position 2))))
882 (setq end (progn (forward-paragraph) (point)))
883 ;; If this comment starts on a line with code,
884 ;; include that line in the filling.
885 (setq beg (progn (backward-paragraph)
886 (if (eq (point) after-line)
887 (forward-line -1))
888 (point)))))
889
890 ;; Find the fill-prefix to use.
891 (cond
892 (fill-prefix) ; Use the user-provided fill prefix.
893 ((and adaptive-fill-mode ; Try adaptive fill mode.
894 (setq fill-prefix (fill-context-prefix beg end))
895 (string-match comment-start-skip fill-prefix)))
896 (t
897 (setq fill-prefix comment-fill-prefix)))
898
899 ;; Don't fill with narrowing.
900 (or
901 (fill-region-as-paragraph
902 beg end justify nil
903 ;; Don't canonicalize spaces within the code just before
904 ;; the comment.
905 (save-excursion
906 (goto-char beg)
907 (if (looking-at fill-prefix)
908 nil
909 (re-search-forward comment-start-skip))))
910 ;; Make sure we don't return nil.
911 t))))))
912
913 (defun fill-region (from to &optional justify nosqueeze to-eop)
914 "Fill each of the paragraphs in the region.
915 A prefix arg means justify as well.
916 Ordinarily the variable `fill-column' controls the width.
917
918 Noninteractively, the third argument JUSTIFY specifies which
919 kind of justification to do: `full', `left', `right', `center',
920 or `none' (equivalent to nil). t means handle each paragraph
921 as specified by its text properties.
922
923 The fourth arg NOSQUEEZE non-nil means to leave
924 whitespace other than line breaks untouched, and fifth arg TO-EOP
925 non-nil means to keep filling to the end of the paragraph (or next
926 hard newline, if variable `use-hard-newlines' is on).
927
928 Return the fill-prefix used for filling the last paragraph.
929
930 If `sentence-end-double-space' is non-nil, then period followed by one
931 space does not end a sentence, so don't break a line there."
932 (interactive (progn
933 (barf-if-buffer-read-only)
934 (list (region-beginning) (region-end)
935 (if current-prefix-arg 'full))))
936 (unless (memq justify '(t nil none full center left right))
937 (setq justify 'full))
938 (let (max beg fill-pfx)
939 (goto-char (max from to))
940 (when to-eop
941 (skip-chars-backward "\n")
942 (forward-paragraph))
943 (setq max (copy-marker (point) t))
944 (goto-char (setq beg (min from to)))
945 (beginning-of-line)
946 (while (< (point) max)
947 (let ((initial (point))
948 end)
949 ;; If using hard newlines, break at every one for filling
950 ;; purposes rather than using paragraph breaks.
951 (if use-hard-newlines
952 (progn
953 (while (and (setq end (text-property-any (point) max
954 'hard t))
955 (not (= ?\n (char-after end)))
956 (not (>= end max)))
957 (goto-char (1+ end)))
958 (setq end (if end (min max (1+ end)) max))
959 (goto-char initial))
960 (forward-paragraph 1)
961 (setq end (min max (point)))
962 (forward-paragraph -1))
963 (if (< (point) beg)
964 (goto-char beg))
965 (if (>= (point) initial)
966 (setq fill-pfx
967 (fill-region-as-paragraph (point) end justify nosqueeze))
968 (goto-char end))))
969 fill-pfx))
970
971 \f
972 (defcustom default-justification 'left
973 "*Method of justifying text not otherwise specified.
974 Possible values are `left', `right', `full', `center', or `none'.
975 The requested kind of justification is done whenever lines are filled.
976 The `justification' text-property can locally override this variable."
977 :type '(choice (const left)
978 (const right)
979 (const full)
980 (const center)
981 (const none))
982 :group 'fill)
983 (make-variable-buffer-local 'default-justification)
984
985 (defun current-justification ()
986 "How should we justify this line?
987 This returns the value of the text-property `justification',
988 or the variable `default-justification' if there is no text-property.
989 However, it returns nil rather than `none' to mean \"don't justify\"."
990 (let ((j (or (get-text-property
991 ;; Make sure we're looking at paragraph body.
992 (save-excursion (skip-chars-forward " \t")
993 (if (and (eobp) (not (bobp)))
994 (1- (point)) (point)))
995 'justification)
996 default-justification)))
997 (if (eq 'none j)
998 nil
999 j)))
1000
1001 (defun set-justification (begin end style &optional whole-par)
1002 "Set the region's justification style to STYLE.
1003 This commands prompts for the kind of justification to use.
1004 If the mark is not active, this command operates on the current paragraph.
1005 If the mark is active, it operates on the region. However, if the
1006 beginning and end of the region are not at paragraph breaks, they are
1007 moved to the beginning and end \(respectively) of the paragraphs they
1008 are in.
1009
1010 If variable `use-hard-newlines' is true, all hard newlines are
1011 taken to be paragraph breaks.
1012
1013 When calling from a program, operates just on region between BEGIN and END,
1014 unless optional fourth arg WHOLE-PAR is non-nil. In that case bounds are
1015 extended to include entire paragraphs as in the interactive command."
1016 (interactive (list (if mark-active (region-beginning) (point))
1017 (if mark-active (region-end) (point))
1018 (let ((s (completing-read
1019 "Set justification to: "
1020 '(("left") ("right") ("full")
1021 ("center") ("none"))
1022 nil t)))
1023 (if (equal s "") (error ""))
1024 (intern s))
1025 t))
1026 (save-excursion
1027 (save-restriction
1028 (if whole-par
1029 (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
1030 (paragraph-ignore-fill-prefix (if use-hard-newlines t
1031 paragraph-ignore-fill-prefix)))
1032 (goto-char begin)
1033 (while (and (bolp) (not (eobp))) (forward-char 1))
1034 (backward-paragraph)
1035 (setq begin (point))
1036 (goto-char end)
1037 (skip-chars-backward " \t\n" begin)
1038 (forward-paragraph)
1039 (setq end (point))))
1040
1041 (narrow-to-region (point-min) end)
1042 (unjustify-region begin (point-max))
1043 (put-text-property begin (point-max) 'justification style)
1044 (fill-region begin (point-max) nil t))))
1045
1046 (defun set-justification-none (b e)
1047 "Disable automatic filling for paragraphs in the region.
1048 If the mark is not active, this applies to the current paragraph."
1049 (interactive (list (if mark-active (region-beginning) (point))
1050 (if mark-active (region-end) (point))))
1051 (set-justification b e 'none t))
1052
1053 (defun set-justification-left (b e)
1054 "Make paragraphs in the region left-justified.
1055 This means they are flush at the left margin and ragged on the right.
1056 This is usually the default, but see the variable `default-justification'.
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 'left t))
1061
1062 (defun set-justification-right (b e)
1063 "Make paragraphs in the region right-justified.
1064 This means they are flush at the right margin and ragged on the left.
1065 If the mark is not active, this applies to the current paragraph."
1066 (interactive (list (if mark-active (region-beginning) (point))
1067 (if mark-active (region-end) (point))))
1068 (set-justification b e 'right t))
1069
1070 (defun set-justification-full (b e)
1071 "Make paragraphs in the region fully justified.
1072 This makes lines flush on both margins by inserting spaces between words.
1073 If the mark is not active, this applies to the current paragraph."
1074 (interactive (list (if mark-active (region-beginning) (point))
1075 (if mark-active (region-end) (point))))
1076 (set-justification b e 'full t))
1077
1078 (defun set-justification-center (b e)
1079 "Make paragraphs in the region centered.
1080 If the mark is not active, this applies to the current paragraph."
1081 (interactive (list (if mark-active (region-beginning) (point))
1082 (if mark-active (region-end) (point))))
1083 (set-justification b e 'center t))
1084
1085 ;; A line has up to six parts:
1086 ;;
1087 ;; >>> hello.
1088 ;; [Indent-1][FP][ Indent-2 ][text][trailing whitespace][newline]
1089 ;;
1090 ;; "Indent-1" is the left-margin indentation; normally it ends at column
1091 ;; given by the `current-left-margin' function.
1092 ;; "FP" is the fill-prefix. It can be any string, including whitespace.
1093 ;; "Indent-2" is added to justify a line if the `current-justification' is
1094 ;; `center' or `right'. In `left' and `full' justification regions, any
1095 ;; whitespace there is part of the line's text, and should not be changed.
1096 ;; Trailing whitespace is not counted as part of the line length when
1097 ;; center- or right-justifying.
1098 ;;
1099 ;; All parts of the line are optional, although the final newline can
1100 ;; only be missing on the last line of the buffer.
1101
1102 (defun justify-current-line (&optional how eop nosqueeze)
1103 "Do some kind of justification on this line.
1104 Normally does full justification: adds spaces to the line to make it end at
1105 the column given by `current-fill-column'.
1106 Optional first argument HOW specifies alternate type of justification:
1107 it can be `left', `right', `full', `center', or `none'.
1108 If HOW is t, will justify however the `current-justification' function says to.
1109 If HOW is nil or missing, full justification is done by default.
1110 Second arg EOP non-nil means that this is the last line of the paragraph, so
1111 it will not be stretched by full justification.
1112 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
1113 otherwise it is made canonical."
1114 (interactive "*")
1115 (if (eq t how) (setq how (or (current-justification) 'none))
1116 (if (null how) (setq how 'full)
1117 (or (memq how '(none left right center))
1118 (setq how 'full))))
1119 (or (memq how '(none left)) ; No action required for these.
1120 (let ((fc (current-fill-column))
1121 (pos (point-marker))
1122 fp-end ; point at end of fill prefix
1123 beg ; point at beginning of line's text
1124 end ; point at end of line's text
1125 indent ; column of `beg'
1126 endcol ; column of `end'
1127 ncols ; new indent point or offset
1128 (nspaces 0) ; number of spaces between words
1129 ; in line (not space characters)
1130 fracspace ; fractional amount of space to be
1131 ; added between each words
1132 (curr-fracspace 0) ; current fractional space amount
1133 count)
1134 (end-of-line)
1135 ;; Check if this is the last line of the paragraph.
1136 (if (and use-hard-newlines (null eop)
1137 (get-text-property (point) 'hard))
1138 (setq eop t))
1139 (skip-chars-backward " \t")
1140 ;; Quick exit if it appears to be properly justified already
1141 ;; or there is no text.
1142 (if (or (bolp)
1143 (and (memq how '(full right))
1144 (= (current-column) fc)))
1145 nil
1146 (setq end (point))
1147 (beginning-of-line)
1148 (skip-chars-forward " \t")
1149 ;; Skip over fill-prefix.
1150 (if (and fill-prefix
1151 (not (string-equal fill-prefix ""))
1152 (equal fill-prefix
1153 (buffer-substring
1154 (point) (min (point-max) (+ (length fill-prefix)
1155 (point))))))
1156 (forward-char (length fill-prefix))
1157 (if (and adaptive-fill-mode
1158 (looking-at adaptive-fill-regexp))
1159 (goto-char (match-end 0))))
1160 (setq fp-end (point))
1161 (skip-chars-forward " \t")
1162 ;; This is beginning of the line's text.
1163 (setq indent (current-column))
1164 (setq beg (point))
1165 (goto-char end)
1166 (setq endcol (current-column))
1167
1168 ;; HOW can't be null or left--we would have exited already
1169 (cond ((eq 'right how)
1170 (setq ncols (- fc endcol))
1171 (if (< ncols 0)
1172 ;; Need to remove some indentation
1173 (delete-region
1174 (progn (goto-char fp-end)
1175 (if (< (current-column) (+ indent ncols))
1176 (move-to-column (+ indent ncols) t))
1177 (point))
1178 (progn (move-to-column indent) (point)))
1179 ;; Need to add some
1180 (goto-char beg)
1181 (indent-to (+ indent ncols))
1182 ;; If point was at beginning of text, keep it there.
1183 (if (= beg pos)
1184 (move-marker pos (point)))))
1185
1186 ((eq 'center how)
1187 ;; Figure out how much indentation is needed
1188 (setq ncols (+ (current-left-margin)
1189 (/ (- fc (current-left-margin) ;avail. space
1190 (- endcol indent)) ;text width
1191 2)))
1192 (if (< ncols indent)
1193 ;; Have too much indentation - remove some
1194 (delete-region
1195 (progn (goto-char fp-end)
1196 (if (< (current-column) ncols)
1197 (move-to-column ncols t))
1198 (point))
1199 (progn (move-to-column indent) (point)))
1200 ;; Have too little - add some
1201 (goto-char beg)
1202 (indent-to ncols)
1203 ;; If point was at beginning of text, keep it there.
1204 (if (= beg pos)
1205 (move-marker pos (point)))))
1206
1207 ((eq 'full how)
1208 ;; Insert extra spaces between words to justify line
1209 (save-restriction
1210 (narrow-to-region beg end)
1211 (or nosqueeze
1212 (canonically-space-region beg end))
1213 (goto-char (point-max))
1214 ;; count word spaces in line
1215 (while (search-backward " " nil t)
1216 (setq nspaces (1+ nspaces))
1217 (skip-chars-backward " "))
1218 (setq ncols (- fc endcol))
1219 ;; Ncols is number of additional space chars needed
1220 (if (and (> ncols 0) (> nspaces 0) (not eop))
1221 (progn
1222 (setq curr-fracspace (+ ncols (/ (1+ nspaces) 2))
1223 count nspaces)
1224 (while (> count 0)
1225 (skip-chars-forward " ")
1226 (insert-and-inherit
1227 (make-string (/ curr-fracspace nspaces) ?\ ))
1228 (search-forward " " nil t)
1229 (setq count (1- count)
1230 curr-fracspace
1231 (+ (% curr-fracspace nspaces) ncols)))))))
1232 (t (error "Unknown justification value"))))
1233 (goto-char pos)
1234 (move-marker pos nil)))
1235 nil)
1236
1237 (defun unjustify-current-line ()
1238 "Remove justification whitespace from current line.
1239 If the line is centered or right-justified, this function removes any
1240 indentation past the left margin. If the line is full-justified, it removes
1241 extra spaces between words. It does nothing in other justification modes."
1242 (let ((justify (current-justification)))
1243 (cond ((eq 'left justify) nil)
1244 ((eq nil justify) nil)
1245 ((eq 'full justify) ; full justify: remove extra spaces
1246 (beginning-of-line-text)
1247 (canonically-space-region (point) (line-end-position)))
1248 ((memq justify '(center right))
1249 (save-excursion
1250 (move-to-left-margin nil t)
1251 ;; Position ourselves after any fill-prefix.
1252 (if (and fill-prefix
1253 (not (string-equal fill-prefix ""))
1254 (equal fill-prefix
1255 (buffer-substring
1256 (point) (min (point-max) (+ (length fill-prefix)
1257 (point))))))
1258 (forward-char (length fill-prefix)))
1259 (delete-region (point) (progn (skip-chars-forward " \t")
1260 (point))))))))
1261
1262 (defun unjustify-region (&optional begin end)
1263 "Remove justification whitespace from region.
1264 For centered or right-justified regions, this function removes any indentation
1265 past the left margin from each line. For full-justified lines, it removes
1266 extra spaces between words. It does nothing in other justification modes.
1267 Arguments BEGIN and END are optional; default is the whole buffer."
1268 (save-excursion
1269 (save-restriction
1270 (if end (narrow-to-region (point-min) end))
1271 (goto-char (or begin (point-min)))
1272 (while (not (eobp))
1273 (unjustify-current-line)
1274 (forward-line 1)))))
1275
1276 \f
1277 (defun fill-nonuniform-paragraphs (min max &optional justifyp citation-regexp)
1278 "Fill paragraphs within the region, allowing varying indentation within each.
1279 This command divides the region into \"paragraphs\",
1280 only at paragraph-separator lines, then fills each paragraph
1281 using as the fill prefix the smallest indentation of any line
1282 in the paragraph.
1283
1284 When calling from a program, pass range to fill as first two arguments.
1285
1286 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1287 JUSTIFY to justify paragraphs (prefix arg),
1288 When filling a mail message, pass a regexp for CITATION-REGEXP
1289 which will match the prefix of a line which is a citation marker
1290 plus whitespace, but no other kind of prefix.
1291 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1292 (interactive (progn
1293 (barf-if-buffer-read-only)
1294 (list (region-beginning) (region-end)
1295 (if current-prefix-arg 'full))))
1296 (let ((fill-individual-varying-indent t))
1297 (fill-individual-paragraphs min max justifyp citation-regexp)))
1298
1299 (defun fill-individual-paragraphs (min max &optional justify citation-regexp)
1300 "Fill paragraphs of uniform indentation within the region.
1301 This command divides the region into \"paragraphs\",
1302 treating every change in indentation level or prefix as a paragraph boundary,
1303 then fills each paragraph using its indentation level as the fill prefix.
1304
1305 There is one special case where a change in indentation does not start
1306 a new paragraph. This is for text of this form:
1307
1308 foo> This line with extra indentation starts
1309 foo> a paragraph that continues on more lines.
1310
1311 These lines are filled together.
1312
1313 When calling from a program, pass the range to fill
1314 as the first two arguments.
1315
1316 Optional third and fourth arguments JUSTIFY and MAIL-FLAG:
1317 JUSTIFY to justify paragraphs (prefix arg),
1318 When filling a mail message, pass a regexp for CITATION-REGEXP
1319 which will match the prefix of a line which is a citation marker
1320 plus whitespace, but no other kind of prefix.
1321 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1322 (interactive (progn
1323 (barf-if-buffer-read-only)
1324 (list (region-beginning) (region-end)
1325 (if current-prefix-arg 'full))))
1326 (save-restriction
1327 (save-excursion
1328 (goto-char min)
1329 (beginning-of-line)
1330 (narrow-to-region (point) max)
1331 (if citation-regexp
1332 (while (and (not (eobp))
1333 (or (looking-at "[ \t]*[^ \t\n]+:")
1334 (looking-at "[ \t]*$")))
1335 (if (looking-at "[ \t]*[^ \t\n]+:")
1336 (search-forward "\n\n" nil 'move)
1337 (forward-line 1))))
1338 (narrow-to-region (point) max)
1339 ;; Loop over paragraphs.
1340 (while (let ((here (point)))
1341 ;; Skip over all paragraph-separating lines
1342 ;; so as to not include them in any paragraph.
1343 (while (and (not (eobp))
1344 (progn (move-to-left-margin)
1345 (and (not (eobp))
1346 (looking-at paragraph-separate))))
1347 (forward-line 1))
1348 (skip-chars-forward " \t\n") (not (eobp)))
1349 (move-to-left-margin)
1350 (let ((start (point))
1351 fill-prefix fill-prefix-regexp)
1352 ;; Find end of paragraph, and compute the smallest fill-prefix
1353 ;; that fits all the lines in this paragraph.
1354 (while (progn
1355 ;; Update the fill-prefix on the first line
1356 ;; and whenever the prefix good so far is too long.
1357 (if (not (and fill-prefix
1358 (looking-at fill-prefix-regexp)))
1359 (setq fill-prefix
1360 (fill-individual-paragraphs-prefix
1361 citation-regexp)
1362 fill-prefix-regexp (regexp-quote fill-prefix)))
1363 (forward-line 1)
1364 (if (bolp)
1365 ;; If forward-line went past a newline,
1366 ;; move further to the left margin.
1367 (move-to-left-margin))
1368 ;; Now stop the loop if end of paragraph.
1369 (and (not (eobp))
1370 (if fill-individual-varying-indent
1371 ;; If this line is a separator line, with or
1372 ;; without prefix, end the paragraph.
1373 (and
1374 (not (looking-at paragraph-separate))
1375 (save-excursion
1376 (not (and (looking-at fill-prefix-regexp)
1377 (progn (forward-char
1378 (length fill-prefix))
1379 (looking-at
1380 paragraph-separate))))))
1381 ;; If this line has more or less indent
1382 ;; than the fill prefix wants, end the paragraph.
1383 (and (looking-at fill-prefix-regexp)
1384 ;; If fill prefix is shorter than a new
1385 ;; fill prefix computed here, end paragraph.
1386 (let ((this-line-fill-prefix
1387 (fill-individual-paragraphs-prefix
1388 citation-regexp)))
1389 (>= (length fill-prefix)
1390 (length this-line-fill-prefix)))
1391 (save-excursion
1392 (not (progn (forward-char
1393 (length fill-prefix))
1394 (or (looking-at "[ \t]")
1395 (looking-at paragraph-separate)
1396 (looking-at paragraph-start)))))
1397 (not (and (equal fill-prefix "")
1398 citation-regexp
1399 (looking-at citation-regexp))))))))
1400 ;; Fill this paragraph, but don't add a newline at the end.
1401 (let ((had-newline (bolp)))
1402 (fill-region-as-paragraph start (point) justify)
1403 (if (and (bolp) (not had-newline))
1404 (delete-char -1))))))))
1405 (defun fill-individual-paragraphs-prefix (citation-regexp)
1406 (let* ((adaptive-fill-first-line-regexp ".*")
1407 (just-one-line-prefix
1408 ;; Accept any prefix rather than just the ones matched by
1409 ;; adaptive-fill-first-line-regexp.
1410 (fill-context-prefix (point) (line-beginning-position 2)))
1411 (two-lines-prefix
1412 (fill-context-prefix (point) (line-beginning-position 3))))
1413 (if (not just-one-line-prefix)
1414 (buffer-substring
1415 (point) (save-excursion (skip-chars-forward " \t") (point)))
1416 ;; See if the citation part of JUST-ONE-LINE-PREFIX
1417 ;; is the same as that of TWO-LINES-PREFIX,
1418 ;; except perhaps with longer whitespace.
1419 (if (and just-one-line-prefix two-lines-prefix
1420 (let* ((one-line-citation-part
1421 (fill-individual-paragraphs-citation
1422 just-one-line-prefix citation-regexp))
1423 (two-lines-citation-part
1424 (fill-individual-paragraphs-citation
1425 two-lines-prefix citation-regexp))
1426 (adjusted-two-lines-citation-part
1427 (substring two-lines-citation-part 0
1428 (string-match "[ \t]*\\'"
1429 two-lines-citation-part))))
1430 (and
1431 (string-match (concat "\\`"
1432 (regexp-quote
1433 adjusted-two-lines-citation-part)
1434 "[ \t]*\\'")
1435 one-line-citation-part)
1436 (>= (string-width one-line-citation-part)
1437 (string-width two-lines-citation-part)))))
1438 two-lines-prefix
1439 just-one-line-prefix))))
1440
1441 (defun fill-individual-paragraphs-citation (string citation-regexp)
1442 (if citation-regexp
1443 (if (string-match citation-regexp string)
1444 (match-string 0 string)
1445 "")
1446 string))
1447
1448 ;;; arch-tag: 727ad455-1161-4fa9-8df5-0f74b179216d
1449 ;;; fill.el ends here