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