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