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