Document reserved keys
[emacs.git] / lisp / progmodes / flymake.el
blob58bad8f366e3ce1c21c82a95214f391dd226ad11
1 ;;; flymake.el --- A universal on-the-fly syntax checker -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2003-2018 Free Software Foundation, Inc.
5 ;; Author: Pavel Kobyakov <pk_at_work@yahoo.com>
6 ;; Maintainer: Leo Liu <sdl.web@gmail.com>
7 ;; Version: 0.3
8 ;; Keywords: c languages tools
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Flymake is a minor Emacs mode performing on-the-fly syntax checks.
29 ;; Flymake collects diagnostic information for multiple sources,
30 ;; called backends, and visually annotates the relevant portions in
31 ;; the buffer.
33 ;; This file contains the UI for displaying and interacting with the
34 ;; results produced by these backends, as well as entry points for
35 ;; backends to hook on to.
37 ;; The main entry points are `flymake-mode' and `flymake-start'
39 ;; The docstrings of these variables are relevant to understanding how
40 ;; Flymake works for both the user and the backend programmer:
42 ;; * `flymake-diagnostic-functions'
43 ;; * `flymake-diagnostic-types-alist'
45 ;;; Code:
47 (require 'cl-lib)
48 (require 'thingatpt) ; end-of-thing
49 (require 'warnings) ; warning-numeric-level, display-warning
50 (require 'compile) ; for some faces
51 ;; when-let*, if-let*, hash-table-keys, hash-table-values:
52 (eval-when-compile (require 'subr-x))
54 (defgroup flymake nil
55 "Universal on-the-fly syntax checker."
56 :version "23.1"
57 :link '(custom-manual "(flymake) Top")
58 :group 'tools)
60 (defcustom flymake-error-bitmap '(flymake-double-exclamation-mark
61 compilation-error)
62 "Bitmap (a symbol) used in the fringe for indicating errors.
63 The value may also be a list of two elements where the second
64 element specifies the face for the bitmap. For possible bitmap
65 symbols, see `fringe-bitmaps'. See also `flymake-warning-bitmap'.
67 The option `flymake-fringe-indicator-position' controls how and where
68 this is used."
69 :version "24.3"
70 :type '(choice (symbol :tag "Bitmap")
71 (list :tag "Bitmap and face"
72 (symbol :tag "Bitmap")
73 (face :tag "Face"))))
75 (defcustom flymake-warning-bitmap '(exclamation-mark compilation-warning)
76 "Bitmap (a symbol) used in the fringe for indicating warnings.
77 The value may also be a list of two elements where the second
78 element specifies the face for the bitmap. For possible bitmap
79 symbols, see `fringe-bitmaps'. See also `flymake-error-bitmap'.
81 The option `flymake-fringe-indicator-position' controls how and where
82 this is used."
83 :version "24.3"
84 :type '(choice (symbol :tag "Bitmap")
85 (list :tag "Bitmap and face"
86 (symbol :tag "Bitmap")
87 (face :tag "Face"))))
89 (defcustom flymake-note-bitmap '(exclamation-mark compilation-info)
90 "Bitmap (a symbol) used in the fringe for indicating info notes.
91 The value may also be a list of two elements where the second
92 element specifies the face for the bitmap. For possible bitmap
93 symbols, see `fringe-bitmaps'. See also `flymake-error-bitmap'.
95 The option `flymake-fringe-indicator-position' controls how and where
96 this is used."
97 :version "26.1"
98 :type '(choice (symbol :tag "Bitmap")
99 (list :tag "Bitmap and face"
100 (symbol :tag "Bitmap")
101 (face :tag "Face"))))
103 (defcustom flymake-fringe-indicator-position 'left-fringe
104 "The position to put Flymake fringe indicator.
105 The value can be nil (do not use indicators), `left-fringe' or `right-fringe'.
106 See `flymake-error-bitmap' and `flymake-warning-bitmap'."
107 :version "24.3"
108 :type '(choice (const left-fringe)
109 (const right-fringe)
110 (const :tag "No fringe indicators" nil)))
112 (defcustom flymake-start-syntax-check-on-newline t
113 "Start syntax check if newline char was added/removed from the buffer."
114 :type 'boolean)
116 (defcustom flymake-no-changes-timeout 0.5
117 "Time to wait after last change before automatically checking buffer.
118 If nil, never start checking buffer automatically like this."
119 :type 'number)
121 (defcustom flymake-gui-warnings-enabled t
122 "Enables/disables GUI warnings."
123 :type 'boolean)
124 (make-obsolete-variable 'flymake-gui-warnings-enabled
125 "it no longer has any effect." "26.1")
127 (define-obsolete-variable-alias 'flymake-start-syntax-check-on-find-file
128 'flymake-start-on-flymake-mode "26.1")
130 (defcustom flymake-start-on-flymake-mode t
131 "Start syntax check when `flymake-mode' is enabled.
132 Specifically, start it when the buffer is actually displayed."
133 :version "26.1"
134 :type 'boolean)
136 (defcustom flymake-log-level -1
137 "Obsolete and ignored variable."
138 :type 'integer)
139 (make-obsolete-variable 'flymake-log-level
140 "it is superseded by `warning-minimum-log-level.'"
141 "26.1")
143 (defcustom flymake-wrap-around t
144 "If non-nil, moving to errors wraps around buffer boundaries."
145 :version "26.1"
146 :type 'boolean)
148 (when (fboundp 'define-fringe-bitmap)
149 (define-fringe-bitmap 'flymake-double-exclamation-mark
150 (vector #b00000000
151 #b00000000
152 #b00000000
153 #b00000000
154 #b01100110
155 #b01100110
156 #b01100110
157 #b01100110
158 #b01100110
159 #b01100110
160 #b01100110
161 #b01100110
162 #b00000000
163 #b01100110
164 #b00000000
165 #b00000000
166 #b00000000)))
168 (defvar-local flymake-timer nil
169 "Timer for starting syntax check.")
171 (defvar-local flymake-check-start-time nil
172 "Time at which syntax check was started.")
174 (defun flymake--log-1 (level sublog msg &rest args)
175 "Do actual work for `flymake-log'."
176 (let (;; never popup the log buffer
177 (warning-minimum-level :emergency)
178 (warning-type-format
179 (format " [%s %s]"
180 (or sublog 'flymake)
181 (current-buffer))))
182 (display-warning (list 'flymake sublog)
183 (apply #'format-message msg args)
184 (if (numberp level)
185 (or (nth level
186 '(:emergency :error :warning :debug :debug) )
187 :error)
188 level)
189 "*Flymake log*")))
191 (defun flymake-switch-to-log-buffer ()
192 "Go to the *Flymake log* buffer."
193 (interactive)
194 (switch-to-buffer "*Flymake log*"))
196 ;;;###autoload
197 (defmacro flymake-log (level msg &rest args)
198 "Log, at level LEVEL, the message MSG formatted with ARGS.
199 LEVEL is passed to `display-warning', which is used to display
200 the warning. If this form is included in a byte-compiled file,
201 the generated warning contains an indication of the file that
202 generated it."
203 (let* ((compile-file (and (boundp 'byte-compile-current-file)
204 (symbol-value 'byte-compile-current-file)))
205 (sublog (if (and
206 compile-file
207 (not load-file-name))
208 (intern
209 (file-name-nondirectory
210 (file-name-sans-extension compile-file))))))
211 `(flymake--log-1 ,level ',sublog ,msg ,@args)))
213 (defun flymake-error (text &rest args)
214 "Format TEXT with ARGS and signal an error for Flymake."
215 (let ((msg (apply #'format-message text args)))
216 (flymake-log :error msg)
217 (error (concat "[Flymake] " msg))))
219 (cl-defstruct (flymake--diag
220 (:constructor flymake--diag-make))
221 buffer beg end type text backend)
223 ;;;###autoload
224 (defun flymake-make-diagnostic (buffer
227 type
228 text)
229 "Make a Flymake diagnostic for BUFFER's region from BEG to END.
230 TYPE is a key to `flymake-diagnostic-types-alist' and TEXT is a
231 description of the problem detected in this region."
232 (flymake--diag-make :buffer buffer :beg beg :end end :type type :text text))
234 ;;;###autoload
235 (defun flymake-diagnostics (&optional beg end)
236 "Get Flymake diagnostics in region determined by BEG and END.
238 If neither BEG or END is supplied, use the whole buffer,
239 otherwise if BEG is non-nil and END is nil, consider only
240 diagnostics at BEG."
241 (mapcar (lambda (ov) (overlay-get ov 'flymake-diagnostic))
242 (flymake--overlays :beg beg :end end)))
244 (defmacro flymake--diag-accessor (public internal thing)
245 "Make PUBLIC an alias for INTERNAL, add doc using THING."
246 `(defsubst ,public (diag)
247 ,(format "Get Flymake diagnostic DIAG's %s." (symbol-name thing))
248 (,internal diag)))
250 (flymake--diag-accessor flymake-diagnostic-buffer flymake--diag-buffer buffer)
251 (flymake--diag-accessor flymake-diagnostic-text flymake--diag-text text)
252 (flymake--diag-accessor flymake-diagnostic-type flymake--diag-type type)
253 (flymake--diag-accessor flymake-diagnostic-beg flymake--diag-beg beg)
254 (flymake--diag-accessor flymake-diagnostic-end flymake--diag-end end)
255 (flymake--diag-accessor flymake-diagnostic-backend flymake--diag-backend backend)
257 (cl-defun flymake--overlays (&key beg end filter compare key)
258 "Get flymake-related overlays.
259 If BEG is non-nil and END is nil, consider only `overlays-at'
260 BEG. Otherwise consider `overlays-in' the region comprised by BEG
261 and END, defaulting to the whole buffer. Remove all that do not
262 verify FILTER, a function, and sort them by COMPARE (using KEY)."
263 (save-restriction
264 (widen)
265 (let ((ovs (cl-remove-if-not
266 (lambda (ov)
267 (and (overlay-get ov 'flymake-diagnostic)
268 (or (not filter)
269 (funcall filter ov))))
270 (if (and beg (null end))
271 (overlays-at beg t)
272 (overlays-in (or beg (point-min))
273 (or end (point-max)))))))
274 (if compare
275 (cl-sort ovs compare :key (or key
276 #'identity))
277 ovs))))
279 (defun flymake-delete-own-overlays (&optional filter)
280 "Delete all Flymake overlays in BUFFER."
281 (mapc #'delete-overlay (flymake--overlays :filter filter)))
283 (defface flymake-error
284 '((((supports :underline (:style wave)))
285 :underline (:style wave :color "Red1"))
287 :inherit error))
288 "Face used for marking error regions."
289 :version "24.4")
291 (defface flymake-warning
292 '((((supports :underline (:style wave)))
293 :underline (:style wave :color "deep sky blue"))
295 :inherit warning))
296 "Face used for marking warning regions."
297 :version "24.4")
299 (defface flymake-note
300 '((((supports :underline (:style wave)))
301 :underline (:style wave :color "yellow green"))
303 :inherit warning))
304 "Face used for marking note regions."
305 :version "26.1")
307 (define-obsolete-face-alias 'flymake-warnline 'flymake-warning "26.1")
308 (define-obsolete-face-alias 'flymake-errline 'flymake-error "26.1")
310 ;;;###autoload
311 (defun flymake-diag-region (buffer line &optional col)
312 "Compute BUFFER's region (BEG . END) corresponding to LINE and COL.
313 If COL is nil, return a region just for LINE. Return nil if the
314 region is invalid."
315 (condition-case-unless-debug _err
316 (with-current-buffer buffer
317 (let ((line (min (max line 1)
318 (line-number-at-pos (point-max) 'absolute))))
319 (save-excursion
320 (goto-char (point-min))
321 (forward-line (1- line))
322 (cl-flet ((fallback-bol
324 (back-to-indentation)
325 (if (eobp)
326 (line-beginning-position 0)
327 (point)))
328 (fallback-eol
329 (beg)
330 (progn
331 (end-of-line)
332 (skip-chars-backward " \t\f\t\n" beg)
333 (if (eq (point) beg)
334 (line-beginning-position 2)
335 (point)))))
336 (if (and col (cl-plusp col))
337 (let* ((beg (progn (forward-char (1- col))
338 (point)))
339 (sexp-end (ignore-errors (end-of-thing 'sexp)))
340 (end (or (and sexp-end
341 (not (= sexp-end beg))
342 sexp-end)
343 (and (< (goto-char (1+ beg)) (point-max))
344 (point)))))
345 (if end
346 (cons beg end)
347 (cons (setq beg (fallback-bol))
348 (fallback-eol beg))))
349 (let* ((beg (fallback-bol))
350 (end (fallback-eol beg)))
351 (cons beg end)))))))
352 (error (flymake-log :warning "Invalid region line=%s col=%s" line col)
353 nil)))
355 (defvar flymake-diagnostic-functions nil
356 "Special hook of Flymake backends that check a buffer.
358 The functions in this hook diagnose problems in a buffer's
359 contents and provide information to the Flymake user interface
360 about where and how to annotate problems diagnosed in a buffer.
362 Each backend function must be prepared to accept an arbitrary
363 number of arguments:
365 * the first argument is always REPORT-FN, a callback function
366 detailed below;
368 * the remaining arguments are keyword-value pairs in the
369 form (:KEY VALUE :KEY2 VALUE2...). Currently, Flymake provides
370 no such arguments, but backend functions must be prepared to
371 accept and possibly ignore any number of them.
373 Whenever Flymake or the user decides to re-check the buffer,
374 backend functions are called as detailed above and are expected
375 to initiate this check, but aren't required to complete it before
376 exiting: if the computation involved is expensive, especially for
377 large buffers, that task can be scheduled for the future using
378 asynchronous processes or other asynchronous mechanisms.
380 In any case, backend functions are expected to return quickly or
381 signal an error, in which case the backend is disabled. Flymake
382 will not try disabled backends again for any future checks of
383 this buffer. Certain commands, like turning `flymake-mode' off
384 and on again, reset the list of disabled backends.
386 If the function returns, Flymake considers the backend to be
387 \"running\". If it has not done so already, the backend is
388 expected to call the function REPORT-FN with a single argument
389 REPORT-ACTION also followed by an optional list of keyword-value
390 pairs in the form (:REPORT-KEY VALUE :REPORT-KEY2 VALUE2...).
392 Currently accepted values for REPORT-ACTION are:
394 * A (possibly empty) list of diagnostic objects created with
395 `flymake-make-diagnostic', causing Flymake to annotate the
396 buffer with this information.
398 A backend may call REPORT-FN repeatedly in this manner, but
399 only until Flymake considers that the most recently requested
400 buffer check is now obsolete because, say, buffer contents have
401 changed in the meantime. The backend is only given notice of
402 this via a renewed call to the backend function. Thus, to
403 prevent making obsolete reports and wasting resources, backend
404 functions should first cancel any ongoing processing from
405 previous calls.
407 * The symbol `:panic', signaling that the backend has encountered
408 an exceptional situation and should be disabled.
410 Currently accepted REPORT-KEY arguments are:
412 * `:explanation' value should give user-readable details of
413 the situation encountered, if any.
415 * `:force': value should be a boolean suggesting that Flymake
416 consider the report even if it was somehow unexpected.")
418 (defvar flymake-diagnostic-types-alist
419 `((:error
420 . ((flymake-category . flymake-error)))
421 (:warning
422 . ((flymake-category . flymake-warning)))
423 (:note
424 . ((flymake-category . flymake-note))))
425 "Alist ((KEY . PROPS)*) of properties of Flymake diagnostic types.
426 KEY designates a kind of diagnostic can be anything passed as
427 `:type' to `flymake-make-diagnostic'.
429 PROPS is an alist of properties that are applied, in order, to
430 the diagnostics of the type designated by KEY. The recognized
431 properties are:
433 * Every property pertaining to overlays, except `category' and
434 `evaporate' (see Info Node `(elisp)Overlay Properties'), used
435 to affect the appearance of Flymake annotations.
437 * `bitmap', an image displayed in the fringe according to
438 `flymake-fringe-indicator-position'. The value actually
439 follows the syntax of `flymake-error-bitmap' (which see). It
440 is overridden by any `before-string' overlay property.
442 * `severity', a non-negative integer specifying the diagnostic's
443 severity. The higher, the more serious. If the overlay
444 property `priority' is not specified, `severity' is used to set
445 it and help sort overlapping overlays.
447 * `flymake-category', a symbol whose property list is considered
448 a default for missing values of any other properties. This is
449 useful to backend authors when creating new diagnostic types
450 that differ from an existing type by only a few properties.")
452 (put 'flymake-error 'face 'flymake-error)
453 (put 'flymake-error 'bitmap 'flymake-error-bitmap)
454 (put 'flymake-error 'severity (warning-numeric-level :error))
455 (put 'flymake-error 'mode-line-face 'compilation-error)
457 (put 'flymake-warning 'face 'flymake-warning)
458 (put 'flymake-warning 'bitmap 'flymake-warning-bitmap)
459 (put 'flymake-warning 'severity (warning-numeric-level :warning))
460 (put 'flymake-warning 'mode-line-face 'compilation-warning)
462 (put 'flymake-note 'face 'flymake-note)
463 (put 'flymake-note 'bitmap 'flymake-note-bitmap)
464 (put 'flymake-note 'severity (warning-numeric-level :debug))
465 (put 'flymake-note 'mode-line-face 'compilation-info)
467 (defun flymake--lookup-type-property (type prop &optional default)
468 "Look up PROP for TYPE in `flymake-diagnostic-types-alist'.
469 If TYPE doesn't declare PROP in either
470 `flymake-diagnostic-types-alist' or in the symbol of its
471 associated `flymake-category' return DEFAULT."
472 (let ((alist-probe (assoc type flymake-diagnostic-types-alist)))
473 (cond (alist-probe
474 (let* ((alist (cdr alist-probe))
475 (prop-probe (assoc prop alist)))
476 (if prop-probe
477 (cdr prop-probe)
478 (if-let* ((cat (assoc-default 'flymake-category alist))
479 (plist (and (symbolp cat)
480 (symbol-plist cat)))
481 (cat-probe (plist-member plist prop)))
482 (cadr cat-probe)
483 default))))
485 default))))
487 (defun flymake--fringe-overlay-spec (bitmap &optional recursed)
488 (if (and (symbolp bitmap)
489 (boundp bitmap)
490 (not recursed))
491 (flymake--fringe-overlay-spec
492 (symbol-value bitmap) t)
493 (and flymake-fringe-indicator-position
494 bitmap
495 (propertize "!" 'display
496 (cons flymake-fringe-indicator-position
497 (if (listp bitmap)
498 bitmap
499 (list bitmap)))))))
501 (defun flymake--highlight-line (diagnostic)
502 "Highlight buffer with info in DIAGNOSTIC."
503 (when-let* ((ov (make-overlay
504 (flymake--diag-beg diagnostic)
505 (flymake--diag-end diagnostic))))
506 ;; First set `category' in the overlay, then copy over every other
507 ;; property.
509 (let ((alist (assoc-default (flymake--diag-type diagnostic)
510 flymake-diagnostic-types-alist)))
511 (overlay-put ov 'category (assoc-default 'flymake-category alist))
512 (cl-loop for (k . v) in alist
513 unless (eq k 'category)
514 do (overlay-put ov k v)))
515 ;; Now ensure some essential defaults are set
517 (cl-flet ((default-maybe
518 (prop value)
519 (unless (or (plist-member (overlay-properties ov) prop)
520 (let ((cat (overlay-get ov
521 'flymake-category)))
522 (and cat
523 (plist-member (symbol-plist cat) prop))))
524 (overlay-put ov prop value))))
525 (default-maybe 'bitmap 'flymake-error-bitmap)
526 (default-maybe 'face 'flymake-error)
527 (default-maybe 'before-string
528 (flymake--fringe-overlay-spec
529 (overlay-get ov 'bitmap)))
530 (default-maybe 'help-echo
531 (lambda (window _ov pos)
532 (with-selected-window window
533 (mapconcat
534 #'flymake--diag-text
535 (flymake-diagnostics pos)
536 "\n"))))
537 (default-maybe 'severity (warning-numeric-level :error))
538 (default-maybe 'priority (+ 100 (overlay-get ov 'severity))))
539 ;; Some properties can't be overridden.
541 (overlay-put ov 'evaporate t)
542 (overlay-put ov 'flymake-diagnostic diagnostic)))
544 ;; Nothing in Flymake uses this at all any more, so this is just for
545 ;; third-party compatibility.
546 (define-obsolete-function-alias 'flymake-display-warning 'message-box "26.1")
548 (defvar-local flymake--backend-state nil
549 "Buffer-local hash table of a Flymake backend's state.
550 The keys to this hash table are functions as found in
551 `flymake-diagnostic-functions'. The values are structures
552 of the type `flymake--backend-state', with these slots:
554 `running', a symbol to keep track of a backend's replies via its
555 REPORT-FN argument. A backend is running if this key is
556 present. If nil, Flymake isn't expecting any replies from the
557 backend.
559 `diags', a (possibly empty) list of recent diagnostic objects
560 created by the backend with `flymake-make-diagnostic'.
562 `reported-p', a boolean indicating if the backend has replied
563 since it last was contacted.
565 `disabled', a string with the explanation for a previous
566 exceptional situation reported by the backend, nil if the
567 backend is operating normally.")
569 (cl-defstruct (flymake--backend-state
570 (:constructor flymake--make-backend-state))
571 running reported-p disabled diags)
573 (defmacro flymake--with-backend-state (backend state-var &rest body)
574 "Bind BACKEND's STATE-VAR to its state, run BODY."
575 (declare (indent 2) (debug (sexp sexp &rest form)))
576 (let ((b (make-symbol "b")))
577 `(let* ((,b ,backend)
578 (,state-var
579 (or (gethash ,b flymake--backend-state)
580 (puthash ,b (flymake--make-backend-state)
581 flymake--backend-state))))
582 ,@body)))
584 (defun flymake-is-running ()
585 "Tell if Flymake has running backends in this buffer"
586 (flymake-running-backends))
588 (cl-defun flymake--handle-report (backend token report-action
589 &key explanation force
590 &allow-other-keys)
591 "Handle reports from BACKEND identified by TOKEN.
592 BACKEND, REPORT-ACTION and EXPLANATION, and FORCE conform to the calling
593 convention described in `flymake-diagnostic-functions' (which
594 see). Optional FORCE says to handle a report even if TOKEN was
595 not expected."
596 (let* ((state (gethash backend flymake--backend-state))
597 (first-report (not (flymake--backend-state-reported-p state))))
598 (setf (flymake--backend-state-reported-p state) t)
599 (let (expected-token
600 new-diags)
601 (cond
602 ((null state)
603 (flymake-error
604 "Unexpected report from unknown backend %s" backend))
605 ((flymake--backend-state-disabled state)
606 (flymake-error
607 "Unexpected report from disabled backend %s" backend))
608 ((progn
609 (setq expected-token (flymake--backend-state-running state))
610 (null expected-token))
611 ;; should never happen
612 (flymake-error "Unexpected report from stopped backend %s" backend))
613 ((not (or (eq expected-token token)
614 force))
615 (flymake-error "Obsolete report from backend %s with explanation %s"
616 backend explanation))
617 ((eq :panic report-action)
618 (flymake--disable-backend backend explanation))
619 ((not (listp report-action))
620 (flymake--disable-backend backend
621 (format "Unknown action %S" report-action))
622 (flymake-error "Expected report, but got unknown key %s" report-action))
624 (setq new-diags report-action)
625 (save-restriction
626 (widen)
627 ;; only delete overlays if this is the first report
628 (when first-report
629 (flymake-delete-own-overlays
630 (lambda (ov)
631 (eq backend
632 (flymake--diag-backend
633 (overlay-get ov 'flymake-diagnostic))))))
634 (mapc (lambda (diag)
635 (flymake--highlight-line diag)
636 (setf (flymake--diag-backend diag) backend))
637 new-diags)
638 (setf (flymake--backend-state-diags state)
639 (append new-diags (flymake--backend-state-diags state)))
640 (when flymake-check-start-time
641 (flymake-log :debug "backend %s reported %d diagnostics in %.2f second(s)"
642 backend
643 (length new-diags)
644 (- (float-time) flymake-check-start-time)))
645 (when (and (get-buffer (flymake--diagnostics-buffer-name))
646 (get-buffer-window (flymake--diagnostics-buffer-name))
647 (null (cl-set-difference (flymake-running-backends)
648 (flymake-reporting-backends))))
649 (flymake-show-diagnostics-buffer))))))))
651 (defun flymake-make-report-fn (backend &optional token)
652 "Make a suitable anonymous report function for BACKEND.
653 BACKEND is used to help Flymake distinguish different diagnostic
654 sources. If provided, TOKEN helps Flymake distinguish between
655 different runs of the same backend."
656 (let ((buffer (current-buffer)))
657 (lambda (&rest args)
658 (when (buffer-live-p buffer)
659 (with-current-buffer buffer
660 (apply #'flymake--handle-report backend token args))))))
662 (defun flymake--collect (fn &optional message-prefix)
663 "Collect Flymake backends matching FN.
664 If MESSAGE-PREFIX, echo a message using that prefix"
665 (unless flymake--backend-state
666 (user-error "Flymake is not initialized"))
667 (let (retval)
668 (maphash (lambda (backend state)
669 (when (funcall fn state) (push backend retval)))
670 flymake--backend-state)
671 (when message-prefix
672 (message "%s%s"
673 message-prefix
674 (mapconcat (lambda (s) (format "%s" s))
675 retval ", ")))
676 retval))
678 (defun flymake-running-backends ()
679 "Compute running Flymake backends in current buffer."
680 (interactive)
681 (flymake--collect #'flymake--backend-state-running
682 (and (called-interactively-p 'interactive)
683 "Running backends: ")))
685 (defun flymake-disabled-backends ()
686 "Compute disabled Flymake backends in current buffer."
687 (interactive)
688 (flymake--collect #'flymake--backend-state-disabled
689 (and (called-interactively-p 'interactive)
690 "Disabled backends: ")))
692 (defun flymake-reporting-backends ()
693 "Compute reporting Flymake backends in current buffer."
694 (interactive)
695 (flymake--collect #'flymake--backend-state-reported-p
696 (and (called-interactively-p 'interactive)
697 "Reporting backends: ")))
699 (defun flymake--disable-backend (backend &optional explanation)
700 "Disable BACKEND because EXPLANATION.
701 If it is running also stop it."
702 (flymake-log :warning "Disabling backend %s because %s" backend explanation)
703 (flymake--with-backend-state backend state
704 (setf (flymake--backend-state-running state) nil
705 (flymake--backend-state-disabled state) explanation
706 (flymake--backend-state-reported-p state) t)))
708 (defun flymake--run-backend (backend)
709 "Run the backend BACKEND, reenabling if necessary."
710 (flymake-log :debug "Running backend %s" backend)
711 (let ((run-token (cl-gensym "backend-token")))
712 (flymake--with-backend-state backend state
713 (setf (flymake--backend-state-running state) run-token
714 (flymake--backend-state-disabled state) nil
715 (flymake--backend-state-diags state) nil
716 (flymake--backend-state-reported-p state) nil))
717 ;; FIXME: Should use `condition-case-unless-debug' here, but don't
718 ;; for two reasons: (1) that won't let me catch errors from inside
719 ;; `ert-deftest' where `debug-on-error' appears to be always
720 ;; t. (2) In cases where the user is debugging elisp somewhere
721 ;; else, and using flymake, the presence of a frequently
722 ;; misbehaving backend in the global hook (most likely the legacy
723 ;; backend) will trigger an annoying backtrace.
725 (condition-case err
726 (funcall backend
727 (flymake-make-report-fn backend run-token))
728 (error
729 (flymake--disable-backend backend err)))))
731 (defun flymake-start (&optional deferred force)
732 "Start a syntax check for the current buffer.
733 DEFERRED is a list of symbols designating conditions to wait for
734 before actually starting the check. If it is nil (the list is
735 empty), start it immediately, else defer the check to when those
736 conditions are met. Currently recognized conditions are
737 `post-command', for waiting until the current command is over,
738 `on-display', for waiting until the buffer is actually displayed
739 in a window. If DEFERRED is t, wait for all known conditions.
741 With optional FORCE run even disabled backends.
743 Interactively, with a prefix arg, FORCE is t."
744 (interactive (list nil current-prefix-arg))
745 (let ((deferred (if (eq t deferred)
746 '(post-command on-display)
747 deferred))
748 (buffer (current-buffer)))
749 (cl-labels
750 ((start-post-command
752 (remove-hook 'post-command-hook #'start-post-command
753 nil)
754 ;; The buffer may have disappeared already, e.g. because of
755 ;; code like `(with-temp-buffer (python-mode) ...)'.
756 (when (buffer-live-p buffer)
757 (with-current-buffer buffer
758 (flymake-start (remove 'post-command deferred) force))))
759 (start-on-display
761 (remove-hook 'window-configuration-change-hook #'start-on-display
762 'local)
763 (flymake-start (remove 'on-display deferred) force)))
764 (cond ((and (memq 'post-command deferred)
765 this-command)
766 (add-hook 'post-command-hook
767 #'start-post-command
768 'append nil))
769 ((and (memq 'on-display deferred)
770 (not (get-buffer-window (current-buffer))))
771 (add-hook 'window-configuration-change-hook
772 #'start-on-display
773 'append 'local))
775 (setq flymake-check-start-time (float-time))
776 (run-hook-wrapped
777 'flymake-diagnostic-functions
778 (lambda (backend)
779 (cond
780 ((and (not force)
781 (flymake--with-backend-state backend state
782 (flymake--backend-state-disabled state)))
783 (flymake-log :debug "Backend %s is disabled, not starting"
784 backend))
786 (flymake--run-backend backend)))
787 nil)))))))
789 (defvar flymake-mode-map
790 (let ((map (make-sparse-keymap))) map)
791 "Keymap for `flymake-mode'")
793 ;;;###autoload
794 (define-minor-mode flymake-mode
795 "Toggle Flymake mode on or off.
796 With a prefix argument ARG, enable Flymake mode if ARG is
797 positive, and disable it otherwise. If called from Lisp, enable
798 the mode if ARG is omitted or nil, and toggle it if ARG is `toggle'.
800 Flymake is an Emacs minor mode for on-the-fly syntax checking.
801 Flymake collects diagnostic information from multiple sources,
802 called backends, and visually annotates the buffer with the
803 results.
805 Flymake performs these checks while the user is editing. The
806 customization variables `flymake-start-on-flymake-mode',
807 `flymake-no-changes-timeout' and
808 `flymake-start-syntax-check-on-newline' determine the exact
809 circumstances whereupon Flymake decides to initiate a check of
810 the buffer.
812 The commands `flymake-goto-next-error' and
813 `flymake-goto-prev-error' can be used to navigate among Flymake
814 diagnostics annotated in the buffer.
816 The visual appearance of each type of diagnostic can be changed
817 in the variable `flymake-diagnostic-types-alist'.
819 Activation or deactivation of backends used by Flymake in each
820 buffer happens via the special hook
821 `flymake-diagnostic-functions'.
823 Some backends may take longer than others to respond or complete,
824 and some may decide to disable themselves if they are not
825 suitable for the current buffer. The commands
826 `flymake-running-backends', `flymake-disabled-backends' and
827 `flymake-reporting-backends' summarize the situation, as does the
828 special *Flymake log* buffer." :group 'flymake :lighter
829 flymake--mode-line-format :keymap flymake-mode-map
830 (cond
831 ;; Turning the mode ON.
832 (flymake-mode
833 (add-hook 'after-change-functions 'flymake-after-change-function nil t)
834 (add-hook 'after-save-hook 'flymake-after-save-hook nil t)
835 (add-hook 'kill-buffer-hook 'flymake-kill-buffer-hook nil t)
837 (setq flymake--backend-state (make-hash-table))
839 (when flymake-start-on-flymake-mode (flymake-start t)))
841 ;; Turning the mode OFF.
843 (remove-hook 'after-change-functions 'flymake-after-change-function t)
844 (remove-hook 'after-save-hook 'flymake-after-save-hook t)
845 (remove-hook 'kill-buffer-hook 'flymake-kill-buffer-hook t)
846 ;;+(remove-hook 'find-file-hook (function flymake-find-file-hook) t)
848 (flymake-delete-own-overlays)
850 (when flymake-timer
851 (cancel-timer flymake-timer)
852 (setq flymake-timer nil)))))
854 (defun flymake--schedule-timer-maybe ()
855 "(Re)schedule an idle timer for checking the buffer.
856 Do it only if `flymake-no-changes-timeout' is non-nil."
857 (when flymake-timer (cancel-timer flymake-timer))
858 (when flymake-no-changes-timeout
859 (setq
860 flymake-timer
861 (run-with-idle-timer
862 (seconds-to-time flymake-no-changes-timeout)
864 (lambda (buffer)
865 (when (buffer-live-p buffer)
866 (with-current-buffer buffer
867 (when (and flymake-mode
868 flymake-no-changes-timeout)
869 (flymake-log
870 :debug "starting syntax check after idle for %s seconds"
871 flymake-no-changes-timeout)
872 (flymake-start t))
873 (setq flymake-timer nil))))
874 (current-buffer)))))
876 ;;;###autoload
877 (defun flymake-mode-on ()
878 "Turn Flymake mode on."
879 (flymake-mode 1))
881 ;;;###autoload
882 (defun flymake-mode-off ()
883 "Turn Flymake mode off."
884 (flymake-mode 0))
886 (make-obsolete 'flymake-mode-on 'flymake-mode "26.1")
887 (make-obsolete 'flymake-mode-off 'flymake-mode "26.1")
889 (defun flymake-after-change-function (start stop _len)
890 "Start syntax check for current buffer if it isn't already running."
891 (let((new-text (buffer-substring start stop)))
892 (when (and flymake-start-syntax-check-on-newline (equal new-text "\n"))
893 (flymake-log :debug "starting syntax check as new-line has been seen")
894 (flymake-start t))
895 (flymake--schedule-timer-maybe)))
897 (defun flymake-after-save-hook ()
898 (when flymake-mode
899 (flymake-log :debug "starting syntax check as buffer was saved")
900 (flymake-start t)))
902 (defun flymake-kill-buffer-hook ()
903 (when flymake-timer
904 (cancel-timer flymake-timer)
905 (setq flymake-timer nil)))
907 (defun flymake-find-file-hook ()
908 (unless (or flymake-mode
909 (null flymake-diagnostic-functions))
910 (flymake-mode)
911 (flymake-log :warning "Turned on in `flymake-find-file-hook'")))
913 (defun flymake-goto-next-error (&optional n filter interactive)
914 "Go to Nth next Flymake diagnostic that matches FILTER.
915 Interactively, always move to the next diagnostic. With a prefix
916 arg, skip any diagnostics with a severity less than `:warning'.
918 If `flymake-wrap-around' is non-nil and no more next diagnostics,
919 resumes search from top.
921 FILTER is a list of diagnostic types found in
922 `flymake-diagnostic-types-alist', or nil, if no filter is to be
923 applied."
924 ;; TODO: let filter be a number, a severity below which diags are
925 ;; skipped.
926 (interactive (list 1
927 (if current-prefix-arg
928 '(:error :warning))
930 (let* ((n (or n 1))
931 (ovs (flymake--overlays :filter
932 (lambda (ov)
933 (let ((diag (overlay-get
935 'flymake-diagnostic)))
936 (and diag
937 (or (not filter)
938 (memq (flymake--diag-type diag)
939 filter)))))
940 :compare (if (cl-plusp n) #'< #'>)
941 :key #'overlay-start))
942 (tail (cl-member-if (lambda (ov)
943 (if (cl-plusp n)
944 (> (overlay-start ov)
945 (point))
946 (< (overlay-start ov)
947 (point))))
948 ovs))
949 (chain (if flymake-wrap-around
950 (if tail
951 (progn (setcdr (last tail) ovs) tail)
952 (and ovs (setcdr (last ovs) ovs)))
953 tail))
954 (target (nth (1- n) chain)))
955 (cond (target
956 (goto-char (overlay-start target))
957 (when interactive
958 (message
959 "%s"
960 (funcall (overlay-get target 'help-echo)
961 (selected-window) target (point)))))
962 (interactive
963 (user-error "No more Flymake errors%s"
964 (if filter
965 (format " of types %s" filter)
966 ""))))))
968 (defun flymake-goto-prev-error (&optional n filter interactive)
969 "Go to Nth previous Flymake diagnostic that matches FILTER.
970 Interactively, always move to the previous diagnostic. With a
971 prefix arg, skip any diagnostics with a severity less than
972 `:warning'.
974 If `flymake-wrap-around' is non-nil and no more previous
975 diagnostics, resumes search from bottom.
977 FILTER is a list of diagnostic types found in
978 `flymake-diagnostic-types-alist', or nil, if no filter is to be
979 applied."
980 (interactive (list 1 (if current-prefix-arg
981 '(:error :warning))
983 (flymake-goto-next-error (- (or n 1)) filter interactive))
986 ;;; Mode-line and menu
988 (easy-menu-define flymake-menu flymake-mode-map "Flymake"
989 `("Flymake"
990 [ "Go to next problem" flymake-goto-next-error t ]
991 [ "Go to previous problem" flymake-goto-prev-error t ]
992 [ "Check now" flymake-start t ]
993 [ "List all problems" flymake-show-diagnostics-buffer t ]
994 "--"
995 [ "Go to log buffer" flymake-switch-to-log-buffer t ]
996 [ "Turn off Flymake" flymake-mode t ]))
998 (defvar flymake--mode-line-format `(:eval (flymake--mode-line-format)))
1000 (put 'flymake--mode-line-format 'risky-local-variable t)
1002 (defun flymake--mode-line-format ()
1003 "Produce a pretty minor mode indicator."
1004 (let* ((known (hash-table-keys flymake--backend-state))
1005 (running (flymake-running-backends))
1006 (disabled (flymake-disabled-backends))
1007 (reported (flymake-reporting-backends))
1008 (diags-by-type (make-hash-table))
1009 (all-disabled (and disabled (null running)))
1010 (some-waiting (cl-set-difference running reported)))
1011 (maphash (lambda (_b state)
1012 (mapc (lambda (diag)
1013 (push diag
1014 (gethash (flymake--diag-type diag)
1015 diags-by-type)))
1016 (flymake--backend-state-diags state)))
1017 flymake--backend-state)
1018 `((:propertize " Flymake"
1019 mouse-face mode-line-highlight
1020 help-echo
1021 ,(concat (format "%s known backends\n" (length known))
1022 (format "%s running\n" (length running))
1023 (format "%s disabled\n" (length disabled))
1024 "mouse-1: Display minor mode menu\n"
1025 "mouse-2: Show help for minor mode")
1026 keymap
1027 ,(let ((map (make-sparse-keymap)))
1028 (define-key map [mode-line down-mouse-1]
1029 flymake-menu)
1030 (define-key map [mode-line mouse-2]
1031 (lambda ()
1032 (interactive)
1033 (describe-function 'flymake-mode)))
1034 map))
1035 ,@(pcase-let ((`(,ind ,face ,explain)
1036 (cond ((null known)
1037 `("?" mode-line "No known backends"))
1038 (some-waiting
1039 `("Wait" compilation-mode-line-run
1040 ,(format "Waiting for %s running backend(s)"
1041 (length some-waiting))))
1042 (all-disabled
1043 `("!" compilation-mode-line-run
1044 "All backends disabled"))
1046 `(nil nil nil)))))
1047 (when ind
1048 `((":"
1049 (:propertize ,ind
1050 face ,face
1051 help-echo ,explain
1052 keymap
1053 ,(let ((map (make-sparse-keymap)))
1054 (define-key map [mode-line mouse-1]
1055 'flymake-switch-to-log-buffer)
1056 map))))))
1057 ,@(unless (or all-disabled
1058 (null known))
1059 (cl-loop
1060 for (type . severity)
1061 in (cl-sort (mapcar (lambda (type)
1062 (cons type (flymake--lookup-type-property
1063 type
1064 'severity
1065 (warning-numeric-level :error))))
1066 (cl-union (hash-table-keys diags-by-type)
1067 '(:error :warning)))
1069 :key #'cdr)
1070 for diags = (gethash type diags-by-type)
1071 for face = (flymake--lookup-type-property type
1072 'mode-line-face
1073 'compilation-error)
1074 when (or diags
1075 (>= severity (warning-numeric-level :warning)))
1076 collect `(:propertize
1077 ,(format "%d" (length diags))
1078 face ,face
1079 mouse-face mode-line-highlight
1080 keymap
1081 ,(let ((map (make-sparse-keymap))
1082 (type type))
1083 (define-key map (vector 'mode-line
1084 mouse-wheel-down-event)
1085 (lambda (event)
1086 (interactive "e")
1087 (with-selected-window (posn-window (event-start event))
1088 (flymake-goto-prev-error 1 (list type) t))))
1089 (define-key map (vector 'mode-line
1090 mouse-wheel-up-event)
1091 (lambda (event)
1092 (interactive "e")
1093 (with-selected-window (posn-window (event-start event))
1094 (flymake-goto-next-error 1 (list type) t))))
1095 map)
1096 help-echo
1097 ,(concat (format "%s diagnostics of type %s\n"
1098 (propertize (format "%d"
1099 (length diags))
1100 'face face)
1101 (propertize (format "%s" type)
1102 'face face))
1103 (format "%s/%s: previous/next of this type"
1104 mouse-wheel-down-event
1105 mouse-wheel-up-event)))
1106 into forms
1107 finally return
1108 `((:propertize "[")
1109 ,@(cl-loop for (a . rest) on forms by #'cdr
1110 collect a when rest collect
1111 '(:propertize " "))
1112 (:propertize "]")))))))
1114 ;;; Diagnostics buffer
1116 (defvar-local flymake--diagnostics-buffer-source nil)
1118 (defvar flymake-diagnostics-buffer-mode-map
1119 (let ((map (make-sparse-keymap)))
1120 (define-key map (kbd "RET") 'flymake-goto-diagnostic)
1121 (define-key map (kbd "SPC") 'flymake-show-diagnostic)
1122 map))
1124 (defun flymake-show-diagnostic (pos &optional other-window)
1125 "Show location of diagnostic at POS."
1126 (interactive (list (point) t))
1127 (let* ((id (or (tabulated-list-get-id pos)
1128 (user-error "Nothing at point")))
1129 (diag (plist-get id :diagnostic)))
1130 (with-current-buffer (flymake--diag-buffer diag)
1131 (with-selected-window
1132 (display-buffer (current-buffer) other-window)
1133 (goto-char (flymake--diag-beg diag))
1134 (pulse-momentary-highlight-region (flymake--diag-beg diag)
1135 (flymake--diag-end diag)
1136 'highlight))
1137 (current-buffer))))
1139 (defun flymake-goto-diagnostic (pos)
1140 "Show location of diagnostic at POS.
1141 POS can be a buffer position or a button"
1142 (interactive "d")
1143 (pop-to-buffer
1144 (flymake-show-diagnostic (if (button-type pos) (button-start pos) pos))))
1146 (defun flymake--diagnostics-buffer-entries ()
1147 (with-current-buffer flymake--diagnostics-buffer-source
1148 (cl-loop for diag in
1149 (cl-sort (flymake-diagnostics) #'< :key #'flymake-diagnostic-beg)
1150 for (line . col) =
1151 (save-excursion
1152 (goto-char (flymake--diag-beg diag))
1153 (cons (line-number-at-pos)
1154 (- (point)
1155 (line-beginning-position))))
1156 for type = (flymake--diag-type diag)
1157 collect
1158 (list (list :diagnostic diag
1159 :line line
1160 :severity (flymake--lookup-type-property
1161 type
1162 'severity (warning-numeric-level :error)))
1163 `[,(format "%s" line)
1164 ,(format "%s" col)
1165 ,(propertize (format "%s" type)
1166 'face (flymake--lookup-type-property
1167 type 'mode-line-face 'flymake-error))
1168 (,(format "%s" (flymake--diag-text diag))
1169 mouse-face highlight
1170 help-echo "mouse-2: visit this diagnostic"
1171 face nil
1172 action flymake-goto-diagnostic
1173 mouse-action flymake-goto-diagnostic)]))))
1175 (define-derived-mode flymake-diagnostics-buffer-mode tabulated-list-mode
1176 "Flymake diagnostics"
1177 "A mode for listing Flymake diagnostics."
1178 (setq tabulated-list-format
1179 `[("Line" 5 (lambda (l1 l2)
1180 (< (plist-get (car l1) :line)
1181 (plist-get (car l2) :line)))
1182 :right-align t)
1183 ("Col" 3 nil :right-align t)
1184 ("Type" 8 (lambda (l1 l2)
1185 (< (plist-get (car l1) :severity)
1186 (plist-get (car l2) :severity))))
1187 ("Message" 0 t)])
1188 (setq tabulated-list-entries
1189 'flymake--diagnostics-buffer-entries)
1190 (tabulated-list-init-header))
1192 (defun flymake--diagnostics-buffer-name ()
1193 (format "*Flymake diagnostics for %s*" (current-buffer)))
1195 (defun flymake-show-diagnostics-buffer ()
1196 "Show a list of Flymake diagnostics for current buffer."
1197 (interactive)
1198 (let* ((name (flymake--diagnostics-buffer-name))
1199 (source (current-buffer))
1200 (target (or (get-buffer name)
1201 (with-current-buffer (get-buffer-create name)
1202 (flymake-diagnostics-buffer-mode)
1203 (setq flymake--diagnostics-buffer-source source)
1204 (current-buffer)))))
1205 (with-current-buffer target
1206 (revert-buffer)
1207 (display-buffer (current-buffer)))))
1209 (provide 'flymake)
1211 (require 'flymake-proc)
1213 ;;; flymake.el ends here