checkdoc.el 70.8 KB
Newer Older
Karl Heuer's avatar
Karl Heuer committed
1 2
;;; checkdoc --- Check documentation strings for style requirements

3
;;;  Copyright (C) 1997, 1998  Free Software Foundation
Eric M. Ludlam's avatar
Eric M. Ludlam committed
4

5
;; Author: Eric M. Ludlam <zappo@gnu.org>
6
;; Version: 0.5.1
Karl Heuer's avatar
Karl Heuer committed
7
;; Keywords: docs, maint, lisp
Eric M. Ludlam's avatar
Eric M. Ludlam committed
8

Karl Heuer's avatar
Karl Heuer committed
9
;; This file is part of GNU Emacs.
Eric M. Ludlam's avatar
Eric M. Ludlam committed
10

Karl Heuer's avatar
Karl Heuer committed
11 12 13 14
;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
Eric M. Ludlam's avatar
Eric M. Ludlam committed
15

Karl Heuer's avatar
Karl Heuer committed
16 17 18 19
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
Eric M. Ludlam's avatar
Eric M. Ludlam committed
20

Karl Heuer's avatar
Karl Heuer committed
21 22 23 24 25 26 27
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
28
;;   The Emacs Lisp manual has a nice chapter on how to write
Karl Heuer's avatar
Karl Heuer committed
29 30 31 32 33 34 35 36 37
;; documentation strings.  Many stylistic suggestions are fairly
;; deterministic and easy to check for syntactically, but also easy
;; to forget.  The main checkdoc engine will perform the stylistic
;; checks needed to make sure these styles are remembered.
;;
;; There are two ways to use checkdoc:
;;   1) Periodically use `checkdoc'. `checkdoc-current-buffer' and
;;      `checkdoc-defun' to check your documentation.
;;   2) Use `checkdoc-minor-mode' to automatically check your
Richard M. Stallman's avatar
Richard M. Stallman committed
38
;;      documentation whenever you evaluate Lisp code with C-M-x
Karl Heuer's avatar
Karl Heuer committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
;;      or [menu-bar emacs-lisp eval-buffer].  Additional key-bindings
;;      are also provided under C-c ? KEY
;;        (require 'checkdoc)
;;        (add-hook 'emacs-lisp-mode-hook
;;	             '(lambda () (checkdoc-minor-mode 1)))
;;
;; Auto-fixing:
;;
;;   There are four classifications of style errors in terms of how
;; easy they are to fix.  They are simple, complex, really complex,
;; and impossible.  (Impossible really means that checkdoc does not
;; have a fixing routine yet.)  Typically white-space errors are
;; classified as simple, and are auto-fixed by default.  Typographic
;; changes are considered complex, and the user is asked if they want
;; the problem fixed before checkdoc makes the change.  These changes
;; can be done without asking if `checkdoc-autofix-flag' is properly
;; set.  Potentially redundant changes are considered really complex,
;; and the user is always asked before a change is inserted.  The
;; variable `checkdoc-autofix-flag' controls how these types of errors
;; are fixed.
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
60
;; Spell checking doc strings:
Karl Heuer's avatar
Karl Heuer committed
61 62 63 64 65 66 67 68 69 70 71
;;
;;   The variable `checkdoc-spellcheck-documentation-flag' can be set
;; to customize how spell checking is to be done.  Since spell
;; checking can be quite slow, you can optimize how best you want your
;; checking done.  The default is 'defun, which spell checks each time
;; `checkdoc-defun' or `checkdoc-eval-defun' is used.  Setting to nil
;; prevents spell checking during normal usage.
;;   Setting this variable to nil does not mean you cannot take
;; advantage of the spell checking.  You can instead use the
;; interactive functions `checkdoc-ispell-*' to check the spelling of
;; your documentation.
Richard M. Stallman's avatar
Richard M. Stallman committed
72 73
;;   There is a list of Lisp-specific words which checkdoc will
;; install into Ispell on the fly, but only if Ispell is not already
Karl Heuer's avatar
Karl Heuer committed
74 75 76
;; running.  Use `ispell-kill-ispell' to make checkdoc restart it with
;; these words enabled.
;;
77 78
;; Checking parameters
;;
Karl Heuer's avatar
Karl Heuer committed
79
;;   You might not always want a function to have its parameters listed
80 81 82 83 84 85 86 87 88 89
;; in order.  When this is the case, put the following comment just in
;; front of the documentation string: "; checkdoc-order: nil"  This
;; overrides the value of `checkdoc-arguments-in-order-flag'.
;;
;;   If you specifically wish to avoid mentioning a parameter of a
;; function in the doc string (such as a hidden parameter, or a
;; parameter which is very obvious like events), you can have checkdoc
;; skip looking for it by putting the following comment just in front
;; of the documentation string: "; checkdoc-params: (args go here)"
;;
90 91 92 93 94 95 96 97
;; Checking message strings
;;
;;   The text that follows the `error', and `y-or-n-p' commands is
;; also checked.  The documentation for `error' clearly states some
;; simple style rules to follow which checkdoc will auto-fix for you.
;; `y-or-n-p' also states that it should end in a space.  I added that
;; it should end in "? " since that is almost always used.
;;
Karl Heuer's avatar
Karl Heuer committed
98 99 100 101 102 103 104
;; Adding your own checks:
;;
;;   You can experiment with adding your own checks by setting the
;; hooks `checkdoc-style-hooks' and `checkdoc-comment-style-hooks'.
;; Return a string which is the error you wish to report.  The cursor
;; position should be preserved.
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
105
;; This file requires lisp-mnt (Lisp maintenance routines) for the
Karl Heuer's avatar
Karl Heuer committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119
;; comment checkers.

;;; TO DO:
;;   Hook into the byte compiler on a defun/defver level to generate
;;     warnings in the byte-compiler's warning/error buffer.
;;   Better ways to override more typical `eval' functions.  Advice
;;     might be good but hard to turn on/off as a minor mode.
;;
;;; Maybe Do:
;;   Code sweep checks for "forbidden functions", proper use of hooks,
;;     proper keybindings, and other items from the manual that are
;;     not specifically docstring related.  Would this even be useful?

;;; Code:
120
(defvar checkdoc-version "0.5.1"
Karl Heuer's avatar
Karl Heuer committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134
  "Release version of checkdoc you are currently running.")

;; From custom web page for compatibility between versions of custom:
(eval-and-compile
  (condition-case ()
      (require 'custom)
    (error nil))
  (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
      nil ;; We've got what we needed
    ;; We have the old custom-library, hack around it!
    (defmacro defgroup (&rest args)
      nil)
    (defmacro custom-add-option (&rest args)
      nil)
135
    (defmacro defcustom (var value doc &rest args)
Karl Heuer's avatar
Karl Heuer committed
136 137 138
      (` (defvar (, var) (, value) (, doc))))))

(defcustom checkdoc-autofix-flag 'semiautomatic
Richard M. Stallman's avatar
Richard M. Stallman committed
139 140 141
  "*Non-nil means attempt auto-fixing of doc strings.
If this value is the symbol `query', then the user is queried before
any change is made.  If the value is `automatic', then all changes are
Karl Heuer's avatar
Karl Heuer committed
142
made without asking unless the change is very-complex.  If the value
Richard M. Stallman's avatar
Richard M. Stallman committed
143
is `semiautomatic', or any other value, then simple fixes are made
Karl Heuer's avatar
Karl Heuer committed
144
without asking, and complex changes are made by asking the user first.
Richard M. Stallman's avatar
Richard M. Stallman committed
145
The value `never' is the same as nil, never ask or change anything."
Karl Heuer's avatar
Karl Heuer committed
146 147 148
  :group 'checkdoc
  :type '(choice (const automatic)
		 (const query)
149 150
		 (const never)
		 (other :tag "semiautomatic" semiautomatic)))
Karl Heuer's avatar
Karl Heuer committed
151 152

(defcustom checkdoc-bouncy-flag t
Richard M. Stallman's avatar
Richard M. Stallman committed
153
  "*Non-nil means to \"bounce\" to auto-fix locations.
Karl Heuer's avatar
Karl Heuer committed
154 155 156 157 158 159 160 161 162
Setting this to nil will silently make fixes that require no user
interaction.  See `checkdoc-autofix-flag' for auto-fixing details."
  :group 'checkdoc
  :type 'boolean)

(defcustom checkdoc-force-docstrings-flag t
  "*Non-nil means that all checkable definitions should have documentation.
Style guide dictates that interactive functions MUST have documentation,
and that its good but not required practice to make non user visible items
Richard M. Stallman's avatar
Richard M. Stallman committed
163
have doc strings."
Karl Heuer's avatar
Karl Heuer committed
164 165 166 167 168
  :group 'checkdoc
  :type 'boolean)

(defcustom checkdoc-tripple-semi-comment-check-flag t
  "*Non-nil means to check for multiple adjacent occurrences of ;;; comments.
Richard M. Stallman's avatar
Richard M. Stallman committed
169
According to the style of Emacs code in the Lisp libraries, a block
Karl Heuer's avatar
Karl Heuer committed
170 171 172 173 174 175
comment can look like this:
;;; Title
;;  text
;;  text
But when inside a function, code can be commented out using the ;;;
construct for all lines.  When this variable is nil, the ;;; construct
Karl Heuer's avatar
Karl Heuer committed
176
is ignored regardless of its location in the code."
Karl Heuer's avatar
Karl Heuer committed
177 178 179 180
  :group 'checkdoc
  :type 'boolean)

(defcustom checkdoc-spellcheck-documentation-flag nil
Richard M. Stallman's avatar
Richard M. Stallman committed
181 182
  "*Non-nil means run Ispell on doc strings based on value.
This is automatically set to nil if Ispell does not exist on your
Karl Heuer's avatar
Karl Heuer committed
183 184
system.  Possible values are:

Richard M. Stallman's avatar
Richard M. Stallman committed
185 186 187 188 189
  nil         - Don't spell-check during basic style checks.
  defun       - Spell-check when style checking a single defun
  buffer      - Spell-check only when style checking the whole buffer
  interactive - Spell-check only during `checkdoc-interactive'
  t           - Always spell-check"
Karl Heuer's avatar
Karl Heuer committed
190 191 192 193 194 195 196 197
  :group 'checkdoc
  :type '(choice (const nil)
		 (const defun)
		 (const buffer)
		 (const interactive)
		 (const t)))

