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