Merge from origin/emacs-26
[emacs.git] / doc / misc / flymake.texi
blob1e7a5e82c618ad0fad73da72ff97944c2aac6114
1 \input texinfo   @c -*-texinfo; coding: utf-8 -*-
2 @comment %**start of header
3 @setfilename ../../info/flymake.info
4 @set VERSION 1.0
5 @set UPDATED June 2018
6 @settitle GNU Flymake @value{VERSION}
7 @include docstyle.texi
8 @syncodeindex pg cp
9 @syncodeindex vr cp
10 @syncodeindex fn cp
11 @comment %**end of header
13 @copying
14 This manual is for GNU Flymake (version @value{VERSION}, @value{UPDATED}),
15 which is a universal on-the-fly syntax checker for GNU Emacs.
17 Copyright @copyright{} 2004--2018 Free Software Foundation, Inc.
19 @quotation
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with the Front-Cover Texts being ``A GNU Manual,''
24 and with the Back-Cover Texts as in (a) below.  A copy of the license
25 is included in the section entitled ``GNU Free Documentation License''.
27 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
28 modify this GNU manual.''
29 @end quotation
30 @end copying
32 @dircategory Emacs misc features
33 @direntry
34 * Flymake: (flymake).           A universal on-the-fly syntax checker.
35 @end direntry
37 @titlepage
38 @title GNU Flymake
39 @subtitle for version @value{VERSION}, @value{UPDATED}
40 @author João Távora and Pavel Kobiakov(@email{pk_at_work@@yahoo.com}).
41 @page
42 @vskip 0pt plus 1filll
43 @insertcopying
44 @end titlepage
46 @contents
48 @ifnottex
49 @node Top
50 @top GNU Flymake
51 @insertcopying
52 @end ifnottex
54 @menu
55 * Using Flymake::
56 * Extending Flymake::
57 * The legacy Proc backend::
58 * GNU Free Documentation License::
59 * Index::
60 @end menu
62 @node Using Flymake
63 @chapter Using Flymake
64 @cindex overview of flymake
65 @cindex using flymake
67 Flymake is a universal on-the-fly buffer checker implemented as an
68 Emacs minor mode.  To use Flymake, you must first activate
69 @code{flymake-mode} by using the command @kbd{flymake-mode}.
71 When enabled, Flymake collects information about problems in the
72 buffer, called @dfn{diagnostics}, from one or more different sources,
73 or @dfn{backends}, and then visually annotates the buffer by
74 highlighting problematic buffer regions with a special face.
76 It also displays an overall buffer status in the mode line containing
77 totals for different types of diagnostics.
79 Syntax check is done ``on-the-fly''.  It is started whenever
81 @itemize @bullet
82 @item
83 @code{flymake-mode} is started, unless
84 @code{flymake-start-on-flymake-mode} is nil;
86 @item
87 the buffer is saved, unless @code{flymake-start-on-save-buffer} is
88 nil;
90 @item
91 a newline character is added to the buffer, unless
92 @code{flymake-start-syntax-check-on-newline} is nil;
94 @item
95 some changes were made to the buffer more than @code{0.5} seconds ago
96 (the delay is configurable in @code{flymake-no-changes-timeout}).
97 @end itemize
99 Syntax check can also be started manually by typing the @kbd{M-x
100 flymake-start @key{RET}} command.
102 @code{flymake-goto-next-error} and @code{flymake-goto-prev-error} are
103 commands that allow easy navigation to the next/previous erroneous
104 line, respectively.  If might be a good idea to map them to @kbd{M-n}
105 and @kbd{M-p} in @code{flymake-mode}, by adding to your init file:
107 @lisp
108 (define-key flymake-mode-map (kbd "M-n") 'flymake-goto-next-error)
109 (define-key flymake-mode-map (kbd "M-p") 'flymake-goto-prev-error)
110 @end lisp
112 Flymake is a universal syntax checker in the sense that it's easily
113 extended to support new backends (@pxref{Extending Flymake}).
115 Historically, Flymake used to accept diagnostics from a single
116 backend, albeit a reasonably flexible one.
118 This backend isn't (yet) obsolete, and so is still available as a
119 fallback and active by default (@pxref{The legacy Proc backend}).  It works by
120 selecting a syntax check tool from a preconfigured list (compiler for
121 C@t{++} files, @command{perl} for Perl files, etc.), and executing it in the
122 background, passing it a temporary file which is a copy of the current
123 buffer, and parsing the output for known error/warning message
124 patterns.
126 @menu
127 * Syntax check statuses::
128 * Backend exceptions::
129 * Customizable variables::
130 @end menu
132 @node Syntax check statuses
133 @section Syntax check statuses
134 @cindex Syntax check statuses
136 When enabled, Flymake displays its status in the mode line, which
137 provides a visual summary of diagnostic collection.  It may also hint
138 at certain exceptional situations encountered when communicating with
139 backends.
141 The following statuses are defined:
143 @multitable @columnfractions 0.25 0.75
144 @item [@var{nerrors} @var{nwarnings} ...]
145 @tab Normal operation. @var{nerrors} and @var{nwarnings} are, respectively,
146 the total number of errors and warnings found during the last buffer
147 check, for all backends. They may be followed by other totals for
148 other types of diagnostics (@pxref{Flymake error types}).
150 @item @code{Wait}
151 @tab  Some Flymake backends haven't reported since the last time they
152 where questioned.  It is reasonable to assume that this is a temporary
153 delay and Flymake will resume normal operation soon.
155 @item @code{!}
156 @tab All the configured Flymake backends have disabled themselves: Flymake
157 cannot annotate the buffer and action from the user is needed to
158 investigate and remedy the situation (@pxref{Backend exceptions}).
160 @item @code{?}
161 @tab There are no applicable Flymake backends for this buffer, thus Flymake
162 cannot annotate it.  To fix this, a user may look to extending Flymake
163 and add a new backend (@pxref{Extending Flymake}).
165 @end multitable
167 @node Backend exceptions
168 @section Backend exceptions
169 @cindex backend exceptions
171 @cindex disabled backends
172 @cindex backends, disabled
173 Some backends may take longer than others to respond or complete, and
174 some may decide to @emph{disable} themselves if they are not suitable
175 for the current buffer or encounter some unavoidable problem.  A
176 disabled backend is not tried again for future checks of the current
177 buffer.
179 @findex flymake-reporting-backends
180 @findex flymake-running-backends
181 @findex flymake-disabled-backends
182 The commands @code{flymake-reporting-backends},
183 @code{flymake-running-backends} and @code{flymake-disabled-backends}
184 show the backends currently used and those which are disabled.
186 @cindex reset disabled backends
187 Toggling @code{flymake-mode} off and on again, or invoking
188 @code{flymake-start} with a prefix argument is one way to reset the
189 disabled backend list, so that they will be tried again in the next check.
191 @cindex logging
192 @cindex flymake logging
193 Flymake also uses a simple logging facility for indicating important
194 points in the control flow.  The logging facility sends logging
195 messages to the @file{*Flymake log*} buffer.  The information logged
196 can be used for resolving various problems related to Flymake.  For
197 convenience, a shortcut to this buffer can be found in Flymake's menu,
198 accessible from the top menu bar or just left of the status indicator.
200 @vindex warning-minimum-log-level
201 @vindex warning-minimum-level
202 Logging output is controlled by the Emacs @code{warning-minimum-log-level}
203 and @code{warning-minimum-level} variables.
205 @node Customizable variables
206 @section Customizable variables
207 @cindex customizable variables
208 @cindex variables for customizing flymake
210 This section summarizes customization variables used for the
211 configuration of the Flymake user interface.
213 @vtable @code
214 @item flymake-no-changes-timeout
215 If any changes are made to the buffer, syntax check is automatically
216 started after this many seconds, unless the user makes another change,
217 which resets the timer.
219 @item flymake-start-syntax-check-on-newline
220 A boolean flag indicating whether to start syntax check immediately
221 after a newline character is inserted into the buffer.
223 @item flymake-start-on-flymake-mode
224 A boolean flag indicating whether to start syntax check immediately
225 after enabling @code{flymake-mode}.
227 @item flymake-start-on-save-buffer
228 A boolean flag indicating whether to start syntax check after saving
229 the buffer.
231 @item flymake-error
232 A custom face for highlighting regions for which an error has been
233 reported.
235 @item flymake-warning
236 A custom face for highlighting regions for which a warning has been
237 reported.
239 @item flymake-note
240 A custom face for highlighting regions for which a note has been
241 reported.
243 @item flymake-error-bitmap
244 A bitmap used in the fringe to mark lines for which an error has
245 been reported.
247 @item flymake-warning-bitmap
248 A bitmap used in the fringe to mark lines for which a warning has
249 been reported.
251 @item flymake-fringe-indicator-position
252 Which fringe (if any) should show the warning/error bitmaps.
254 @item flymake-wrap-around
255 If non-nil, moving to errors with @code{flymake-goto-next-error} and
256 @code{flymake-goto-prev-error} wraps around buffer boundaries.
257 @end vtable
259 @node Extending Flymake
260 @chapter Extending Flymake
261 @cindex extending flymake
263 Flymake can primarily be extended in one of two ways:
265 @enumerate
266 @item
267 By changing the look and feel of the annotations produced by the
268 different backends.
270 @item
271 By adding a new buffer-checking backend.
272 @end enumerate
274 The following sections discuss each approach in detail.
276 @menu
277 * Flymake error types::
278 * Backend functions::
279 @end menu
281 @node Flymake error types
282 @section Customizing Flymake error types
283 @cindex customizing error types
284 @cindex error types, customization
286 To customize the appearance of error types, set properties on the
287 symbols associated with each diagnostic type.  The standard diagnostic
288 symbols are @code{:error}, @code{:warning} and @code{:note} (though
289 the backend may define more, @pxref{Backend functions}).
291 The following properties can be set:
293 @itemize
295 @item
296 @cindex bitmap of diagnostic
297 @code{flymake-bitmap}, an image displayed in the fringe according to
298 @code{flymake-fringe-indicator-position}.  The value actually follows
299 the syntax of @code{flymake-error-bitmap} (@pxref{Customizable
300 variables}).  It is overridden by any @code{before-string} overlay
301 property.
303 @item
304 @code{flymake-overlay-control}, an alist ((@var{OVPROP} . @var{VALUE})
305 @var{...}) of further properties used to affect the appearance of
306 Flymake annotations.  With the exception of @code{category} and
307 @code{evaporate}, these properties are applied directly to the created
308 overlay (@pxref{Overlay Properties,,, elisp, The Emacs Lisp Reference
309 Manual}).
311 As an example, here's how to make diagnostics of the type @code{:note}
312 stand out more prominently:
314 @example
315 (push '(face . highlight) (get :note 'flymake-overlay-control))
316 @end example
318 If you push another alist entry in front, it overrides the previous
319 one.  So this effectively removes the face from @code{:note}
320 diagnostics:
322 @example
323 (push '(face . nil) (get :note 'flymake-overlay-control))
324 @end example
326 To restore the original look for @code{:note} types, empty or remove
327 its @code{flymake-overlay-control} property:
329 @example
330 (put :note 'flymake-overlay-control '())
331 @end example
333 @item
334 @cindex severity of diagnostic
335 @code{flymake-severity} is a non-negative integer specifying the
336 diagnostic's severity.  The higher the value, the more serious is the
337 error.  If the overlay property @code{priority} is not specified in
338 @code{flymake-overlay-control}, @code{flymake-severity} is used to set
339 it and help sort overlapping overlays.
341 @item
342 @vindex flymake-category
343 @code{flymake-category} is a symbol whose property list is considered
344 the default for missing values of any other properties.
345 @end itemize
347 @cindex predefined diagnostic types
348 @vindex flymake-error
349 @vindex flymake-warning
350 @vindex flymake-note
351 Three default diagnostic types are predefined: @code{:error},
352 @code{:warning}, and @code{:note}.  By default, each one of them has a
353 @code{flymake-category} property whose value is, respectively, the
354 category symbol @code{flymake-error}, @code{flymake-warning} and
355 @code{flymake-note}.
357 These category symbols' plist is where the values of customizable
358 variables and faces (such as @code{flymake-error-bitmap}) are found.
359 Thus, if you change their plists, Flymake may stop honoring these user
360 customizations.
362 The @code{flymake-category} special property is especially useful for
363 backends which create diagnostics objects with non-default types that
364 differ from an existing type by only a few properties (@pxref{Flymake
365 utility functions}).
367 As an example, consider configuring a new diagnostic type
368 @code{:low-priority-note} that behaves much like @code{:note}, but
369 without an overlay face.
371 @example
372 (put :low-priority-note 'flymake-overlay-control '((face . nil)))
373 (put :low-priority-note 'flymake-category 'flymake-note)
374 @end example
376 @vindex flymake-diagnostics
377 @vindex flymake-diagnostic-backend
378 @vindex flymake-diagnostic-buffer
379 @vindex flymake-diagnostic-text
380 @vindex flymake-diagnostic-beg
381 @vindex flymake-diagnostic-end
382 As you might have guessed, Flymake's annotations are implemented as
383 overlays (@pxref{Overlays,,, elisp, The Emacs Lisp Reference Manual}).
384 Along with the properties that you specify for the specific type of
385 diagnostic, Flymake adds the property @code{flymake-diagnostic} to
386 these overlays, and sets it to the object that the backend created
387 with @code{flymake-make-diagnostic}.
389 Since overlays also support arbitrary keymaps, you can use this along
390 with the functions @code{flymake-diagnostics} and
391 @code{flymake-diagnostic-text} (@pxref{Flymake utility functions}) to
392 create interactive annotations, such as in the following example of
393 binding a @code{mouse-3} event (middle mouse button click) to an
394 Internet search for the text of a @code{:warning} or @code{:error}.
396 @example
397 (defun my-search-for-message (event)
398   (interactive "e")
399   (let* ((diags (flymake-diagnostics (posn-point (event-start event))))
400          (topmost-diag (car diags)))
401     (eww-browse-url
402        (concat
403         "https://duckduckgo.com/?q="
404         (replace-regexp-in-string
405           " " "+" (flymake-diagnostic-text topmost-diag)))
406        t)))
408 (dolist (type '(:warning :error))
409   (push '(mouse-face . highlight) (get type 'flymake-overlay-control))
410   (push `(keymap . ,(let ((map (make-sparse-keymap)))
411                       (define-key map [mouse-2]
412                         'my-search-for-message)
413                       map))
414         (get type 'flymake-overlay-control)))
415 @end example
417 @node Backend functions
418 @section Backend functions
419 @cindex backend functions
421 @vindex flymake-diagnostic-functions
422 Flymake backends are Lisp functions placed in the special hook
423 @code{flymake-diagnostic-functions}.
425 A backend's responsibility is to diagnose the contents of a buffer for
426 problems, registering the problem's positions, type, and summary
427 description.  This information is collected in the form of diagnostic
428 objects created by the function @code{flymake-make-diagnostic}
429 (@pxref{Flymake utility functions}), and
430 then handed over to Flymake, which proceeds to annotate the
431 buffer.
433 A request for a buffer check, and the subsequent delivery of
434 diagnostics, are two key events of the interaction between Flymake
435 and backend.  Each such event corresponds to a well-defined function
436 calling convention: one for calls made by Flymake into the backend via
437 the backend function, the other in the reverse direction via a
438 callback.  To be usable, backends must adhere to both.
440 The first argument passed to a backend function is always
441 @var{report-fn}, a callback function detailed below.  Beyond it,
442 functions must be prepared to accept (and possibly ignore) an
443 arbitrary number of keyword-value pairs of the form
444 @w{@code{(@var{:key} @var{value} @var{:key2} @var{value2}...)}}.
446 Currently, Flymake may pass the following keywords and values to the
447 backend function:
449 @itemize
451 @item @code{:recent-changes}
452 The value is a list recent changes since the last time the backend
453 function was called for the buffer.  If the list is empty, this
454 indicates that no changes have been recorded.  If it is the first time
455 that this backend function is called for this activation of
456 @code{flymake-mode}, then this argument isn't provided at all
457 (i.e. it's not merely nil).
459 Each element is in the form (@var{beg} @var{end} @var{text}) where
460 @var{beg} and @var{end} are buffer positions, and @var{text} is a
461 string containing the text contained between those positions (if any),
462 after the change was performed.
464 @item @code{:changes-start} and @code{:changes-end}
465 The value is, repectively, the minimum and maximum buffer positions
466 touched by the recent changes.  These are provided for convenience and
467 only if @code{:recent-changes} is also provided.
469 @end itemize
471 Whenever Flymake or the user decide to re-check the buffer, backend
472 functions are called as detailed above, and are expected to initiate
473 this check, but aren't in any way required to complete it before
474 exiting: if the computation involved is expensive, as
475 is often the case with large buffers, that slower task should be
476 scheduled for the future using asynchronous sub-processes
477 (@pxref{Asynchronous Processes,,, elisp, The Emacs Lisp reference
478 manual}) or other asynchronous mechanisms.
480 In any case, backend functions are expected to return quickly or
481 signal an error, in which case the backend is disabled
482 (@pxref{Backend exceptions}).
484 If the function returns, Flymake considers the backend to be
485 @dfn{running}.  If it has not done so already, the backend is expected
486 to call the function @var{report-fn} passed to it, at which point
487 Flymake considers the backend to be @dfn{reporting}.  Backends call
488 @var{report-fn} by passing it a single argument @var{report-action}
489 followed by an optional list of keyword-value pairs of the form
490 @w{@code{(@var{:report-key} @var{value} @var{:report-key2} @var{value2}...)}}.
492 Currently accepted values for @var{report-action} are:
494 @itemize
495 @item
496 A (possibly empty) list of diagnostic objects created by
497 @code{flymake-make-diagnostic}, causing Flymake to annotate the
498 buffer with this information.
500 A backend may call @var{report-fn} repeatedly in this manner, but only
501 until Flymake considers that the most recently requested buffer check
502 is now obsolete, because, say, buffer contents have changed in the
503 meantime.  The backend is only given notice of this via a renewed call
504 to the backend function.  Thus, to prevent making obsolete reports and
505 wasting resources, backend functions should first cancel any ongoing
506 processing from previous calls.
508 @item
509 The symbol @code{:panic}, signaling that the backend has encountered
510 an exceptional situation and should be disabled.
511 @end itemize
513 Currently accepted @var{report-key} arguments are:
515 @itemize
516 @item
517 @code{:explanation}, whose value should give user-readable
518 details of the situation encountered, if any.
520 @item
521 @code{:force}, whose value should be a boolean suggesting
522 that Flymake consider the report even if it was somehow
523 unexpected.
525 @item
526 @code{:region}, a cons (@var{beg} . @var{end}) of buffer positions
527 indicating that the report applies to that region and that previous
528 reports targeting other parts of the buffer remain valid.
529 @end itemize
531 @menu
532 * Flymake utility functions::
533 * An annotated example backend::
534 @end menu
536 @node Flymake utility functions
537 @subsection Flymake utility functions
538 @cindex utility functions
540 @cindex create diagnostic object
541 Before delivering them to Flymake, backends create diagnostic objects
542 by calling the function @code{flymake-make-diagnostic}.
544 @deffn Function flymake-make-diagnostic buffer beg end type text
545 Make a Flymake diagnostic for @var{buffer}'s region from @var{beg} to
546 @var{end}.  @var{type} is a diagnostic symbol (@pxref{Flymake error
547 types}), and @var{text} is a description of the problem detected in
548 this region.
549 @end deffn
551 @cindex access diagnostic object
552 These objects' properties can be accessed with the functions
553 @code{flymake-diagnostic-backend}, @code{flymake-diagnostic-buffer},
554 @code{flymake-diagnostic-text}, @code{flymake-diagnostic-beg},
555 @code{flymake-diagnostic-end} and @code{flymake-diagnostic-type}.
557 Additionally, the function @code{flymake-diagnostics} will collect
558 such objects in the region you specify.
560 @cindex collect diagnostic objects
561 @deffn Function flymake-diagnostics beg end
562 Get a list of Flymake diagnostics in the region determined by
563 @var{beg} and @var{end}.  If neither @var{beg} or @var{end} is
564 supplied, use the whole buffer, otherwise if @var{beg} is
565 non-@code{nil} and @var{end} is @code{nil}, consider only diagnostics
566 at @var{beg}.
567 @end deffn
569 @cindex buffer position from line and column number
570 It is often the case with external syntax tools that a diagnostic's
571 position is reported in terms of a line number, and sometimes a column
572 number.  To convert this information into a buffer position, backends
573 can use the following function:
575 @deffn Function flymake-diag-region buffer line &optional col
576 Compute @var{buffer}'s region (@var{beg} .  @var{end}) corresponding
577 to @var{line} and @var{col}.  If @var{col} is @code{nil}, return a
578 region just for @var{line}.  Return @code{nil} if the region is
579 invalid.
580 @end deffn
582 @cindex add a log message
583 For troubleshooting purposes, backends may record arbitrary
584 exceptional or erroneous situations into the Flymake log
585 buffer (@pxref{Backend exceptions}):
587 @deffn Macro flymake-log level msg &optional args
588 Log, at level @var{level}, the message @var{msg} formatted with
589 @var{args}.  @var{level} is passed to @code{display-warning}
590 (@pxref{Warning Basics,,, elisp, The Emacs Lisp reference Manual}), which is
591 used to display the warning in Flymake's log buffer.
592 @end deffn
594 @node An annotated example backend
595 @subsection An annotated example backend
596 @cindex example of backend
597 @cindex backend, annotated example
599 This section presents an annotated example of a complete working
600 Flymake backend.  The example illustrates the process of writing a
601 backend as outlined above.
603 The backend in question is used for checking Ruby source files.  It
604 uses asynchronous sub-processes (@pxref{Asynchronous Processes,,, elisp,
605 The Emacs Lisp Reference Manual}), a common technique for performing
606 parallel processing in Emacs.
608 The following code needs lexical binding (@pxref{Using Lexical
609 Binding,,, elisp, The Emacs Lisp Reference Manual}) to be active.
611 @example
612 ;;; ruby-flymake.el --- A ruby Flymake backend  -*- lexical-binding: t; -*-
613 (defvar-local ruby--flymake-proc nil)
615 (defun ruby-flymake (report-fn &rest _args)
616   ;; Not having a ruby interpreter is a serious problem which should cause
617   ;; the backend to disable itself, so an @code{error} is signaled.
618   ;;
619   (unless (executable-find
620            "ruby") (error "Cannot find a suitable ruby"))
621   ;; If a live process launched in an earlier check was found, that
622   ;; process is killed.  When that process's sentinel eventually runs,
623   ;; it will notice its obsoletion, since it have since reset
624   ;; `ruby-flymake-proc' to a different value
625   ;;
626   (when (process-live-p ruby--flymake-proc)
627     (kill-process ruby--flymake-proc))
629   ;; Save the current buffer, the narrowing restriction, remove any
630   ;; narrowing restriction.
631   ;;
632   (let ((source (current-buffer)))
633     (save-restriction
634       (widen)
635       ;; Reset the `ruby--flymake-proc' process to a new process
636       ;; calling the ruby tool.
637       ;;
638       (setq
639        ruby--flymake-proc
640        (make-process
641         :name "ruby-flymake" :noquery t :connection-type 'pipe
642         ;; Make output go to a temporary buffer.
643         ;;
644         :buffer (generate-new-buffer " *ruby-flymake*")
645         :command '("ruby" "-w" "-c")
646         :sentinel
647         (lambda (proc _event)
648           ;; Check that the process has indeed exited, as it might
649           ;; be simply suspended.
650           ;;
651           (when (eq 'exit (process-status proc))
652             (unwind-protect
653                 ;; Only proceed if `proc' is the same as
654                 ;; `ruby--flymake-proc', which indicates that
655                 ;; `proc' is not an obsolete process.
656                 ;;
657                 (if (with-current-buffer source (eq proc ruby--flymake-proc))
658                     (with-current-buffer (process-buffer proc)
659                       (goto-char (point-min))
660                       ;; Parse the output buffer for diagnostic's
661                       ;; messages and locations, collect them in a list
662                       ;; of objects, and call `report-fn'.
663                       ;;
664                       (cl-loop
665                        while (search-forward-regexp
666                               "^\\(?:.*.rb\\|-\\):\\([0-9]+\\): \\(.*\\)$"
667                               nil t)
668                        for msg = (match-string 2)
669                        for (beg . end) = (flymake-diag-region
670                                           source
671                                           (string-to-number (match-string 1)))
672                        for type = (if (string-match "^warning" msg)
673                                       :warning
674                                     :error)
675                        collect (flymake-make-diagnostic source
676                                                         beg
677                                                         end
678                                                         type
679                                                         msg)
680                        into diags
681                        finally (funcall report-fn diags)))
682                   (flymake-log :warning "Canceling obsolete check %s"
683                                proc))
684               ;; Cleanup the temporary buffer used to hold the
685               ;; check's output.
686               ;;
687               (kill-buffer (process-buffer proc)))))))
688       ;; Send the buffer contents to the process's stdin, followed by
689       ;; an EOF.
690       ;;
691       (process-send-region ruby--flymake-proc (point-min) (point-max))
692       (process-send-eof ruby--flymake-proc))))
694 (defun ruby-setup-flymake-backend ()
695   (add-hook 'flymake-diagnostic-functions 'ruby-flymake nil t))
697 (add-hook 'ruby-mode-hook 'ruby-setup-flymake-backend)
698 @end example
700 @node The legacy Proc backend
701 @chapter The legacy ``Proc'' backend
702 @cindex legacy proc backend
704 @menu
705 * Proc customization variables::
706 * Adding support for a new syntax check tool::
707 * Implementation overview::
708 * Making a temporary copy::
709 * Locating a master file::
710 * Getting the include directories::
711 * Locating the buildfile::
712 * Starting the syntax check process::
713 * Parsing the output::
714 * Interaction with other modes::
715 @end menu
717 @findex flymake-proc-legacy-backend
718 The backend @code{flymake-proc-legacy-backend} was originally designed
719 to be extended for supporting new syntax check tools and error message
720 patterns.  It is also controlled by its own set of customization variables
722 @node Proc customization variables
723 @section Customization variables for the Proc backend
724 @cindex proc backend customization variables
726 @vtable @code
727 @item flymake-proc-allowed-file-name-masks
728 A list of @code{(filename-regexp, init-function, cleanup-function
729 getfname-function)} for configuring syntax check tools.  @xref{Adding
730 support for a new syntax check tool}.
732 @item flymake-proc-master-file-dirs
733 A list of directories for searching a master file.  @xref{Locating a
734 master file}.
736 @item flymake-proc-get-project-include-dirs-function
737 A function used for obtaining a list of project include dirs (C/C++
738 specific).  @xref{Getting the include directories}.
740 @item flymake-proc-master-file-count-limit
741 @itemx flymake-proc-check-file-limit
742 Used when looking for a master file.  @xref{Locating a master file}.
744 @item flymake-proc-err-line-patterns
745 Patterns for error/warning messages in the form @code{(regexp file-idx
746 line-idx col-idx err-text-idx)}.  @xref{Parsing the output}.
748 @item flymake-proc-diagnostic-type-pred
749 A function to classify a diagnostic text as particular type of error.
750 Should be a function taking an error text and returning a diagnostic
751 symbol (@pxref{Flymake error types}).  If non-nil is returned but
752 there is no such symbol in that table, a warning is assumed.  If nil
753 is returned, an error is assumed.  Can also be a regular expression
754 that should match only warnings.  This variable replaces the old
755 @code{flymake-warning-re} and @code{flymake-warning-predicate}.
757 @item flymake-proc-compilation-prevents-syntax-check
758 A flag indicating whether compilation and syntax check of the same
759 file cannot be run simultaneously.  @xref{Interaction with other modes}.
760 @end vtable
762 @node Adding support for a new syntax check tool
763 @section Adding support for a new syntax check tool
764 @cindex adding support for a new syntax check tool
766 @menu
767 * Example---Configuring a tool called directly::
768 * Example---Configuring a tool called via make::
769 @end menu
771 Syntax check tools are configured using the
772 @code{flymake-proc-allowed-file-name-masks} list.  Each item of this list
773 has the following format:
775 @lisp
776 (filename-regexp, init-function, cleanup-function, getfname-function)
777 @end lisp
779 @table @code
780 @item filename-regexp
781 This field is used as a key for locating init/cleanup/getfname
782 functions for the buffer.  Items in
783 @code{flymake-proc-allowed-file-name-masks} are searched sequentially.
784 The first item with @code{filename-regexp} matching buffer filename is
785 selected.  If no match is found, @code{flymake-mode} is switched off.
787 @item init-function
788 @code{init-function} is required to initialize the syntax check,
789 usually by creating a temporary copy of the buffer contents.  The
790 function must return @code{(list cmd-name arg-list)}.  If
791 @code{init-function} returns null, syntax check is aborted, but
792 @code{flymake-mode} is not switched off.
794 @item cleanup-function
795 @code{cleanup-function} is called after the syntax check process is
796 complete and should take care of proper deinitialization, which is
797 usually deleting a temporary copy created by the @code{init-function}.
799 @item getfname-function
800 This function is used for translating filenames reported by the syntax
801 check tool into ``real'' filenames.  Filenames reported by the tool
802 will be different from the real ones, as actually the tool works with
803 the temporary copy.  In most cases, the default implementation
804 provided by Flymake, @code{flymake-proc-get-real-file-name}, can be
805 used as @code{getfname-function}.
806 @end table
808 To add support for a new syntax check tool, write the corresponding
809 @code{init-function} and, optionally, @code{cleanup-function} and
810 @code{getfname-function}.  If the format of error messages reported by
811 the new tool is not yet supported by Flymake, add a new entry to
812 the @code{flymake-proc-err-line-patterns} list.
814 The following sections contain some examples of configuring Flymake
815 support for various syntax check tools.
817 @node Example---Configuring a tool called directly
818 @subsection Example---Configuring a tool called directly
819 @cindex adding support for perl
821 In this example, we will add support for @command{perl} as a syntax check
822 tool.  @command{perl} supports the @option{-c} option which does syntax
823 checking.
825 First, we write the @code{init-function}:
827 @lisp
828 (defun flymake-proc-perl-init ()
829   (let* ((temp-file (flymake-proc-init-create-temp-buffer-copy
830                      'flymake-proc-create-temp-inplace))
831          (local-file (file-relative-name
832                       temp-file
833                       (file-name-directory buffer-file-name))))
834     (list "perl" (list "-wc " local-file))))
835 @end lisp
837 @code{flymake-proc-perl-init} creates a temporary copy of the buffer
838 contents with the help of
839 @code{flymake-proc-init-create-temp-buffer-copy}, and builds an appropriate
840 command line.
842 Next, we add a new entry to the
843 @code{flymake-proc-allowed-file-name-masks}:
845 @lisp
846 (setq flymake-proc-allowed-file-name-masks
847       (cons '(".+\\.pl$"
848               flymake-proc-perl-init
849               flymake-proc-simple-cleanup
850               flymake-proc-get-real-file-name)
851             flymake-proc-allowed-file-name-masks))
852 @end lisp
854 Note that we use standard @code{cleanup-function} and
855 @code{getfname-function}.
857 Finally, we add an entry to @code{flymake-proc-err-line-patterns}:
859 @lisp
860 (setq flymake-proc-err-line-patterns
861       (cons '("\\(.*\\) at \\([^ \n]+\\) line \\([0-9]+\\)[,.\n]"
862               2 3 nil 1)
863             flymake-proc-err-line-patterns))
864 @end lisp
866 @node Example---Configuring a tool called via make
867 @subsection Example---Configuring a tool called via make
868 @cindex adding support for C (gcc+make)
870 In this example we will add support for C files syntax checked by
871 @command{gcc} called via @command{make}.
873 We're not required to write any new functions, as Flymake already has
874 functions for @command{make}.  We just add a new entry to the
875 @code{flymake-proc-allowed-file-name-masks}:
877 @lisp
878 (setq flymake-proc-allowed-file-name-masks
879       (cons '(".+\\.c$"
880               flymake-proc-simple-make-init
881               flymake-proc-simple-cleanup
882               flymake-proc-get-real-file-name)
883             flymake-proc-allowed-file-name-masks))
884 @end lisp
886 @code{flymake-proc-simple-make-init} builds the following @command{make}
887 command line:
889 @lisp
890 (list "make"
891       (list "-s" "-C"
892             base-dir
893             (concat "CHK_SOURCES=" source)
894             "SYNTAX_CHECK_MODE=1"
895             "check-syntax"))
896 @end lisp
898 @code{base-dir} is a directory containing the @file{Makefile}, see
899 @ref{Locating the buildfile}.
901 Thus, @file{Makefile} must contain the @code{check-syntax} target.  In
902 our case this target might look like this:
904 @verbatim
905 check-syntax:
906         gcc -o /dev/null -S ${CHK_SOURCES} || true
907 @end verbatim
909 @noindent
910 The format of error messages reported by @command{gcc} is already
911 supported by Flymake, so we don't have to add a new entry to
912 @code{flymake-err-line-patterns}.  Note that if you are using
913 Automake, you may want to replace @code{gcc} with the standard
914 Automake variable @code{COMPILE}:
916 @verbatim
917 check-syntax:
918         $(COMPILE) -o /dev/null -S ${CHK_SOURCES} || true
919 @end verbatim
921 @node Implementation overview
922 @section Implementation overview
923 @cindex syntax check models
924 @cindex master file
926 @code{flymake-proc-legacy-backend} saves a copy of the buffer in a
927 temporary file in the buffer's directory (or in the system temporary
928 directory, for Java files), creates a syntax check command and
929 launches a process with this command.  The output is parsed using a
930 list of error message patterns, and error information (file name, line
931 number, type and text) is saved.  After the process has finished,
932 Flymake highlights erroneous lines in the buffer using the accumulated
933 error information.
935 Syntax check is considered possible if there's an entry in
936 @code{flymake-proc-allowed-file-name-masks} matching buffer's filename and
937 its @code{init-function} returns non-@code{nil} value.
939 Two syntax check modes are distinguished:
941 @enumerate
943 @item
944 Buffer can be syntax checked in a standalone fashion, that is, the
945 file (its temporary copy, in fact) can be passed over to the compiler to
946 do the syntax check.  Examples are C/C@t{++} sources (@file{.c},
947 @file{.cpp}) and Java (@file{.java}).
949 @item
950 Buffer can be syntax checked, but additional file, called master file,
951 is required to perform this operation.  A master file is a file that
952 includes the current file, so that running a syntax check tool on it
953 will also check syntax in the current file.  Examples are C/C@t{++}
954 headers (@file{.h}, @file{.hpp}).
956 @end enumerate
958 These modes are handled inside init/cleanup/getfname functions, see
959 @ref{Adding support for a new syntax check tool}.
961 The Proc backend contains implementations of all functionality
962 required to support different syntax check modes described above
963 (making temporary copies, finding master files, etc.), as well as some
964 tool-specific (routines for Make, Ant, etc.)@: code.
967 @node Making a temporary copy
968 @section Making a temporary copy
969 @cindex temporary copy of the buffer
971 After the possibility of the syntax check has been determined, a
972 temporary copy of the current buffer is made so that the most recent
973 unsaved changes could be seen by the syntax check tool.  Making a copy
974 is quite straightforward in a standalone case (mode @code{1}), as it's
975 just saving buffer contents to a temporary file.
977 Things get trickier, however, when master file is involved, as it
978 requires to
980 @itemize @bullet
981 @item
982 locate a master file
983 @item
984 patch it to include the current file using its new (temporary) name.
985 @end itemize
987 Locating a master file is discussed in the following section.
989 Patching just changes all appropriate lines of the master file so that they
990 use the new (temporary) name of the current file.  For example, suppose current
991 file name is @code{file.h}, the master file is @code{file.cpp}, and
992 it includes current file via @code{#include "file.h"}.  Current file's copy
993 is saved to file @code{file_flymake.h}, so the include line must be
994 changed to @code{#include "file_flymake.h"}.  Finally, patched master file
995 is saved to @code{file_flymake_master.cpp}, and the last one is passed to
996 the syntax check tool.
998 @node Locating a master file
999 @section Locating a master file
1000 @cindex locating a master file
1001 @cindex master file, locating
1003 Master file is located in two steps.
1005 First, a list of possible master files is built.  A simple name
1006 matching is used to find the files.  For a C++ header @file{file.h},
1007 the Proc backend searches for all @file{.cpp} files in the directories
1008 whose relative paths are stored in a customizable variable
1009 @code{flymake-proc-master-file-dirs}, which usually contains something
1010 like @code{("." "./src")}.  No more than
1011 @code{flymake-proc-master-file-count-limit} entries is added to the
1012 master file list.  The list is then sorted to move files with names
1013 @file{file.cpp} to the top.
1015 Next, each master file in a list is checked to contain the appropriate
1016 include directives.  No more than @code{flymake-proc-check-file-limit} of each
1017 file are parsed.
1019 For @file{file.h}, the include directives to look for are
1020 @code{#include "file.h"}, @code{#include "../file.h"}, etc.  Each
1021 include is checked against a list of include directories
1022 (see @ref{Getting the include directories}) to be sure it points to the
1023 correct @file{file.h}.
1025 First matching master file found stops the search.  The master file is then
1026 patched and saved to disk.  In case no master file is found, syntax check is
1027 aborted, and corresponding status (@samp{!}) is reported in the mode line.
1028 @xref{Syntax check statuses}.
1030 @node Getting the include directories
1031 @section Getting the include directories
1032 @cindex include directories (C/C++ specific)
1034 Two sets of include directories are distinguished: system include directories
1035 and project include directories.  The former is just the contents of the
1036 @code{INCLUDE} environment variable.  The latter is not so easy to obtain,
1037 and the way it can be obtained can vary greatly for different projects.
1038 Therefore, a customizable variable
1039 @code{flymake-proc-get-project-include-dirs-function} is used to provide the
1040 way to implement the desired behavior.
1042 The default implementation, @code{flymake-proc-get-project-include-dirs-imp},
1043 uses a @command{make} call.  This requires a correct base directory, that is, a
1044 directory containing a correct @file{Makefile}, to be determined.
1046 As obtaining the project include directories might be a costly operation, its
1047 return value is cached in the hash table.  The cache is cleared in the beginning
1048 of every syntax check attempt.
1050 @node Locating the buildfile
1051 @section Locating the buildfile
1052 @cindex locating the buildfile
1053 @cindex buildfile, locating
1054 @cindex Makefile, locating
1056 The Proc backend can be configured to use different tools for
1057 performing syntax checks.  For example, it can use direct compiler
1058 call to syntax check a perl script or a call to @command{make} for a
1059 more complicated case of a C/C@t{++} source.  The general idea is
1060 that simple files, like Perl scripts and @acronym{HTML} pages, can be checked by
1061 directly invoking a corresponding tool.  Files that are usually more
1062 complex and generally used as part of larger projects, might require
1063 non-trivial options to be passed to the syntax check tool, like
1064 include directories for C@t{++}.  The latter files are syntax checked
1065 using some build tool, like Make or Ant.
1067 All Make configuration data is usually stored in a file called
1068 @file{Makefile}.  To allow for future extensions, Flymake uses a notion of
1069 buildfile to reference the @dfn{project configuration} file.
1071 @findex flymake-proc-find-buildfile
1072 Special function, @code{flymake-proc-find-buildfile} is provided for locating buildfiles.
1073 Searching for a buildfile is done in a manner similar to that of searching
1074 for possible master files.
1075 @ignore
1076 A customizable variable
1077 @code{flymake-proc-buildfile-dirs} holds a list of relative paths to the
1078 buildfile.  They are checked sequentially until a buildfile is found.
1079 @end ignore
1080 In case there's no build file, the syntax check is aborted.
1082 Buildfile values are also cached.
1084 @node Starting the syntax check process
1085 @section Starting the syntax check process
1086 @cindex syntax check process, legacy proc backend
1088 The command line (command name and the list of arguments) for
1089 launching a process is returned by the initialization function.  The
1090 Proc backend then just starts an asynchronous process and configures a
1091 process filter and sentinel, which are used for processing the output
1092 of the syntax check tool.  When exiting Emacs, running processes will
1093 be killed without prompting the user.
1095 @node Parsing the output
1096 @section Parsing the output
1097 @cindex parsing the output, legacy proc backend
1099 The output generated by the syntax check tool is parsed in the process
1100 filter/sentinel using the error message patterns stored in the
1101 @code{flymake-proc-err-line-patterns} variable.  This variable contains a
1102 list of items of the form @w{@code{(regexp file-idx line-idx
1103 err-text-idx)}}, used to determine whether a particular line is an
1104 error message and extract file name, line number and error text,
1105 respectively.  Error type (error/warning) is also guessed by matching
1106 error text with the @samp{^[wW]arning} pattern.  Anything that was not
1107 classified as a warning is considered an error.  Type is then used to
1108 sort error menu items, which shows error messages first.
1110 The Proc backend is also able to interpret error message patterns
1111 missing err-text-idx information.  This is done by merely taking the
1112 rest of the matched line (@code{(substring line (match-end 0))}) as
1113 error text.  This trick allows making use of a huge collection of
1114 error message line patterns from @file{compile.el}.  All these error
1115 patterns are appended to the end of
1116 @code{flymake-proc-err-line-patterns}.
1118 The error information obtained is saved in a buffer local
1119 variable.  The buffer for which the process output belongs is
1120 determined from the process-id@w{}->@w{}buffer mapping updated
1121 after every process launch/exit.
1123 @node Interaction with other modes
1124 @section Interaction with other modes
1125 @cindex interaction with other modes, legacy proc backend
1126 @cindex interaction with compile mode, legacy proc backend
1128 The only mode the Proc backend currently knows about is
1129 @code{compile}.
1131 The Proc backend can be configured to not start syntax check if it
1132 thinks the compilation is in progress, by testing the
1133 @code{compilation-in-progress} variable.  The reason why this might be
1134 useful is saving CPU time in case both syntax check and compilation
1135 are very CPU intensive.  The original reason for adding this feature,
1136 though, was working around a locking problem with MS Visual C++
1137 compiler.  The variable in question is
1138 @code{flymake-proc-compilation-prevents-syntax-check}.
1140 @findex flymake-proc-compile
1141 The Proc backend also provides an alternative command for starting
1142 compilation, @code{flymake-proc-compile}.  It just kills all the active
1143 syntax check processes before calling @code{compile}.
1145 @node GNU Free Documentation License
1146 @appendix GNU Free Documentation License
1147 @include doclicense.texi
1149 @node Index
1150 @unnumbered Index
1152 @printindex cp
1154 @bye