]> 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 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 comstart)
859 ;; Return nil, so the normal filling will take place.
860 nil
861
862 ;; Narrow to include only the comment, and then fill the region.
863 (let* ((fill-prefix fill-prefix)
864 (commark
865 (comment-string-strip (buffer-substring comstart comin) nil t))
866 (comment-re
867 ;; A regexp more specialized than comment-start-skip, that only
868 ;; matches the current commark rather than any valid commark.
869 ;;
870 ;; The specialized regexp only works for "normal" comment
871 ;; syntax, not for Texinfo's "@c" (which can't be immediately
872 ;; followed by word-chars) or Fortran's "C" (which needs to be
873 ;; at bol), so check that comment-start-skip indeed allows the
874 ;; commark to appear in the middle of the line and followed by
875 ;; word chars. The choice of "\0" and "a" is mostly arbitrary.
876 (if (string-match comment-start-skip (concat "\0" commark "a"))
877 (concat "[ \t]*" (regexp-quote commark)
878 ;; Make sure we only match comments that
879 ;; use the exact same comment marker.
880 "[^" (substring commark -1) "]")
881 (concat "[ \t]*\\(?:" comment-start-skip "\\)")))
882 (comment-fill-prefix ; Compute a fill prefix.
883 (save-excursion
884 (goto-char comstart)
885 (if has-code-and-comment
886 (concat
887 (if (not indent-tabs-mode)
888 (make-string (current-column) ?\s)
889 (concat
890 (make-string (/ (current-column) tab-width) ?\t)
891 (make-string (% (current-column) tab-width) ?\s)))
892 (buffer-substring (point) comin))
893 (buffer-substring (line-beginning-position) comin))))
894 beg end)
895 (save-excursion
896 (save-restriction
897 (beginning-of-line)
898 (narrow-to-region
899 ;; Find the first line we should include in the region to fill.
900 (if has-code-and-comment
901 (line-beginning-position)
902 (save-excursion
903 (while (and (zerop (forward-line -1))
904 (looking-at comment-re)))
905 ;; We may have gone too far. Go forward again.
906 (line-beginning-position
907 (if (progn
908 (goto-char
909 (or (comment-search-forward (line-end-position) t)
910 (point)))
911 (looking-at comment-re))
912 (progn (setq comstart (point)) 1)
913 (progn (setq comstart (point)) 2)))))
914 ;; Find the beginning of the first line past the region to fill.
915 (save-excursion
916 (while (progn (forward-line 1)
917 (looking-at comment-re)))
918 (point)))
919 ;; Obey paragraph starters and boundaries within comments.
920 (let* ((paragraph-separate
921 ;; Use the default values since they correspond to
922 ;; the values to use for plain text.
923 (concat paragraph-separate "\\|[ \t]*\\(?:"
924 comment-start-skip "\\)\\(?:"
925 (default-value 'paragraph-separate) "\\)"))
926 (paragraph-start
927 (concat paragraph-start "\\|[ \t]*\\(?:"
928 comment-start-skip "\\)\\(?:"
929 (default-value 'paragraph-start) "\\)"))
930 ;; We used to rely on fill-prefix to break paragraph at
931 ;; comment-starter changes, but it did not work for the
932 ;; first line (mixed comment&code).
933 ;; We now use comment-re instead to "manually" make sure
934 ;; we treat comment-marker changes as paragraph boundaries.
935 ;; (paragraph-ignore-fill-prefix nil)
936 ;; (fill-prefix comment-fill-prefix)
937 (after-line (if has-code-and-comment
938 (line-beginning-position 2))))
939 (setq end (progn (forward-paragraph) (point)))
940 ;; If this comment starts on a line with code,
941 ;; include that line in the filling.
942 (setq beg (progn (backward-paragraph)
943 (if (eq (point) after-line)
944 (forward-line -1))
945 (point)))))
946
947 ;; Find the fill-prefix to use.
948 (cond
949 (fill-prefix) ; Use the user-provided fill prefix.
950 ((and adaptive-fill-mode ; Try adaptive fill mode.
951 (setq fill-prefix (fill-context-prefix beg end))
952 (string-match comment-start-skip fill-prefix)))
953 (t
954 (setq fill-prefix comment-fill-prefix)))
955
956 ;; Don't fill with narrowing.
957 (or
958 (fill-region-as-paragraph
959 (max comstart beg) end justify nil
960 ;; Don't canonicalize spaces within the code just before
961 ;; the comment.
962 (save-excursion
963 (goto-char beg)
964 (if (looking-at fill-prefix)
965 nil
966 (re-search-forward comment-start-skip))))
967 ;; Make sure we don't return nil.
968 t))))))
969
970 (defun fill-region (from to &optional justify nosqueeze to-eop)
971 "Fill each of the paragraphs in the region.
972 A prefix arg means justify as well.
973 Ordinarily the variable `fill-column' controls the width.
974
975 Noninteractively, the third argument JUSTIFY specifies which
976 kind of justification to do: `full', `left', `right', `center',
977 or `none' (equivalent to nil). A value of t means handle each
978 paragraph as specified by its text properties.
979
980 The fourth arg NOSQUEEZE non-nil means to leave whitespace other
981 than line breaks untouched, and fifth arg TO-EOP non-nil means
982 to keep filling to the end of the paragraph (or next hard newline,
983 if variable `use-hard-newlines' is on).
984
985 Return the fill-prefix used for filling the last paragraph.
986
987 If `sentence-end-double-space' is non-nil, then period followed by one
988 space does not end a sentence, so don't break a line there."
989 (interactive (progn
990 (barf-if-buffer-read-only)
991 (list (region-beginning) (region-end)
992 (if current-prefix-arg 'full))))
993 (unless (memq justify '(t nil none full center left right))
994 (setq justify 'full))
995 (let (max beg fill-pfx)
996 (goto-char (max from to))
997 (when to-eop
998 (skip-chars-backward "\n")
999 (forward-paragraph))
1000 (setq max (copy-marker (point) t))
1001 (goto-char (setq beg (min from to)))
1002 (beginning-of-line)
1003 (while (< (point) max)
1004 (let ((initial (point))
1005 end)
1006 ;; If using hard newlines, break at every one for filling
1007 ;; purposes rather than using paragraph breaks.
1008 (if use-hard-newlines
1009 (progn
1010 (while (and (setq end (text-property-any (point) max
1011 'hard t))
1012 (not (= ?\n (char-after end)))
1013 (not (>= end max)))
1014 (goto-char (1+ end)))
1015 (setq end (if end (min max (1+ end)) max))
1016 (goto-char initial))
1017 (forward-paragraph 1)
1018 (setq end (min max (point)))
1019 (forward-paragraph -1))
1020 (if (< (point) beg)
1021 (goto-char beg))
1022 (if (>= (point) initial)
1023 (setq fill-pfx
1024 (fill-region-as-paragraph (point) end justify nosqueeze))
1025 (goto-char end))))
1026 fill-pfx))
1027
1028 \f
1029 (defcustom default-justification 'left
1030 "*Method of justifying text not otherwise specified.
1031 Possible values are `left', `right', `full', `center', or `none'.
1032 The requested kind of justification is done whenever lines are filled.
1033 The `justification' text-property can locally override this variable."
1034 :type '(choice (const left)
1035 (const right)
1036 (const full)
1037 (const center)
1038 (const none))
1039 :group 'fill)
1040 (make-variable-buffer-local 'default-justification)
1041
1042 (defun current-justification ()
1043 "How should we justify this line?
1044 This returns the value of the text-property `justification',
1045 or the variable `default-justification' if there is no text-property.
1046 However, it returns nil rather than `none' to mean \"don't justify\"."
1047 (let ((j (or (get-text-property
1048 ;; Make sure we're looking at paragraph body.
1049 (save-excursion (skip-chars-forward " \t")
1050 (if (and (eobp) (not (bobp)))
1051 (1- (point)) (point)))
1052 'justification)
1053 default-justification)))
1054 (if (eq 'none j)
1055 nil
1056 j)))
1057
1058 (defun set-justification (begin end style &optional whole-par)
1059 "Set the region's justification style to STYLE.
1060 This commands prompts for the kind of justification to use.
1061 If the mark is not active, this command operates on the current paragraph.
1062 If the mark is active, it operates on the region. However, if the
1063 beginning and end of the region are not at paragraph breaks, they are
1064 moved to the beginning and end \(respectively) of the paragraphs they
1065 are in.
1066
1067 If variable `use-hard-newlines' is true, all hard newlines are
1068 taken to be paragraph breaks.
1069
1070 When calling from a program, operates just on region between BEGIN and END,
1071 unless optional fourth arg WHOLE-PAR is non-nil. In that case bounds are
1072 extended to include entire paragraphs as in the interactive command."
1073 (interactive (list (if mark-active (region-beginning) (point))
1074 (if mark-active (region-end) (point))
1075 (let ((s (completing-read
1076 "Set justification to: "
1077 '(("left") ("right") ("full")
1078 ("center") ("none"))
1079 nil t)))
1080 (if (equal s "") (error ""))
1081 (intern s))
1082 t))
1083 (save-excursion
1084 (save-restriction
1085 (if whole-par
1086 (let ((paragraph-start (if use-hard-newlines "." paragraph-start))
1087 (paragraph-ignore-fill-prefix (if use-hard-newlines t
1088 paragraph-ignore-fill-prefix)))
1089 (goto-char begin)
1090 (while (and (bolp) (not (eobp))) (forward-char 1))
1091 (backward-paragraph)
1092 (setq begin (point))
1093 (goto-char end)
1094 (skip-chars-backward " \t\n" begin)
1095 (forward-paragraph)
1096 (setq end (point))))
1097
1098 (narrow-to-region (point-min) end)
1099 (unjustify-region begin (point-max))
1100 (put-text-property begin (point-max) 'justification style)
1101 (fill-region begin (point-max) nil t))))
1102
1103 (defun set-justification-none (b e)
1104 "Disable automatic filling for paragraphs in the region.
1105 If the mark is not active, this applies to the current paragraph."
1106 (interactive (list (if mark-active (region-beginning) (point))
1107 (if mark-active (region-end) (point))))
1108 (set-justification b e 'none t))
1109
1110 (defun set-justification-left (b e)
1111 "Make paragraphs in the region left-justified.
1112 This means they are flush at the left margin and ragged on the right.
1113 This is usually the default, but see the variable `default-justification'.
1114 If the mark is not active, this applies to the current paragraph."
1115 (interactive (list (if mark-active (region-beginning) (point))
1116 (if mark-active (region-end) (point))))
1117 (set-justification b e 'left t))
1118
1119 (defun set-justification-right (b e)
1120 "Make paragraphs in the region right-justified.
1121 This means they are flush at the right margin and ragged on the left.
1122 If the mark is not active, this applies to the current paragraph."
1123 (interactive (list (if mark-active (region-beginning) (point))
1124 (if mark-active (region-end) (point))))
1125 (set-justification b e 'right t))
1126
1127 (defun set-justification-full (b e)
1128 "Make paragraphs in the region fully justified.
1129 This makes lines flush on both margins by inserting spaces between words.
1130 If the mark is not active, this applies to the current paragraph."
1131 (interactive (list (if mark-active (region-beginning) (point))
1132 (if mark-active (region-end) (point))))
1133 (set-justification b e 'full t))
1134
1135 (defun set-justification-center (b e)
1136 "Make paragraphs in the region centered.
1137 If the mark is not active, this applies to the current paragraph."
1138 (interactive (list (if mark-active (region-beginning) (point))
1139 (if mark-active (region-end) (point))))
1140 (set-justification b e 'center t))
1141
1142 ;; A line has up to six parts:
1143 ;;
1144 ;; >>> hello.
1145 ;; [Indent-1][FP][ Indent-2 ][text][trailing whitespace][newline]
1146 ;;
1147 ;; "Indent-1" is the left-margin indentation; normally it ends at column
1148 ;; given by the `current-left-margin' function.
1149 ;; "FP" is the fill-prefix. It can be any string, including whitespace.
1150 ;; "Indent-2" is added to justify a line if the `current-justification' is
1151 ;; `center' or `right'. In `left' and `full' justification regions, any
1152 ;; whitespace there is part of the line's text, and should not be changed.
1153 ;; Trailing whitespace is not counted as part of the line length when
1154 ;; center- or right-justifying.
1155 ;;
1156 ;; All parts of the line are optional, although the final newline can
1157 ;; only be missing on the last line of the buffer.
1158
1159 (defun justify-current-line (&optional how eop nosqueeze)
1160 "Do some kind of justification on this line.
1161 Normally does full justification: adds spaces to the line to make it end at
1162 the column given by `current-fill-column'.
1163 Optional first argument HOW specifies alternate type of justification:
1164 it can be `left', `right', `full', `center', or `none'.
1165 If HOW is t, will justify however the `current-justification' function says to.
1166 If HOW is nil or missing, full justification is done by default.
1167 Second arg EOP non-nil means that this is the last line of the paragraph, so
1168 it will not be stretched by full justification.
1169 Third arg NOSQUEEZE non-nil means to leave interior whitespace unchanged,
1170 otherwise it is made canonical."
1171 (interactive "*")
1172 (if (eq t how) (setq how (or (current-justification) 'none))
1173 (if (null how) (setq how 'full)
1174 (or (memq how '(none left right center))
1175 (setq how 'full))))
1176 (or (memq how '(none left)) ; No action required for these.
1177 (let ((fc (current-fill-column))
1178 (pos (point-marker))
1179 fp-end ; point at end of fill prefix
1180 beg ; point at beginning of line's text
1181 end ; point at end of line's text
1182 indent ; column of `beg'
1183 endcol ; column of `end'
1184 ncols ; new indent point or offset
1185 (nspaces 0) ; number of spaces between words
1186 ; in line (not space characters)
1187 (curr-fracspace 0) ; current fractional space amount
1188 count)
1189 (end-of-line)
1190 ;; Check if this is the last line of the paragraph.
1191 (if (and use-hard-newlines (null eop)
1192 (get-text-property (point) 'hard))
1193 (setq eop t))
1194 (skip-chars-backward " \t")
1195 ;; Quick exit if it appears to be properly justified already
1196 ;; or there is no text.
1197 (if (or (bolp)
1198 (and (memq how '(full right))
1199 (= (current-column) fc)))
1200 nil
1201 (setq end (point))
1202 (beginning-of-line)
1203 (skip-chars-forward " \t")
1204 ;; Skip over fill-prefix.
1205 (if (and fill-prefix
1206 (not (string-equal fill-prefix ""))
1207 (equal fill-prefix
1208 (buffer-substring
1209 (point) (min (point-max) (+ (length fill-prefix)
1210 (point))))))
1211 (forward-char (length fill-prefix))
1212 (if (and adaptive-fill-mode
1213 (looking-at adaptive-fill-regexp))
1214 (goto-char (match-end 0))))
1215 (setq fp-end (point))
1216 (skip-chars-forward " \t")
1217 ;; This is beginning of the line's text.
1218 (setq indent (current-column))
1219 (setq beg (point))
1220 (goto-char end)
1221 (setq endcol (current-column))
1222
1223 ;; HOW can't be null or left--we would have exited already
1224 (cond ((eq 'right how)
1225 (setq ncols (- fc endcol))
1226 (if (< ncols 0)
1227 ;; Need to remove some indentation
1228 (delete-region
1229 (progn (goto-char fp-end)
1230 (if (< (current-column) (+ indent ncols))
1231 (move-to-column (+ indent ncols) t))
1232 (point))
1233 (progn (move-to-column indent) (point)))
1234 ;; Need to add some
1235 (goto-char beg)
1236 (indent-to (+ indent ncols))
1237 ;; If point was at beginning of text, keep it there.
1238 (if (= beg pos)
1239 (move-marker pos (point)))))
1240
1241 ((eq 'center how)
1242 ;; Figure out how much indentation is needed
1243 (setq ncols (+ (current-left-margin)
1244 (/ (- fc (current-left-margin) ;avail. space
1245 (- endcol indent)) ;text width
1246 2)))
1247 (if (< ncols indent)
1248 ;; Have too much indentation - remove some
1249 (delete-region
1250 (progn (goto-char fp-end)
1251 (if (< (current-column) ncols)
1252 (move-to-column ncols t))
1253 (point))
1254 (progn (move-to-column indent) (point)))
1255 ;; Have too little - add some
1256 (goto-char beg)
1257 (indent-to ncols)
1258 ;; If point was at beginning of text, keep it there.
1259 (if (= beg pos)
1260 (move-marker pos (point)))))
1261
1262 ((eq 'full how)
1263 ;; Insert extra spaces between words to justify line
1264 (save-restriction
1265 (narrow-to-region beg end)
1266 (or nosqueeze
1267 (canonically-space-region beg end))
1268 (goto-char (point-max))
1269 ;; count word spaces in line
1270 (while (search-backward " " nil t)
1271 (setq nspaces (1+ nspaces))
1272 (skip-chars-backward " "))
1273 (setq ncols (- fc endcol))
1274 ;; Ncols is number of additional space chars needed
1275 (if (and (> ncols 0) (> nspaces 0) (not eop))
1276 (progn
1277 (setq curr-fracspace (+ ncols (/ (1+ nspaces) 2))
1278 count nspaces)
1279 (while (> count 0)
1280 (skip-chars-forward " ")
1281 (insert-and-inherit
1282 (make-string (/ curr-fracspace nspaces) ?\s))
1283 (search-forward " " nil t)
1284 (setq count (1- count)
1285 curr-fracspace
1286 (+ (% curr-fracspace nspaces) ncols)))))))
1287 (t (error "Unknown justification value"))))
1288 (goto-char pos)
1289 (move-marker pos nil)))
1290 nil)
1291
1292 (defun unjustify-current-line ()
1293 "Remove justification whitespace from current line.
1294 If the line is centered or right-justified, this function removes any
1295 indentation past the left margin. If the line is full-justified, it removes
1296 extra spaces between words. It does nothing in other justification modes."
1297 (let ((justify (current-justification)))
1298 (cond ((eq 'left justify) nil)
1299 ((eq nil justify) nil)
1300 ((eq 'full justify) ; full justify: remove extra spaces
1301 (beginning-of-line-text)
1302 (canonically-space-region (point) (line-end-position)))
1303 ((memq justify '(center right))
1304 (save-excursion
1305 (move-to-left-margin nil t)
1306 ;; Position ourselves after any fill-prefix.
1307 (if (and fill-prefix
1308 (not (string-equal fill-prefix ""))
1309 (equal fill-prefix
1310 (buffer-substring
1311 (point) (min (point-max) (+ (length fill-prefix)
1312 (point))))))
1313 (forward-char (length fill-prefix)))
1314 (delete-region (point) (progn (skip-chars-forward " \t")
1315 (point))))))))
1316
1317 (defun unjustify-region (&optional begin end)
1318 "Remove justification whitespace from region.
1319 For centered or right-justified regions, this function removes any indentation
1320 past the left margin from each line. For full-justified lines, it removes
1321 extra spaces between words. It does nothing in other justification modes.
1322 Arguments BEGIN and END are optional; default is the whole buffer."
1323 (save-excursion
1324 (save-restriction
1325 (if end (narrow-to-region (point-min) end))
1326 (goto-char (or begin (point-min)))
1327 (while (not (eobp))
1328 (unjustify-current-line)
1329 (forward-line 1)))))
1330
1331 \f
1332 (defun fill-nonuniform-paragraphs (min max &optional justifyp citation-regexp)
1333 "Fill paragraphs within the region, allowing varying indentation within each.
1334 This command divides the region into \"paragraphs\",
1335 only at paragraph-separator lines, then fills each paragraph
1336 using as the fill prefix the smallest indentation of any line
1337 in the paragraph.
1338
1339 When calling from a program, pass range to fill as first two arguments.
1340
1341 Optional third and fourth arguments JUSTIFYP and CITATION-REGEXP:
1342 JUSTIFYP to justify paragraphs (prefix arg).
1343 When filling a mail message, pass a regexp for CITATION-REGEXP
1344 which will match the prefix of a line which is a citation marker
1345 plus whitespace, but no other kind of prefix.
1346 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1347 (interactive (progn
1348 (barf-if-buffer-read-only)
1349 (list (region-beginning) (region-end)
1350 (if current-prefix-arg 'full))))
1351 (let ((fill-individual-varying-indent t))
1352 (fill-individual-paragraphs min max justifyp citation-regexp)))
1353
1354 (defun fill-individual-paragraphs (min max &optional justify citation-regexp)
1355 "Fill paragraphs of uniform indentation within the region.
1356 This command divides the region into \"paragraphs\",
1357 treating every change in indentation level or prefix as a paragraph boundary,
1358 then fills each paragraph using its indentation level as the fill prefix.
1359
1360 There is one special case where a change in indentation does not start
1361 a new paragraph. This is for text of this form:
1362
1363 foo> This line with extra indentation starts
1364 foo> a paragraph that continues on more lines.
1365
1366 These lines are filled together.
1367
1368 When calling from a program, pass the range to fill
1369 as the first two arguments.
1370
1371 Optional third and fourth arguments JUSTIFY and CITATION-REGEXP:
1372 JUSTIFY to justify paragraphs (prefix arg).
1373 When filling a mail message, pass a regexp for CITATION-REGEXP
1374 which will match the prefix of a line which is a citation marker
1375 plus whitespace, but no other kind of prefix.
1376 Also, if CITATION-REGEXP is non-nil, don't fill header lines."
1377 (interactive (progn
1378 (barf-if-buffer-read-only)
1379 (list (region-beginning) (region-end)
1380 (if current-prefix-arg 'full))))
1381 (save-restriction
1382 (save-excursion
1383 (goto-char min)
1384 (beginning-of-line)
1385 (narrow-to-region (point) max)
1386 (if citation-regexp
1387 (while (and (not (eobp))
1388 (or (looking-at "[ \t]*[^ \t\n]+:")
1389 (looking-at "[ \t]*$")))
1390 (if (looking-at "[ \t]*[^ \t\n]+:")
1391 (search-forward "\n\n" nil 'move)
1392 (forward-line 1))))
1393 (narrow-to-region (point) max)
1394 ;; Loop over paragraphs.
1395 (while (progn
1396 ;; Skip over all paragraph-separating lines
1397 ;; so as to not include them in any paragraph.
1398 (while (and (not (eobp))
1399 (progn (move-to-left-margin)
1400 (and (not (eobp))
1401 (looking-at paragraph-separate))))
1402 (forward-line 1))
1403 (skip-chars-forward " \t\n") (not (eobp)))
1404 (move-to-left-margin)
1405 (let ((start (point))
1406 fill-prefix fill-prefix-regexp)
1407 ;; Find end of paragraph, and compute the smallest fill-prefix
1408 ;; that fits all the lines in this paragraph.
1409 (while (progn
1410 ;; Update the fill-prefix on the first line
1411 ;; and whenever the prefix good so far is too long.
1412 (if (not (and fill-prefix
1413 (looking-at fill-prefix-regexp)))
1414 (setq fill-prefix
1415 (fill-individual-paragraphs-prefix
1416 citation-regexp)
1417 fill-prefix-regexp (regexp-quote fill-prefix)))
1418 (forward-line 1)
1419 (if (bolp)
1420 ;; If forward-line went past a newline,
1421 ;; move further to the left margin.
1422 (move-to-left-margin))
1423 ;; Now stop the loop if end of paragraph.
1424 (and (not (eobp))
1425 (if fill-individual-varying-indent
1426 ;; If this line is a separator line, with or
1427 ;; without prefix, end the paragraph.
1428 (and
1429 (not (looking-at paragraph-separate))
1430 (save-excursion
1431 (not (and (looking-at fill-prefix-regexp)
1432 (progn (forward-char
1433 (length fill-prefix))
1434 (looking-at
1435 paragraph-separate))))))
1436 ;; If this line has more or less indent
1437 ;; than the fill prefix wants, end the paragraph.
1438 (and (looking-at fill-prefix-regexp)
1439 ;; If fill prefix is shorter than a new
1440 ;; fill prefix computed here, end paragraph.
1441 (let ((this-line-fill-prefix
1442 (fill-individual-paragraphs-prefix
1443 citation-regexp)))
1444 (>= (length fill-prefix)
1445 (length this-line-fill-prefix)))
1446 (save-excursion
1447 (not (progn (forward-char
1448 (length fill-prefix))
1449 (or (looking-at "[ \t]")
1450 (looking-at paragraph-separate)
1451 (looking-at paragraph-start)))))
1452 (not (and (equal fill-prefix "")
1453 citation-regexp
1454 (looking-at citation-regexp))))))))
1455 ;; Fill this paragraph, but don't add a newline at the end.
1456 (let ((had-newline (bolp)))
1457 (fill-region-as-paragraph start (point) justify)
1458 (if (and (bolp) (not had-newline))
1459 (delete-char -1))))))))
1460
1461 (defun fill-individual-paragraphs-prefix (citation-regexp)
1462 (let* ((adaptive-fill-first-line-regexp ".*")
1463 (just-one-line-prefix
1464 ;; Accept any prefix rather than just the ones matched by
1465 ;; adaptive-fill-first-line-regexp.
1466 (fill-context-prefix (point) (line-beginning-position 2)))
1467 (two-lines-prefix
1468 (fill-context-prefix (point) (line-beginning-position 3))))
1469 (if (not just-one-line-prefix)
1470 (buffer-substring
1471 (point) (save-excursion (skip-chars-forward " \t") (point)))
1472 ;; See if the citation part of JUST-ONE-LINE-PREFIX
1473 ;; is the same as that of TWO-LINES-PREFIX,
1474 ;; except perhaps with longer whitespace.
1475 (if (and just-one-line-prefix two-lines-prefix
1476 (let* ((one-line-citation-part
1477 (fill-individual-paragraphs-citation
1478 just-one-line-prefix citation-regexp))
1479 (two-lines-citation-part
1480 (fill-individual-paragraphs-citation
1481 two-lines-prefix citation-regexp))
1482 (adjusted-two-lines-citation-part
1483 (substring two-lines-citation-part 0
1484 (string-match "[ \t]*\\'"
1485 two-lines-citation-part))))
1486 (and
1487 (string-match (concat "\\`"
1488 (regexp-quote
1489 adjusted-two-lines-citation-part)
1490 "[ \t]*\\'")
1491 one-line-citation-part)
1492 (>= (string-width one-line-citation-part)
1493 (string-width two-lines-citation-part)))))
1494 two-lines-prefix
1495 just-one-line-prefix))))
1496
1497 (defun fill-individual-paragraphs-citation (string citation-regexp)
1498 (if citation-regexp
1499 (if (string-match citation-regexp string)
1500 (match-string 0 string)
1501 "")
1502 string))
1503
1504 ;; arch-tag: 727ad455-1161-4fa9-8df5-0f74b179216d
1505 ;;; fill.el ends here