(defvar checkdoc-ispell-lisp-words
Richard M. Stallman's avatar
Richard M. Stallman committed
198 199
  '("alist" "etags" "iff" "keymap" "paren" "regexp" "sexp" "emacs" "xemacs")
  "List of words that are correct when spell-checking Lisp documentation.")
Karl Heuer's avatar
Karl Heuer committed
200 201

(defcustom checkdoc-max-keyref-before-warn 10
Richard M. Stallman's avatar
Richard M. Stallman committed
202
  "*The number of \\ [command-to-keystroke] tokens allowed in a doc string.
Karl Heuer's avatar
Karl Heuer committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
Any more than this and a warning is generated suggesting that the construct
\\ {keymap} be used instead."
  :group 'checkdoc
  :type 'integer)

(defcustom checkdoc-arguments-in-order-flag t
  "*Non-nil means warn if arguments appear out of order.
Setting this to nil will mean only checking that all the arguments
appear in the proper form in the documentation, not that they are in
the same order as they appear in the argument list.  No mention is
made in the style guide relating to order."
  :group 'checkdoc
  :type 'boolean)

(defvar checkdoc-style-hooks nil
  "Hooks called after the standard style check is completed.
All hooks must return nil or a string representing the error found.
Useful for adding new user implemented commands.

Each hook is called with two parameters, (DEFUNINFO ENDPOINT).
DEFUNINFO is the return value of `checkdoc-defun-info'.  ENDPOINT is the
location of end of the documentation string.")

(defvar checkdoc-comment-style-hooks nil
  "Hooks called after the standard comment style check is completed.
Must return nil if no errors are found, or a string describing the
problem discovered.  This is useful for adding additional checks.")

(defvar checkdoc-diagnostic-buffer "*Style Warnings*"
232
  "Name of warning message buffer.")
Karl Heuer's avatar
Karl Heuer committed
233 234 235 236 237 238 239 240

(defvar checkdoc-defun-regexp
  "^(def\\(un\\|var\\|custom\\|macro\\|const\\|subst\\|advice\\)\
\\s-+\\(\\(\\sw\\|\\s_\\)+\\)[ \t\n]+"
  "Regular expression used to identify a defun.
A search leaves the cursor in front of the parameter list.")

(defcustom checkdoc-verb-check-experimental-flag t
Richard M. Stallman's avatar
Richard M. Stallman committed
241
  "*Non-nil means to attempt to check the voice of the doc string.
Karl Heuer's avatar
Karl Heuer committed
242
This check keys off some words which are commonly misused.  See the
Richard M. Stallman's avatar
Richard M. Stallman committed
243
variable `checkdoc-common-verbs-wrong-voice' if you wish to add your own."
Karl Heuer's avatar
Karl Heuer committed
244 245 246 247 248 249 250 251 252 253
  :group 'checkdoc
  :type 'boolean)

(defvar checkdoc-common-verbs-regexp nil
  "Regular expression derived from `checkdoc-common-verbs-regexp'.")

(defvar checkdoc-common-verbs-wrong-voice
  '(("adds" . "add")
    ("allows" . "allow")
    ("appends" . "append")
Karl Heuer's avatar
Karl Heuer committed
254 255
    ("applies" . "apply")
    ("arranges" . "arrange")
Karl Heuer's avatar
Karl Heuer committed
256 257 258 259 260 261 262 263 264 265
    ("brings" . "bring")
    ("calls" . "call")
    ("catches" . "catch")
    ("changes" . "change")
    ("checks" . "check")
    ("contains" . "contain")
    ("creates" . "create")
    ("destroys" . "destroy")
    ("disables" . "disable")
    ("executes" . "execute")
Karl Heuer's avatar
Karl Heuer committed
266
    ("evals" . "evaluate")
Karl Heuer's avatar
Karl Heuer committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    ("evaluates" . "evaluate")
    ("finds" . "find")
    ("forces" . "force")
    ("gathers" . "gather")
    ("generates" . "generate")
    ("goes" . "go")
    ("guesses" . "guess")
    ("highlights" . "highlight")
    ("holds" . "hold")
    ("ignores" . "ignore")
    ("indents" . "indent")
    ("initializes" . "initialize")
    ("inserts" . "insert")
    ("installs" . "install")
    ("investigates" . "investigate")
    ("keeps" . "keep")
    ("kills" . "kill")
    ("leaves" . "leave")
    ("lets" . "let")
    ("loads" . "load")
    ("looks" . "look")
    ("makes" . "make")
    ("marks" . "mark")
    ("matches" . "match")
    ("notifies" . "notify")
    ("offers" . "offer")
    ("parses" . "parse")
    ("performs" . "perform")
    ("prepares" . "prepare")
    ("prepends" . "prepend")
    ("reads" . "read")
    ("raises" . "raise")
    ("removes" . "remove")
    ("replaces" . "replace")
    ("resets" . "reset")
    ("restores" . "restore")
    ("returns" . "return")
    ("runs" . "run")
    ("saves" . "save")
    ("says" . "say")
    ("searches" . "search")
    ("selects" . "select")
    ("sets" . "set")
    ("sex" . "s*x")
    ("shows" . "show")
    ("signifies" . "signify")
    ("sorts" . "sort")
    ("starts" . "start")
    ("stores" . "store")
    ("switches" . "switch")
    ("tells" . "tell")
    ("tests" . "test")
    ("toggles" . "toggle")
Karl Heuer's avatar
Karl Heuer committed
320
    ("tries" . "try")
Karl Heuer's avatar
Karl Heuer committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    ("turns" . "turn")
    ("undoes" . "undo")
    ("unloads" . "unload")
    ("unmarks" . "unmark")
    ("updates" . "update")
    ("uses" . "use")
    ("yanks" . "yank")
    )
  "Alist of common words in the wrong voice and what should be used instead.
Set `checkdoc-verb-check-experimental-flag' to nil to avoid this costly
and experimental check.  Do not modify this list without setting
the value of `checkdoc-common-verbs-regexp' to nil which cause it to
be re-created.")

(defvar checkdoc-syntax-table nil
  "Syntax table used by checkdoc in document strings.")

(if checkdoc-syntax-table
    nil
  (setq checkdoc-syntax-table (copy-syntax-table emacs-lisp-mode-syntax-table))
Richard M. Stallman's avatar
Richard M. Stallman committed
341
  ;; When dealing with syntax in doc strings, make sure that - are encompased
Karl Heuer's avatar
Karl Heuer committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  ;; in words so we can use cheap \\> to get the end of a symbol, not the
  ;; end of a word in a conglomerate.
  (modify-syntax-entry ?- "w" checkdoc-syntax-table)
  )
	

;;; Compatibility
;;
(if (string-match "X[Ee]macs" emacs-version)
    (progn
      (defalias 'checkdoc-make-overlay 'make-extent)
      (defalias 'checkdoc-overlay-put 'set-extent-property)
      (defalias 'checkdoc-delete-overlay 'delete-extent)
      (defalias 'checkdoc-overlay-start 'extent-start)
      (defalias 'checkdoc-overlay-end 'extent-end)
      (defalias 'checkdoc-mode-line-update 'redraw-modeline)
      (defalias 'checkdoc-call-eval-buffer 'eval-buffer)
      )
  (defalias 'checkdoc-make-overlay 'make-overlay)
  (defalias 'checkdoc-overlay-put 'overlay-put)
  (defalias 'checkdoc-delete-overlay 'delete-overlay)
  (defalias 'checkdoc-overlay-start 'overlay-start)
  (defalias 'checkdoc-overlay-end 'overlay-end)
  (defalias 'checkdoc-mode-line-update 'force-mode-line-update)
  (defalias 'checkdoc-call-eval-buffer 'eval-current-buffer)
  )

;; Emacs 20s have MULE characters which dont equate to numbers.
(if (fboundp 'char=)
    (defalias 'checkdoc-char= 'char=)
  (defalias 'checkdoc-char= '=))

;; Emacs 19.28 and earlier don't have the handy 'add-to-list function
(if (fboundp 'add-to-list)

    (defalias 'checkdoc-add-to-list 'add-to-list)

  (defun checkdoc-add-to-list (list-var element)
    "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet."
    (if (not (member element (symbol-value list-var)))
	(set list-var (cons element (symbol-value list-var)))))
  )

Richard M. Stallman's avatar
Richard M. Stallman committed
385
;; To be safe in new Emacsen, we want to read events, not characters
Karl Heuer's avatar
Karl Heuer committed
386 387 388 389 390 391 392 393 394 395
(if (fboundp 'read-event)
    (defalias 'checkdoc-read-event 'read-event)
  (defalias 'checkdoc-read-event 'read-char))

;;; User level commands
;;
;;;###autoload
(defun checkdoc-eval-current-buffer ()
  "Evaluate and check documentation for the current buffer.
Evaluation is done first because good documentation for something that
Richard M. Stallman's avatar
Richard M. Stallman committed
396
doesn't work is just not useful.  Comments, doc strings, and rogue
Karl Heuer's avatar
Karl Heuer committed
397 398 399 400 401 402 403
spacing are all verified."
  (interactive)
  (checkdoc-call-eval-buffer nil)
  (checkdoc-current-buffer t))

;;;###autoload
(defun checkdoc-current-buffer (&optional take-notes)
404
  "Check current buffer for document, comment, error style, and rogue spaces.
Richard M. Stallman's avatar
Richard M. Stallman committed
405 406 407
With a prefix argument (in Lisp, the argument TAKE-NOTES),
store all errors found in a warnings buffer,
otherwise stop after the first error."
Karl Heuer's avatar
Karl Heuer committed
408 409 410 411 412 413 414 415 416
  (interactive "P")
  (if (interactive-p) (message "Checking buffer for style..."))
  ;; Assign a flag to spellcheck flag
  (let ((checkdoc-spellcheck-documentation-flag
	 (memq checkdoc-spellcheck-documentation-flag '(buffer t))))
    ;; every test is responsible for returning the cursor.
    (or (and buffer-file-name ;; only check comments in a file
	     (checkdoc-comments take-notes))
	(checkdoc take-notes)
417
	(checkdoc-message-text take-notes)
Karl Heuer's avatar
Karl Heuer committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
	(checkdoc-rogue-spaces take-notes)
	(not (interactive-p))
	(message "Checking buffer for style...Done."))))

;;;###autoload
(defun checkdoc-interactive (&optional start-here)
  "Interactively check the current buffers for errors.
Prefix argument START-HERE will start the checking from the current
point, otherwise the check starts at the beginning of the current
buffer.  Allows navigation forward and backwards through document
errors.  Does not check for comment or space warnings."
  (interactive "P")
  ;; Determine where to start the test
  (let* ((begin (prog1 (point)
		  (if (not start-here) (goto-char (point-min)))))
	 ;; Assign a flag to spellcheck flag
	 (checkdoc-spellcheck-documentation-flag
	  (member checkdoc-spellcheck-documentation-flag
		  '(buffer interactive t)))
	 ;; Fetch the error list
	 (err-list (list (checkdoc-next-error))))
    (if (not (car err-list)) (setq err-list nil))
    ;; Include whatever function point is in for good measure.
    (beginning-of-defun)
    (while err-list
      (goto-char (cdr (car err-list)))
Richard M. Stallman's avatar
Richard M. Stallman committed
444
      ;; The cursor should be just in front of the offending doc string
Karl Heuer's avatar
Karl Heuer committed
445 446 447 448 449 450 451 452
      (let ((cdo (save-excursion
		   (checkdoc-make-overlay (point)
					  (progn (forward-sexp 1)
						 (point)))))
	    c)
	(unwind-protect
	    (progn
	      (checkdoc-overlay-put cdo 'face 'highlight)
Richard M. Stallman's avatar
Richard M. Stallman committed
453
	      ;; Make sure the whole doc string is visible if possible.
Karl Heuer's avatar
Karl Heuer committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
	      (sit-for 0)
	      (if (not (pos-visible-in-window-p
			(save-excursion (forward-sexp 1) (point))
			(selected-window)))
		  (recenter))
	      (message "%s(? e n p q)" (car (car err-list)))
	      (setq c (checkdoc-read-event))
	      (if (not (integerp c)) (setq c ??))
	      (cond ((or (checkdoc-char= c ?n) (checkdoc-char= c ?\ ))
		     (let ((ne (checkdoc-next-error)))
		       (if (not ne)
			   (progn
			     (message "No More Stylistic Errors.")
			     (sit-for 2))
			 (setq err-list (cons ne err-list)))))
		    ((or (checkdoc-char= c ?p) (checkdoc-char= c ?\C-?))
		     (if (/= (length err-list) 1)
			 (progn
			   (setq err-list (cdr err-list))
			   ;; This will just re-ask fixup questions if
			   ;; it was skipped the last time.
			   (checkdoc-next-error))
		       (message "No Previous Errors.")
		       (sit-for 2)))
		    ((checkdoc-char= c ?e)
		     (message "Edit the docstring, and press C-M-c to exit.")
		     (recursive-edit)
		     (checkdoc-delete-overlay cdo)
		     (setq err-list (cdr err-list)) ;back up the error found.
		     (beginning-of-defun)
		     (let ((ne (checkdoc-next-error)))
		       (if (not ne)
			   (progn
			     (message "No More Stylistic Errors.")
			     (sit-for 2))
			 (setq err-list (cons ne err-list)))))
		    ((checkdoc-char= c ?q)
		     (setq err-list nil
			   begin (point)))
		    (t
		     (message "[E]dit [SPC|n] next error [DEL|p] prev error\
 [q]uit [?] help: ")
		     (sit-for 5))))
	  (checkdoc-delete-overlay cdo))))
    (goto-char begin)
    (message "Checkdoc: Done.")))

(defun checkdoc-next-error ()
  "Find and return the next checkdoc error list, or nil.
Add error vector is of the form (WARNING . POSITION) where WARNING
is the warning text, and POSITION is the point in the buffer where the
error was found.  We can use points and not markers because we promise
not to edit the buffer before point without re-executing this check."
  (let ((msg nil) (p (point)))
    (condition-case nil
	(while (and (not msg) (checkdoc-next-docstring))
Richard M. Stallman's avatar
Richard M. Stallman committed
510
	  (message "Searching for doc string error...%d%%"
Karl Heuer's avatar
Karl Heuer committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
		   (/ (* 100 (point)) (point-max)))
	  (if (setq msg (checkdoc-this-string-valid))
	      (setq msg (cons msg (point)))))
      ;; Quit.. restore position,  Other errors, leave alone
      (quit (goto-char p)))
    msg))

;;;###autoload
(defun checkdoc (&optional take-notes)
  "Use `checkdoc-continue' starting at the beginning of the current buffer.
Prefix argument TAKE-NOTES means to collect all the warning messages into
a separate buffer."
  (interactive "P")
  (let ((p (point)))
    (goto-char (point-min))
    (checkdoc-continue take-notes)
    ;; Go back since we can't be here without success above.
    (goto-char p)
    nil))

;;;###autoload
(defun checkdoc-continue (&optional take-notes)
Richard M. Stallman's avatar
Richard M. Stallman committed
533
  "Find the next docstring in the current buffer which is stylisticly poor.
Karl Heuer's avatar
Karl Heuer committed
534
Prefix argument TAKE-NOTES means to continue through the whole buffer and
Karl Heuer's avatar
Karl Heuer committed
535
save warnings in a separate buffer."
Karl Heuer's avatar
Karl Heuer committed
536 537 538 539 540 541 542 543 544 545 546
  (interactive "P")
  (let ((wrong nil) (msg nil) (errors nil)
	;; Assign a flag to spellcheck flag
	(checkdoc-spellcheck-documentation-flag
	 (member checkdoc-spellcheck-documentation-flag
		 '(buffer t))))
    (save-excursion
      ;; If we are taking notes, encompass the whole buffer, otherwise
      ;; the user is navigating down through the buffer.
      (if take-notes (checkdoc-start-section "checkdoc"))
      (while (and (not wrong) (checkdoc-next-docstring))
Richard M. Stallman's avatar
Richard M. Stallman committed
547
	;; OK, lets look at the doc string.
Eric M. Ludlam's avatar
Eric M. Ludlam committed
548 549 550 551 552 553 554 555
	(setq msg (checkdoc-this-string-valid))
	(if msg
	    ;; Oops
	    (if take-notes
		(progn
		  (checkdoc-error (point) msg)
		  (setq errors t))
	      (setq wrong (point))))))
Karl Heuer's avatar
Karl Heuer committed
556 557 558 559 560 561 562 563 564 565
    (if wrong
	(progn
	  (goto-char wrong)
	  (error msg)))
    (if (and take-notes errors)
	(checkdoc-show-diagnostics)
      (if (interactive-p)
	  (message "No style warnings.")))))

(defun checkdoc-next-docstring ()
Richard M. Stallman's avatar
Richard M. Stallman committed
566 567
  "Move to the next doc string after point, and return t.
Return nil if there are no more doc strings."
Karl Heuer's avatar
Karl Heuer committed
568 569 570 571 572 573 574 575 576 577
  (if (not (re-search-forward checkdoc-defun-regexp nil t))
      nil
    ;; search drops us after the identifier.  The next sexp is either
    ;; the argument list or the value of the variable.  skip it.
    (forward-sexp 1)
    (skip-chars-forward " \n\t")
    t))

;;; ###autoload
(defun checkdoc-comments (&optional take-notes)
Richard M. Stallman's avatar
Richard M. Stallman committed
578
  "Find missing comment sections in the current Emacs Lisp file.
Karl Heuer's avatar
Karl Heuer committed
579 580 581 582 583 584
Prefix argument TAKE-NOTES non-nil means to save warnings in a
separate buffer.  Otherwise print a message.  This returns the error
if there is one."
  (interactive "P")
  (if take-notes (checkdoc-start-section "checkdoc-comments"))
  (if (not buffer-file-name)
585
     (error "Can only check comments for a file buffer"))
Karl Heuer's avatar
Karl Heuer committed
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
  (let* ((checkdoc-spellcheck-documentation-flag
	  (member checkdoc-spellcheck-documentation-flag
		  '(buffer t)))
	 (e (checkdoc-file-comments-engine)))
    (if e
	(if take-notes
	    (checkdoc-error nil e)
	  (error e)))
    (if (and e take-notes)
	(checkdoc-show-diagnostics))
    e))

;;;###autoload
(defun checkdoc-rogue-spaces (&optional take-notes)
  "Find extra spaces at the end of lines in the current file.
Prefix argument TAKE-NOTES non-nil means to save warnings in a
separate buffer.  Otherwise print a message.  This returns the error
if there is one."
  (interactive "P")
  (if take-notes (checkdoc-start-section "checkdoc-rogue-spaces"))
  (let ((e (checkdoc-rogue-space-check-engine)))
    (if e
	(if take-notes
	    (checkdoc-error nil e)
	  (message e)))
    (if (and e take-notes)
	(checkdoc-show-diagnostics))
    (if (not (interactive-p))
	e
      (if e (message e) (message "Space Check: done.")))))
      

;;;###autoload
(defun checkdoc-eval-defun ()
Karl Heuer's avatar
Karl Heuer committed
620
  "Evaluate the current form with `eval-defun' and check its documentation.
Karl Heuer's avatar
Karl Heuer committed
621 622 623 624 625 626 627 628 629
Evaluation is done first so the form will be read before the
documentation is checked.  If there is a documentation error, then the display
of what was evaluated will be overwritten by the diagnostic message."
  (interactive)
  (eval-defun nil)
  (checkdoc-defun))

;;;###autoload
(defun checkdoc-defun (&optional no-error)
Richard M. Stallman's avatar
Richard M. Stallman committed
630 631
  "Examine the doc string of the function or variable under point.
Call `error' if the doc string has problems.  If NO-ERROR is
Karl Heuer's avatar
Karl Heuer committed
632
non-nil, then do not call error, but call `message' instead.
Richard M. Stallman's avatar
Richard M. Stallman committed
633
If the doc string passes the test, then check the function for rogue white
Karl Heuer's avatar
Karl Heuer committed
634 635 636 637 638 639 640
space at the end of each line."
  (interactive)
  (save-excursion
    (beginning-of-defun)
    (if (not (looking-at checkdoc-defun-regexp))
	;; I found this more annoying than useful.
	;;(if (not no-error)
Richard M. Stallman's avatar
Richard M. Stallman committed
641
	;;    (message "Cannot check this sexp's docstring."))
Karl Heuer's avatar
Karl Heuer committed
642 643 644 645 646 647 648 649 650
	nil
      ;; search drops us after the identifier.  The next sexp is either
      ;; the argument list or the value of the variable.  skip it.
      (goto-char (match-end 0))
      (forward-sexp 1)
      (skip-chars-forward " \n\t")
      (let* ((checkdoc-spellcheck-documentation-flag
	      (member checkdoc-spellcheck-documentation-flag
		      '(defun t)))
651 652
	     (beg (save-excursion (beginning-of-defun) (point)))
	     (end (save-excursion (end-of-defun) (point)))
Karl Heuer's avatar
Karl Heuer committed
653 654
	     (msg (checkdoc-this-string-valid)))
	(if msg (if no-error (message msg) (error msg))
655
	  (setq msg (checkdoc-message-text-search beg end))
Karl Heuer's avatar
Karl Heuer committed
656
	  (if msg (if no-error (message msg) (error msg))
657 658 659
	    (setq msg (checkdoc-rogue-space-check-engine beg end))
	    (if msg (if no-error (message msg) (error msg)))))
	(if (interactive-p) (message "Checkdoc: done."))))))
Karl Heuer's avatar
Karl Heuer committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

;;; Ispell interface for forcing a spell check
;;

;;;###autoload
(defun checkdoc-ispell-current-buffer (&optional take-notes)
  "Check the style and spelling of the current buffer interactively.
Calls `checkdoc-current-buffer' with spell-checking turned on.
Prefix argument TAKE-NOTES is the same as for `checkdoc-current-buffer'"
  (interactive)
  (let ((checkdoc-spellcheck-documentation-flag t))
    (call-interactively 'checkdoc-current-buffer nil current-prefix-arg)))

;;;###autoload
(defun checkdoc-ispell-interactive (&optional take-notes)
  "Check the style and spelling of the current buffer interactively.
Calls `checkdoc-interactive' with spell-checking turned on.
Prefix argument TAKE-NOTES is the same as for `checkdoc-interacitve'"
  (interactive)
  (let ((checkdoc-spellcheck-documentation-flag t))
    (call-interactively 'checkdoc-interactive nil current-prefix-arg)))

;;;###autoload
(defun checkdoc-ispell (&optional take-notes)
  "Check the style and spelling of the current buffer.
Calls `checkdoc' with spell-checking turned on.
Prefix argument TAKE-NOTES is the same as for `checkdoc'"
  (interactive)
  (let ((checkdoc-spellcheck-documentation-flag t))
    (call-interactively 'checkdoc nil current-prefix-arg)))

;;;###autoload
(defun checkdoc-ispell-continue (&optional take-notes)
  "Check the style and spelling of the current buffer after point.
Calls `checkdoc-continue' with spell-checking turned on.
Prefix argument TAKE-NOTES is the same as for `checkdoc-continue'"
  (interactive)
  (let ((checkdoc-spellcheck-documentation-flag t))
    (call-interactively 'checkdoc-continue nil current-prefix-arg)))

;;;###autoload
(defun checkdoc-ispell-comments (&optional take-notes)
  "Check the style and spelling of the current buffer's comments.
Calls `checkdoc-comments' with spell-checking turned on.
Prefix argument TAKE-NOTES is the same as for `checkdoc-comments'"
  (interactive)
  (let ((checkdoc-spellcheck-documentation-flag t))
    (call-interactively 'checkdoc-comments nil current-prefix-arg)))

;;;###autoload
(defun checkdoc-ispell-defun (&optional take-notes)
Richard M. Stallman's avatar
Richard M. Stallman committed
711
  "Check the style and spelling of the current defun with Ispell.
Karl Heuer's avatar
Karl Heuer committed
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
Calls `checkdoc-defun' with spell-checking turned on.
Prefix argument TAKE-NOTES is the same as for `checkdoc-defun'"
  (interactive)
  (let ((checkdoc-spellcheck-documentation-flag t))
    (call-interactively 'checkdoc-defun nil current-prefix-arg)))

;;; Minor Mode specification
;;
(defvar checkdoc-minor-mode nil
  "Non-nil in `emacs-lisp-mode' for automatic documentation checking.")
(make-variable-buffer-local 'checkdoc-minor-mode)

(checkdoc-add-to-list 'minor-mode-alist '(checkdoc-minor-mode " CDoc"))

(defvar checkdoc-minor-keymap
  (let ((map (make-sparse-keymap))
	(pmap (make-sparse-keymap)))
    ;; Override some bindings
    (define-key map "\C-\M-x" 'checkdoc-eval-defun)
    (if (not (string-match "XEmacs" emacs-version))
	(define-key map [menu-bar emacs-lisp eval-buffer]
	  'checkdoc-eval-current-buffer))
    (define-key pmap "x" 'checkdoc-defun)
    (define-key pmap "X" 'checkdoc-ispell-defun)
    (define-key pmap "`" 'checkdoc-continue)
    (define-key pmap "~" 'checkdoc-ispell-continue)
    (define-key pmap "d" 'checkdoc)
    (define-key pmap "D" 'checkdoc-ispell)
    (define-key pmap "i" 'checkdoc-interactive)
    (define-key pmap "I" 'checkdoc-ispell-interactive)
    (define-key pmap "b" 'checkdoc-current-buffer)
    (define-key pmap "B" 'checkdoc-ispell-current-buffer)
    (define-key pmap "e" 'checkdoc-eval-current-buffer)
745
    (define-key pmap "m" 'checkdoc-message-text)
Karl Heuer's avatar
Karl Heuer committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
    (define-key pmap "c" 'checkdoc-comments)
    (define-key pmap "C" 'checkdoc-ispell-comments)
    (define-key pmap " " 'checkdoc-rogue-spaces)

    ;; bind our submap into map
    (define-key map "\C-c?" pmap)
    map)
  "Keymap used to override evaluation key-bindings for documentation checking.")

;; Add in a menubar with easy-menu

(if checkdoc-minor-keymap
    (easy-menu-define
     checkdoc-minor-menu checkdoc-minor-keymap "Checkdoc Minor Mode Menu"
     '("CheckDoc"
       ["First Style Error" checkdoc t]
       ["First Style or Spelling Error " checkdoc-ispell t]
       ["Next Style Error" checkdoc-continue t]
       ["Next Style or Spelling  Error" checkdoc-ispell-continue t]
       ["Interactive Style Check" checkdoc-interactive t]
       ["Interactive Style and Spelling Check" checkdoc-ispell-interactive t]
       ["Check Defun" checkdoc-defun t]
       ["Check and Spell Defun" checkdoc-ispell-defun t]
       ["Check and Evaluate Defun" checkdoc-eval-defun t]
       ["Check Buffer" checkdoc-current-buffer t]
       ["Check and Spell Buffer" checkdoc-ispell-current-buffer t]
       ["Check and Evaluate Buffer" checkdoc-eval-current-buffer t]
       ["Check Comment Style" checkdoc-comments buffer-file-name]
       ["Check Comment Style and Spelling" checkdoc-ispell-comments
	buffer-file-name]
776
       ["Check message text" checkdoc-message-text t]
Karl Heuer's avatar
Karl Heuer committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790
       ["Check for Rogue Spaces" checkdoc-rogue-spaces t]
       )))
;; XEmacs requires some weird stuff to add this menu in a minor mode.
;; What is it?

;; Allow re-insertion of a new keymap
(let ((a (assoc 'checkdoc-minor-mode minor-mode-map-alist)))
  (if a
      (setcdr a checkdoc-minor-keymap)
    (checkdoc-add-to-list 'minor-mode-map-alist (cons 'checkdoc-minor-mode
						      checkdoc-minor-keymap))))

;;;###autoload
(defun checkdoc-minor-mode (&optional arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
791 792
  "Toggle Checkdoc minor mode, a mode for checking Lisp doc strings.
With prefix ARG, turn Checkdoc minor mode on iff ARG is positive.
Karl Heuer's avatar
Karl Heuer committed
793

Richard M. Stallman's avatar
Richard M. Stallman committed
794
In Checkdoc minor mode, the usual bindings for `eval-defun' which is
Karl Heuer's avatar
Karl Heuer committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
bound to \\<checkdoc-minor-keymap> \\[checkdoc-eval-defun] and `checkdoc-eval-current-buffer' are overridden to include
checking of documentation strings.

\\{checkdoc-minor-keymap}"
  (interactive "P")
  (setq checkdoc-minor-mode
	(not (or (and (null arg) checkdoc-minor-mode)
		 (<= (prefix-numeric-value arg) 0))))
  (checkdoc-mode-line-update))

;;; Subst utils
;;
(defsubst checkdoc-run-hooks (hookvar &rest args)
  "Run hooks in HOOKVAR with ARGS."
  (if (fboundp 'run-hook-with-args-until-success)
      (apply 'run-hook-with-args-until-success hookvar args)
    ;; This method was similar to above.  We ignore the warning
Richard M. Stallman's avatar
Richard M. Stallman committed
812
    ;; since we will use the above for future Emacs versions
Karl Heuer's avatar
Karl Heuer committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    (apply 'run-hook-with-args hookvar args)))

(defsubst checkdoc-create-common-verbs-regexp ()
  "Rebuild the contents of `checkdoc-common-verbs-regexp'."
  (or checkdoc-common-verbs-regexp
      (setq checkdoc-common-verbs-regexp
	    (concat "\\<\\("
		    (mapconcat (lambda (e) (concat (car e)))
			       checkdoc-common-verbs-wrong-voice "\\|")
		    "\\)\\>"))))

;; Profiler says this is not yet faster than just calling assoc
;;(defun checkdoc-word-in-alist-vector (word vector)
;;  "Check to see if WORD is in the car of an element of VECTOR.
;;VECTOR must be sorted.  The CDR should be a replacement.  Since the
;;word list is getting bigger, it is time for a quick bisecting search."
;;  (let ((max (length vector)) (min 0) i
;;	(found nil) (fw nil))
;;    (setq i (/ max 2))
;;    (while (and (not found) (/= min max))
;;      (setq fw (car (aref vector i)))
;;      (cond ((string= word fw) (setq found (cdr (aref vector i))))
;;	    ((string< word fw) (setq max i))
;;	    (t (setq min i)))
;;      (setq i (/ (+ max min) 2))
;;      )
;;    found))

;;; Checking engines
;;
(defun checkdoc-this-string-valid ()
Richard M. Stallman's avatar
Richard M. Stallman committed
844
  "Return a message string if the current doc string is invalid.
Karl Heuer's avatar
Karl Heuer committed
845 846 847 848 849
Check for style only, such as the first line always being a complete
sentence, whitespace restrictions, and making sure there are no
hard-coded key-codes such as C-[char] or mouse-[number] in the comment.
See the style guide in the Emacs Lisp manual for more details."

Richard M. Stallman's avatar
Richard M. Stallman committed
850
  ;; Jump over comments between the last object and the doc string
Karl Heuer's avatar
Karl Heuer committed
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
  (while (looking-at "[ \t\n]*;")
    (forward-line 1)
    (beginning-of-line)
    (skip-chars-forward " \n\t"))

  (if (not (looking-at "[ \t\n]*\""))
      nil
    (let ((old-syntax-table (syntax-table)))
      (unwind-protect
	  (progn
	    (set-syntax-table checkdoc-syntax-table)
	    (checkdoc-this-string-valid-engine))
	(set-syntax-table old-syntax-table)))))

(defun checkdoc-this-string-valid-engine ()
Richard M. Stallman's avatar
Richard M. Stallman committed
866
  "Return a message string if the current doc string is invalid.
Karl Heuer's avatar
Karl Heuer committed
867 868 869 870 871
Depends on `checkdoc-this-string-valid' to reset the syntax table so that
regexp short cuts work."
  (let ((case-fold-search nil)
	;; Use a marker so if an early check modifies the text,
	;; we won't accidentally loose our place.  This could cause
Richard M. Stallman's avatar
Richard M. Stallman committed
872
	;; end-of doc string whitespace to also delete the " char.
Karl Heuer's avatar
Karl Heuer committed
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
	(e (save-excursion (forward-sexp 1) (point-marker)))
	(fp (checkdoc-defun-info)))
    (or
     ;; * *Do not* indent subsequent lines of a documentation string so that
     ;;   the text is lined up in the source code with the text of the first
     ;;   line.  This looks nice in the source code, but looks bizarre when
     ;;   users view the documentation.  Remember that the indentation
     ;;   before the starting double-quote is not part of the string!
     (save-excursion
       (forward-line 1)
       (beginning-of-line)
       (if (and (< (point) e)
		(looking-at "\\([ \t]+\\)[^ \t\n]"))
	   (if (checkdoc-autofix-ask-replace (match-beginning 1)
					     (match-end 1)
888
					     "Remove this whitespace? "
Karl Heuer's avatar
Karl Heuer committed
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
					     "")
	       nil
	     "Second line should not have indentation")))
     ;; * Do not start or end a documentation string with whitespace.
     (let (start end)
       (if (or (if (looking-at "\"\\([ \t\n]+\\)")
		   (setq start (match-beginning 1)
			 end (match-end 1)))
	       (save-excursion
		 (forward-sexp 1)
		 (forward-char -1)
		 (if (/= (skip-chars-backward " \t\n") 0)
		     (setq start (point)
			   end (1- e)))))
	   (if (checkdoc-autofix-ask-replace
904
		start end "Remove this whitespace? " "")
Karl Heuer's avatar
Karl Heuer committed
905 906 907 908 909 910 911 912 913 914 915 916
	       nil
	     "Documentation strings should not start or end with whitespace")))
     ;; * Every command, function, or variable intended for users to know
     ;;   about should have a documentation string.
     ;;
     ;; * An internal variable or subroutine of a Lisp program might as well
     ;;   have a documentation string.  In earlier Emacs versions, you could
     ;;   save space by using a comment instead of a documentation string,
     ;;   but that is no longer the case.
     (if (and (not (nth 1 fp))		; not a variable
	      (or (nth 2 fp)		; is interactive
		  checkdoc-force-docstrings-flag) ;or we always complain
Richard M. Stallman's avatar
Richard M. Stallman committed
917
	      (not (checkdoc-char= (following-char) ?\"))) ; no doc string
Karl Heuer's avatar
Karl Heuer committed
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
	 (if (nth 2 fp)
	     "All interactive functions should have documentation"
	   "All variables and subroutines might as well have a \
documentation string"))
     ;; * The first line of the documentation string should consist of one
     ;;   or two complete sentences that stand on their own as a summary.
     ;;   `M-x apropos' displays just the first line, and if it doesn't
     ;;   stand on its own, the result looks bad.  In particular, start the
     ;;   first line with a capital letter and end with a period.
     (save-excursion
       (end-of-line)
       (skip-chars-backward " \t\n")
       (if (> (point) e) (goto-char e)) ;of the form (defun n () "doc" nil)
       (forward-char -1)
       (cond
	((and (checkdoc-char= (following-char) ?\")
	      ;; A backslashed double quote at the end of a sentence
	      (not (checkdoc-char= (preceding-char) ?\\)))
	 ;; We might have to add a period in this case
	 (forward-char -1)
	 (if (looking-at "[.!]")
	     nil
	   (forward-char 1)
	   (if (checkdoc-autofix-ask-replace
942
		(point) (1+ (point)) "Add period to sentence? "
Karl Heuer's avatar
Karl Heuer committed
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
		".\"" t)
	       nil
	     "First sentence should end with punctuation.")))
	((looking-at "[\\!;:.)]")
	 ;; These are ok
	 nil)
	(t
	 ;; If it is not a complete sentence, lets see if we can
	 ;; predict a clever way to make it one.
	 (let ((msg "First line is not a complete sentence")
	       (e (point)))
	   (beginning-of-line)
	   (if (re-search-forward "\\. +" e t)
	       ;; Here we have found a complete sentence, but no break.
	       (if (checkdoc-autofix-ask-replace
		    (1+ (match-beginning 0)) (match-end 0)
959
		    "First line not a complete sentence.  Add RET here? "
Karl Heuer's avatar
Karl Heuer committed
960 961 962 963 964 965 966 967 968 969
		    "\n" t)
		   (let (l1 l2)
		     (forward-line 1)
		     (end-of-line)
		     (setq l1 (current-column)
			   l2 (save-excursion
				(forward-line 1)
				(end-of-line)
				(current-column)))
		     (if (> (+ l1 l2 1) 80)
Richard M. Stallman's avatar
Richard M. Stallman committed
970
			 (setq msg "Incomplete auto-fix; doc string \
971
may require more formatting")
Karl Heuer's avatar
Karl Heuer committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
		       ;; We can merge these lines!  Replace this CR
		       ;; with a space.
		       (delete-char 1) (insert " ")
		       (setq msg nil))))
	     ;; Lets see if there is enough room to draw the next
	     ;; line's sentence up here.  I often get hit w/
	     ;; auto-fill moving my words around.
	     (let ((numc (progn (end-of-line) (- 80 (current-column))))
		   (p    (point)))
	       (forward-line 1)
	       (beginning-of-line)
	       (if (and (re-search-forward "[.!:\"][ \n\"]" (save-excursion
							      (end-of-line)
							      (point))
					   t)
			(< (current-column) numc))
		   (if (checkdoc-autofix-ask-replace
			p (1+ p)
Richard M. Stallman's avatar
Richard M. Stallman committed
990
			"1st line not a complete sentence.  Join these lines? "
Karl Heuer's avatar
Karl Heuer committed
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
			" " t)
		       (progn
			 ;; They said yes.  We have more fill work to do...
			 (delete-char 1)
			 (insert "\n")
			 (setq msg nil))))))
	   msg))))
     ;; Continuation of above.  Make sure our sentence is capitalized.
     (save-excursion
       (skip-chars-forward "\"\\*")
       (if (looking-at "[a-z]")
	   (if (checkdoc-autofix-ask-replace
		(match-beginning 0) (match-end 0)
1004
		"Capitalize your sentence? " (upcase (match-string 0))
Karl Heuer's avatar
Karl Heuer committed
1005 1006
		t)
	       nil
1007
	     "First line should be capitalized")
Karl Heuer's avatar
Karl Heuer committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	 nil))
     ;; * For consistency, phrase the verb in the first sentence of a
     ;;   documentation string as an infinitive with "to" omitted.  For
     ;;   instance, use "Return the cons of A and B." in preference to
     ;;   "Returns the cons of A and B."  Usually it looks good to do
     ;;   likewise for the rest of the first paragraph.  Subsequent
     ;;   paragraphs usually look better if they have proper subjects.
     ;;
     ;; For our purposes, just check to first sentence.  A more robust
     ;; grammar checker would be preferred for the rest of the
     ;; documentation string.
     (and checkdoc-verb-check-experimental-flag
	  (save-excursion
	    ;; Maybe rebuild the monster-regex
	    (checkdoc-create-common-verbs-regexp)
	    (let ((lim (save-excursion
			 (end-of-line)
			 ;; check string-continuation
			 (if (checkdoc-char= (preceding-char) ?\\)
			     (progn (forward-line 1)
				    (end-of-line)))
			 (point)))
		  (rs nil) replace original (case-fold-search t))
	      (while (and (not rs)
			  (re-search-forward checkdoc-common-verbs-regexp
					     lim t))
		(setq original (buffer-substring-no-properties
				(match-beginning 1) (match-end 1))
		      rs (assoc (downcase original)
				checkdoc-common-verbs-wrong-voice))
1038
		(if (not rs) (error "Verb voice alist corrupted"))
Karl Heuer's avatar
Karl Heuer committed
1039 1040 1041 1042 1043 1044 1045
		(setq replace (let ((case-fold-search nil))
				(save-match-data
				  (if (string-match "^[A-Z]" original)
				      (capitalize (cdr rs))
				    (cdr rs)))))
		(if (checkdoc-autofix-ask-replace
		     (match-beginning 1) (match-end 1)
1046
		     (format "Wrong voice for verb `%s'.  Replace with `%s'? "
Karl Heuer's avatar
Karl Heuer committed
1047 1048 1049 1050 1051 1052
			     original replace)
		     replace t)
		    (setq rs nil)))
	      (if rs
		  ;; there was a match, but no replace
		  (format
1053
		   "Incorrect voice in sentence.  Use `%s' instead of `%s'"
Karl Heuer's avatar
Karl Heuer committed
1054 1055 1056 1057 1058
		   replace original)))))
     ;;   * Don't write key sequences directly in documentation strings.
     ;;     Instead, use the `\\[...]' construct to stand for them.
     (save-excursion
       (let ((f nil) (m nil) (start (point))
Eric M. Ludlam's avatar
Eric M. Ludlam committed
1059
	     (re "[^`A-Za-z0-9_]\\([CMA]-[a-zA-Z]\\|\\(\\([CMA]-\\)?\
Karl Heuer's avatar
Karl Heuer committed
1060 1061 1062 1063 1064 1065 1066
mouse-[0-3]\\)\\)\\>"))
	 ;; Find the first key sequence not in a sample
	 (while (and (not f) (setq m (re-search-forward re e t)))
	   (setq f (not (checkdoc-in-sample-code-p start e))))
	 (if m
	     (concat
	      "Keycode " (match-string 1)
Richard M. Stallman's avatar
Richard M. Stallman committed
1067
	      " embedded in doc string.  Use \\\\<keymap> & \\\\[function] "
Karl Heuer's avatar
Karl Heuer committed
1068 1069 1070 1071 1072 1073 1074 1075 1076
	      "instead"))))
     ;; It is not practical to use `\\[...]' very many times, because
     ;; display of the documentation string will become slow.  So use this
     ;; to describe the most important commands in your major mode, and
     ;; then use `\\{...}' to display the rest of the mode's keymap.
     (save-excursion
       (if (re-search-forward "\\\\\\\\\\[\\w+" e t
			      (1+ checkdoc-max-keyref-before-warn))
	   "Too many occurrences of \\[function].  Use \\{keymap} instead"))
Richard M. Stallman's avatar
Richard M. Stallman committed
1077
     ;; Ambiguous quoted symbol.  When a symbol is both bound and fbound,
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
     ;; and is referred to in documentation, it should be prefixed with
     ;; something to disambiguate it.  This check must be before the
     ;; 80 column check because it will probably break that.
     (save-excursion
       (let ((case-fold-search t)
	     (ret nil))
	 (while (and
		 (re-search-forward
		  "\\(\\<\\(variable\\|option\\|function\\|command\\|symbol\\)\
\\s-+\\)?`\\(\\sw\\(\\sw\\|\\s_\\)+\\)'" e t)
		 (not ret))
	   (let ((sym (intern-soft (match-string 3)))
		 (mb (match-beginning 3)))
	     (if (and sym (boundp sym) (fboundp sym) (not (match-string 1)))
		 (if (checkdoc-autofix-ask-replace
		      mb (match-end 3) "Prefix this ambiguous symbol? "
		      (match-string 3) t)
		     ;; We didn't actuall replace anything.  Here we find
		     ;; out what special word form they wish to use as
		     ;; a prefix.
		     (let ((disambiguate
			    (completing-read
			     "Disambiguating Keyword (default: variable): "
			     '(("function") ("command") ("variable")
			       ("option") ("symbol"))
			     nil t nil nil "variable")))
		       (goto-char (1- mb))
		       (insert disambiguate " ")
		       (forward-word 1))
		   (setq ret
			 (format "Disambiguate %s by preceeding w/ \
function,command,variable,option or symbol." (match-string 3)))))))
	 ret))
Karl Heuer's avatar
Karl Heuer committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
     ;; * Format the documentation string so that it fits in an
     ;;   Emacs window on an 80-column screen.  It is a good idea
     ;;   for most lines to be no wider than 60 characters.  The
     ;;   first line can be wider if necessary to fit the
     ;;   information that ought to be there.
     (save-excursion
       (let ((start (point)))
	 (while (and (< (point) e)
		     (or (progn (end-of-line) (< (current-column) 80))
			 (progn (beginning-of-line)
				(re-search-forward "\\\\\\\\[[<{]"
						   (save-excursion
						     (end-of-line)
						     (point)) t))
			 (checkdoc-in-sample-code-p start e)))
	   (forward-line 1))
	 (end-of-line)
	 (if (and (< (point) e) (> (current-column) 80))
	     "Some lines are over 80 columns wide")))
     ;;* When a documentation string refers to a Lisp symbol, write it as
     ;;  it would be printed (which usually means in lower case), with
     ;;  single-quotes around it.  For example: `lambda'.  There are two
     ;;  exceptions: write t and nil without single-quotes.  (In this
     ;;  manual, we normally do use single-quotes for those symbols.)
     (save-excursion
       (let ((found nil) (start (point)) (msg nil) (ms nil))
	 (while (and (not msg)
		     (re-search-forward
		      "[^([`':]\\(\\w\+[:-]\\(\\w\\|\\s_\\)+\\)[^]']"
		      e t))
	   (setq ms (match-string 1))
	   (save-match-data
	     ;; A . is a \s_ char, so we must remove periods from
	     ;; sentences more carefully.
	     (if (string-match "\\.$" ms)
		 (setq ms (substring ms 0 (1- (length ms))))))
	   (if (and (not (checkdoc-in-sample-code-p start e))
		    (setq found (intern-soft ms))
		    (or (boundp found) (fboundp found)))
	       (progn
Richard M. Stallman's avatar
Richard M. Stallman committed
1151
		 (setq msg (format "Add quotes around Lisp symbol `%s'? "
Karl Heuer's avatar
Karl Heuer committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
				   ms))
		 (if (checkdoc-autofix-ask-replace
		      (match-beginning 1) (+ (match-beginning 1)
					     (length ms))
		      msg (concat "`" ms "'") t)
		     (setq msg nil)))))
	 msg))
     ;; t and nil case
     (save-excursion
       (if (re-search-forward "\\(`\\(t\\|nil\\)'\\)" e t)
	   (if (checkdoc-autofix-ask-replace
		(match-beginning 1) (match-end 1)
Richard M. Stallman's avatar
Richard M. Stallman committed
1164
		(format "%s should not appear in quotes.  Remove? "
Karl Heuer's avatar
Karl Heuer committed
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
			(match-string 2))
		(match-string 2) t)
	       nil
	     "Symbols t and nil should not appear in `quotes'")))
     ;; Here we deviate to tests based on a variable or function.
     (cond ((eq (nth 1 fp) t)
	    ;; This is if we are in a variable
	    (or
	     ;; * The documentation string for a variable that is a
	     ;;   yes-or-no flag should start with words such as "Non-nil
	     ;;   means...", to make it clear that all non-`nil' values are
	     ;;   equivalent and indicate explicitly what `nil' and non-`nil'
	     ;;   mean.
	     ;; * If a user option variable records a true-or-false
	     ;;   condition, give it a name that ends in `-flag'.

	     ;; If the variable has -flag in the name, make sure
	     (if (and (string-match "-flag$" (car fp))
		      (not (looking-at "\"\\*?Non-nil\\s-+means\\s-+")))
Richard M. Stallman's avatar
Richard M. Stallman committed
1184 1185
		 "Flag variable doc strings should start: Non-nil means")
	     ;; If the doc string starts with "Non-nil means"
Karl Heuer's avatar
Karl Heuer committed
1186 1187
	     (if (and (looking-at "\"\\*?Non-nil\\s-+means\\s-+")
		      (not (string-match "-flag$" (car fp))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1188
		 "Flag variables should end in `-flag'")
Karl Heuer's avatar
Karl Heuer committed
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	     ;; Done with variables
	     ))
	   (t
	    ;; This if we are in a function definition
	    (or
	     ;; * When a function's documentation string mentions the value
	     ;;   of an argument of the function, use the argument name in
	     ;;   capital letters as if it were a name for that value.  Thus,
	     ;;   the documentation string of the function `/' refers to its
	     ;;   second argument as `DIVISOR', because the actual argument
	     ;;   name is `divisor'.

	     ;;   Addendum:  Make sure they appear in the doc in the same
	     ;;              order that they are found in the arg list.
	     (let ((args (cdr (cdr (cdr (cdr fp)))))
		   (last-pos 0)
		   (found 1)
		   (order (and (nth 3 fp) (car (nth 3 fp))))
1207 1208
		   (nocheck (append '("&optional" "&rest") (nth 3 fp)))
		   (inopts nil))
Karl Heuer's avatar
Karl Heuer committed
1209 1210
	       (while (and args found (> found last-pos))
		 (if (member (car args) nocheck)
1211 1212
		     (setq args (cdr args)
			   inopts t)
Karl Heuer's avatar
Karl Heuer committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
		   (setq last-pos found
			 found (save-excursion
				 (re-search-forward
				  (concat "\\<" (upcase (car args))
					  ;; Require whitespace OR
					  ;; ITEMth<space> OR
					  ;; ITEMs<space>
					  "\\(\\>\\|th\\>\\|s\\>\\)")
				  e t)))
		   (if (not found)
		       (let ((case-fold-search t))
			 ;; If the symbol was not found, lets see if we
			 ;; can find it with a different capitalization
			 ;; and see if the user wants to capitalize it.
			 (if (save-excursion
			       (re-search-forward
				  (concat "\\<\\(" (car args)
					  ;; Require whitespace OR
					  ;; ITEMth<space> OR
					  ;; ITEMs<space>
					  "\\)\\(\\>\\|th\\>\\|s\\>\\)")
				  e t))
			     (if (checkdoc-autofix-ask-replace
				  (match-beginning 1) (match-end 1)
				  (format
Richard M. Stallman's avatar
Richard M. Stallman committed
1238
				   "Argument `%s' should appear as `%s'.  Fix? "
Karl Heuer's avatar
Karl Heuer committed
1239 1240 1241 1242 1243
				   (car args) (upcase (car args)))
				  (upcase (car args)) t)
				 (setq found (match-beginning 1))))))
		   (if found (setq args (cdr args)))))
	       (if (not found)
1244 1245 1246
		   ;; It wasn't found at all!  Offer to attach this new symbol
		   ;; to the end of the documentation string.
		   (if (y-or-n-p
Richard M. Stallman's avatar
Richard M. Stallman committed
1247
			(format "Add %s documentation to end of doc string?"
1248
				(upcase (car args))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1249
		       ;; Now do some magic and invent a doc string.
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
		       (save-excursion
			 (goto-char e) (forward-char -1)
			 (insert "\n"
				 (if inopts "Optional a" "A")
				 "rgument " (upcase (car args))
				 " ")
			 (insert (read-string "Describe: "))
			 (if (not (save-excursion (forward-char -1)
						  (looking-at "[.?!]")))
			     (insert "."))
			 nil)
		     (format
Richard M. Stallman's avatar
Richard M. Stallman committed
1262
		      "Argument `%s' should appear as `%s' in the doc string"
1263
		      (car args) (upcase (car args))))
Karl Heuer's avatar
Karl Heuer committed
1264 1265 1266
		 (if (or (and order (eq order 'yes))
			 (and (not order) checkdoc-arguments-in-order-flag))
		     (if (< found last-pos)
Richard M. Stallman's avatar
Richard M. Stallman committed
1267
			 "Arguments occur in the doc string out of order"))))
Karl Heuer's avatar
Karl Heuer committed
1268 1269
	     ;; Done with functions
	     )))
Richard M. Stallman's avatar
Richard M. Stallman committed
1270 1271 1272
     ;; Make sure the doc string has correctly spelled english words
     ;; in it.  This functions is extracted due to its complexity,
     ;; and reliance on the Ispell program.
Karl Heuer's avatar
Karl Heuer committed
1273 1274 1275 1276 1277 1278 1279 1280 1281
     (checkdoc-ispell-docstring-engine e)
     ;; User supplied checks
     (save-excursion (checkdoc-run-hooks 'checkdoc-style-hooks fp e))
     ;; Done!
     )))

(defun checkdoc-defun-info nil
  "Return a list of details about the current sexp.
It is a list of the form:
Richard M. Stallman's avatar
Richard M. Stallman committed
1282
   (NAME VARIABLE INTERACTIVE NODOCPARAMS PARAMETERS ...)
Karl Heuer's avatar
Karl Heuer committed
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
where NAME is the name, VARIABLE is t if this is a `defvar',
INTERACTIVE is nil if this is not an interactive function, otherwise
it is the position of the `interactive' call, and PARAMETERS is a
string which is the name of each variable in the function's argument
list.  The NODOCPARAMS is a sublist of parameters specified by a checkdoc
comment for a given defun.  If the first element is not a string, then
the token checkdoc-order: <TOKEN> exists, and TOKEN is a symbol read
from the comment."
  (save-excursion
    (beginning-of-defun)
    (let ((defun (looking-at "(def\\(un\\|macro\\|subst\\|advice\\)"))
	  (is-advice (looking-at "(defadvice"))
	  (lst nil)
	  (ret nil)
	  (oo (make-vector 3 0)))	;substitute obarray for `read'
      (forward-char 1)
      (forward-sexp 1)
      (skip-chars-forward " \n\t")
      (setq ret
	    (list (buffer-substring-no-properties
		   (point) (progn (forward-sexp 1) (point)))))
      (if (not defun)
	  (setq ret (cons t ret))
	;; The variable spot
	(setq ret (cons nil ret))
	;; Interactive
	(save-excursion
	  (setq ret (cons
		     (re-search-forward "(interactive"
					(save-excursion (end-of-defun) (point))
					t)
		     ret)))
	(skip-chars-forward " \t\n")
	(let ((bss (buffer-substring (point) (save-excursion (forward-sexp 1)
							     (point))))
	      ;; Overload th main obarray so read doesn't intern the
	      ;; local symbols of the function we are checking.
	      ;; Without this we end up cluttering the symbol space w/
	      ;; useless symbols.
	      (obarray oo))
	  ;; Ok, check for checkdoc parameter comment here
	  (save-excursion
	    (setq ret
		  (cons
		   (let ((sl1 nil))
		     (if (re-search-forward ";\\s-+checkdoc-order:\\s-+"
					    (save-excursion (end-of-defun)
							    (point))
					    t)
			 (setq sl1 (list (cond ((looking-at "nil") 'no)
					       ((looking-at "t") 'yes)))))
		     (if (re-search-forward ";\\s-+checkdoc-params:\\s-+"
					    (save-excursion (end-of-defun)
							    (point))
					    t)
			 (let ((sl nil))
			   (goto-char (match-end 0))
			   (setq lst (read (current-buffer)))
			   (while lst
			     (setq sl (cons (symbol-name (car lst)) sl)
				   lst (cdr lst)))
			   (setq sl1 (append sl1 sl))))
		     sl1)
		   ret)))
	  ;; Read the list of paramters, but do not put the symbols in
	  ;; the standard obarray.
	  (setq lst (read bss)))
	;; This is because read will intern nil if it doesn't into the
	;; new obarray.
	(if (not (listp lst)) (setq lst nil))
	(if is-advice nil
	  (while lst
	    (setq ret (cons (symbol-name (car lst)) ret)
		  lst (cdr lst)))))
      (nreverse ret))))

(defun checkdoc-in-sample-code-p (start limit)
Richard M. Stallman's avatar
Richard M. Stallman committed
1360
  "Return non-nil if the current point is in a code fragment.
Karl Heuer's avatar
Karl Heuer committed
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
A code fragment is identified by an open parenthesis followed by a
symbol which is a valid function, or a parenthesis that is quoted with the '
character.  Only the region from START to LIMIT is is allowed while
searching for the bounding parenthesis."
  (save-match-data
    (save-restriction
      (narrow-to-region start limit)
      (save-excursion
	(and (condition-case nil (progn (up-list 1) t) (error nil))
	     (condition-case nil (progn (forward-list -1) t) (error nil))
	     (or (save-excursion (forward-char -1) (looking-at "'("))
		 (and (looking-at "(\\(\\(\\w\\|[-:_]\\)+\\)[ \t\n;]")
		      (let ((ms (buffer-substring-no-properties
				 (match-beginning 1) (match-end 1))))
			;; if this string is function bound, we are in
			;; sample code.  If it has a - or : character in
			;; the name, then it is probably supposed to be bound
			;; but isn't yet.
			(or (fboundp (intern-soft ms))
			    (string-match "\\w[-:_]+\\w" ms))))))))))

;;; Ispell engine
;;
(eval-when-compile (require 'ispell))

(defun checkdoc-ispell-init ()
Richard M. Stallman's avatar
Richard M. Stallman committed
1387
  "Initialize Ispell process (default version) with Lisp words.
Karl Heuer's avatar
Karl Heuer committed
1388 1389 1390 1391 1392 1393 1394 1395
The words used are from `checkdoc-ispell-lisp-words'.  If `ispell'
cannot be loaded, then set `checkdoc-spellcheck-documentation-flag' to
nil."
  (require 'ispell)
  (if (not (symbol-value 'ispell-process)) ;Silence byteCompiler
      (condition-case nil
	  (progn
	    (ispell-buffer-local-words)
Richard M. Stallman's avatar
Richard M. Stallman committed
1396
	    ;; This code copied in part from ispell.el Emacs 19.34
Karl Heuer's avatar
Karl Heuer committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
	    (let ((w checkdoc-ispell-lisp-words))
	      (while w
		(process-send-string
		 ;;  Silence byte compiler
		 (symbol-value 'ispell-process)
		 (concat "@" (car w) "\n"))
		(setq w (cdr w)))))
	(error (setq checkdoc-spellcheck-documentation-flag nil)))))

(defun checkdoc-ispell-docstring-engine (end)
Richard M. Stallman's avatar
Richard M. Stallman committed
1407 1408 1409
  "Run the Ispell tools on the doc string between point and END.
Since Ispell isn't Lisp-smart, we must pre-process the doc string
before using the Ispell engine on it."
Karl Heuer's avatar
Karl Heuer committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
  (if (not checkdoc-spellcheck-documentation-flag)
      nil
    (checkdoc-ispell-init)
    (save-excursion
      (skip-chars-forward "^a-zA-Z")
      (let ((word nil) (sym nil) (case-fold-search nil) (err nil))
	(while (and (not err) (< (point) end))
	  (if (save-excursion (forward-char -1) (looking-at "[('`]"))
	      ;; Skip lists describing meta-syntax, or bound variables
	      (forward-sexp 1)
	    (setq word (buffer-substring-no-properties
			(point) (progn
				  (skip-chars-forward "a-zA-Z-")
				  (point)))
		  sym (intern-soft word))
	    (if (and sym (or (boundp sym) (fboundp sym)))
		;; This is probably repetative in most cases, but not always.
		nil
	      ;; Find out how we spell-check this word.
	      (if (or
1430 1431 1432
		   ;; All caps w/ option th, or s tacked on the end
		   ;; for pluralization or nuberthness.
		   (string-match "^[A-Z][A-Z]+\\(s\\|th\\)?$" word)
Karl Heuer's avatar
Karl Heuer committed
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
		   (looking-at "}") ; a keymap expression
		   )
		  nil
		(save-excursion
		  (if (not (eq checkdoc-autofix-flag 'never))
		      (let ((lk last-input-event))
			(ispell-word nil t)
			(if (not (equal last-input-event lk))
			    (progn
			      (sit-for 0)
			      (message "Continuing..."))))
		    ;; Nothing here.
		    )))))
	  (skip-chars-forward "^a-zA-Z"))
	err))))

;;; Rogue space checking engine
;;
(defun checkdoc-rogue-space-check-engine (&optional start end)
  "Return a message string if there is a line with white space at the end.
If `checkdoc-autofix-flag' permits, delete that whitespace instead.
If optional arguments START and END are non nil, bound the check to
this region."
  (let ((p (point))
	(msg nil))
    (if (not start) (setq start (point-min)))
    ;; If end is nil, it means end of buffer to search anyway
    (or
     ;; Checkfor and error if `? ' or `?\ ' is used at the end of a line.
     ;; (It's dangerous)
     (progn
       (goto-char start)
       (if (re-search-forward "\\?\\\\?[ \t][ \t]*$" end t)
	   (setq msg
		 "Don't use `? ' at the end of a line. \
Some editors & news agents may remove it")))
     ;; Check for, and pottentially remove whitespace appearing at the
     ;; end of different lines.
     (progn
       (goto-char start)
Richard M. Stallman's avatar
Richard M. Stallman committed
1473
       ;; There is no documentation in the Emacs Lisp manual about this check,
Karl Heuer's avatar
Karl Heuer committed
1474 1475 1476 1477 1478
       ;; it is intended to help clean up messy code and reduce the file size.
       (while (and (not msg) (re-search-forward "[^ \t\n]\\([ \t]+\\)$" end t))
	 ;; This is not a complex activity
	 (if (checkdoc-autofix-ask-replace
	      (match-beginning 1) (match-end 1)
Richard M. Stallman's avatar
Richard M. Stallman committed
1479
	      "White space at end of line.  Remove? " "")
Karl Heuer's avatar
Karl Heuer committed
1480
	     nil
1481
	   (setq msg "White space found at end of line")))))
Karl Heuer's avatar
Karl Heuer committed
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    ;; Return an error and leave the cursor at that spot, or restore
    ;; the cursor.
    (if msg
	msg
      (goto-char p)
      nil)))

;;; Comment checking engine
;;
(eval-when-compile
  ;; We must load this to:
  ;; a) get symbols for comple and
  ;; b) determine if we have lm-history symbol which doesn't always exist
  (require 'lisp-mnt))

(defun checkdoc-file-comments-engine ()
Richard M. Stallman's avatar
Richard M. Stallman committed
1498
  "Return a message string if this file does not match the Emacs standard.
Karl Heuer's avatar
Karl Heuer committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
This checks for style only, such as the first line, Commentary:,
Code:, and others referenced in the style guide."
  (if (featurep 'lisp-mnt)
      nil
    (require 'lisp-mnt)
    ;; Old Xemacs don't have `lm-commentary-mark'
    (if (and (not (fboundp 'lm-commentary-mark)) (boundp 'lm-commentary))
	(defalias 'lm-commentary-mark 'lm-commentary)))
  (save-excursion
    (let* ((f1 (file-name-nondirectory (buffer-file-name)))
	   (fn (file-name-sans-extension f1))
	   (fe (substring f1 (length fn))))
      (goto-char (point-min))
      (or
       ;; Lisp Maintenance checks first
       ;; Was: (lm-verify) -> not flexible enough for some people
       ;; * Summary at the beginning of the file:
       (if (not (lm-summary))
	   ;; This certifies as very complex so always ask unless
	   ;; it's set to never
	   (if (and checkdoc-autofix-flag
		    (not (eq checkdoc-autofix-flag 'never))
1521
		    (y-or-n-p "There is no first line summary!  Add one? "))
Karl Heuer's avatar
Karl Heuer committed
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
	       (progn
		 (goto-char (point-min))
		 (insert ";;; " fn fe " --- " (read-string "Summary: ") "\n"))
	     "The first line should be of the form: \";;; package --- Summary\"")
	 nil)
       ;; * Commentary Section
       (if (not (lm-commentary-mark))
	   "You should have a section marked \";;; Commentary:\""
	 nil)
       ;; * History section.  Say nothing if there is a file ChangeLog
       (if (or (file-exists-p "ChangeLog")
	       (let ((fn 'lm-history-mark)) ;bestill byte-compiler
		 (and (fboundp fn) (funcall fn))))
	   nil
	 "You should have a section marked \";;; History:\" or use a ChangeLog")
       ;; * Code section
       (if (not (lm-code-mark))
	   (let ((cont t))
	     (goto-char (point-min))
	     (while (and cont (re-search-forward "^(" nil t))
	       (setq cont (looking-at "require\\s-+")))
	     (if (and (not cont)
		      checkdoc-autofix-flag
		      (not (eq checkdoc-autofix-flag 'never))
		      (y-or-n-p "There is no ;;; Code: marker.  Insert one? "))
		 (progn (beginning-of-line)
			(insert ";;; Code:\n")
			nil)
	       "You should have a section marked \";;; Code:\""))
	 nil)
       ;; * A footer.  Not compartamentalized from lm-verify: too bad.
       ;;              The following is partially clipped from lm-verify
       (save-excursion
	 (goto-char (point-max))
	 (if (not (re-search-backward
		   (concat "^;;;[ \t]+" fn "\\(" (regexp-quote fe)
			   "\\)?[ \t]+ends here[ \t]*$"
			   "\\|^;;;[ \t]+ End of file[ \t]+"
			   fn "\\(" (regexp-quote fe) "\\)?")
		   nil t))
	     (if (and checkdoc-autofix-flag
		      (not (eq checkdoc-autofix-flag 'never))
1564
		      (y-or-n-p "No identifiable footer!  Add one? "))
Karl Heuer's avatar
Karl Heuer committed
1565 1566 1567 1568 1569 1570