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