Initial Commit
[packages] / xemacs-packages / xemacs-devel / checkdoc.el
1 ;;; checkdoc --- Check documentation strings for style requirements
2
3 ;;;  Copyright (C) 1997, 1998, 1999, 2000  Free Software Foundation
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6 ;; Version: 0.7
7 ;; Keywords: docs, maint, lisp
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27 ;;
28 ;;   The Emacs Lisp manual has a nice chapter on how to write
29 ;; documentation strings.  Many stylistic suggestions are fairly
30 ;; deterministic and easy to check for syntactically, but also easy
31 ;; to forget.  The main checkdoc engine will perform the stylistic
32 ;; checks needed to make sure these styles are remembered.
33 ;;
34 ;; There are two ways to use checkdoc:
35 ;;   1) Periodically use `checkdoc' or `checkdoc-current-buffer'.
36 ;;      `checkdoc' is a more interactive version of
37 ;;      `checkdoc-current-buffer'
38 ;;   2) Use `checkdoc-minor-mode' to automatically check your
39 ;;      documentation whenever you evaluate Lisp code with C-M-x
40 ;;      or [menu-bar emacs-lisp eval-buffer].  Additional key-bindings
41 ;;      are also provided under C-c ? KEY
42 ;;        (require 'checkdoc)
43 ;;        (add-hook 'emacs-lisp-mode-hook
44 ;;                   '(lambda () (checkdoc-minor-mode 1)))
45 ;;
46 ;; Using `checkdoc':
47 ;;
48 ;;   The commands `checkdoc' and `checkdoc-ispell' are the top-level
49 ;; entry points to all of the different checks that are available.  It
50 ;; breaks examination of your Lisp file into four sections (comments,
51 ;; documentation, messages, and spacing) and indicates its current
52 ;; state in a status buffer.
53 ;;
54 ;;   The Comments check examines your headers, footers, and
55 ;; various tags (such as "Code:") to make sure that your code is ready
56 ;; for easy integration into existing systems.
57 ;;
58 ;;   The Documentation check deals with documentation strings
59 ;; and their elements that help make Emacs easier to use.
60 ;;
61 ;;   The Messages check ensures that the strings displayed in the
62 ;; minibuffer by some commands (such as `error' and `y-or-n-p')
63 ;; are consistent with the Emacs environment.
64 ;;
65 ;;   The Spacing check cleans up white-space at the end of lines.
66 ;;
67 ;;   The interface while working with documentation and messages is
68 ;; slightly different when being run in the interactive mode.  The
69 ;; interface offers several options, including the ability to skip to
70 ;; the next error, or back up to previous errors.  Auto-fixing is
71 ;; turned off at this stage, but you can use the `f' or `F' key to fix
72 ;; a given error (if the fix is available.)
73 ;;
74 ;; Auto-fixing:
75 ;;
76 ;;   There are four classifications of style errors in terms of how
77 ;; easy they are to fix.  They are simple, complex, really complex,
78 ;; and impossible.  (Impossible really means that checkdoc does not
79 ;; have a fixing routine yet.)  Typically white-space errors are
80 ;; classified as simple, and are auto-fixed by default.  Typographic
81 ;; changes are considered complex, and the user is asked if they want
82 ;; the problem fixed before checkdoc makes the change.  These changes
83 ;; can be done without asking if `checkdoc-autofix-flag' is properly
84 ;; set.  Potentially redundant changes are considered really complex,
85 ;; and the user is always asked before a change is inserted.  The
86 ;; variable `checkdoc-autofix-flag' controls how these types of errors
87 ;; are fixed.
88 ;;
89 ;; Spell checking text:
90 ;;
91 ;;   The variable `checkdoc-spellcheck-documentation-flag' can be set
92 ;; to customize how spell checking is to be done.  Since spell
93 ;; checking can be quite slow, you can optimize how best you want your
94 ;; checking done.  The default is 'defun, which spell checks each time
95 ;; `checkdoc-defun' or `checkdoc-eval-defun' is used.  Setting to nil
96 ;; prevents spell checking during normal usage.
97 ;;   Setting this variable to nil does not mean you cannot take
98 ;; advantage of the spell checking.  You can instead use the
99 ;; interactive functions `checkdoc-ispell-*' to check the spelling of
100 ;; your documentation.
101 ;;   There is a list of Lisp-specific words which checkdoc will
102 ;; install into Ispell on the fly, but only if Ispell is not already
103 ;; running.  Use `ispell-kill-ispell' to make checkdoc restart it with
104 ;; these words enabled.
105 ;;
106 ;; Checking parameters:
107 ;;
108 ;;   You might not always want a function to have its parameters listed
109 ;; in order.  When this is the case, put the following comment just in
110 ;; front of the documentation string: "; checkdoc-order: nil"  This
111 ;; overrides the value of `checkdoc-arguments-in-order-flag'.
112 ;;
113 ;;   If you specifically wish to avoid mentioning a parameter of a
114 ;; function in the doc string (such as a hidden parameter, or a
115 ;; parameter which is very obvious like events), you can have checkdoc
116 ;; skip looking for it by putting the following comment just in front
117 ;; of the documentation string: "; checkdoc-params: (args go here)"
118 ;;
119 ;; Checking message strings:
120 ;;
121 ;;   The text that follows the `error' and `y-or-n-p' commands is
122 ;; also checked.  The documentation for `error' clearly states some
123 ;; simple style rules to follow which checkdoc will auto-fix for you.
124 ;; `y-or-n-p' also states that it should end in a space.  I added that
125 ;; it should end in "? " since that is almost always used.
126 ;;
127 ;; Adding your own checks:
128 ;;
129 ;;   You can experiment with adding your own checks by setting the
130 ;; hooks `checkdoc-style-hooks' and `checkdoc-comment-style-hooks'.
131 ;; Return a string which is the error you wish to report.  The cursor
132 ;; position should be preserved.
133 ;;
134 ;; Error errors:
135 ;;
136 ;;   Checkdoc does not always flag errors correctly.  There are a
137 ;; couple ways you can coax your file into passing all of checkdoc's
138 ;; tests through buffer local variables.
139 ;;
140 ;;   The variable `checkdoc-verb-check-experimental-flag' can be used
141 ;; to turn off the check for verb-voice in case you use words that are
142 ;; not semantically verbs, but are still in the incomplete list.
143 ;;
144 ;;   The variable `checkdoc-symbol-words' can be a list of words that
145 ;; happen to also be symbols.  This is not a problem for one-word
146 ;; symbols, but if you use a hyphenated word that is also a symbol,
147 ;; then you may need this.
148 ;;
149 ;;   The symbol `checkdoc-force-docstrings-flag' can be set to nil if
150 ;; you have many undocumented functions you don't wish to document.
151 ;;
152 ;;   See the above section "Checking Parameters" for details about
153 ;; parameter checking.
154 ;;
155 ;; Dependencies:
156 ;;
157 ;;   This file requires lisp-mnt (Lisp maintenance routines) for the
158 ;;   comment checkers.
159 ;;
160 ;;   Requires custom for Emacs v20.
161
162 ;;; TO DO:
163 ;;   Hook into the byte compiler on a defun/defvar level to generate
164 ;;     warnings in the byte-compiler's warning/error buffer.
165 ;;   Better ways to override more typical `eval' functions.  Advice
166 ;;     might be good but hard to turn on/off as a minor mode.
167 ;;
168 ;;; Maybe Do:
169 ;;   Code sweep checks for "forbidden functions", proper use of hooks,
170 ;;     proper keybindings, and other items from the manual that are
171 ;;     not specifically docstring related.  Would this even be useful?
172
173 ;;; Code:
174 (defvar checkdoc-version "0.7"
175   "Release version of checkdoc you are currently running.")
176
177 ;; From custom web page for compatibility between versions of custom:
178 (eval-and-compile
179   (condition-case ()
180       (require 'custom)
181     (error nil))
182   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
183       nil ;; We've got what we needed
184     ;; We have the old custom-library, hack around it!
185     (defmacro defgroup (&rest args)
186       nil)
187     (defmacro custom-add-option (&rest args)
188       nil)
189     (defmacro defcustom (var value doc &rest args)
190       (` (defvar (, var) (, value) (, doc))))))
191
192 (defvar checkdoc-xemacs-p (featurep 'xemacs))
193
194 (defcustom checkdoc-autofix-flag 'semiautomatic
195   "*Non-nil means attempt auto-fixing of doc strings.
196 If this value is the symbol `query', then the user is queried before
197 any change is made.  If the value is `automatic', then all changes are
198 made without asking unless the change is very-complex.  If the value
199 is `semiautomatic' or any other value, then simple fixes are made
200 without asking, and complex changes are made by asking the user first.
201 The value `never' is the same as nil, never ask or change anything."
202   :group 'checkdoc
203   :type '(choice (const automatic)
204                  (const query)
205                  (const never)
206                  (const semiautomatic)
207                  ;(other :tag "semiautomatic" semiautomatic)
208                  ))
209
210 (defcustom checkdoc-bouncy-flag t
211   "*Non-nil means to \"bounce\" to auto-fix locations.
212 Setting this to nil will silently make fixes that require no user
213 interaction.  See `checkdoc-autofix-flag' for auto-fixing details."
214   :group 'checkdoc
215   :type 'boolean)
216
217 (defcustom checkdoc-force-docstrings-flag t
218   "*Non-nil means that all checkable definitions should have documentation.
219 Style guide dictates that interactive functions MUST have documentation,
220 and that it's good but not required practice to make non user visible items
221 have doc strings."
222   :group 'checkdoc
223   :type 'boolean)
224
225 (defcustom checkdoc-force-history-flag t
226   "*Non-nil means that files should have a History section or ChangeLog file.
227 This helps document the evolution of, and recent changes to, the package."
228   :group 'checkdoc
229   :type 'boolean)
230
231 (defcustom checkdoc-permit-comma-termination-flag nil
232   "*Non-nil means the first line of a docstring may end with a comma.
233 Ordinarily, a full sentence is required.  This may be misleading when
234 there is a substantial caveat to the one-line description -- the comma
235 should be used when the first part could stand alone as a sentence, but
236 it indicates that a modifying clause follows."
237   :group 'checkdoc
238   :type 'boolean)
239
240 (defcustom checkdoc-triple-semi-comment-check-flag t
241   "*Non-nil means to check for multiple adjacent occurrences of ;;; comments.
242 According to the style of Emacs code in the Lisp libraries, a block
243 comment can look like this:
244 ;;; Title
245 ;;  text
246 ;;  text
247 But when inside a function, code can be commented out using the ;;;
248 construct for all lines.  When this variable is nil, the ;;; construct
249 is ignored regardless of its location in the code."
250   :group 'checkdoc
251   :type 'boolean)
252
253 (defcustom checkdoc-spellcheck-documentation-flag nil
254   "*Non-nil means run Ispell on text based on value.
255 This is automatically set to nil if Ispell does not exist on your
256 system.  Possible values are:
257
258   nil         - Don't spell-check during basic style checks.
259   defun       - Spell-check when style checking a single defun
260   buffer      - Spell-check when style checking the whole buffer
261   interactive - Spell-check during any interactive check.
262   t           - Always spell-check"
263   :group 'checkdoc
264   :type '(choice (const nil)
265                  (const defun)
266                  (const buffer)
267                  (const interactive)
268                  (const t)))
269
270 (defvar checkdoc-ispell-lisp-words
271   '("alist" "emacs" "etags" "iff" "keymap" "paren" "regexp" "sexp" "xemacs")
272   "List of words that are correct when spell-checking Lisp documentation.")
273
274 (defcustom checkdoc-max-keyref-before-warn 10
275   "*The number of \\ [command-to-keystroke] tokens allowed in a doc string.
276 Any more than this and a warning is generated suggesting that the construct
277 \\ {keymap} be used instead."
278   :group 'checkdoc
279   :type 'integer)
280
281 (defcustom checkdoc-arguments-in-order-flag t
282   "*Non-nil means warn if arguments appear out of order.
283 Setting this to nil will mean only checking that all the arguments
284 appear in the proper form in the documentation, not that they are in
285 the same order as they appear in the argument list.  No mention is
286 made in the style guide relating to order."
287   :group 'checkdoc
288   :type 'boolean)
289
290 (defvar checkdoc-style-hooks nil
291   "Hooks called after the standard style check is completed.
292 All hooks must return nil or a string representing the error found.
293 Useful for adding new user implemented commands.
294
295 Each hook is called with two parameters, (DEFUNINFO ENDPOINT).
296 DEFUNINFO is the return value of `checkdoc-defun-info'.  ENDPOINT is the
297 location of end of the documentation string.")
298
299 (defvar checkdoc-comment-style-hooks nil
300   "Hooks called after the standard comment style check is completed.
301 Must return nil if no errors are found, or a string describing the
302 problem discovered.  This is useful for adding additional checks.")
303
304 (defvar checkdoc-diagnostic-buffer "*Style Warnings*"
305   "Name of warning message buffer.")
306
307 (defcustom checkdoc-defun-regexp
308   "^(def\\(un\\|var\\|custom\\|macro\\|const\\|subst\\|advice\\|method\\)\
309 \\s-+\\(\\(\\sw\\|\\s_\\)+\\)[ \t\n]+"
310   "*Regular expression used to identify a defun.
311 A search leaves the cursor in front of the parameter list."
312   :group 'checkdoc
313   :type 'string)
314
315 (defcustom checkdoc-verb-check-experimental-flag t
316   "*Non-nil means to attempt to check the voice of the doc string.
317 This check keys off some words which are commonly misused.  See the
318 variable `checkdoc-common-verbs-wrong-voice' if you wish to add your own."
319   :group 'checkdoc
320   :type 'boolean)
321
322 (defvar checkdoc-generate-compile-warnings-flag nil
323   "Non-nil means generate warnings in a buffer for browsing.
324 Do not set this by hand, use a function like `checkdoc-current-buffer'
325 with a universal argument.")
326
327 (defcustom checkdoc-symbol-words nil
328   "A list of symbols which also happen to make good words.
329 These symbol-words are ignored when unquoted symbols are searched for.
330 This should be set in an Emacs Lisp file's local variables."
331   :group 'checkdoc
332   :type '(repeat (symbol :tag "Word")))
333
334 (defvar checkdoc-proper-noun-list
335   '("ispell" "xemacs" "emacs" "lisp")
336   "List of words (not capitalized) which should be capitalized.")
337
338 (defvar checkdoc-proper-noun-regexp
339   (let ((expr "\\<\\(")
340         (l checkdoc-proper-noun-list))
341     (while l
342       (setq expr (concat expr (car l) (if (cdr l) "\\|" ""))
343             l (cdr l)))
344     (concat expr "\\)\\>"))
345   "Regular expression derived from `checkdoc-proper-noun-regexp'.")
346
347 (defvar checkdoc-common-verbs-regexp nil
348   "Regular expression derived from `checkdoc-common-verbs-regexp'.")
349
350 (defvar checkdoc-common-verbs-wrong-voice
351   '(("adds" . "add")
352     ("allows" . "allow")
353     ("appends" . "append")
354     ("applies" . "apply")
355     ("arranges" . "arrange")
356     ("brings" . "bring")
357     ("calls" . "call")
358     ("catches" . "catch")
359     ("changes" . "change")
360     ("checks" . "check")
361     ("contains" . "contain")
362     ("creates" . "create")
363     ("destroys" . "destroy")
364     ("disables" . "disable")
365     ("executes" . "execute")
366     ("evals" . "evaluate")
367     ("evaluates" . "evaluate")
368     ("finds" . "find")
369     ("forces" . "force")
370     ("gathers" . "gather")
371     ("generates" . "generate")
372     ("goes" . "go")
373     ("guesses" . "guess")
374     ("highlights" . "highlight")
375     ("holds" . "hold")
376     ("ignores" . "ignore")
377     ("indents" . "indent")
378     ("initializes" . "initialize")
379     ("inserts" . "insert")
380     ("installs" . "install")
381     ("investigates" . "investigate")
382     ("keeps" . "keep")
383     ("kills" . "kill")
384     ("leaves" . "leave")
385     ("lets" . "let")
386     ("loads" . "load")
387     ("looks" . "look")
388     ("makes" . "make")
389     ("marks" . "mark")
390     ("matches" . "match")
391     ("notifies" . "notify")
392     ("offers" . "offer")
393     ("parses" . "parse")
394     ("performs" . "perform")
395     ("prepares" . "prepare")
396     ("prepends" . "prepend")
397     ("reads" . "read")
398     ("raises" . "raise")
399     ("removes" . "remove")
400     ("replaces" . "replace")
401     ("resets" . "reset")
402     ("restores" . "restore")
403     ("returns" . "return")
404     ("runs" . "run")
405     ("saves" . "save")
406     ("says" . "say")
407     ("searches" . "search")
408     ("selects" . "select")
409     ("sets" . "set")
410     ("sex" . "s*x")
411     ("shows" . "show")
412     ("signifies" . "signify")
413     ("sorts" . "sort")
414     ("starts" . "start")
415     ("stores" . "store")
416     ("switches" . "switch")
417     ("tells" . "tell")
418     ("tests" . "test")
419     ("toggles" . "toggle")
420     ("tries" . "try")
421     ("turns" . "turn")
422     ("undoes" . "undo")
423     ("unloads" . "unload")
424     ("unmarks" . "unmark")
425     ("updates" . "update")
426     ("uses" . "use")
427     ("yanks" . "yank")
428     )
429   "Alist of common words in the wrong voice and what should be used instead.
430 Set `checkdoc-verb-check-experimental-flag' to nil to avoid this costly
431 and experimental check.  Do not modify this list without setting
432 the value of `checkdoc-common-verbs-regexp' to nil which cause it to
433 be re-created.")
434
435 (defvar checkdoc-syntax-table nil
436   "Syntax table used by checkdoc in document strings.")
437
438 (if checkdoc-syntax-table
439     nil
440   (setq checkdoc-syntax-table (copy-syntax-table emacs-lisp-mode-syntax-table))
441   ;; When dealing with syntax in doc strings, make sure that - are encompassed
442   ;; in words so we can use cheap \\> to get the end of a symbol, not the
443   ;; end of a word in a conglomerate.
444   (modify-syntax-entry ?- "w" checkdoc-syntax-table)
445   )
446         
447
448 ;;; Compatibility
449 ;;
450 (if checkdoc-xemacs-p
451     (progn
452       (defalias 'checkdoc-make-overlay 'make-extent)
453       (defalias 'checkdoc-overlay-put 'set-extent-property)
454       (defalias 'checkdoc-delete-overlay 'delete-extent)
455       (defalias 'checkdoc-mode-line-update 'redraw-modeline)
456       (defalias 'checkdoc-call-eval-buffer 'eval-buffer)
457       )
458   (defalias 'checkdoc-make-overlay 'make-overlay)
459   (defalias 'checkdoc-overlay-put 'overlay-put)
460   (defalias 'checkdoc-delete-overlay 'delete-overlay)
461   (defalias 'checkdoc-mode-line-update 'force-mode-line-update)
462   (defalias 'checkdoc-call-eval-buffer 'eval-current-buffer)
463   )
464
465 ;; Emacs 20 has this handy function.
466 (if (not (fboundp 'princ-list))
467     (defun princ-list (&rest args)
468       "Call `princ' on ARGS."
469       (mapcar 'princ args)))
470
471 ;; Emacs 20s have MULE characters which don't equate to numbers.
472 (if (fboundp 'char=)
473     (defalias 'checkdoc-char= 'char=)
474   (defalias 'checkdoc-char= '=))
475
476 ;; Emacs 19.28 and earlier don't have the handy 'add-to-list function
477 (if (fboundp 'add-to-list)
478
479     (defalias 'checkdoc-add-to-list 'add-to-list)
480
481   (defun checkdoc-add-to-list (list-var element)
482     "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet."
483     (if (not (member element (symbol-value list-var)))
484         (set list-var (cons element (symbol-value list-var)))))
485   )
486
487 ;; To be safe in new Emacsen, we want to read events, not characters
488 (if (fboundp 'read-event)
489     (defalias 'checkdoc-read-event 'read-event)
490   (defalias 'checkdoc-read-event 'read-char))
491
492 ;;; User level commands
493 ;;
494 ;;;###autoload
495 (defun checkdoc ()
496   "Interactively check the entire buffer for style errors.
497 The current status of the check will be displayed in a buffer for
498 user to view as each check is completed."
499   (interactive)
500   (let ((status (list "Checking..." "-" "-" "-"))
501         (checkdoc-spellcheck-documentation-flag
502          (member checkdoc-spellcheck-documentation-flag
503                  '(buffer interactive t)))
504         ;; if the user set autofix to never, then that breaks the
505         ;; obviously requested asking implied by using this function.
506         ;; Set it to paranoia level.
507         (checkdoc-autofix-flag (if (or (not checkdoc-autofix-flag)
508                                        (eq checkdoc-autofix-flag 'never))
509                                    'query
510                                  checkdoc-autofix-flag))
511         tmp)
512     (checkdoc-display-status-buffer status)
513     ;; check the comments
514     (if (not buffer-file-name)
515         (setcar status "Not checked")
516       (if (checkdoc-file-comments-engine)
517           (setcar status "Errors")
518         (setcar status "Ok")))
519     (setcar (cdr status) "Checking...")
520     (checkdoc-display-status-buffer status)
521     ;; Check the documentation
522     (setq tmp (checkdoc-interactive nil t))
523     (if tmp
524         (setcar (cdr status) (format "%d Errors" (length tmp)))
525       (setcar (cdr status) "Ok"))
526     (setcar (cdr (cdr status)) "Checking...")
527     (checkdoc-display-status-buffer status)
528     ;; Check the message text
529     (if (setq tmp (checkdoc-message-interactive nil t))
530         (setcar (cdr (cdr status)) (format "%d Errors" (length tmp)))
531       (setcar (cdr (cdr status)) "Ok"))
532     (setcar (cdr (cdr (cdr status))) "Checking...")
533     (checkdoc-display-status-buffer status)
534     ;; Rogue spacing
535     (if (condition-case nil
536             (checkdoc-rogue-spaces nil t)
537           (error t))
538         (setcar (cdr (cdr (cdr status))) "Errors")
539       (setcar (cdr (cdr (cdr status))) "Ok"))
540     (checkdoc-display-status-buffer status)))
541
542 (defun checkdoc-display-status-buffer (check)
543   "Display and update the status buffer for the current checkdoc mode.
544 CHECK is a vector stating the current status of each test as an
545 element is the status of that level of test."
546   (let (temp-buffer-setup-hook)
547     (with-output-to-temp-buffer " *Checkdoc Status*"
548       (with-current-buffer " *Checkdoc Status*"
549         (fundamental-mode))
550       (princ-list
551        "Buffer comments and tags:  " (nth 0 check) "\n"
552        "Documentation style:       " (nth 1 check) "\n"
553        "Message/Query text style:  " (nth 2 check) "\n"
554        "Unwanted Spaces:           " (nth 3 check)
555        )))
556   (shrink-window-if-larger-than-buffer
557    (get-buffer-window " *Checkdoc Status*"))
558   (message nil)
559   (sit-for 0))
560
561 ;;;###autoload
562 (defun checkdoc-interactive (&optional start-here showstatus)
563   "Interactively check the current buffer for doc string errors.
564 Prefix argument START-HERE will start the checking from the current
565 point, otherwise the check starts at the beginning of the current
566 buffer.  Allows navigation forward and backwards through document
567 errors.  Does not check for comment or space warnings.
568 Optional argument SHOWSTATUS indicates that we should update the
569 checkdoc status window instead of the usual behavior."
570   (interactive "P")
571   (let ((checkdoc-spellcheck-documentation-flag
572          (member checkdoc-spellcheck-documentation-flag
573                  '(interactive t))))
574     (checkdoc-interactive-loop start-here showstatus 'checkdoc-next-error)))
575
576 ;;;###autoload
577 (defun checkdoc-message-interactive (&optional start-here showstatus)
578   "Interactively check the current buffer for message string errors.
579 Prefix argument START-HERE will start the checking from the current
580 point, otherwise the check starts at the beginning of the current
581 buffer.  Allows navigation forward and backwards through document
582 errors.  Does not check for comment or space warnings.
583 Optional argument SHOWSTATUS indicates that we should update the
584 checkdoc status window instead of the usual behavior."
585   (interactive "P")
586   (let ((checkdoc-spellcheck-documentation-flag
587          (member checkdoc-spellcheck-documentation-flag
588                  '(interactive t))))
589     (checkdoc-interactive-loop start-here showstatus
590                                'checkdoc-next-message-error)))
591
592 (defun checkdoc-interactive-loop (start-here showstatus findfunc)
593   "Interactively loop over all errors that can be found by a given method.
594 Searching starts at START-HERE.  SHOWSTATUS expresses the verbosity
595 of the search, and whether ending the search will auto-exit this function.
596 FINDFUNC is a symbol representing a function that will position the
597 cursor, and return error message text to present to the user.  It is
598 assumed that the cursor will stop just before a major sexp, which will
599 be highlighted to present the user with feedback as to the offending
600 style."
601   ;; Determine where to start the test
602   (let* ((begin (prog1 (point)
603                   (if (not start-here) (goto-char (point-min)))))
604          ;; Assign a flag to spellcheck flag
605          (checkdoc-spellcheck-documentation-flag
606           (member checkdoc-spellcheck-documentation-flag
607                   '(buffer interactive t)))
608          ;; Fetch the error list
609          (err-list (list (funcall findfunc nil)))
610          (cdo nil)
611          (returnme nil)
612          c)
613     (save-window-excursion
614       (if (not (car err-list)) (setq err-list nil))
615       ;; Include whatever function point is in for good measure.
616       (beginning-of-defun)
617       (while err-list
618         (goto-char (cdr (car err-list)))
619         ;; The cursor should be just in front of the offending doc string
620         (if (stringp (car (car err-list)))
621             (setq cdo (save-excursion (checkdoc-make-overlay
622                                        (point) (progn (forward-sexp 1)
623                                                       (point)))))
624           (setq cdo (checkdoc-make-overlay
625                      (checkdoc-error-start (car (car err-list)))
626                      (checkdoc-error-end (car (car err-list))))))
627         (unwind-protect
628             (progn
629               (checkdoc-overlay-put cdo 'face 'highlight)
630               ;; Make sure the whole doc string is visible if possible.
631               (sit-for 0)
632               (if (and (looking-at "\"")
633                        (not (pos-visible-in-window-p
634                              (save-excursion (forward-sexp 1) (point))
635                              (selected-window))))
636                   (let ((l (count-lines (point)
637                                         (save-excursion
638                                           (forward-sexp 1) (point)))))
639                     (if (> l (window-height))
640                         (recenter 1)
641                       (recenter (/ (- (window-height) l) 2))))
642                 (recenter))
643               (message "%s (C-h,%se,n,p,q)" (checkdoc-error-text
644                                               (car (car err-list)))
645                        (if (checkdoc-error-unfixable (car (car err-list)))
646                            "" "f,"))
647               (save-excursion
648                 (goto-char (checkdoc-error-start (car (car err-list))))
649                 (if (not (pos-visible-in-window-p))
650                     (recenter (- (window-height) 2)))
651                 (setq c (checkdoc-read-event)))
652               (if (and (not checkdoc-xemacs-p)
653                        (not (integerp c)))
654                   (setq c ??))
655               (cond
656                ;; Exit condition
657                ((checkdoc-char= c ?\C-g) (signal 'quit nil))
658                ;; Request an auto-fix
659                ((or (checkdoc-char= c ?y) (checkdoc-char= c ?f))
660                 (checkdoc-delete-overlay cdo)
661                 (setq cdo nil)
662                 (goto-char (cdr (car err-list)))
663                 ;; `automatic-then-never' tells the autofix function
664                 ;; to only allow one fix to be automatic.  The autofix
665                 ;; function will than set the flag to 'never, allowing
666                 ;; the checker to return a different error.
667                 (let ((checkdoc-autofix-flag 'automatic-then-never)
668                       (fixed nil))
669                   (funcall findfunc t)
670                   (setq fixed (not (eq checkdoc-autofix-flag
671                                        'automatic-then-never)))
672                   (if (not fixed)
673                       (progn
674                         (message "A Fix was not available.")
675                         (sit-for 2))
676                     (setq err-list (cdr err-list))))
677                 (beginning-of-defun)
678                 (let ((pe (car err-list))
679                       (ne (funcall findfunc nil)))
680                   (if ne
681                       (setq err-list (cons ne err-list))
682                     (cond ((not err-list)
683                            (message "No More Stylistic Errors.")
684                            (sit-for 2))
685                           (t
686                            (message
687                             "No Additional style errors.  Continuing...")
688                            (sit-for 2))))))
689                ;; Move to the next error (if available)
690                ((or (checkdoc-char= c ?n) (checkdoc-char= c ?\ ))
691                 (let ((ne (funcall findfunc nil)))
692                   (if (not ne)
693                       (if showstatus
694                           (setq returnme err-list
695                                 err-list nil)
696                         (if (not err-list)
697                             (message "No More Stylistic Errors.")
698                           (message "No Additional style errors.  Continuing..."))
699                         (sit-for 2))
700                     (setq err-list (cons ne err-list)))))
701                ;; Go backwards in the list of errors
702                ((or (checkdoc-char= c ?p) (checkdoc-char= c ?\C-?))
703                 (if (/= (length err-list) 1)
704                     (progn
705                       (setq err-list (cdr err-list))
706                       (goto-char (cdr (car err-list)))
707                       (beginning-of-defun))
708                   (message "No Previous Errors.")
709                   (sit-for 2)))
710                ;; Edit the buffer recursively.
711                ((checkdoc-char= c ?e)
712                 (checkdoc-recursive-edit
713                  (checkdoc-error-text (car (car err-list))))
714                 (checkdoc-delete-overlay cdo)
715                 (setq err-list (cdr err-list)) ;back up the error found.
716                 (beginning-of-defun)
717                 (let ((ne (funcall findfunc nil)))
718                   (if (not ne)
719                       (if showstatus
720                           (setq returnme err-list
721                                 err-list nil)
722                         (message "No More Stylistic Errors.")
723                         (sit-for 2))
724                     (setq err-list (cons ne err-list)))))
725                ;; Quit checkdoc
726                ((checkdoc-char= c ?q)
727                 (setq returnme err-list
728                       err-list nil
729                       begin (point)))
730                ;; Goofy s tuff
731                (t
732                 (if (get-buffer-window "*Checkdoc Help*")
733                     (progn
734                       (delete-window (get-buffer-window "*Checkdoc Help*"))
735                       (kill-buffer "*Checkdoc Help*"))
736                   (with-output-to-temp-buffer "*Checkdoc Help*"
737                     (princ-list
738                      "Checkdoc Keyboard Summary:\n"
739                      (if (checkdoc-error-unfixable (car (car err-list)))
740                          ""
741                        (concat
742                         "f, y    - auto Fix this warning without asking (if\
743  available.)\n"
744                         "         Very complex operations will still query.\n")
745                        )
746                      "e      - Enter recursive Edit.  Press C-M-c to exit.\n"
747                      "SPC, n - skip to the Next error.\n"
748                      "DEL, p - skip to the Previous error.\n"
749                      "q      - Quit checkdoc.\n"
750                      "C-h    - Toggle this help buffer."))
751                   (shrink-window-if-larger-than-buffer
752                    (get-buffer-window "*Checkdoc Help*"))))))
753           (if cdo (checkdoc-delete-overlay cdo)))))
754     (goto-char begin)
755     (if (get-buffer "*Checkdoc Help*") (kill-buffer "*Checkdoc Help*"))
756     (message "Checkdoc: Done.")
757     returnme))
758
759 (defun checkdoc-next-error (enable-fix)
760   "Find and return the next checkdoc error list, or nil.
761 Only documentation strings are checked.
762 Add error vector is of the form (WARNING . POSITION) where WARNING
763 is the warning text, and POSITION is the point in the buffer where the
764 error was found.  We can use points and not markers because we promise
765 not to edit the buffer before point without re-executing this check.
766 Argument ENABLE-FIX will enable auto-fixing while looking for the next
767 error.  This argument assumes that the cursor is already positioned to
768 perform the fix."
769   (if enable-fix
770       (checkdoc-this-string-valid)
771     (let ((msg nil) (p (point))
772           (checkdoc-autofix-flag nil))
773       (condition-case nil
774           (while (and (not msg) (checkdoc-next-docstring))
775             (message "Searching for doc string error...%d%%"
776                      (/ (* 100 (point)) (point-max)))
777             (if (setq msg (checkdoc-this-string-valid))
778                 (setq msg (cons msg (point)))))
779         ;; Quit.. restore position,  Other errors, leave alone
780         (quit (goto-char p)))
781       msg)))
782
783 (defun checkdoc-next-message-error (enable-fix)
784   "Find and return the next checkdoc message related error list, or nil.
785 Only text for error and `y-or-n-p' strings are checked.  See
786 `checkdoc-next-error' for details on the return value.
787 Argument ENABLE-FIX turns on the auto-fix feature.  This argument
788 assumes that the cursor is already positioned to perform the fix."
789   (if enable-fix
790       (checkdoc-message-text-engine)
791     (let ((msg nil) (p (point)) (type nil)
792           (checkdoc-autofix-flag nil))
793       (condition-case nil
794           (while (and (not msg)
795                       (setq type
796                             (checkdoc-message-text-next-string (point-max))))
797             (message "Searching for message string error...%d%%"
798                      (/ (* 100 (point)) (point-max)))
799             (if (setq msg (checkdoc-message-text-engine type))
800                 (setq msg (cons msg (point)))))
801         ;; Quit.. restore position,  Other errors, leave alone
802         (quit (goto-char p)))
803       msg)))
804
805 (defun checkdoc-recursive-edit (msg)
806   "Enter recursive edit to permit a user to fix some error checkdoc has found.
807 MSG is the error that was found, which is displayed in a help buffer."
808   (with-output-to-temp-buffer "*Checkdoc Help*"
809     (princ-list
810      "Error message:\n  " msg
811      "\n\nEdit to fix this problem, and press C-M-c to continue."))
812   (shrink-window-if-larger-than-buffer
813    (get-buffer-window "*Checkdoc Help*"))
814   (message "When you're done editing press C-M-c to continue.")
815   (unwind-protect
816       (recursive-edit)
817     (if (get-buffer-window "*Checkdoc Help*")
818         (progn
819           (delete-window (get-buffer-window "*Checkdoc Help*"))
820           (kill-buffer "*Checkdoc Help*")))))
821
822 ;;;###autoload
823 (defun checkdoc-eval-current-buffer ()
824   "Evaluate and check documentation for the current buffer.
825 Evaluation is done first because good documentation for something that
826 doesn't work is just not useful.  Comments, doc strings, and rogue
827 spacing are all verified."
828   (interactive)
829   (checkdoc-call-eval-buffer nil)
830   (checkdoc-current-buffer t))
831
832 ;;;###autoload
833 (defun checkdoc-current-buffer (&optional take-notes)
834   "Check current buffer for document, comment, error style, and rogue spaces.
835 With a prefix argument (in Lisp, the argument TAKE-NOTES),
836 store all errors found in a warnings buffer,
837 otherwise stop after the first error."
838   (interactive "P")
839   (if (interactive-p) (message "Checking buffer for style..."))
840   ;; Assign a flag to spellcheck flag
841   (let ((checkdoc-spellcheck-documentation-flag
842          (memq checkdoc-spellcheck-documentation-flag '(buffer t)))
843         (checkdoc-autofix-flag (if take-notes 'never
844                                  checkdoc-autofix-flag))
845         (checkdoc-generate-compile-warnings-flag
846          (or take-notes checkdoc-generate-compile-warnings-flag)))
847     (if take-notes
848         (checkdoc-start-section "checkdoc-current-buffer"))
849     ;; every test is responsible for returning the cursor.
850     (or (and buffer-file-name ;; only check comments in a file
851              (checkdoc-comments))
852         (checkdoc-start)
853         (checkdoc-message-text)
854         (checkdoc-rogue-spaces)
855         (not (interactive-p))
856         (if take-notes (checkdoc-show-diagnostics))
857         (message "Checking buffer for style...Done."))))
858
859 ;;;###autoload
860 (defun checkdoc-start (&optional take-notes)
861   "Start scanning the current buffer for documentation string style errors.
862 Only documentation strings are checked.
863 Use `checkdoc-continue' to continue checking if an error cannot be fixed.
864 Prefix argument TAKE-NOTES means to collect all the warning messages into
865 a separate buffer."
866   (interactive "P")
867   (let ((p (point)))
868     (goto-char (point-min))
869     (if (and take-notes (interactive-p))
870         (checkdoc-start-section "checkdoc-start"))
871     (if (interactive-p)
872         (call-interactively 'checkdoc-continue take-notes)
873       (checkdoc-continue take-notes))
874     ;; Go back since we can't be here without success above.
875     (goto-char p)
876     nil))
877
878 ;;;###autoload
879 (defun checkdoc-continue (&optional take-notes)
880   "Find the next doc string in the current buffer which has a style error.
881 Prefix argument TAKE-NOTES means to continue through the whole buffer and
882 save warnings in a separate buffer."
883   (interactive "P")
884   (let ((wrong nil) (msg nil) (errors nil)
885         ;; Assign a flag to spellcheck flag
886         (checkdoc-spellcheck-documentation-flag
887          (member checkdoc-spellcheck-documentation-flag
888                  '(buffer t)))
889         (checkdoc-autofix-flag (if take-notes 'never
890                                  checkdoc-autofix-flag))
891         (checkdoc-generate-compile-warnings-flag
892          (or take-notes checkdoc-generate-compile-warnings-flag)))
893     (save-excursion
894       ;; If we are taking notes, encompass the whole buffer, otherwise
895       ;; the user is navigating down through the buffer.
896       (while (and (not wrong) (checkdoc-next-docstring))
897         ;; OK, let's look at the doc string.
898         (setq msg (checkdoc-this-string-valid))
899         (if msg (setq wrong (point)))))
900     (if wrong
901         (progn
902           (goto-char wrong)
903           (if (not take-notes)
904               (error (checkdoc-error-text msg)))))
905     (checkdoc-show-diagnostics)
906     (if (interactive-p)
907         (message "No style warnings."))))
908
909 (defun checkdoc-next-docstring ()
910   "Move to the next doc string after point, and return t.
911 Return nil if there are no more doc strings."
912   (if (not (re-search-forward checkdoc-defun-regexp nil t))
913       nil
914     ;; If we are in a method, a :starting symbol may exist.
915     (if (looking-at "\\s-*:\\w+") (forward-sexp 1))
916     ;; search drops us after the identifier.  The next sexp is either
917     ;; the argument list or the value of the variable.  skip it.
918     (forward-sexp 1)
919     (skip-chars-forward " \n\t")
920     t))
921
922 ;;; ###autoload
923 (defun checkdoc-directory (dir &optional take-notes)
924   "Run checkdoc on all Emacs Lisp files in DIR.
925 Prefix argument TAKE-NOTES means to continue through all files and
926 save warnings in a buffer."
927   (interactive "DDirectory: \nP")
928   (let* ((files (directory-files dir t "\\.el$"))
929          (n (length files))
930          kill kill-me)
931     (if (and take-notes (interactive-p))
932         (checkdoc-start-section (format "checkdoc-directory: %s" dir)))
933     (while files
934       (setq kill (get-file-buffer (car files)))
935       (set-buffer (setq kill-me (find-file-noselect (car files))))
936       (if (interactive-p)
937           (message "File %d of %d: %s" (- n (length files) -1) n
938                    (file-name-nondirectory (car files))))
939       (checkdoc-start take-notes)
940       (if (not kill) (kill-buffer kill-me))
941       (sit-for 0)
942       (setq files (cdr files)))
943     (checkdoc-show-diagnostics)))
944
945 ;;; ###autoload
946 (defun checkdoc-comments (&optional take-notes)
947   "Find missing comment sections in the current Emacs Lisp file.
948 Prefix argument TAKE-NOTES non-nil means to save warnings in a
949 separate buffer.  Otherwise print a message.  This returns the error
950 if there is one."
951   (interactive "P")
952   (if take-notes (checkdoc-start-section "checkdoc-comments"))
953   (if (not buffer-file-name)
954      (error "Can only check comments for a file buffer"))
955   (let* ((checkdoc-spellcheck-documentation-flag
956           (member checkdoc-spellcheck-documentation-flag
957                   '(buffer t)))
958          (checkdoc-autofix-flag (if take-notes 'never checkdoc-autofix-flag))
959          ;; This is just irritating when taking notes.
960          (checkdoc-triple-semi-comment-check-flag
961           (if take-notes nil checkdoc-triple-semi-comment-check-flag))
962          (e (checkdoc-file-comments-engine))
963         (checkdoc-generate-compile-warnings-flag
964          (or take-notes checkdoc-generate-compile-warnings-flag)))
965     (if e (error (checkdoc-error-text e)))
966     (checkdoc-show-diagnostics)
967     e))
968
969 ;;;###autoload
970 (defun checkdoc-rogue-spaces (&optional take-notes interact)
971   "Find extra spaces at the end of lines in the current file.
972 Prefix argument TAKE-NOTES non-nil means to save warnings in a
973 separate buffer.  Otherwise print a message.  This returns the error
974 if there is one.
975 Optional argument INTERACT permits more interactive fixing."
976   (interactive "P")
977   (if take-notes (checkdoc-start-section "checkdoc-rogue-spaces"))
978   (let* ((checkdoc-autofix-flag (if take-notes 'never checkdoc-autofix-flag))
979          (e (checkdoc-rogue-space-check-engine nil nil interact))
980         (checkdoc-generate-compile-warnings-flag
981          (or take-notes checkdoc-generate-compile-warnings-flag)))
982     (if (not (interactive-p))
983         e
984       (if e
985           (message (checkdoc-error-text e))
986         (checkdoc-show-diagnostics)
987         (message "Space Check: done.")))))
988
989 ;;;###autoload
990 (defun checkdoc-message-text (&optional take-notes)
991   "Scan the buffer for occurrences of the error function, and verify text.
992 Optional argument TAKE-NOTES causes all errors to be logged."
993   (interactive "P")
994   (if take-notes (checkdoc-start-section "checkdoc-message-text"))
995   (let* ((p (point)) e
996          (checkdoc-autofix-flag (if take-notes 'never checkdoc-autofix-flag))
997          (checkdoc-generate-compile-warnings-flag
998           (or take-notes checkdoc-generate-compile-warnings-flag)))
999     (setq e (checkdoc-message-text-search))
1000     (if (not (interactive-p))
1001         e
1002       (if e
1003           (error (checkdoc-error-text e))
1004         (checkdoc-show-diagnostics)))
1005     (goto-char p))
1006   (if (interactive-p) (message "Checking interactive message text...done.")))
1007     
1008 ;;;###autoload
1009 (defun checkdoc-eval-defun ()
1010   "Evaluate the current form with `eval-defun' and check its documentation.
1011 Evaluation is done first so the form will be read before the
1012 documentation is checked.  If there is a documentation error, then the display
1013 of what was evaluated will be overwritten by the diagnostic message."
1014   (interactive)
1015   (eval-defun nil)
1016   (checkdoc-defun))
1017
1018 ;;;###autoload
1019 (defun checkdoc-defun (&optional no-error)
1020   "Examine the doc string of the function or variable under point.
1021 Call `error' if the doc string has problems.  If NO-ERROR is
1022 non-nil, then do not call error, but call `message' instead.
1023 If the doc string passes the test, then check the function for rogue white
1024 space at the end of each line."
1025   (interactive)
1026   (save-excursion
1027     (beginning-of-defun)
1028     (if (not (looking-at checkdoc-defun-regexp))
1029         ;; I found this more annoying than useful.
1030         ;;(if (not no-error)
1031         ;;    (message "Cannot check this sexp's doc string."))
1032         nil
1033       ;; search drops us after the identifier.  The next sexp is either
1034       ;; the argument list or the value of the variable.  skip it.
1035       (goto-char (match-end 0))
1036       ;; If we are in a method, a :starting symbol may exist.
1037       (if (looking-at "\\s-*:\\w+") (forward-sexp 1))
1038       (forward-sexp 1)
1039       (skip-chars-forward " \n\t")
1040       (let* ((checkdoc-spellcheck-documentation-flag
1041               (member checkdoc-spellcheck-documentation-flag
1042                       '(defun t)))
1043              (beg (save-excursion (beginning-of-defun) (point)))
1044              (end (save-excursion (end-of-defun) (point)))
1045              (msg (checkdoc-this-string-valid)))
1046         (if msg (if no-error
1047                     (message (checkdoc-error-text msg))
1048                   (error (checkdoc-error-text msg)))
1049           (setq msg (checkdoc-message-text-search beg end))
1050           (if msg (if no-error
1051                       (message (checkdoc-error-text msg))
1052                     (error (checkdoc-error-text msg)))
1053             (setq msg (checkdoc-rogue-space-check-engine beg end))
1054             (if msg (if no-error
1055                         (message (checkdoc-error-text msg))
1056                       (error (checkdoc-error-text msg))))))
1057         (if (interactive-p) (message "Checkdoc: done."))))))
1058
1059 ;;; Ispell interface for forcing a spell check
1060 ;;
1061
1062 ;;;###autoload
1063 (defun checkdoc-ispell (&optional take-notes)
1064   "Check the style and spelling of everything interactively.
1065 Calls `checkdoc' with spell-checking turned on.
1066 Prefix argument TAKE-NOTES is the same as for `checkdoc'"
1067   (interactive)
1068   (let ((checkdoc-spellcheck-documentation-flag t))
1069     (call-interactively 'checkdoc nil current-prefix-arg)))
1070
1071 ;;;###autoload
1072 (defun checkdoc-ispell-current-buffer (&optional take-notes)
1073   "Check the style and spelling of the current buffer.
1074 Calls `checkdoc-current-buffer' with spell-checking turned on.
1075 Prefix argument TAKE-NOTES is the same as for `checkdoc-current-buffer'"
1076   (interactive)
1077   (let ((checkdoc-spellcheck-documentation-flag t))
1078     (call-interactively 'checkdoc-current-buffer nil current-prefix-arg)))
1079
1080 ;;;###autoload
1081 (defun checkdoc-ispell-interactive (&optional take-notes)
1082   "Check the style and spelling of the current buffer interactively.
1083 Calls `checkdoc-interactive' with spell-checking turned on.
1084 Prefix argument TAKE-NOTES is the same as for `checkdoc-interactive'"
1085   (interactive)
1086   (let ((checkdoc-spellcheck-documentation-flag t))
1087     (call-interactively 'checkdoc-interactive nil current-prefix-arg)))
1088
1089 ;;;###autoload
1090 (defun checkdoc-ispell-message-interactive (&optional take-notes)
1091   "Check the style and spelling of message text interactively.
1092 Calls `checkdoc-message-interactive' with spell-checking turned on.
1093 Prefix argument TAKE-NOTES is the same as for `checkdoc-message-interactive'"
1094   (interactive)
1095   (let ((checkdoc-spellcheck-documentation-flag t))
1096     (call-interactively 'checkdoc-message-interactive nil current-prefix-arg)))
1097
1098 ;;;###autoload
1099 (defun checkdoc-ispell-message-text (&optional take-notes)
1100   "Check the style and spelling of message text interactively.
1101 Calls `checkdoc-message-text' with spell-checking turned on.
1102 Prefix argument TAKE-NOTES is the same as for `checkdoc-message-text'"
1103   (interactive)
1104   (let ((checkdoc-spellcheck-documentation-flag t))
1105     (call-interactively 'checkdoc-message-text nil current-prefix-arg)))
1106
1107 ;;;###autoload
1108 (defun checkdoc-ispell-start (&optional take-notes)
1109   "Check the style and spelling of the current buffer.
1110 Calls `checkdoc-start' with spell-checking turned on.
1111 Prefix argument TAKE-NOTES is the same as for `checkdoc-start'"
1112   (interactive)
1113   (let ((checkdoc-spellcheck-documentation-flag t))
1114     (call-interactively 'checkdoc-start nil current-prefix-arg)))
1115
1116 ;;;###autoload
1117 (defun checkdoc-ispell-continue (&optional take-notes)
1118   "Check the style and spelling of the current buffer after point.
1119 Calls `checkdoc-continue' with spell-checking turned on.
1120 Prefix argument TAKE-NOTES is the same as for `checkdoc-continue'"
1121   (interactive)
1122   (let ((checkdoc-spellcheck-documentation-flag t))
1123     (call-interactively 'checkdoc-continue nil current-prefix-arg)))
1124
1125 ;;;###autoload
1126 (defun checkdoc-ispell-comments (&optional take-notes)
1127   "Check the style and spelling of the current buffer's comments.
1128 Calls `checkdoc-comments' with spell-checking turned on.
1129 Prefix argument TAKE-NOTES is the same as for `checkdoc-comments'"
1130   (interactive)
1131   (let ((checkdoc-spellcheck-documentation-flag t))
1132     (call-interactively 'checkdoc-comments nil current-prefix-arg)))
1133
1134 ;;;###autoload
1135 (defun checkdoc-ispell-defun (&optional take-notes)
1136   "Check the style and spelling of the current defun with Ispell.
1137 Calls `checkdoc-defun' with spell-checking turned on.
1138 Prefix argument TAKE-NOTES is the same as for `checkdoc-defun'"
1139   (interactive)
1140   (let ((checkdoc-spellcheck-documentation-flag t))
1141     (call-interactively 'checkdoc-defun nil current-prefix-arg)))
1142
1143 ;;; Error Management
1144 ;;
1145 ;; Errors returned from checkdoc functions can have various
1146 ;; features and behaviors, so we need some ways of specifying
1147 ;; them, and making them easier to use in the wacked-out interfaces
1148 ;; people are requesting
1149 (defun checkdoc-create-error (text start end &optional unfixable)
1150   "Used to create the return error text returned from all engines.
1151 TEXT is the descriptive text of the error.  START and END define the region
1152 it is sensible to highlight when describing the problem.
1153 Optional argument UNFIXABLE means that the error has no auto-fix available.
1154
1155 A list of the form (TEXT START END UNFIXABLE) is returned if we are not
1156 generating a buffered list of errors."
1157   (if checkdoc-generate-compile-warnings-flag
1158       (progn (checkdoc-error start text)
1159              nil)
1160     (list text start end unfixable)))
1161
1162 (defun checkdoc-error-text (err)
1163   "Return the text specified in the checkdoc ERR."
1164   ;; string-p part is for backwards compatibility
1165   (if (stringp err) err (car err)))
1166
1167 (defun checkdoc-error-start (err)
1168   "Return the start point specified in the checkdoc ERR."
1169   ;; string-p part is for backwards compatibility
1170   (if (stringp err) nil (nth 1 err)))
1171
1172 (defun checkdoc-error-end (err)
1173   "Return the end point specified in the checkdoc ERR."
1174   ;; string-p part is for backwards compatibility
1175   (if (stringp err) nil (nth 2 err)))
1176
1177 (defun checkdoc-error-unfixable (err)
1178   "Return the t if we cannot autofix the error specified in the checkdoc ERR."
1179   ;; string-p part is for backwards compatibility
1180   (if (stringp err) nil (nth 3 err)))
1181
1182 ;;; Minor Mode specification
1183 ;;
1184 (defvar checkdoc-minor-mode nil
1185   "Non-nil in `emacs-lisp-mode' for automatic documentation checking.")
1186 (make-variable-buffer-local 'checkdoc-minor-mode)
1187
1188 (checkdoc-add-to-list 'minor-mode-alist '(checkdoc-minor-mode " CDoc"))
1189
1190 (defvar checkdoc-minor-keymap
1191   (let ((map (make-sparse-keymap))
1192         (pmap (make-sparse-keymap)))
1193     ;; Override some bindings
1194     (define-key map "\C-\M-x" 'checkdoc-eval-defun)
1195     ;(define-key map "\C-x`" 'checkdoc-continue)
1196     (if (not checkdoc-xemacs-p)
1197         (define-key map [menu-bar emacs-lisp eval-buffer]
1198           'checkdoc-eval-current-buffer))
1199     ;; Add some new bindings under C-c ?
1200     (define-key pmap "x" 'checkdoc-defun)
1201     (define-key pmap "X" 'checkdoc-ispell-defun)
1202     (define-key pmap "`" 'checkdoc-continue)
1203     (define-key pmap "~" 'checkdoc-ispell-continue)
1204     (define-key pmap "s" 'checkdoc-start)
1205     (define-key pmap "S" 'checkdoc-ispell-start)
1206     (define-key pmap "d" 'checkdoc)
1207     (define-key pmap "D" 'checkdoc-ispell)
1208     (define-key pmap "b" 'checkdoc-current-buffer)
1209     (define-key pmap "B" 'checkdoc-ispell-current-buffer)
1210     (define-key pmap "e" 'checkdoc-eval-current-buffer)
1211     (define-key pmap "m" 'checkdoc-message-text)
1212     (define-key pmap "M" 'checkdoc-ispell-message-text)
1213     (define-key pmap "c" 'checkdoc-comments)
1214     (define-key pmap "C" 'checkdoc-ispell-comments)
1215     (define-key pmap " " 'checkdoc-rogue-spaces)
1216
1217     ;; bind our submap into map
1218     (define-key map "\C-c?" pmap)
1219     map)
1220   "Keymap used to override evaluation key-bindings for documentation checking.")
1221
1222 ;; Add in a menubar with easy-menu
1223
1224 (if checkdoc-minor-keymap
1225     (easy-menu-define
1226      checkdoc-minor-menu checkdoc-minor-keymap "Checkdoc Minor Mode Menu"
1227      '("CheckDoc"
1228        ["Interactive Buffer Style Check" checkdoc t]
1229        ["Interactive Buffer Style and Spelling Check" checkdoc-ispell t]
1230        ["Check Buffer" checkdoc-current-buffer t]
1231        ["Check and Spell Buffer" checkdoc-ispell-current-buffer t]
1232        "---"
1233        ["Interactive Style Check" checkdoc-interactive t]
1234        ["Interactive Style and Spelling Check" checkdoc-ispell-interactive t]
1235        ["Find First Style Error" checkdoc-start t]
1236        ["Find First Style or Spelling  Error" checkdoc-ispell-start t]
1237        ["Next Style Error" checkdoc-continue t]
1238        ["Next Style or Spelling  Error" checkdoc-ispell-continue t]
1239        ["Interactive Message Text Style Check" checkdoc-message-interactive t]
1240        ["Interactive Message Text Style and Spelling Check"
1241         checkdoc-ispell-message-interactive t]
1242        ["Check Message Text" checkdoc-message-text t]
1243        ["Check and Spell Message Text" checkdoc-ispell-message-text t]
1244        ["Check Comment Style" checkdoc-comments buffer-file-name]
1245        ["Check Comment Style and Spelling" checkdoc-ispell-comments
1246         buffer-file-name]
1247        ["Check for Rogue Spaces" checkdoc-rogue-spaces t]
1248        "---"
1249        ["Check Defun" checkdoc-defun t]
1250        ["Check and Spell Defun" checkdoc-ispell-defun t]
1251        ["Check and Evaluate Defun" checkdoc-eval-defun t]
1252        ["Check and Evaluate Buffer" checkdoc-eval-current-buffer t]
1253        )))
1254 ;; XEmacs requires some weird stuff to add this menu in a minor mode.
1255 ;; What is it?
1256
1257 ;; Allow re-insertion of a new keymap
1258 (let ((a (assoc 'checkdoc-minor-mode minor-mode-map-alist)))
1259   (if a
1260       (setcdr a checkdoc-minor-keymap)
1261     (checkdoc-add-to-list 'minor-mode-map-alist (cons 'checkdoc-minor-mode
1262                                                       checkdoc-minor-keymap))))
1263
1264 ;;;###autoload
1265 (defun checkdoc-minor-mode (&optional arg)
1266   "Toggle Checkdoc minor mode, a mode for checking Lisp doc strings.
1267 With prefix ARG, turn Checkdoc minor mode on iff ARG is positive.
1268
1269 In Checkdoc minor mode, the usual bindings for `eval-defun' which is
1270 bound to \\<checkdoc-minor-keymap> \\[checkdoc-eval-defun] and `checkdoc-eval-current-buffer' are overridden to include
1271 checking of documentation strings.
1272
1273 \\{checkdoc-minor-keymap}"
1274   (interactive "P")
1275   (setq checkdoc-minor-mode
1276         (not (or (and (null arg) checkdoc-minor-mode)
1277                  (<= (prefix-numeric-value arg) 0))))
1278   (checkdoc-mode-line-update))
1279
1280 ;;; Subst utils
1281 ;;
1282 (defsubst checkdoc-run-hooks (hookvar &rest args)
1283   "Run hooks in HOOKVAR with ARGS."
1284   (if (fboundp 'run-hook-with-args-until-success)
1285       (apply 'run-hook-with-args-until-success hookvar args)
1286     ;; This method was similar to above.  We ignore the warning
1287     ;; since we will use the above for future Emacs versions
1288     (apply 'run-hook-with-args hookvar args)))
1289
1290 (defsubst checkdoc-create-common-verbs-regexp ()
1291   "Rebuild the contents of `checkdoc-common-verbs-regexp'."
1292   (or checkdoc-common-verbs-regexp
1293       (setq checkdoc-common-verbs-regexp
1294             (concat "\\<\\("
1295                     (mapconcat (lambda (e) (concat (car e)))
1296                                checkdoc-common-verbs-wrong-voice "\\|")
1297                     "\\)\\>"))))
1298
1299 ;; Profiler says this is not yet faster than just calling assoc
1300 ;;(defun checkdoc-word-in-alist-vector (word vector)
1301 ;;  "Check to see if WORD is in the car of an element of VECTOR.
1302 ;;VECTOR must be sorted.  The CDR should be a replacement.  Since the
1303 ;;word list is getting bigger, it is time for a quick bisecting search."
1304 ;;  (let ((max (length vector)) (min 0) i
1305 ;;      (found nil) (fw nil))
1306 ;;    (setq i (/ max 2))
1307 ;;    (while (and (not found) (/= min max))
1308 ;;      (setq fw (car (aref vector i)))
1309 ;;      (cond ((string= word fw) (setq found (cdr (aref vector i))))
1310 ;;          ((string< word fw) (setq max i))
1311 ;;          (t (setq min i)))
1312 ;;      (setq i (/ (+ max min) 2))
1313 ;;      )
1314 ;;    found))
1315
1316 ;;; Checking engines
1317 ;;
1318 (defun checkdoc-this-string-valid ()
1319   "Return a message string if the current doc string is invalid.
1320 Check for style only, such as the first line always being a complete
1321 sentence, whitespace restrictions, and making sure there are no
1322 hard-coded key-codes such as C-[char] or mouse-[number] in the comment.
1323 See the style guide in the Emacs Lisp manual for more details."
1324
1325   ;; Jump over comments between the last object and the doc string
1326   (while (looking-at "[ \t\n]*;")
1327     (forward-line 1)
1328     (beginning-of-line)
1329     (skip-chars-forward " \n\t"))
1330
1331   (let ((fp (checkdoc-defun-info))
1332         (err nil))
1333     (setq
1334      err
1335      ;; * Every command, function, or variable intended for users to know
1336      ;;   about should have a documentation string.
1337      ;;
1338      ;; * An internal variable or subroutine of a Lisp program might as well
1339      ;;   have a documentation string.  In earlier Emacs versions, you could
1340      ;;   save space by using a comment instead of a documentation string,
1341      ;;   but that is no longer the case.
1342      (if (and (not (nth 1 fp))          ; not a variable
1343               (or (nth 2 fp)            ; is interactive
1344                   checkdoc-force-docstrings-flag) ;or we always complain
1345               (not (checkdoc-char= (following-char) ?\"))) ; no doc string
1346          ;; Sometimes old code has comments where the documentation should
1347          ;; be.  Let's see if we can find the comment, and offer to turn it
1348          ;; into documentation for them.
1349          (let ((have-comment nil)
1350                (comment-start ";"))
1351            (condition-case nil
1352                (progn
1353                  (forward-sexp -1)
1354                  (forward-sexp 1)
1355                  (skip-chars-forward "\n \t")
1356                  (setq have-comment (looking-at comment-start)))
1357              (error nil))
1358            (if have-comment
1359                (if (or (eq checkdoc-autofix-flag
1360                            'automatic-then-never)
1361                        (checkdoc-y-or-n-p
1362                         "Convert comment to documentation? "))
1363                    (save-excursion
1364                      ;; Our point is at the beginning of the comment!
1365                      ;; Insert a quote, then remove the comment chars.
1366                      (insert "\"")
1367                      (let ((docstring-start-point (point)))
1368                        (while (looking-at comment-start)
1369                          (while (looking-at comment-start)
1370                            (delete-char 1))
1371                          (if (looking-at "[ \t]+")
1372                              (delete-region (match-beginning 0) (match-end 0)))
1373                          (forward-line 1)
1374                          (beginning-of-line)
1375                          (skip-chars-forward " \t")
1376                          (if (looking-at comment-start)
1377                              (progn
1378                                (beginning-of-line)
1379                                (zap-to-char 1 ?\;))))
1380                        (beginning-of-line)
1381                        (forward-char -1)
1382                        (insert "\"")
1383                        (forward-char -1)
1384                        ;; quote any double-quote characters in the comment.
1385                        (while (search-backward "\"" docstring-start-point t)
1386                          (insert "\\"))
1387                        (if (eq checkdoc-autofix-flag 'automatic-then-never)
1388                            (setq checkdoc-autofix-flag 'never))))
1389                  (checkdoc-create-error
1390                   "You should convert this comment to documentation"
1391                   (point) (save-excursion (end-of-line) (point))))
1392              (checkdoc-create-error
1393               (if (nth 2 fp)
1394                   "All interactive functions should have documentation"
1395                 "All variables and subroutines might as well have a \
1396 documentation string")
1397               (point) (+ (point) 1) t)))))
1398     (if (and (not err) (looking-at "\""))
1399         (let ((old-syntax-table (syntax-table)))
1400           (unwind-protect
1401               (progn
1402                 (set-syntax-table checkdoc-syntax-table)
1403                 (checkdoc-this-string-valid-engine fp))
1404             (set-syntax-table old-syntax-table)))
1405       err)))
1406
1407 (defun checkdoc-this-string-valid-engine (fp)
1408   "Return an error list or string if the current doc string is invalid.
1409 Depends on `checkdoc-this-string-valid' to reset the syntax table so that
1410 regexp short cuts work.  FP is the function defun information."
1411   (let ((case-fold-search nil)
1412         ;; Use a marker so if an early check modifies the text,
1413         ;; we won't accidentally loose our place.  This could cause
1414         ;; end-of doc string whitespace to also delete the " char.
1415         (s (point))
1416         (e (if (looking-at "\"")
1417                (save-excursion (forward-sexp 1) (point-marker))
1418              (point))))
1419     (or
1420      ;; * *Do not* indent subsequent lines of a documentation string so that
1421      ;;   the text is lined up in the source code with the text of the first
1422      ;;   line.  This looks nice in the source code, but looks bizarre when
1423      ;;   users view the documentation.  Remember that the indentation
1424      ;;   before the starting double-quote is not part of the string!
1425      (save-excursion
1426        (forward-line 1)
1427        (beginning-of-line)
1428        (if (and (< (point) e)
1429                 (looking-at "\\([ \t]+\\)[^ \t\n]"))
1430            (if (checkdoc-autofix-ask-replace (match-beginning 1)
1431                                              (match-end 1)
1432                                              "Remove this whitespace? "
1433                                              "")
1434                nil
1435              (checkdoc-create-error
1436               "Second line should not have indentation"
1437               (match-beginning 1)
1438               (match-end 1)))))
1439      ;; * Do not start or end a documentation string with whitespace.
1440      (let (start end)
1441        (if (or (if (looking-at "\"\\([ \t\n]+\\)")
1442                    (setq start (match-beginning 1)
1443                          end (match-end 1)))
1444                (save-excursion
1445                  (forward-sexp 1)
1446                  (forward-char -1)
1447                  (if (/= (skip-chars-backward " \t\n") 0)
1448                      (setq start (point)
1449                            end (1- e)))))
1450            (if (checkdoc-autofix-ask-replace
1451                 start end "Remove this whitespace? " "")
1452                nil
1453              (checkdoc-create-error
1454               "Documentation strings should not start or end with whitespace"
1455               start end))))
1456      ;; * The first line of the documentation string should consist of one
1457      ;;   or two complete sentences that stand on their own as a summary.
1458      ;;   `M-x apropos' displays just the first line, and if it doesn't
1459      ;;   stand on its own, the result looks bad.  In particular, start the
1460      ;;   first line with a capital letter and end with a period.
1461      (save-excursion
1462        (end-of-line)
1463        (skip-chars-backward " \t\n")
1464        (if (> (point) e) (goto-char e)) ;of the form (defun n () "doc" nil)
1465        (forward-char -1)
1466        (cond
1467         ((and (checkdoc-char= (following-char) ?\")
1468               ;; A backslashed double quote at the end of a sentence
1469               (not (checkdoc-char= (preceding-char) ?\\)))
1470          ;; We might have to add a period in this case
1471          (forward-char -1)
1472          (if (looking-at "[.!?]")
1473              nil
1474            (forward-char 1)
1475            (if (checkdoc-autofix-ask-replace
1476                 (point) (1+ (point)) "Add period to sentence? "
1477                 ".\"" t)
1478                nil
1479              (checkdoc-create-error
1480               "First sentence should end with punctuation"
1481               (point) (1+ (point))))))
1482         ((looking-at "[\\!?;:.)]")
1483          ;; These are ok
1484          nil)
1485         ((and checkdoc-permit-comma-termination-flag (looking-at ","))
1486          nil)
1487         (t
1488          ;; If it is not a complete sentence, let's see if we can
1489          ;; predict a clever way to make it one.
1490          (let ((msg "First line is not a complete sentence")
1491                (e (point)))
1492            (beginning-of-line)
1493            (if (re-search-forward "\\. +" e t)
1494                ;; Here we have found a complete sentence, but no break.
1495                (if (checkdoc-autofix-ask-replace
1496                     (1+ (match-beginning 0)) (match-end 0)
1497                     "First line not a complete sentence.  Add RET here? "
1498                     "\n" t)
1499                    (let (l1 l2)
1500                      (forward-line 1)
1501                      (end-of-line)
1502                      (setq l1 (current-column)
1503                            l2 (save-excursion
1504                                 (forward-line 1)
1505                                 (end-of-line)
1506                                 (current-column)))
1507                      (if (> (+ l1 l2 1) 80)
1508                          (setq msg "Incomplete auto-fix; doc string \
1509 may require more formatting")
1510                        ;; We can merge these lines!  Replace this CR
1511                        ;; with a space.
1512                        (delete-char 1) (insert " ")
1513                        (setq msg nil))))
1514              ;; Let's see if there is enough room to draw the next
1515              ;; line's sentence up here.  I often get hit w/
1516              ;; auto-fill moving my words around.
1517              (let ((numc (progn (end-of-line) (- 80 (current-column))))
1518                    (p    (point)))
1519                (forward-line 1)
1520                (beginning-of-line)
1521                (if (and (re-search-forward "[.!?:\"]\\([ \t\n]+\\|\"\\)"
1522                                            (save-excursion
1523                                              (end-of-line)
1524                                              (point))
1525                                            t)
1526                         (< (current-column) numc))
1527                    (if (checkdoc-autofix-ask-replace
1528                         p (1+ p)
1529                         "1st line not a complete sentence.  Join these lines? "
1530                         " " t)
1531                        (progn
1532                          ;; They said yes.  We have more fill work to do...
1533                          (goto-char (match-beginning 1))
1534                          (delete-region (point) (match-end 1))
1535                          (insert "\n")
1536                          (setq msg nil))))))
1537            (if msg
1538                (checkdoc-create-error msg s (save-excursion
1539                                               (goto-char s)
1540                                               (end-of-line)
1541                                               (point)))
1542              nil) ))))
1543      ;; Continuation of above.  Make sure our sentence is capitalized.
1544      (save-excursion
1545        (skip-chars-forward "\"\\*")
1546        (if (looking-at "[a-z]")
1547            (if (checkdoc-autofix-ask-replace
1548                 (match-beginning 0) (match-end 0)
1549                 "Capitalize your sentence? " (upcase (match-string 0))
1550                 t)
1551                nil
1552              (checkdoc-create-error
1553               "First line should be capitalized"
1554               (match-beginning 0) (match-end 0)))
1555          nil))
1556      ;;   * Don't write key sequences directly in documentation strings.
1557      ;;     Instead, use the `\\[...]' construct to stand for them.
1558      (save-excursion
1559        (let ((f nil) (m nil) (start (point))
1560              (re "[^`A-Za-z0-9_]\\([CMA]-[a-zA-Z]\\|\\(\\([CMA]-\\)?\
1561 mouse-[0-3]\\)\\)\\>"))
1562          ;; Find the first key sequence not in a sample
1563          (while (and (not f) (setq m (re-search-forward re e t)))
1564            (setq f (not (checkdoc-in-sample-code-p start e))))
1565          (if m
1566              (checkdoc-create-error
1567               (concat
1568                "Keycode " (match-string 1)
1569                " embedded in doc string.  Use \\\\<keymap> & \\\\[function] "
1570                "instead")
1571               (match-beginning 1) (match-end 1) t))))
1572      ;; It is not practical to use `\\[...]' very many times, because
1573      ;; display of the documentation string will become slow.  So use this
1574      ;; to describe the most important commands in your major mode, and
1575      ;; then use `\\{...}' to display the rest of the mode's keymap.
1576      (save-excursion
1577        (if (re-search-forward "\\\\\\\\\\[\\w+" e t
1578                               (1+ checkdoc-max-keyref-before-warn))
1579            (checkdoc-create-error
1580             "Too many occurrences of \\[function].  Use \\{keymap} instead"
1581             s (marker-position e))))
1582      ;; Ambiguous quoted symbol.  When a symbol is both bound and fbound,
1583      ;; and is referred to in documentation, it should be prefixed with
1584      ;; something to disambiguate it.  This check must be before the
1585      ;; 80 column check because it will probably break that.
1586      (save-excursion
1587        (let ((case-fold-search t)
1588              (ret nil) mb me)
1589          (while (and (re-search-forward "`\\(\\sw\\(\\sw\\|\\s_\\)+\\)'" e t)
1590                      (not ret))
1591            (let* ((ms1 (match-string 1))
1592                   (sym (intern-soft ms1)))
1593              (setq mb (match-beginning 1)
1594                    me (match-end 1))
1595              (if (and sym (boundp sym) (fboundp sym)
1596                       (save-excursion
1597                         (goto-char mb)
1598                         (forward-word -1)
1599                         (not (looking-at
1600                               "variable\\|option\\|function\\|command\\|symbol"))))
1601                  (if (checkdoc-autofix-ask-replace
1602                       mb me "Prefix this ambiguous symbol? " ms1 t)
1603                      ;; We didn't actually replace anything.  Here we find
1604                      ;; out what special word form they wish to use as
1605                      ;; a prefix.
1606                      (let ((disambiguate
1607                             (completing-read
1608                              "Disambiguating Keyword (default: variable): "
1609                              '(("function") ("command") ("variable")
1610                                ("option") ("symbol"))
1611                              nil t nil nil "variable")))
1612                        (goto-char (1- mb))
1613                        (insert disambiguate " ")
1614                        (forward-word 1))
1615                    (setq ret
1616                          (format "Disambiguate %s by preceding w/ \
1617 function,command,variable,option or symbol." ms1))))))
1618          (if ret
1619              (checkdoc-create-error ret mb me)
1620            nil)))
1621      ;; * Format the documentation string so that it fits in an
1622      ;;   Emacs window on an 80-column screen.  It is a good idea
1623      ;;   for most lines to be no wider than 60 characters.  The
1624      ;;   first line can be wider if necessary to fit the
1625      ;;   information that ought to be there.
1626      (save-excursion
1627        (let ((start (point))
1628              (eol nil))
1629          (while (and (< (point) e)
1630                      (or (progn (end-of-line) (setq eol (point))
1631                                 (< (current-column) 80))
1632                          (progn (beginning-of-line)
1633                                 (re-search-forward "\\\\\\\\[[<{]"
1634                                                    eol t))
1635                          (checkdoc-in-sample-code-p start e)))
1636            (forward-line 1))
1637          (end-of-line)
1638          (if (and (< (point) e) (> (current-column) 80))
1639              (checkdoc-create-error
1640               "Some lines are over 80 columns wide"
1641               s (save-excursion (goto-char s) (end-of-line) (point)) ))))
1642      ;; Here we deviate to tests based on a variable or function.
1643      ;; We must do this before checking for symbols in quotes because there
1644      ;; is a chance that just such a symbol might really be an argument.
1645      (cond ((eq (nth 1 fp) t)
1646             ;; This is if we are in a variable
1647             (or
1648              ;; * The documentation string for a variable that is a
1649              ;;   yes-or-no flag should start with words such as Non-nil
1650              ;;   means..., to make it clear that all non-`nil' values are
1651              ;;   equivalent and indicate explicitly what `nil' and non-`nil'
1652              ;;   mean.
1653              ;; * If a user option variable records a true-or-false
1654              ;;   condition, give it a name that ends in `-flag'.
1655
1656              ;; If the variable has -flag in the name, make sure
1657              (if (and (string-match "-flag$" (car fp))
1658                       (not (looking-at "\"\\*?Non-nil\\s-+means\\s-+")))
1659                  (checkdoc-create-error
1660                   "Flag variable doc strings should start: Non-nil means"
1661                   s (marker-position e) t))
1662              ;; If the doc string starts with "Non-nil means"
1663              (if (and (looking-at "\"\\*?Non-nil\\s-+means\\s-+")
1664                       (not (string-match "-flag$" (car fp))))
1665                  (if (checkdoc-y-or-n-p
1666                       (format
1667                        "Rename to %s and Query-Replace all occurances? "
1668                        (concat (car fp) "-flag")))
1669                      (progn
1670                        (beginning-of-defun)
1671                        (query-replace-regexp
1672                         (concat "\\<" (regexp-quote (car fp)) "\\>")
1673                         (concat (car fp) "-flag")))
1674                    (checkdoc-create-error
1675                     "Flag variables should end in `-flag'" s
1676                     (marker-position e))))
1677              ;; Done with variables
1678              ))
1679            (t
1680             ;; This if we are in a function definition
1681             (or
1682              ;; * When a function's documentation string mentions the value
1683              ;;   of an argument of the function, use the argument name in
1684              ;;   capital letters as if it were a name for that value.  Thus,
1685              ;;   the documentation string of the function `/' refers to its
1686              ;;   second argument as `DIVISOR', because the actual argument
1687              ;;   name is `divisor'.
1688
1689              ;;   Addendum:  Make sure they appear in the doc in the same
1690              ;;              order that they are found in the arg list.
1691              (let ((args (cdr (cdr (cdr (cdr fp)))))
1692                    (last-pos 0)
1693                    (found 1)
1694                    (order (and (nth 3 fp) (car (nth 3 fp))))
1695                    (nocheck (append '("&optional" "&rest") (nth 3 fp)))
1696                    (inopts nil))
1697                (while (and args found (> found last-pos))
1698                  (if (member (car args) nocheck)
1699                      (setq args (cdr args)
1700                            inopts t)
1701                    (setq last-pos found
1702                          found (save-excursion
1703                                  (re-search-forward
1704                                   (concat "\\<" (upcase (car args))
1705                                           ;; Require whitespace OR
1706                                           ;; ITEMth<space> OR
1707                                           ;; ITEMs<space>
1708                                           "\\(\\>\\|th\\>\\|s\\>\\)")
1709                                   e t)))
1710                    (if (not found)
1711                        (let ((case-fold-search t))
1712                          ;; If the symbol was not found, let's see if we
1713                          ;; can find it with a different capitalization
1714                          ;; and see if the user wants to capitalize it.
1715                          (if (save-excursion
1716                                (re-search-forward
1717                                 (concat "\\<\\(" (car args)
1718                                         ;; Require whitespace OR
1719                                         ;; ITEMth<space> OR
1720                                         ;; ITEMs<space>
1721                                         "\\)\\(\\>\\|th\\>\\|s\\>\\)")
1722                                 e t))
1723                              (if (checkdoc-autofix-ask-replace
1724                                   (match-beginning 1) (match-end 1)
1725                                   (format
1726                                    "Argument `%s' should appear as `%s'.  Fix? "
1727                                    (car args) (upcase (car args)))
1728                                   (upcase (car args)) t)
1729                                  (setq found (match-beginning 1))))))
1730                    (if found (setq args (cdr args)))))
1731                (if (not found)
1732                    ;; It wasn't found at all!  Offer to attach this new symbol
1733                    ;; to the end of the documentation string.
1734                    (if (checkdoc-y-or-n-p
1735                         (format
1736                          "Add %s documentation to end of doc string? "
1737                          (upcase (car args))))
1738                        ;; Now do some magic and invent a doc string.
1739                        (save-excursion
1740                          (goto-char e) (forward-char -1)
1741                          (insert "\n"
1742                                  (if inopts "Optional a" "A")
1743                                  "rgument " (upcase (car args))
1744                                  " ")
1745                          (insert (read-string "Describe: "))
1746                          (if (not (save-excursion (forward-char -1)
1747                                                   (looking-at "[.?!]")))
1748                              (insert "."))
1749                          nil)
1750                      ;; Well, they don't want that.  Add ingore param?
1751                      (if (checkdoc-y-or-n-p
1752                           (format "Add %s to be never documented? " (car args)))
1753                          (save-excursion
1754                            (goto-char s)
1755                            (insert "; checkdoc-params: (" (car args) ")\n")
1756                            (indent-for-tab-command)
1757                            )
1758                        (checkdoc-create-error
1759                         (format
1760                          "Argument `%s' should appear (as `%s') in the doc string"
1761                          (car args) (upcase (car args)))
1762                         s (marker-position e))))
1763                  (if (or (and order (eq order 'yes))
1764                          (and (not order) checkdoc-arguments-in-order-flag))
1765                      (if (< found last-pos)
1766                          (checkdoc-create-error
1767                           "Arguments occur in the doc string out of order"
1768                           s (marker-position e) t)))))
1769              ;; * For consistency, phrase the verb in the first sentence of a
1770              ;;   documentation string for functions as an infinitive with
1771              ;;   "to" omitted.  For instance, use `Return the cons of A and
1772              ;;   B.' in preference to `Returns the cons of A and B.'
1773              ;;   Usually it looks good to do likewise for the rest of the
1774              ;;   first paragraph.  Subsequent paragraphs usually look better
1775              ;;   if they have proper subjects.
1776              ;;
1777              ;; This is the least important of the above tests.  Make sure
1778              ;; it occurs last.
1779              (and checkdoc-verb-check-experimental-flag
1780                   (save-excursion
1781                     ;; Maybe rebuild the monster-regex
1782                     (checkdoc-create-common-verbs-regexp)
1783                     (let ((lim (save-excursion
1784                                  (end-of-line)
1785                                  ;; check string-continuation
1786                                  (if (checkdoc-char= (preceding-char) ?\\)
1787                                      (progn (forward-line 1)
1788                                             (end-of-line)))
1789                                  (point)))
1790                           (rs nil) replace original (case-fold-search t))
1791                       (while (and (not rs)
1792                                   (re-search-forward
1793                                    checkdoc-common-verbs-regexp
1794                                    lim t))
1795                         (setq original (buffer-substring-no-properties
1796                                         (match-beginning 1) (match-end 1))
1797                               rs (assoc (downcase original)
1798                                         checkdoc-common-verbs-wrong-voice))
1799                         (if (not rs) (error "Verb voice alist corrupted"))
1800                         (setq replace (let ((case-fold-search nil))
1801                                         (save-match-data
1802                                           (if (string-match "^[A-Z]" original)
1803                                               (capitalize (cdr rs))
1804                                             (cdr rs)))))
1805                         (if (checkdoc-autofix-ask-replace
1806                              (match-beginning 1) (match-end 1)
1807                              (format "Use the infinitive for `%s'.  \
1808 Replace with `%s'? " original replace)
1809                              replace t)
1810                             (setq rs nil)))
1811                       (if rs
1812                           ;; there was a match, but no replace
1813                           (checkdoc-create-error
1814                            (format
1815                             "Infinitive `%s' should be replaced with `%s'"
1816                             original replace)
1817                            (match-beginning 1) (match-end 1))))))
1818              ;; Done with functions
1819              )))
1820      ;;* When a documentation string refers to a Lisp symbol, write it as
1821      ;;  it would be printed (which usually means in lower case), with
1822      ;;  single-quotes around it.  For example: `lambda'.  There are two
1823      ;;  exceptions: write t and nil without single-quotes.  (In this
1824      ;;  manual, we normally do use single-quotes for those symbols.)
1825      (save-excursion
1826        (let ((found nil) (start (point)) (msg nil) (ms nil))
1827          (while (and (not msg)
1828                      (re-search-forward
1829                       "[^-([`':a-zA-Z]\\(\\w+[:-]\\(\\w\\|\\s_\\)+\\)[^]']"
1830                       e t))
1831            (setq ms (match-string 1))
1832            (save-match-data
1833              ;; A . is a \s_ char, so we must remove periods from
1834              ;; sentences more carefully.
1835              (if (string-match "\\.$" ms)
1836                  (setq ms (substring ms 0 (1- (length ms))))))
1837            (if (and (not (checkdoc-in-sample-code-p start e))
1838                     (not (checkdoc-in-example-string-p start e))
1839                     (not (member ms checkdoc-symbol-words))
1840                     (setq found (intern-soft ms))
1841                     (or (boundp found) (fboundp found)))
1842                (progn
1843                  (setq msg (format "Add quotes around Lisp symbol `%s'? "
1844                                    ms))
1845                  (if (checkdoc-autofix-ask-replace
1846                       (match-beginning 1) (+ (match-beginning 1)
1847                                              (length ms))
1848                       msg (concat "`" ms "'") t)
1849                      (setq msg nil)
1850                    (setq msg
1851                          (format "Lisp symbol `%s' should appear in quotes"
1852                                  ms))))))
1853          (if msg
1854              (checkdoc-create-error msg (match-beginning 1)
1855                                     (+ (match-beginning 1)
1856                                        (length ms)))
1857            nil)))
1858      ;; t and nil case
1859      (save-excursion
1860        (if (re-search-forward "\\(`\\(t\\|nil\\)'\\)" e t)
1861            (if (checkdoc-autofix-ask-replace
1862                 (match-beginning 1) (match-end 1)
1863                 (format "%s should not appear in quotes.  Remove? "
1864                         (match-string 2))
1865                 (match-string 2) t)
1866                nil
1867              (checkdoc-create-error
1868               "Symbols t and nil should not appear in `quotes'"
1869               (match-beginning 1) (match-end 1)))))
1870      ;; Here is some basic sentence formatting
1871      (checkdoc-sentencespace-region-engine (point) e)
1872      ;; Here are common proper nouns that should always appear capitalized.
1873      (checkdoc-proper-noun-region-engine (point) e)
1874      ;; Make sure the doc string has correctly spelled English words
1875      ;; in it.  This function is extracted due to its complexity,
1876      ;; and reliance on the Ispell program.
1877      (checkdoc-ispell-docstring-engine e)
1878      ;; User supplied checks
1879      (save-excursion (checkdoc-run-hooks 'checkdoc-style-hooks fp e))
1880      ;; Done!
1881      )))
1882
1883 (defun checkdoc-defun-info nil
1884   "Return a list of details about the current sexp.
1885 It is a list of the form:
1886    (NAME VARIABLE INTERACTIVE NODOCPARAMS PARAMETERS ...)
1887 where NAME is the name, VARIABLE is t if this is a `defvar',
1888 INTERACTIVE is nil if this is not an interactive function, otherwise
1889 it is the position of the `interactive' call, and PARAMETERS is a
1890 string which is the name of each variable in the function's argument
1891 list.  The NODOCPARAMS is a sublist of parameters specified by a checkdoc
1892 comment for a given defun.  If the first element is not a string, then
1893 the token checkdoc-order: <TOKEN> exists, and TOKEN is a symbol read
1894 from the comment."
1895   (save-excursion
1896     (beginning-of-defun)
1897     (let ((defun (looking-at "(def\\(un\\|macro\\|subst\\|advice\\|method\\)"))
1898           (is-advice (looking-at "(defadvice"))
1899           (is-method (looking-at "(defmethod"))
1900           (lst nil)
1901           (ret nil)
1902           (oo (make-vector 3 0)))       ;substitute obarray for `read'
1903       (forward-char 1)
1904       (forward-sexp 1)
1905       (skip-chars-forward " \n\t")
1906       (setq ret
1907             (list (buffer-substring-no-properties
1908                    (point) (progn (forward-sexp 1) (point)))))
1909       (if (not defun)
1910           (setq ret (cons t ret))
1911         ;; The variable spot
1912         (setq ret (cons nil ret))
1913         ;; Interactive
1914         (save-excursion
1915           (setq ret (cons
1916                      (re-search-forward "(interactive"
1917                                         (save-excursion (end-of-defun) (point))
1918                                         t)
1919                      ret)))
1920         (skip-chars-forward " \t\n")
1921         (let ((bss (buffer-substring (point) (save-excursion (forward-sexp 1)
1922                                                              (point))))
1923               ;; Overload th main obarray so read doesn't intern the
1924               ;; local symbols of the function we are checking.
1925               ;; Without this we end up cluttering the symbol space w/
1926               ;; useless symbols.
1927               (obarray oo))
1928           (if (and (symbolp (read bss)) is-method)
1929               (save-excursion
1930                 (setq bss (buffer-substring (progn (forward-sexp 1) (point))
1931                                             (save-excursion (forward-sexp 1)
1932                                                             (point))))))
1933           ;; Ok, check for checkdoc parameter comment here
1934           (save-excursion
1935             (setq ret
1936                   (cons
1937                    (let ((sl1 nil))
1938                      (if (re-search-forward ";\\s-+checkdoc-order:\\s-+"
1939                                             (save-excursion (end-of-defun)
1940                                                             (point))
1941                                             t)
1942                          (setq sl1 (list (cond ((looking-at "nil") 'no)
1943                                                ((looking-at "t") 'yes)))))
1944                      (if (re-search-forward ";\\s-+checkdoc-params:\\s-+"
1945                                             (save-excursion (end-of-defun)
1946                                                             (point))
1947                                             t)
1948                          (let ((sl nil))
1949                            (goto-char (match-end 0))
1950                            (condition-case nil
1951                                (setq lst (read (current-buffer)))
1952                              (error (setq lst nil))) ; error in text
1953                            (if (not (listp lst)) ; not a list of args
1954                                (setq lst (list lst)))
1955                            (if (and lst (not (symbolp (car lst)))) ;weird arg
1956                                (setq lst nil))
1957                            (while lst
1958                              (setq sl (cons (symbol-name (car lst)) sl)
1959                                    lst (cdr lst)))
1960                            (setq sl1 (append sl1 sl))))
1961                      sl1)
1962                    ret)))
1963           ;; Read the list of parameters, but do not put the symbols in
1964           ;; the standard obarray.
1965           (setq lst (read bss)))
1966         ;; If we are in a method, the first argument is itself a list;
1967         (if (and is-method (listp (car lst)))
1968             (setcar lst (car (car lst))))
1969         ;; This is because read will intern nil if it doesn't into the
1970         ;; new obarray.
1971         (if (not (listp lst)) (setq lst nil))
1972         (if is-advice nil
1973           (while lst
1974             (setq ret (cons (symbol-name (car lst)) ret)
1975                   lst (cdr lst)))))
1976       (nreverse ret))))
1977
1978 (defun checkdoc-in-sample-code-p (start limit)
1979   "Return non-nil if the current point is in a code fragment.
1980 A code fragment is identified by an open parenthesis followed by a
1981 symbol which is a valid function or a word in all CAPS, or a parenthesis
1982 that is quoted with the ' character.  Only the region from START to LIMIT
1983 is is allowed while searching for the bounding parenthesis."
1984   (save-match-data
1985     (save-restriction
1986       (narrow-to-region start limit)
1987       (save-excursion
1988         (and (condition-case nil (progn (up-list 1) t) (error nil))
1989              (condition-case nil (progn (forward-list -1) t) (error nil))
1990              (or (save-excursion (forward-char -1) (looking-at "'("))
1991                  (and (looking-at "(\\(\\(\\w\\|[-:_]\\)+\\)[ \t\n;]")
1992                       (let ((ms (buffer-substring-no-properties
1993                                  (match-beginning 1) (match-end 1))))
1994                         ;; if this string is function bound, we are in
1995                         ;; sample code.  If it has a - or : character in
1996                         ;; the name, then it is probably supposed to be bound
1997                         ;; but isn't yet.
1998                         (or (fboundp (intern-soft ms))
1999                             (let ((case-fold-search nil))
2000                               (string-match "^[A-Z-]+$" ms))
2001                             (string-match "\\w[-:_]+\\w" ms))))))))))
2002
2003 (defun checkdoc-in-example-string-p (start limit)
2004   "Return non-nil if the current point is in an \"example string\".
2005 This string is identified by the characters \\\" surrounding the text.
2006 The text checked is between START and LIMIT."
2007   (save-match-data
2008     (save-excursion
2009       (let ((p (point))
2010             (c 0))
2011         (goto-char start)
2012         (while (and (< (point) p) (re-search-forward "\\\\\"" limit t))
2013           (setq c (1+ c)))
2014         (and (< 0 c) (= (% c 2) 0))))))
2015
2016 (defun checkdoc-proper-noun-region-engine (begin end)
2017   "Check all text between BEGIN and END for lower case proper nouns.
2018 These are Emacs centric proper nouns which should be capitalized for
2019 consistency.  Return an error list if any are not fixed, but
2020 internally skip over no answers.
2021 If the offending word is in a piece of quoted text, then it is skipped."
2022   (save-excursion
2023     (let ((case-fold-search nil)
2024           (errtxt nil) bb be
2025           (old-syntax-table (syntax-table)))
2026       (unwind-protect
2027           (progn
2028             (set-syntax-table checkdoc-syntax-table)
2029             (goto-char begin)
2030             (while (re-search-forward checkdoc-proper-noun-regexp end t)
2031               (let ((text (match-string 1))
2032                     (b (match-beginning 1))
2033                     (e (match-end 1)))
2034                 (if (and (not (save-excursion
2035                                 (goto-char b)
2036                                 (forward-char -1)
2037                                 (looking-at "`\\|\"\\|\\.\\|\\\\")))
2038                          ;; surrounded by /, as in a URL or filename: /emacs/
2039                          (not (and (= ?/ (char-after e))
2040                                    (= ?/ (char-before b))))
2041                          (not (checkdoc-in-example-string-p begin end)))
2042                     (if (checkdoc-autofix-ask-replace
2043                          b e (format "Text %s should be capitalized.  Fix? "
2044                                      text)
2045                          (capitalize text) t)
2046                         nil
2047                       (if errtxt
2048                           ;; If there is already an error, then generate
2049                           ;; the warning output if applicable
2050                           (if checkdoc-generate-compile-warnings-flag
2051                               (checkdoc-create-error
2052                                (format
2053                                 "Name %s should appear capitalized as %s"
2054                                 text (capitalize text))
2055                                b e))
2056                         (setq errtxt
2057                               (format
2058                                "Name %s should appear capitalized as %s"
2059                                text (capitalize text))
2060                               bb b be e)))))))
2061         (set-syntax-table old-syntax-table))
2062       (if errtxt (checkdoc-create-error errtxt bb be)))))
2063
2064 (defun checkdoc-sentencespace-region-engine (begin end)
2065   "Make sure all sentences have double spaces between BEGIN and END."
2066   (if sentence-end-double-space
2067       (save-excursion
2068         (let ((case-fold-search nil)
2069               (errtxt nil) bb be
2070               (old-syntax-table (syntax-table)))
2071           (unwind-protect
2072               (progn
2073                 (set-syntax-table checkdoc-syntax-table)
2074                 (goto-char begin)
2075                 (while (re-search-forward "[^.0-9]\\(\\. \\)[^ \n]" end t)
2076                   (let ((b (match-beginning 1))
2077                         (e (match-end 1)))
2078                     (if (and (not (checkdoc-in-sample-code-p begin end))
2079                              (not (checkdoc-in-example-string-p begin end))
2080                              (not (save-excursion
2081                                     (goto-char (match-beginning 1))
2082                                     (condition-case nil
2083                                         (progn
2084                                           (forward-sexp -1)
2085                                           ;; piece of an abbreviation
2086                                           (looking-at
2087                                            "\\([a-z]\\|[iI]\\.?e\\|[eE]\\.?g\\)\\."))
2088                                       (error t)))))
2089                         (if (checkdoc-autofix-ask-replace
2090                              b e
2091                              "There should be two spaces after a period.  Fix? "
2092                              ".  ")
2093                             nil
2094                           (if errtxt
2095                               ;; If there is already an error, then generate
2096                               ;; the warning output if applicable
2097                               (if checkdoc-generate-compile-warnings-flag
2098                                   (checkdoc-create-error
2099                                    "There should be two spaces after a period"
2100                                    b e))
2101                             (setq errtxt
2102                                   "There should be two spaces after a period"
2103                                   bb b be e)))))))
2104             (set-syntax-table old-syntax-table))
2105           (if errtxt (checkdoc-create-error errtxt bb be))))))
2106
2107 ;;; Ispell engine
2108 ;;
2109 (eval-when-compile (require 'ispell))
2110
2111 (defun checkdoc-ispell-init ()
2112   "Initialize Ispell process (default version) with Lisp words.
2113 The words used are from `checkdoc-ispell-lisp-words'.  If `ispell'
2114 cannot be loaded, then set `checkdoc-spellcheck-documentation-flag' to
2115 nil."
2116   (require 'ispell)
2117   (if (not (symbol-value 'ispell-process)) ;Silence byteCompiler
2118       (condition-case nil
2119           (progn
2120             (ispell-buffer-local-words)
2121             ;; This code copied in part from ispell.el Emacs 19.34
2122             (let ((w checkdoc-ispell-lisp-words))
2123               (while w
2124                 (process-send-string
2125                  ;;  Silence byte compiler
2126                  (symbol-value 'ispell-process)
2127                  (concat "@" (car w) "\n"))
2128                 (setq w (cdr w)))))
2129         (error (setq checkdoc-spellcheck-documentation-flag nil)))))
2130
2131 (defun checkdoc-ispell-docstring-engine (end)
2132   "Run the Ispell tools on the doc string between point and END.
2133 Since Ispell isn't Lisp-smart, we must pre-process the doc string
2134 before using the Ispell engine on it."
2135   (if (or (not checkdoc-spellcheck-documentation-flag)
2136           ;; If the user wants no questions or fixing, then we must
2137           ;; disable spell checking as not useful.
2138           (not checkdoc-autofix-flag)
2139           (eq checkdoc-autofix-flag 'never))
2140       nil
2141     (checkdoc-ispell-init)
2142     (save-excursion
2143       (skip-chars-forward "^a-zA-Z")
2144       (let ((word nil) (sym nil) (case-fold-search nil) (err nil))
2145         (while (and (not err) (< (point) end))
2146           (if (save-excursion (forward-char -1) (looking-at "[('`]"))
2147               ;; Skip lists describing meta-syntax, or bound variables
2148               (forward-sexp 1)
2149             (setq word (buffer-substring-no-properties
2150                         (point) (progn
2151                                   (skip-chars-forward "a-zA-Z-")
2152                                   (point)))
2153                   sym (intern-soft word))
2154             (if (and sym (or (boundp sym) (fboundp sym)))
2155                 ;; This is probably repetitive in most cases, but not always.
2156                 nil
2157               ;; Find out how we spell-check this word.
2158               (if (or
2159                    ;; All caps w/ option th, or s tacked on the end
2160                    ;; for pluralization or numberthness.
2161                    (string-match "^[A-Z][A-Z]+\\(s\\|th\\)?$" word)
2162                    (looking-at "}") ; a keymap expression
2163                    )
2164                   nil
2165                 (save-excursion
2166                   (if (not (eq checkdoc-autofix-flag 'never))
2167                       (let ((lk last-input-event))
2168                         (ispell-word nil t)
2169                         (if (not (equal last-input-event lk))
2170                             (progn
2171                               (sit-for 0)
2172                               (message "Continuing..."))))
2173                     ;; Nothing here.
2174                     )))))
2175           (skip-chars-forward "^a-zA-Z"))
2176         err))))
2177
2178 ;;; Rogue space checking engine
2179 ;;
2180 (defun checkdoc-rogue-space-check-engine (&optional start end interact)
2181   "Return a message list if there is a line with white space at the end.
2182 If `checkdoc-autofix-flag' permits, delete that whitespace instead.
2183 If optional arguments START and END are non nil, bound the check to
2184 this region.
2185 Optional argument INTERACT may permit the user to fix problems on the fly."
2186   (let ((p (point))
2187         (msg nil) s e (f nil))
2188     (if (not start) (setq start (point-min)))
2189     ;; If end is nil, it means end of buffer to search anyway
2190     (or
2191      ;; Check for an error if `? ' or `?\ ' is used at the end of a line.
2192      ;; (It's dangerous)
2193      (progn
2194        (goto-char start)
2195        (while (and (not msg) (re-search-forward "\\?\\\\?[ \t][ \t]*$" end t))
2196          (setq msg
2197                "Don't use `? ' at the end of a line. \
2198 News agents may remove it"
2199                s (match-beginning 0) e (match-end 0) f t)
2200          ;; If interactive is passed down, give them a chance to fix things.
2201          (if (and interact (y-or-n-p (concat msg ". Fix? ")))
2202              (progn
2203                (checkdoc-recursive-edit msg)
2204                (setq msg nil)
2205                (goto-char s)
2206                (beginning-of-line)))))
2207      ;; Check for, and potentially remove whitespace appearing at the
2208      ;; end of different lines.
2209      (progn
2210        (goto-char start)
2211        ;; There is no documentation in the Emacs Lisp manual about this check,
2212        ;; it is intended to help clean up messy code and reduce the file size.
2213        (while (and (not msg) (re-search-forward "[^ \t\n;]\\([ \t]+\\)$" end t))
2214          ;; This is not a complex activity
2215          (if (checkdoc-autofix-ask-replace
2216               (match-beginning 1) (match-end 1)
2217               "White space at end of line.  Remove? " "")
2218              nil
2219            (setq msg "White space found at end of line"
2220                  s (match-beginning 1) e (match-end 1))))))
2221     ;; Return an error and leave the cursor at that spot, or restore
2222     ;; the cursor.
2223     (if msg
2224         (checkdoc-create-error msg s e f)
2225       (goto-char p)
2226       nil)))
2227
2228 ;;; Comment checking engine
2229 ;;
2230 (eval-when-compile
2231   ;; We must load this to:
2232   ;; a) get symbols for compile and
2233   ;; b) determine if we have lm-history symbol which doesn't always exist
2234   (require 'lisp-mnt))
2235
2236 (defun checkdoc-file-comments-engine ()
2237   "Return a message list if this file does not match the Emacs standard.
2238 This checks for style only, such as the first line, Commentary:,
2239 Code:, and others referenced in the style guide."
2240   (if (featurep 'lisp-mnt)
2241       nil
2242     (require 'lisp-mnt)
2243     ;; Old XEmacs don't have `lm-commentary-mark'
2244     (if (and (not (fboundp 'lm-commentary-mark)) (boundp 'lm-commentary))
2245         (defalias 'lm-commentary-mark 'lm-commentary)))
2246   (save-excursion
2247     (let* ((f1 (file-name-nondirectory (buffer-file-name)))
2248            (fn (file-name-sans-extension f1))
2249            (fe (substring f1 (length fn)))
2250            (err nil))
2251       (goto-char (point-min))
2252       ;; This file has been set up where ERR is a variable.  Each check is
2253       ;; asked, and the function will make sure that if the user does not
2254       ;; auto-fix some error, that we still move on to the next auto-fix,
2255       ;; AND we remember the past errors.
2256       (setq
2257        err
2258        ;; Lisp Maintenance checks first
2259        ;; Was: (lm-verify) -> not flexible enough for some people
2260        ;; * Summary at the beginning of the file:
2261        (if (not (lm-summary))
2262            ;; This certifies as very complex so always ask unless
2263            ;; it's set to never
2264            (if (checkdoc-y-or-n-p "There is no first line summary!  Add one? ")
2265                (progn
2266                  (goto-char (point-min))
2267                  (insert ";;; " fn fe " --- " (read-string "Summary: ") "\n"))
2268              (checkdoc-create-error
2269               "The first line should be of the form: \";;; package --- Summary\""
2270               (point-min) (save-excursion (goto-char (point-min)) (end-of-line)
2271                                           (point))))
2272          nil))
2273       (setq
2274        err
2275        (or
2276         ;; * Commentary Section
2277         (if (not (lm-commentary-mark))
2278             (progn
2279               (goto-char (point-min))
2280               (cond
2281                ((re-search-forward
2282                  "write\\s-+to\\s-+the\\s-+Free Software Foundation, Inc."
2283                  nil t)
2284                 (re-search-forward "^;;\\s-*\n\\|^\n" nil t))
2285                ((or (re-search-forward "^;;; History" nil t)
2286                     (re-search-forward "^;;; Code" nil t)
2287                     (re-search-forward "^(require" nil t)
2288                     (re-search-forward "^("))
2289                 (beginning-of-line)))
2290               (if (checkdoc-y-or-n-p
2291                    "You should have a \";;; Commentary:\", add one? ")
2292                   (insert "\n;;; Commentary:\n;; \n\n")
2293                 (checkdoc-create-error
2294                  "You should have a section marked \";;; Commentary:\""
2295                  nil nil t)))
2296           nil)
2297         err))
2298       (setq
2299        err
2300        (or
2301         ;; * History section.  Say nothing if there is a file ChangeLog
2302         (if (or (not checkdoc-force-history-flag)
2303                 (file-exists-p "ChangeLog")
2304                 (file-exists-p "../ChangeLog")
2305                 (and (boundp 'change-log-default-name)
2306                      (file-exists-p change-log-default-name))
2307                 (let ((fn 'lm-history-mark)) ;bestill byte-compiler
2308                   (and (fboundp fn) (funcall fn))))
2309             nil
2310           (progn
2311             (goto-char (or (lm-commentary-mark) (point-min)))
2312             (cond
2313              ((re-search-forward
2314                "write\\s-+to\\s-+the\\s-+Free Software Foundation, Inc."
2315                nil t)
2316               (re-search-forward "^;;\\s-*\n\\|^\n" nil t))
2317              ((or (re-search-forward "^;;; Code" nil t)
2318                   (re-search-forward "^(require" nil t)
2319                   (re-search-forward "^("))
2320               (beginning-of-line)))
2321             (if (checkdoc-y-or-n-p
2322                  "You should have a \";;; History:\", add one? ")
2323                 (insert "\n;;; History:\n;; \n\n")
2324               (checkdoc-create-error
2325                "You should have a section marked \";;; History:\" or use a ChangeLog"
2326                (point) nil))))
2327         err))
2328       (setq
2329        err
2330        (or
2331         ;; * Code section
2332         (if (not (lm-code-mark))
2333             (let ((cont t))
2334               (goto-char (point-min))
2335               (while (and cont (re-search-forward "^(" nil t))
2336                 (setq cont (looking-at "require\\s-+")))
2337               (if (and (not cont)
2338                        (checkdoc-y-or-n-p
2339                         "There is no ;;; Code: marker.  Insert one? "))
2340                   (progn (beginning-of-line)
2341                          (insert ";;; Code:\n")
2342                          nil)
2343                 (checkdoc-create-error
2344                  "You should have a section marked \";;; Code:\""
2345                  (point) nil)))
2346           nil)
2347         err))
2348       (setq
2349        err
2350        (or
2351         ;; * A footer.  Not compartmentalized from lm-verify: too bad.
2352         ;;              The following is partially clipped from lm-verify
2353         (save-excursion
2354           (goto-char (point-max))
2355           (if (not (re-search-backward
2356                     (concat "^;;;[ \t]+" fn "\\(" (regexp-quote fe)
2357                             "\\)?[ \t]+ends here[ \t]*$"
2358                             "\\|^;;;[ \t]+ End of file[ \t]+"
2359                             fn "\\(" (regexp-quote fe) "\\)?")
2360                     nil t))
2361               (if (checkdoc-y-or-n-p "No identifiable footer!  Add one? ")
2362                   (progn
2363                     (goto-char (point-max))
2364                     (insert "\n(provide '" fn ")\n\n;;; " fn fe " ends here\n"))
2365                 (checkdoc-create-error
2366                  (format "The footer should be: (provide '%s)\\n;;; %s%s ends here"
2367                          fn fn fe)
2368                  (1- (point-max)) (point-max)))))
2369         err))
2370       ;; The below checks will not return errors if the user says NO
2371       
2372       ;; Ok, now let's look for multiple occurrences of ;;;, and offer
2373       ;; to remove the extra ";" if applicable.  This pre-supposes
2374       ;; that the user has semiautomatic fixing on to be useful.
2375       
2376       ;; In the info node (elisp)Library Headers a header is three ;
2377       ;; (the header) followed by text of only two ;
2378       ;; In (elisp)Comment Tips, however it says this:
2379       ;; * Another use for triple-semicolon comments is for commenting out
2380       ;;   lines within a function.  We use triple-semicolons for this
2381       ;;   precisely so that they remain at the left margin.
2382       (let ((msg nil))
2383         (goto-char (point-min))
2384         (while (and checkdoc-triple-semi-comment-check-flag
2385                     (not msg) (re-search-forward "^;;;[^;]" nil t))
2386           ;; We found a triple, let's check all following lines.
2387           (if (not (bolp)) (progn (beginning-of-line) (forward-line 1)))
2388           (let ((complex-replace t)
2389                 (dont-replace nil))
2390             (while (looking-at ";;\\(;\\)[^;#]")
2391               (if (and (not dont-replace)
2392                        (checkdoc-outside-major-sexp) ;in code is ok.
2393                        (checkdoc-autofix-ask-replace
2394                         (match-beginning 1) (match-end 1)
2395                         "Multiple occurrences of ;;; found.  Use ;; instead? "
2396                         "" complex-replace))
2397                   ;; Learn that, yea, the user did want to do this a
2398                   ;; whole bunch of times.
2399                   (setq complex-replace nil)
2400                 ;; In this case, skip all this crap
2401                 (setq dont-replace t))
2402               (beginning-of-line)
2403               (forward-line 1)))))
2404
2405       ;; Let's spellcheck the commentary section.  This is the only
2406       ;; section that is easy to pick out, and it is also the most
2407       ;; visible section (with the finder).
2408       (let ((cm (lm-commentary-mark)))
2409         (if cm
2410             (save-excursion
2411               (goto-char (lm-commentary-mark))
2412               ;; Spellcheck between the commentary, and the first
2413               ;; non-comment line.  We could use lm-commentary, but that
2414               ;; returns a string, and Ispell wants to talk to a buffer.
2415               ;; Since the comments talk about Lisp, use the specialized
2416               ;; spell-checker we also used for doc strings.
2417               (let ((e (save-excursion (re-search-forward "^[^;]" nil t)
2418                                        (point))))
2419                 (checkdoc-sentencespace-region-engine (point) e)
2420                 (checkdoc-proper-noun-region-engine (point) e)
2421                 (checkdoc-ispell-docstring-engine e)))))
2422 ;;; test comment out code
2423 ;;;       (foo 1 3)
2424 ;;;       (bar 5 7)
2425       (setq
2426        err
2427        (or
2428         ;; Generic Full-file checks (should be comment related)
2429         (checkdoc-run-hooks 'checkdoc-comment-style-hooks)
2430         err))
2431       ;; Done with full file comment checks
2432       err)))
2433
2434 (defun checkdoc-outside-major-sexp ()
2435   "Return t if point is outside the bounds of a valid sexp."
2436   (save-match-data
2437     (save-excursion
2438       (let ((p (point)))
2439         (or (progn (beginning-of-defun) (bobp))
2440             (progn (end-of-defun) (< (point) p)))))))
2441
2442 ;;; `error' and `message' text verifier.
2443 ;;
2444 (defun checkdoc-message-text-search (&optional beg end)
2445   "Search between BEG and END for a style error with message text.
2446 Optional arguments BEG and END represent the boundary of the check.
2447 The default boundary is the entire buffer."
2448   (let ((e nil)
2449         (type nil))
2450     (if (not (or beg end)) (setq beg (point-min) end (point-max)))
2451     (goto-char beg)
2452     (while (setq type (checkdoc-message-text-next-string end))
2453       (setq e (checkdoc-message-text-engine type)))
2454     e))
2455   
2456 (defun checkdoc-message-text-next-string (end)
2457   "Move cursor to the next checkable message string after point.
2458 Return the message classification.
2459 Argument END is the maximum bounds to search in."
2460   (let ((return nil))
2461     (while (and (not return)
2462                 (re-search-forward
2463                  "(\\s-*\\(\\(\\w\\|\\s_\\)*error\\|\
2464 \\(\\w\\|\\s_\\)*y-or-n-p\\(-with-timeout\\)?\
2465 \\|checkdoc-autofix-ask-replace\\)[ \t\n]+" end t))
2466       (let* ((fn (match-string 1))
2467              (type (cond ((string-match "error" fn)
2468                           'error)
2469                          (t 'y-or-n-p))))
2470         (if (string-match "checkdoc-autofix-ask-replace" fn)
2471             (progn (forward-sexp 2)
2472                    (skip-chars-forward " \t\n")))
2473         (if (and (eq type 'y-or-n-p)
2474                  (looking-at "(format[ \t\n]+"))
2475             (goto-char (match-end 0)))
2476         (skip-chars-forward " \t\n")
2477         (if (not (looking-at "\""))
2478             nil
2479           (setq return type))))
2480     return))
2481
2482 (defun checkdoc-message-text-engine (&optional type)
2483   "Return or fix errors found in strings passed to a message display function.
2484 According to the documentation for the function `error', the error list
2485 should not end with a period, and should start with a capital letter.
2486 The function `y-or-n-p' has similar constraints.
2487 Argument TYPE specifies the type of question, such as `error or `y-or-n-p."
2488   ;; If type is nil, then attempt to derive it.
2489   (if (not type)
2490       (save-excursion
2491         (up-list -1)
2492         (if (looking-at "(format")
2493             (up-list -1))
2494         (setq type
2495               (cond ((looking-at "(error")
2496                      'error)
2497                     (t 'y-or-n-p)))))
2498   (let ((case-fold-search nil))
2499     (or
2500      ;; From the documentation of the symbol `error':
2501      ;; In Emacs, the convention is that error messages start with a capital
2502      ;; letter but *do not* end with a period.  Please follow this convention
2503      ;; for the sake of consistency.
2504      (if (and (save-excursion (forward-char 1)
2505                               (looking-at "[a-z]\\w+"))
2506               (not (checkdoc-autofix-ask-replace
2507                     (match-beginning 0) (match-end 0)
2508                     "Capitalize your message text? "
2509                     (capitalize (match-string 0))
2510                     t)))
2511          (checkdoc-create-error
2512           "Messages should start with a capital letter"
2513           (match-beginning 0) (match-end 0))
2514        nil)
2515      ;; In general, sentences should have two spaces after the period.
2516      (checkdoc-sentencespace-region-engine (point)
2517                                            (save-excursion (forward-sexp 1)
2518                                                            (point)))
2519      ;; Look for proper nouns in this region too.
2520      (checkdoc-proper-noun-region-engine (point)
2521                                          (save-excursion (forward-sexp 1)
2522                                                          (point)))
2523      ;; Here are message type specific questions.
2524      (if (and (eq type 'error)
2525               (save-excursion (forward-sexp 1)
2526                               (forward-char -2)
2527                               (looking-at "\\."))
2528               (not (checkdoc-autofix-ask-replace (match-beginning 0)
2529                                                  (match-end 0)
2530                                                  "Remove period from error? "
2531                                                  ""
2532                                                  t)))
2533          (checkdoc-create-error
2534           "Error messages should *not* end with a period"
2535           (match-beginning 0) (match-end 0))
2536        nil)
2537      ;; `y-or-n-p' documentation explicitly says:
2538      ;; It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
2539      ;; I added the ? requirement.  Without it, it is unclear that we
2540      ;; ask a question and it appears to be an undocumented style.
2541      (if (eq type 'y-or-n-p)
2542          (if (not (save-excursion (forward-sexp 1)
2543                                   (forward-char -3)
2544                                   (not (looking-at "\\? "))))
2545              nil
2546            (if (save-excursion (forward-sexp 1)
2547                                (forward-char -2)
2548                                (looking-at "\\?"))
2549                ;; If we see a ?, then replace with "? ".
2550                (if (checkdoc-autofix-ask-replace
2551                     (match-beginning 0) (match-end 0)
2552                     "`y-or-n-p' argument should end with \"? \".  Fix? "
2553                     "? " t)
2554                    nil
2555                  (checkdoc-create-error
2556                   "`y-or-n-p' argument should end with \"? \""
2557                   (match-beginning 0) (match-end 0)))
2558              (if (save-excursion (forward-sexp 1)
2559                                  (forward-char -2)
2560                                  (looking-at " "))
2561                  (if (checkdoc-autofix-ask-replace
2562                       (match-beginning 0) (match-end 0)
2563                       "`y-or-n-p' argument should end with \"? \".  Fix? "
2564                       "? " t)
2565                      nil
2566                    (checkdoc-create-error
2567                     "`y-or-n-p' argument should end with \"? \""
2568                     (match-beginning 0) (match-end 0)))
2569                (if (and ;; if this isn't true, we have a problem.
2570                     (save-excursion (forward-sexp 1)
2571                                     (forward-char -1)
2572                                     (looking-at "\""))
2573                     (checkdoc-autofix-ask-replace
2574                      (match-beginning 0) (match-end 0)
2575                      "`y-or-n-p' argument should end with \"? \".  Fix? "
2576                      "? \"" t))
2577                    nil
2578                  (checkdoc-create-error
2579                   "`y-or-n-p' argument should end with \"? \""
2580                   (match-beginning 0) (match-end 0)))))))
2581      ;; Now, let's just run the spell checker on this guy.
2582      (checkdoc-ispell-docstring-engine (save-excursion (forward-sexp 1)
2583                                                        (point)))
2584      )))
2585
2586 ;;; Auto-fix helper functions
2587 ;;
2588 (defun checkdoc-y-or-n-p (question)
2589   "Like `y-or-n-p', but pays attention to `checkdoc-autofix-flag'.
2590 Argument QUESTION is the prompt passed to `y-or-n-p'."
2591   (prog1
2592       (if (or (not checkdoc-autofix-flag)
2593               (eq checkdoc-autofix-flag 'never))
2594           nil
2595         (y-or-n-p question))
2596     (if (eq checkdoc-autofix-flag 'automatic-then-never)
2597         (setq checkdoc-autofix-flag 'never))))
2598
2599 (defun checkdoc-autofix-ask-replace (start end question replacewith
2600                                            &optional complex)
2601   "Highlight between START and END and queries the user with QUESTION.
2602 If the user says yes, or if `checkdoc-autofix-flag' permits, replace
2603 the region marked by START and END with REPLACEWITH.  If optional flag
2604 COMPLEX is non-nil, then we may ask the user a question.  See the
2605 documentation for `checkdoc-autofix-flag' for details.
2606
2607 If a section is auto-replaced without asking the user, this function
2608 will pause near the fixed code so the user will briefly see what
2609 happened.
2610
2611 This function returns non-nil if the text was replaced.
2612
2613 This function will not modify `match-data'."
2614   (if (and checkdoc-autofix-flag
2615            (not (eq checkdoc-autofix-flag 'never)))
2616       (let ((o (checkdoc-make-overlay start end))
2617             (ret nil)
2618             (md (match-data)))
2619         (unwind-protect
2620             (progn
2621               (checkdoc-overlay-put o 'face 'highlight)
2622               (if (or (eq checkdoc-autofix-flag 'automatic)
2623                       (eq checkdoc-autofix-flag 'automatic-then-never)
2624                       (and (eq checkdoc-autofix-flag 'semiautomatic)
2625                            (not complex))
2626                       (and (or (eq checkdoc-autofix-flag 'query) complex)
2627                            (y-or-n-p question)))
2628                   (save-excursion
2629                     (goto-char start)
2630                     ;; On the off chance this is automatic, display
2631                     ;; the question anyway so the user knows what's
2632                     ;; going on.
2633                     (if checkdoc-bouncy-flag (message "%s -> done" question))
2634                     (delete-region start end)
2635                     (insert replacewith)
2636                     (if checkdoc-bouncy-flag (sit-for 0))
2637                     (setq ret t)))
2638               (checkdoc-delete-overlay o)
2639               (set-match-data md))
2640           (checkdoc-delete-overlay o)
2641           (set-match-data md))
2642         (if (eq checkdoc-autofix-flag 'automatic-then-never)
2643             (setq checkdoc-autofix-flag 'never))
2644         ret)))
2645
2646 ;;; Warning management
2647 ;;
2648 (defvar checkdoc-output-font-lock-keywords
2649   '(("\\(\\w+\\.el\\): \\(\\w+\\)"
2650      (1 font-lock-function-name-face)
2651      (2 font-lock-comment-face))
2652     ("^\\(\\w+\\.el\\):" 1 font-lock-function-name-face)
2653     (":\\([0-9]+\\):" 1 font-lock-constant-face))
2654   "Keywords used to highlight a checkdoc diagnostic buffer.")
2655
2656 (defvar checkdoc-output-mode-map nil
2657   "Keymap used in `checkdoc-output-mode'.")
2658
2659 (defvar checkdoc-pending-errors nil
2660   "Non-nil when there are errors that have not been displayed yet.")
2661
2662 (if checkdoc-output-mode-map
2663     nil
2664   (setq checkdoc-output-mode-map (make-sparse-keymap))
2665   (if (not checkdoc-xemacs-p)
2666       (define-key checkdoc-output-mode-map [mouse-2]
2667         'checkdoc-find-error-mouse))
2668   (define-key checkdoc-output-mode-map "\C-c\C-c" 'checkdoc-find-error)
2669   (define-key checkdoc-output-mode-map "\C-m" 'checkdoc-find-error))
2670
2671 (defun checkdoc-output-mode ()
2672   "Create and setup the buffer used to maintain checkdoc warnings.
2673 \\<checkdoc-output-mode-map>\\[checkdoc-find-error]  - Go to this error location
2674 \\[checkdoc-find-error-mouse] - Goto the error clicked on."
2675   (if (get-buffer checkdoc-diagnostic-buffer)
2676       (get-buffer checkdoc-diagnostic-buffer)
2677     (save-excursion
2678       (set-buffer (get-buffer-create checkdoc-diagnostic-buffer))
2679       (kill-all-local-variables)
2680       (setq mode-name "Checkdoc"
2681             major-mode 'checkdoc-output-mode)
2682       (set (make-local-variable 'font-lock-defaults)
2683            '((checkdoc-output-font-lock-keywords) t t ((?- . "w") (?_ . "w"))))
2684       (use-local-map checkdoc-output-mode-map)
2685       (run-hooks 'checkdoc-output-mode-hook)
2686       (current-buffer))))
2687
2688 (defun checkdoc-find-error-mouse (e)
2689   ;; checkdoc-params: (e)
2690   "Call `checkdoc-find-error' where the user clicks the mouse."
2691   (interactive "e")
2692   (mouse-set-point e)
2693   (checkdoc-find-error))
2694
2695 (defun checkdoc-find-error ()
2696   "In a checkdoc diagnostic buffer, find the error under point."
2697   (interactive)
2698   (beginning-of-line)
2699   (if (looking-at "#<buffer \\(\\(\\w+\\|\\s_\\)+\\.el\\)>:\\([0-9]+\\):")
2700       (let ((l (string-to-int (match-string 3)))
2701             (f (match-string 1)))
2702         (if (not (get-buffer f))
2703             (error "Can't find buffer %s" f))
2704         (switch-to-buffer-other-window (get-buffer f))
2705         (goto-line l))))
2706
2707 (defun checkdoc-buffer-label ()
2708   "The name to use for a checkdoc buffer in the error list."
2709   (if (buffer-file-name)
2710       (file-name-nondirectory (buffer-file-name))
2711     (concat "#<buffer "(buffer-name) ">")))
2712
2713 (defun checkdoc-start-section (check-type)
2714   "Initialize the checkdoc diagnostic buffer for a pass.
2715 Create the header so that the string CHECK-TYPE is displayed as the
2716 function called to create the messages."
2717   (checkdoc-output-to-error-buffer
2718    "\n\n\C-l\n*** "
2719    (checkdoc-buffer-label) ": " check-type " V " checkdoc-version))
2720
2721 (defun checkdoc-error (point msg)
2722   "Store POINT and MSG as errors in the checkdoc diagnostic buffer."
2723   (setq checkdoc-pending-errors t)
2724   (checkdoc-output-to-error-buffer
2725    "\n" (checkdoc-buffer-label) ":"
2726    (int-to-string (count-lines (point-min) (or point 1))) ": "
2727    msg))
2728
2729 (defun checkdoc-output-to-error-buffer (&rest text)
2730   "Place TEXT into the checkdoc diagnostic buffer."
2731   (save-excursion
2732     (set-buffer (checkdoc-output-mode))
2733     (goto-char (point-max))
2734     (apply 'insert text)))
2735
2736 (defun checkdoc-show-diagnostics ()
2737   "Display the checkdoc diagnostic buffer in a temporary window."
2738   (if checkdoc-pending-errors
2739       (let ((b (get-buffer checkdoc-diagnostic-buffer)))
2740         (if b (progn (pop-to-buffer b)
2741                      (goto-char (point-max))
2742                      (re-search-backward "\C-l" nil t)
2743                      (beginning-of-line)
2744                      (forward-line 1)
2745                      (recenter 0)))
2746         (other-window -1)
2747         (setq checkdoc-pending-errors nil)
2748         nil)))
2749
2750 (defgroup checkdoc nil
2751   "Support for doc string checking in Emacs Lisp."
2752   :prefix "checkdoc"
2753   :group 'lisp
2754 ;  :version "20.3"
2755   )
2756
2757 (custom-add-option 'emacs-lisp-mode-hook
2758                    (lambda () (checkdoc-minor-mode 1)))
2759
2760 (provide 'checkdoc)
2761
2762 ;;; checkdoc.el ends here