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