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