Initial Commit
[packages] / xemacs-packages / text-modes / filladapt.el
1 ;;; Adaptive fill
2 ;;; Copyright (C) 1989, 1995-1998 Kyle E. Jones
3 ;;;
4 ;;; This program is free software; you can redistribute it and/or modify
5 ;;; it under the terms of the GNU General Public License as published by
6 ;;; the Free Software Foundation; either version 2, or (at your option)
7 ;;; any later version.
8 ;;;
9 ;;; This program is distributed in the hope that it will be useful,
10 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 ;;; GNU General Public License for more details.
13 ;;;
14 ;;; A copy of the GNU General Public License can be obtained from this
15 ;;; program's author (send electronic mail to kyle@uunet.uu.net) or from
16 ;;; the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
17 ;;; 02139, USA.
18 ;;;
19 ;;; Send bug reports to kyle_jones@wonderworks.com
20
21 ;; LCD Archive Entry: 
22 ;; filladapt|Kyle Jones|kyle_jones@wonderworks.com| 
23 ;; Minor mode to adaptively set fill-prefix and overload filling functions|
24 ;; 28-February-1998|2.12|~/packages/filladapt.el| 
25
26 ;; These functions enhance the default behavior of Emacs' Auto Fill
27 ;; mode and the commands fill-paragraph, lisp-fill-paragraph,
28 ;; fill-region-as-paragraph and fill-region.
29 ;;
30 ;; The chief improvement is that the beginning of a line to be
31 ;; filled is examined and, based on information gathered, an
32 ;; appropriate value for fill-prefix is constructed.  Also the
33 ;; boundaries of the current paragraph are located.  This occurs
34 ;; only if the fill prefix is not already non-nil.
35 ;;
36 ;; The net result of this is that blurbs of text that are offset
37 ;; from left margin by asterisks, dashes, and/or spaces, numbered
38 ;; examples, included text from USENET news articles, etc. are
39 ;; generally filled correctly with no fuss.
40 ;;
41 ;; Since this package replaces existing Emacs functions, it cannot
42 ;; be autoloaded.  Save this in a file named filladapt.el in a
43 ;; Lisp directory that Emacs knows about, byte-compile it and put
44 ;;    (require 'filladapt)
45 ;; in your .emacs file.
46 ;;
47 ;; Note that in this release Filladapt mode is a minor mode and it is
48 ;; _off_ by default.  If you want it to be on by default, use
49 ;;   (setq-default filladapt-mode t)
50 ;;
51 ;; M-x filladapt-mode toggles Filladapt mode on/off in the current
52 ;; buffer.
53 ;;
54 ;; Use
55 ;;     (add-hook 'text-mode-hook 'turn-on-filladapt-mode)
56 ;; to have Filladapt always enabled in Text mode.
57 ;;
58 ;; Use
59 ;;     (add-hook 'c-mode-hook 'turn-off-filladapt-mode)
60 ;; to have Filladapt always disabled in C mode.
61 ;;
62 ;; In many cases, you can extend Filladapt by adding appropriate
63 ;; entries to the following three `defvar's.  See `postscript-comment'
64 ;; or `texinfo-comment' as a sample of what needs to be done.
65 ;;
66 ;;     filladapt-token-table
67 ;;     filladapt-token-match-table
68 ;;     filladapt-token-conversion-table
69
70 (and (featurep 'filladapt)
71      (error "filladapt cannot be loaded twice in the same Emacs session."))
72
73 (provide 'filladapt)
74
75 (defvar filladapt-version "2.12"
76   "Version string for filladapt.")
77
78 ;; BLOB to make custom stuff work even without customize
79 (eval-and-compile
80   (condition-case ()
81       (require 'custom)
82     (error nil))
83   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
84       nil ;; We've got what we needed
85     ;; We have the old custom-library, hack around it!
86     (defmacro defgroup (&rest args)
87       nil)
88     (defmacro defcustom (var value doc &rest args) 
89       (` (defvar (, var) (, value) (, doc))))))
90
91 (defgroup filladapt nil
92   "Enhanced filling"
93   :group 'fill)
94
95 (defvar filladapt-mode nil
96   "Non-nil means that Filladapt minor mode is enabled.
97 Use the filladapt-mode command to toggle the mode on/off.")
98 (make-variable-buffer-local 'filladapt-mode)
99
100 (defcustom filladapt-mode-line-string " Filladapt"
101   "*String to display in the modeline when Filladapt mode is active.
102 Set this to nil if you don't want a modeline indicator for Filladapt."
103   :type 'string
104   :group 'filladapt)
105
106 (defcustom filladapt-fill-column-tolerance nil
107   "*Tolerate filled paragraph lines ending this far from the fill column.
108 If any lines other than the last paragraph line end at a column
109 less than fill-column - filladapt-fill-column-tolerance, fill-column will
110 be adjusted using the filladapt-fill-column-*-fuzz variables and
111 the paragraph will be re-filled until the tolerance is achieved
112 or filladapt runs out of fuzz values to try.
113
114 A nil value means behave normally, that is, don't try refilling
115 paragraphs to make filled line lengths fit within any particular
116 range."
117   :type '(choice (const nil)
118                  integer)
119   :group 'filladapt)
120
121 (defcustom filladapt-fill-column-forward-fuzz 5
122   "*Try values from fill-column to fill-column plus this variable
123 when trying to make filled paragraph lines fall with the tolerance
124 range specified by filladapt-fill-column-tolerance."
125   :type 'integer
126   :group 'filladapt)
127
128 (defcustom filladapt-fill-column-backward-fuzz 5
129   "*Try values from fill-column to fill-column minus this variable
130 when trying to make filled paragraph lines fall with the tolerance
131 range specified by filladapt-fill-column-tolerance."
132   :type 'integer
133   :group 'filladapt)
134
135 ;; install on minor-mode-alist
136 (or (assq 'filladapt-mode minor-mode-alist)
137     (setq minor-mode-alist (cons (list 'filladapt-mode
138                                        'filladapt-mode-line-string)
139                                  minor-mode-alist)))
140
141 (defcustom filladapt-token-table
142   '(
143     ;; this must be first
144     ("^" beginning-of-line)
145     ;; Included text in news or mail replies
146     (">+" citation->)
147     ;; Included text generated by SUPERCITE.  We can't hope to match all
148     ;; the possible variations, your mileage may vary.
149     ("\\(\\w\\|[0-9]\\)[^'`\"< \t\n]*>[ \t]*" supercite-citation)
150     ;; Lisp comments
151     (";+" lisp-comment)
152     ;; UNIX shell comments
153     ("#+" sh-comment)
154     ;; Postscript comments
155     ("%+" postscript-comment)
156     ;; C++ comments
157     ("///*" c++-comment)
158     ;; Texinfo comments
159     ("@c[ \t]" texinfo-comment)
160     ("@comment[ \t]" texinfo-comment)
161     ;; Bullet types.
162     ;;
163     ;; LaTex \item
164     ;;
165     ("\\\\item[ \t]" bullet)
166     ;;
167     ;; 1. xxxxx
168     ;;    xxxxx
169     ;;
170     ("[0-9]+\\.[ \t]" bullet)
171     ;;
172     ;; 2.1.3  xxxxx xx x xx x
173     ;;        xxx
174     ;;
175     ("[0-9]+\\(\\.[0-9]+\\)+[ \t]" bullet)
176     ;;
177     ;; a. xxxxxx xx
178     ;;    xxx xxx
179     ;;
180     ("[A-Za-z]\\.[ \t]" bullet)
181     ;;
182     ;; 1) xxxx x xx x xx   or   (1) xx xx x x xx xx
183     ;;    xx xx xxxx                xxx xx x x xx x
184     ;;
185     ("(?[0-9]+)[ \t]" bullet)
186     ;;
187     ;; a) xxxx x xx x xx   or   (a) xx xx x x xx xx
188     ;;    xx xx xxxx                xxx xx x x xx x
189     ;;
190     ("(?[A-Za-z])[ \t]" bullet)
191     ;;
192     ;; 2a. xx x xxx x x xxx
193     ;;     xxx xx x xx x
194     ;;
195     ("[0-9]+[A-Za-z]\\.[ \t]" bullet)
196     ;;
197     ;; 1a) xxxx x xx x xx   or   (1a) xx xx x x xx xx
198     ;;     xx xx xxxx                 xxx xx x x xx x
199     ;;
200     ("(?[0-9]+[A-Za-z])[ \t]" bullet)
201     ;;
202     ;; -  xx xxx xxxx   or   *  xx xx x xxx xxx
203     ;;    xxx xx xx             x xxx x xx x x x
204     ;;
205     ("[-~*+]+[ \t]" bullet)
206     ;;
207     ;; o  xx xxx xxxx xx x xx xxx x xxx xx x xxx
208     ;;    xxx xx xx 
209     ;;
210     ("o[ \t]" bullet)
211     ;; don't touch
212     ("[ \t]+" space)
213     ("$" end-of-line)
214    )
215   "Table of tokens filladapt knows about.
216 Format is
217
218    ((REGEXP SYM) ...)
219
220 filladapt uses this table to build a tokenized representation of
221 the beginning of the current line.  Each REGEXP is matched
222 against the beginning of the line until a match is found.
223 Matching is done case-sensitively.  The corresponding SYM is
224 added to the list, point is moved to (match-end 0) and the
225 process is repeated.  The process ends when there is no REGEXP in
226 the table that matches what is at point."
227   :type '(repeat (list regexp symbol))
228   :group 'filladapt)
229
230 (defcustom filladapt-not-token-table
231   '(
232     "[Ee]\\.g\\.[ \t,]"
233     "[Ii]\\.e\\.[ \t,]"
234     ;; end-of-line isn't a token if whole line is empty
235     "^$"
236    )
237   "List of regexps that can never be a token.
238 Before trying the regular expressions in filladapt-token-table,
239 the regexps in this list are tried.  If any regexp in this list
240 matches what is at point then the token generator gives up and
241 doesn't try any of the regexps in filladapt-token-table.
242
243 Regexp matching is done case-sensitively."
244   :type '(repeat regexp)
245   :group 'filladapt)
246
247 (defcustom filladapt-token-match-table
248   '(
249     (citation-> citation->)
250     (supercite-citation supercite-citation)
251     (lisp-comment lisp-comment)
252     (sh-comment sh-comment)
253     (postscript-comment postscript-comment)
254     (c++-comment c++-comment)
255     (texinfo-comment texinfo-comment)
256     (bullet)
257     (space bullet space)
258     (beginning-of-line beginning-of-line)
259    )
260   "Table describing what tokens a certain token will match.
261
262 To decide whether a line belongs in the current paragraph,
263 filladapt creates a token list for the fill prefix of both lines.
264 Tokens and the columns where tokens end are compared.  This table
265 specifies what a certain token will match.
266
267 Table format is
268
269    (SYM [SYM1 [SYM2 ...]])
270
271 The first symbol SYM is the token, subsequent symbols are the
272 tokens that SYM will match."
273   :type '(repeat (repeat symbol))
274   :group 'filladapt)
275
276 (defcustom filladapt-token-match-many-table
277   '(
278     space
279    )
280   "List of tokens that can match multiple tokens.
281 If one of these tokens appears in a token list, it will eat all
282 matching tokens in a token list being matched against it until it
283 encounters a token that doesn't match or a token that ends on
284 a greater column number."
285   :type '(repeat symbol)
286   :group 'filladapt)
287
288 (defcustom filladapt-token-paragraph-start-table
289   '(
290     bullet
291    )
292   "List of tokens that indicate the start of a paragraph.
293 If parsing a line generates a token list containing one of
294 these tokens, then the line is considered to be the start of a
295 paragraph."
296   :type '(repeat symbol)
297   :group 'filladapt)
298
299 (defcustom filladapt-token-conversion-table
300   '(
301     (citation-> . exact)
302     (supercite-citation . exact)
303     (lisp-comment . exact)
304     (sh-comment . exact)
305     (postscript-comment . exact)
306     (c++-comment . exact)
307     (texinfo-comment . exact)
308     (bullet . spaces)
309     (space . exact)
310     (end-of-line . exact)
311    )
312   "Table that specifies how to convert a token into a fill prefix.
313 Table format is
314
315    ((SYM . HOWTO) ...)
316
317 SYM is the symbol naming the token to be converted.
318 HOWTO specifies how to do the conversion.
319   `exact' means copy the token's string directly into the fill prefix.
320   `spaces' means convert all characters in the token string that are
321       not a TAB or a space into spaces and copy the resulting string into 
322       the fill prefix."
323   :type '(repeat (cons symbol (choice (const exact)
324                                       (const spaces))))
325   :group 'filladapt)
326
327 (defvar filladapt-function-table
328   (let ((assoc-list
329          (list (cons 'fill-paragraph (symbol-function 'fill-paragraph))
330                (cons 'fill-region (symbol-function 'fill-region))
331                (cons 'fill-region-as-paragraph
332                      (symbol-function 'fill-region-as-paragraph))
333                (cons 'do-auto-fill (symbol-function 'do-auto-fill)))))
334     ;; v18 Emacs doesn't have lisp-fill-paragraph
335     (if (fboundp 'lisp-fill-paragraph)
336         (nconc assoc-list
337                (list (cons 'lisp-fill-paragraph
338                            (symbol-function 'lisp-fill-paragraph)))))
339     assoc-list )
340   "Table containing the old function definitions that filladapt usurps.")
341
342 (defcustom filladapt-fill-paragraph-post-hook nil
343   "Hooks run after filladapt runs fill-paragraph."
344   :type 'hook
345   :group 'filladapt)
346
347 (defvar filladapt-inside-filladapt nil
348   "Non-nil if the filladapt version of a fill function executing.
349 Currently this is only checked by the filladapt version of
350 fill-region-as-paragraph to avoid this infinite recursion:
351
352   fill-region-as-paragraph -> fill-paragraph -> fill-region-as-paragraph ...")
353
354 (defcustom filladapt-debug nil
355   "Non-nil means filladapt debugging is enabled.
356 Use the filladapt-debug command to turn on debugging.
357
358 With debugging enabled, filladapt will
359
360     a. display the proposed indentation with the tokens highlighted
361        using filladapt-debug-indentation-face-1 and
362        filladapt-debug-indentation-face-2.
363     b. display the current paragraph using the face specified by
364        filladapt-debug-paragraph-face."
365   :type 'boolean
366   :group 'filladapt)
367
368 (if filladapt-debug
369     (add-hook 'post-command-hook 'filladapt-display-debug-info-maybe))
370
371 (defvar filladapt-debug-indentation-face-1 'highlight
372   "Face used to display the indentation when debugging is enabled.")
373
374 (defvar filladapt-debug-indentation-face-2 'secondary-selection
375   "Another face used to display the indentation when debugging is enabled.")
376
377 (defvar filladapt-debug-paragraph-face 'bold
378   "Face used to display the current paragraph when debugging is enabled.")
379
380 (defvar filladapt-debug-indentation-extents nil)
381 (make-variable-buffer-local 'filladapt-debug-indentation-extents)
382 (defvar filladapt-debug-paragraph-extent nil)
383 (make-variable-buffer-local 'filladapt-debug-paragraph-extent)
384
385 ;; kludge city, see references in code.
386 (defvar filladapt-old-line-prefix)
387
388 (defun do-auto-fill ()
389   (catch 'done
390     (if (and filladapt-mode (null fill-prefix))
391         (save-restriction
392           (let ((paragraph-ignore-fill-prefix nil)
393                 ;; if the user wanted this stuff, they probably
394                 ;; wouldn't be using filladapt-mode.
395                 (adaptive-fill-mode nil)
396                 (adaptive-fill-regexp nil)
397                 ;; need this or Emacs 19 ignores fill-prefix when
398                 ;; inside a comment.
399                 (comment-multi-line t)
400                 (filladapt-inside-filladapt t)
401                 fill-prefix retval)
402             (if (filladapt-adapt nil nil)
403                 (progn
404                   (setq retval (filladapt-funcall 'do-auto-fill))
405                   (throw 'done retval))))))
406     (filladapt-funcall 'do-auto-fill)))
407
408 (defun filladapt-fill-paragraph (function arg)
409   (catch 'done
410     (if (and filladapt-mode (null fill-prefix))
411         (save-restriction
412           (let ((paragraph-ignore-fill-prefix nil)
413                 ;; if the user wanted this stuff, they probably
414                 ;; wouldn't be using filladapt-mode.
415                 (adaptive-fill-mode nil)
416                 (adaptive-fill-regexp nil)
417                 ;; need this or Emacs 19 ignores fill-prefix when
418                 ;; inside a comment.
419                 (comment-multi-line t)
420                 fill-prefix retval)
421             (if (filladapt-adapt t nil)
422                 (progn
423                   (if filladapt-fill-column-tolerance
424                       (let* ((low (- fill-column
425                                      filladapt-fill-column-backward-fuzz))
426                              (high (+ fill-column
427                                       filladapt-fill-column-forward-fuzz))
428                              (old-fill-column fill-column)
429                              (fill-column fill-column)
430                              (lim (- high low))
431                              (done nil)
432                              (sign 1)
433                              (delta 0))
434                         (while (not done)
435                           (setq retval (filladapt-funcall function arg))
436                           (if (filladapt-paragraph-within-fill-tolerance)
437                               (setq done 'success)
438                             (setq delta (1+ delta)
439                                   sign (* sign -1)
440                                   fill-column (+ fill-column (* delta sign)))
441                             (while (and (<= delta lim)
442                                         (or (< fill-column low)
443                                             (> fill-column high)))
444                               (setq delta (1+ delta)
445                                     sign (* sign -1)
446                                     fill-column (+ fill-column
447                                                    (* delta sign))))
448                             (setq done (> delta lim))))
449                         ;; if the paragraph lines never fell
450                         ;; within the tolerances, refill using
451                         ;; the old fill-column.
452                         (if (not (eq done 'success))
453                             (let ((fill-column old-fill-column))
454                               (setq retval (filladapt-funcall function arg)))))
455                     (setq retval (filladapt-funcall function arg)))
456                   (run-hooks 'filladapt-fill-paragraph-post-hook)
457                   (throw 'done retval))))))
458     ;; filladapt-adapt failed, so do fill-paragraph normally.
459     (filladapt-funcall function arg)))
460
461 (defun fill-paragraph (arg)
462   "Fill paragraph at or after point.  Prefix arg means justify as well.
463
464 (This function has been overloaded with the `filladapt' version.)
465
466 If `sentence-end-double-space' is non-nil, then period followed by one
467 space does not end a sentence, so don't break a line there.
468
469 If `fill-paragraph-function' is non-nil, we call it (passing our
470 argument to it), and if it returns non-nil, we simply return its value."
471   (interactive "*P")
472   (let ((filladapt-inside-filladapt t))
473     (filladapt-fill-paragraph 'fill-paragraph arg)))
474
475 (defun lisp-fill-paragraph (&optional arg)
476   "Like \\[fill-paragraph], but handle Emacs Lisp comments.
477
478 (This function has been overloaded with the `filladapt' version.)
479
480 If any of the current line is a comment, fill the comment or the
481 paragraph of it that point is in, preserving the comment's indentation
482 and initial semicolons."
483   (interactive "*P")
484   (let ((filladapt-inside-filladapt t))
485     (filladapt-fill-paragraph 'lisp-fill-paragraph arg)))
486
487 (defun fill-region-as-paragraph (beg end &optional justify
488                                  nosqueeze squeeze-after)
489   "Fill the region as one paragraph.
490
491 (This function has been overloaded with the `filladapt' version.)
492
493 It removes any paragraph breaks in the region and extra newlines at the end,
494 indents and fills lines between the margins given by the
495 `current-left-margin' and `current-fill-column' functions.
496 It leaves point at the beginning of the line following the paragraph.
497
498 Normally performs justification according to the `current-justification'
499 function, but with a prefix arg, does full justification instead.
500
501 From a program, optional third arg JUSTIFY can specify any type of
502 justification.  Fourth arg NOSQUEEZE non-nil means not to make spaces
503 between words canonical before filling.  Fifth arg SQUEEZE-AFTER, if non-nil,
504 means don't canonicalize spaces before that position.
505
506 If `sentence-end-double-space' is non-nil, then period followed by one
507 space does not end a sentence, so don't break a line there."
508   (interactive "*r\nP")
509   (if (and filladapt-mode (not filladapt-inside-filladapt))
510       (save-restriction
511         (narrow-to-region beg end)
512         (let ((filladapt-inside-filladapt t)
513               line-start last-token)
514           (goto-char beg)
515           (while (equal (char-after (point)) ?\n)
516             (delete-char 1))
517           (end-of-line)
518           (while (zerop (forward-line))
519             (if (setq last-token
520                       (car (filladapt-tail (filladapt-parse-prefixes))))
521                 (progn
522                   (setq line-start (point))
523                   (move-to-column (nth 1 last-token))
524                   (delete-region line-start (point))))
525             ;; Dance...
526             ;;
527             ;; Do this instead of (delete-char -1) to keep
528             ;; markers on the correct side of the whitespace.
529             (goto-char (1- (point)))
530             (insert " ")
531             (delete-char 1)
532
533             (end-of-line))
534           (goto-char beg)
535           (fill-paragraph justify))
536         ;; In XEmacs 19.12 and Emacs 18.59 fill-region relies on
537         ;; fill-region-as-paragraph to do this.  If we don't do
538         ;; it, fill-region will spin in an endless loop.
539         (goto-char (point-max)))
540     (condition-case nil
541         ;; five args for Emacs 19.31
542         (filladapt-funcall 'fill-region-as-paragraph beg end
543                            justify nosqueeze squeeze-after)
544       (wrong-number-of-arguments
545        (condition-case nil
546            ;; four args for Emacs 19.29
547            (filladapt-funcall 'fill-region-as-paragraph beg end
548                               justify nosqueeze)
549          ;; three args for the rest of the world.
550          (wrong-number-of-arguments
551           (filladapt-funcall 'fill-region-as-paragraph beg end justify)))))))
552
553 (defun fill-region (beg end &optional justify nosqueeze to-eop)
554   "Fill each of the paragraphs in the region.
555
556 (This function has been overloaded with the `filladapt' version.)
557
558 Prefix arg (non-nil third arg, if called from program) means justify as well.
559
560 Noninteractively, fourth arg NOSQUEEZE non-nil means to leave
561 whitespace other than line breaks untouched, and fifth arg TO-EOP
562 non-nil means to keep filling to the end of the paragraph (or next
563 hard newline, if `use-hard-newlines' is on).
564
565 If `sentence-end-double-space' is non-nil, then period followed by one
566 space does not end a sentence, so don't break a line there."
567   (interactive "*r\nP")
568
569   ;; ensure beg <= end as in core version of fill-region
570   (let ((newbeg (min beg end))
571         (newend (max beg end)))
572     (setq beg newbeg)
573     (setq end newend))
574
575   (if (and filladapt-mode (not filladapt-inside-filladapt))
576       (save-restriction
577         (narrow-to-region beg end)
578         (let ((filladapt-inside-filladapt t)
579               start)
580           (goto-char beg)
581           (while (not (eobp))
582             (setq start (point))
583             (while (and (not (eobp)) (not (filladapt-parse-prefixes)))
584               (forward-line 1))
585             (if (not (equal start (point)))
586                 (progn
587                   (save-restriction
588                     (narrow-to-region start (point))
589                     (fill-region start (point) justify nosqueeze to-eop)
590                     (goto-char (point-max)))
591                   (if (and (not (bolp)) (not (eobp)))
592                       (forward-line 1))))
593             (if (filladapt-parse-prefixes)
594                 (progn
595                   (save-restriction
596                     ;; for the clipping region
597                     (filladapt-adapt t t)
598                     (fill-paragraph justify)
599                     (goto-char (point-max)))
600                   (if (and (not (bolp)) (not (eobp)))
601                       (forward-line 1)))))))
602     (condition-case nil
603         (filladapt-funcall 'fill-region beg end justify nosqueeze to-eop)
604       (wrong-number-of-arguments
605        (condition-case nil
606            (filladapt-funcall 'fill-region beg end justify nosqueeze)
607          (wrong-number-of-arguments
608           (filladapt-funcall 'fill-region beg end justify)))))))
609
610 (defvar zmacs-region-stays) ; for XEmacs
611
612 (defun filladapt-mode (&optional arg)
613   "Toggle Filladapt minor mode.
614 With arg, turn Filladapt mode on iff arg is positive.  When
615 Filladapt mode is enabled, auto-fill-mode and the fill-paragraph
616 command are both smarter about guessing a proper fill-prefix and
617 finding paragraph boundaries when bulleted and indented lines and
618 paragraphs are used."
619   (interactive "P")
620   ;; don't deactivate the region.
621   (setq zmacs-region-stays t)
622   (setq filladapt-mode (or (and arg (> (prefix-numeric-value arg) 0))
623                            (and (null arg) (null filladapt-mode))))
624   (if (fboundp 'force-mode-line-update)
625       (force-mode-line-update)
626     (set-buffer-modified-p (buffer-modified-p))))
627
628 (defun turn-on-filladapt-mode ()
629   "Unconditionally turn on Filladapt mode in the current buffer."
630   (filladapt-mode 1))
631
632 (defun turn-off-filladapt-mode ()
633   "Unconditionally turn off Filladapt mode in the current buffer."
634   (filladapt-mode -1))
635
636 (defun filladapt-funcall (function &rest args)
637   "Call the old definition of a function that filladapt has usurped."
638   (apply (cdr (assoc function filladapt-function-table)) args))
639
640 (defun filladapt-paragraph-start (list)
641   "Returns non-nil if LIST contains a paragraph starting token.
642 LIST should be a token list as returned by filladapt-parse-prefixes."
643   (catch 'done
644     (while list
645       (if (memq (car (car list)) filladapt-token-paragraph-start-table)
646           (throw 'done t))
647       (setq list (cdr list)))))
648
649 (defun filladapt-parse-prefixes ()
650   "Parse all the tokens after point and return a list of them.
651 The tokens regular expressions are specified in
652 filladapt-token-table.  The list returned is of this form
653
654   ((SYM COL STRING) ...)
655
656 SYM is a token symbol as found in filladapt-token-table.
657 COL is the column at which the token ended.
658 STRING is the token's text."
659   (save-excursion
660     (let ((token-list nil)
661           (done nil)
662           (old-point (point))
663           (case-fold-search nil)
664           token-table not-token-table moved)
665       (catch 'done
666         (while (not done)
667           (setq not-token-table filladapt-not-token-table)
668           (while not-token-table
669             (if (looking-at (car not-token-table))
670                 (throw 'done t))
671             (setq not-token-table (cdr not-token-table)))
672           (setq token-table filladapt-token-table
673                 done t)
674           (while token-table
675             (if (null (looking-at (car (car token-table))))
676                 (setq token-table (cdr token-table))
677               (goto-char (match-end 0))
678               (setq token-list (cons (list (nth 1 (car token-table))
679                                            (current-column)
680                                            (buffer-substring
681                                             (match-beginning 0)
682                                             (match-end 0)))
683                                      token-list)
684                     moved (not (eq (point) old-point))
685                     token-table (if moved nil (cdr token-table))
686                     done (not moved)
687                     old-point (point))))))
688       (nreverse token-list))))
689
690 (defun filladapt-tokens-match-p (list1 list2)
691   "Compare two token lists and return non-nil if they match, nil otherwise.
692 The lists are walked through in lockstep, comparing tokens.
693
694 When two tokens A and B are compared, they are considered to
695 match if
696
697     1. A appears in B's list of matching tokens or
698        B appears in A's list of matching tokens
699 and
700     2. A and B both end at the same column
701          or
702        A can match multiple tokens and ends at a column > than B
703          or
704        B can match multiple tokens and ends at a column > than A
705
706 In the case where the end columns differ the list pointer for the
707 token with the greater end column is not moved forward, which
708 allows its current token to be matched against the next token in
709 the other list in the next iteration of the matching loop.
710
711 All tokens must be matched in order for the lists to be considered
712 matching."
713   (let ((matched t)
714         (done nil))
715     (while (and (not done) list1 list2)
716       (let* ((token1 (car (car list1)))
717              (token1-matches-many-p
718                  (memq token1 filladapt-token-match-many-table))
719              (token1-matches (cdr (assq token1 filladapt-token-match-table)))
720              (token1-endcol (nth 1 (car list1)))
721              (token2 (car (car list2)))
722              (token2-matches-many-p
723                  (memq token2 filladapt-token-match-many-table))
724              (token2-matches (cdr (assq token2 filladapt-token-match-table)))
725              (token2-endcol (nth 1 (car list2)))
726              (tokens-match (or (memq token1 token2-matches)
727                                (memq token2 token1-matches))))
728         (cond ((not tokens-match)
729                (setq matched nil
730                      done t))
731               ((and token1-matches-many-p token2-matches-many-p)
732                (cond ((= token1-endcol token2-endcol)
733                       (setq list1 (cdr list1)
734                             list2 (cdr list2)))
735                      ((< token1-endcol token2-endcol)
736                       (setq list1 (cdr list1)))
737                      (t
738                       (setq list2 (cdr list2)))))
739               (token1-matches-many-p
740                (cond ((= token1-endcol token2-endcol)
741                       (setq list1 (cdr list1)
742                             list2 (cdr list2)))
743                      ((< token1-endcol token2-endcol)
744                       (setq matched nil
745                             done t))
746                      (t
747                       (setq list2 (cdr list2)))))
748               (token2-matches-many-p
749                (cond ((= token1-endcol token2-endcol)
750                       (setq list1 (cdr list1)
751                             list2 (cdr list2)))
752                      ((< token2-endcol token1-endcol)
753                       (setq matched nil
754                             done t))
755                      (t
756                       (setq list1 (cdr list1)))))
757               ((= token1-endcol token2-endcol)
758                (setq list1 (cdr list1)
759                      list2 (cdr list2)))
760               (t
761                (setq matched nil
762                      done t)))))
763     (and matched (null list1) (null list2)) ))
764
765 (defun filladapt-make-fill-prefix (list)
766   "Build a fill-prefix for a token LIST.
767 filladapt-token-conversion-table specifies how this is done."
768   (let ((prefix-list nil)
769         (conversion-spec nil))
770     (while list
771       (setq conversion-spec (cdr (assq (car (car list))
772                                        filladapt-token-conversion-table)))
773       (cond ((eq conversion-spec 'spaces)
774              (setq prefix-list
775                    (cons
776                     (filladapt-convert-to-spaces (nth 2 (car list)))
777                     prefix-list)))
778             ((eq conversion-spec 'exact)
779              (setq prefix-list
780                    (cons
781                     (nth 2 (car list))
782                     prefix-list))))
783       (setq list (cdr list)))
784     (apply (function concat) (nreverse prefix-list)) ))
785
786 (defun filladapt-paragraph-within-fill-tolerance ()
787   (catch 'done
788     (save-excursion
789       (let ((low (- fill-column filladapt-fill-column-tolerance))
790             (shortline nil))
791         (goto-char (point-min))
792         (while (not (eobp))
793           (if shortline
794               (throw 'done nil)
795             (end-of-line)
796             (setq shortline (< (current-column) low))
797             (forward-line 1)))
798         t ))))
799
800 (defun filladapt-convert-to-spaces (string)
801   "Return a copy of STRING, with all non-tabs and non-space changed to spaces."
802   (let ((i 0)
803         (space-list '(?\  ?\t))
804         (space ?\ )
805         (lim (length string)))
806     (setq string (copy-sequence string))
807     (while (< i lim)
808       (if (not (memq (aref string i) space-list))
809           (aset string i space))
810       (setq i (1+ i)))
811     string ))
812
813 (defun filladapt-adapt (paragraph debugging)
814   "Set fill-prefix based on the contents of the current line.
815
816 If the first arg PARAGRAPH is non-nil, also set a clipping region
817 around the current paragraph.
818
819 If the second arg DEBUGGING is non-nil, don't do the kludge that's
820 necessary to make certain paragraph fills work properly."
821   (save-excursion
822     (beginning-of-line)
823     (let ((token-list (filladapt-parse-prefixes))
824           curr-list done)
825       (if (null token-list)
826           nil
827         (setq fill-prefix (filladapt-make-fill-prefix token-list))
828         (if paragraph
829             (let (beg end)
830               (if (filladapt-paragraph-start token-list)
831                   (setq beg (point))
832                 (save-excursion
833                   (setq done nil)
834                   (while (not done)
835                     (cond ((not (= 0 (forward-line -1)))
836                            (setq done t
837                                  beg (point)))
838                           ((not (filladapt-tokens-match-p
839                                  token-list
840                                  (setq curr-list (filladapt-parse-prefixes))))
841                            (forward-line 1)
842                            (setq done t
843                                  beg (point)))
844                           ((filladapt-paragraph-start curr-list)
845                            (setq done t
846                                  beg (point)))))))
847               (save-excursion
848                 (setq done nil)
849                 (while (not done)
850                   (cond ((not (= 0 (progn (end-of-line) (forward-line 1))))
851                          (setq done t
852                                end (point)))
853                         ((not (filladapt-tokens-match-p
854                                token-list
855                                (setq curr-list (filladapt-parse-prefixes))))
856                          (setq done t
857                                end (point)))
858                         ((filladapt-paragraph-start curr-list)
859                          (setq done t
860                                end (point))))))
861               (narrow-to-region beg end)
862               ;; Multiple spaces after the bullet at the start of
863               ;; a hanging list paragraph get squashed by
864               ;; fill-paragraph.  We kludge around this by
865               ;; replacing the line prefix with the fill-prefix
866               ;; used by the rest of the lines in the paragraph.
867               ;; fill-paragraph will not alter the fill prefix so
868               ;; we win.  The post hook restores the old line prefix
869               ;; after fill-paragraph has been called.
870               (if (and paragraph (not debugging))
871                   (let (col)
872                     (setq col (nth 1 (car (filladapt-tail token-list))))
873                     (goto-char (point-min))
874                     (move-to-column col)
875                     (setq filladapt-old-line-prefix
876                           (buffer-substring (point-min) (point)))
877                     (delete-region (point-min) (point))
878                     (insert fill-prefix)
879                     (add-hook 'filladapt-fill-paragraph-post-hook
880                               'filladapt-cleanup-kludge-at-point-min)))))
881         t ))))
882
883 (defun filladapt-cleanup-kludge-at-point-min ()
884   "Cleanup the paragraph fill kludge.
885 See filladapt-adapt."
886   (save-excursion
887     (goto-char (point-min))
888     (insert filladapt-old-line-prefix)
889     (delete-char (length fill-prefix))
890     (remove-hook 'filladapt-fill-paragraph-post-hook
891                  'filladapt-cleanup-kludge-at-point-min)))
892
893 (defun filladapt-tail (list)
894   "Returns the last cons in LIST."
895   (if (null list)
896       nil
897     (while (consp (cdr list))
898       (setq list (cdr list)))
899     list ))
900
901 (defun filladapt-delete-extent (e)
902   (if (fboundp 'delete-extent)
903       (delete-extent e)
904     (delete-overlay e)))
905
906 (defun filladapt-make-extent (beg end)
907   (if (fboundp 'make-extent)
908       (make-extent beg end)
909     (make-overlay beg end)))
910
911 (defun filladapt-set-extent-endpoints (e beg end)
912   (if (fboundp 'set-extent-endpoints)
913       (set-extent-endpoints e beg end)
914     (move-overlay e beg end)))
915
916 (defun filladapt-set-extent-property (e prop val)
917   (if (fboundp 'set-extent-property)
918       (set-extent-property e prop val)
919     (overlay-put e prop val)))
920
921 (defun filladapt-debug ()
922   "Toggle filladapt debugging on/off in the current buffer."
923 ;;  (interactive)
924   (make-local-variable 'filladapt-debug)
925   (setq filladapt-debug (not filladapt-debug))
926   (if (null filladapt-debug)
927       (progn
928         (mapcar (function (lambda (e) (filladapt-set-extent-endpoints e 1 1)))
929                 filladapt-debug-indentation-extents)
930         (if filladapt-debug-paragraph-extent
931             (progn
932               (filladapt-delete-extent filladapt-debug-paragraph-extent)
933               (setq filladapt-debug-paragraph-extent nil)))))
934   (add-hook 'post-command-hook 'filladapt-display-debug-info-maybe))
935
936 (defun filladapt-display-debug-info-maybe ()
937   (cond ((null filladapt-debug) nil)
938         (fill-prefix nil)
939         (t
940          (if (null filladapt-debug-paragraph-extent)
941              (let ((e (filladapt-make-extent 1 1)))
942                (filladapt-set-extent-property e 'detachable nil)
943                (filladapt-set-extent-property e 'evaporate nil)
944                (filladapt-set-extent-property e 'face
945                                               filladapt-debug-paragraph-face)
946                (setq filladapt-debug-paragraph-extent e)))
947          (save-excursion
948            (save-restriction
949              (let ((ei-list filladapt-debug-indentation-extents)
950                    (ep filladapt-debug-paragraph-extent)
951                    (face filladapt-debug-indentation-face-1)
952                    fill-prefix token-list)
953                (if (null (filladapt-adapt t t))
954                    (progn
955                      (filladapt-set-extent-endpoints ep 1 1)
956                      (while ei-list
957                        (filladapt-set-extent-endpoints (car ei-list) 1 1)
958                        (setq ei-list (cdr ei-list))))
959                  (filladapt-set-extent-endpoints ep (point-min) (point-max))
960                  (beginning-of-line)
961                  (setq token-list (filladapt-parse-prefixes))
962                  (message "(%s)" (mapconcat (function
963                                            (lambda (q) (symbol-name (car q))))
964                                           token-list
965                                           " "))
966                  (while token-list
967                    (if ei-list
968                        (setq e (car ei-list)
969                              ei-list (cdr ei-list))
970                      (setq e (filladapt-make-extent 1 1))
971                      (filladapt-set-extent-property e 'detachable nil)
972                      (filladapt-set-extent-property e 'evaporate nil)
973                      (setq filladapt-debug-indentation-extents
974                            (cons e filladapt-debug-indentation-extents)))
975                    (filladapt-set-extent-property e 'face face)
976                    (filladapt-set-extent-endpoints e (point)
977                                                    (progn
978                                                      (move-to-column
979                                                       (nth 1
980                                                            (car token-list)))
981                                                      (point)))
982                    (if (eq face filladapt-debug-indentation-face-1)
983                        (setq face filladapt-debug-indentation-face-2)
984                      (setq face filladapt-debug-indentation-face-1))
985                    (setq token-list (cdr token-list)))
986                  (while ei-list
987                    (filladapt-set-extent-endpoints (car ei-list) 1 1)
988                    (setq ei-list (cdr ei-list))))))))))