More minor changes in shell-related nodes of Emacs manual
[emacs.git] / doc / misc / flymake.texi
blobeb82ef04ad17e166570f05568704a525e2570a5f
1 \input texinfo   @c -*-texinfo; coding: utf-8 -*-
2 @comment %**start of header
3 @setfilename ../../info/flymake.info
4 @set VERSION 0.3
5 @set UPDATED April 2004
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 Pavel Kobiakov(@email{pk_at_work@@yahoo.com}) and João Távora.
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 a newline character is added to the buffer, unless
88 @code{flymake-start-syntax-check-on-newline} is nil;
90 @item
91 some changes were made to the buffer more than @code{0.5} seconds ago
92 (the delay is configurable in @code{flymake-no-changes-timeout}).
93 @end itemize
95 Syntax check can also be started manually by typing the @kbd{M-x
96 flymake-start @key{RET}} command.
98 @code{flymake-goto-next-error} and @code{flymake-goto-prev-error} are
99 commands that allow easy navigation to the next/previous erroneous
100 line, respectively.  If might be a good idea to map them to @kbd{M-n}
101 and @kbd{M-p} in @code{flymake-mode}, by adding to your init file:
103 @lisp
104 (define-key flymake-mode-map (kbd "M-n") 'flymake-goto-next-error)
105 (define-key flymake-mode-map (kbd "M-p") 'flymake-goto-prev-error)
106 @end lisp
108 Flymake is a universal syntax checker in the sense that it's easily
109 extended to support new backends (@pxref{Extending Flymake}).
111 Historically, Flymake used to accept diagnostics from a single
112 backend, albeit a reasonably flexible one.
114 This backend isn't (yet) obsolete, and so is still available as a
115 fallback and active by default (@pxref{The legacy Proc backend}).  It works by
116 selecting a syntax check tool from a preconfigured list (compiler for
117 C@t{++} files, @command{perl} for Perl files, etc.), and executing it in the
118 background, passing it a temporary file which is a copy of the current
119 buffer, and parsing the output for known error/warning message
120 patterns.
122 @menu
123 * Syntax check statuses::
124 * Backend exceptions::
125 * Customizable variables::
126 @end menu
128 @node Syntax check statuses
129 @section Syntax check statuses
130 @cindex Syntax check statuses
132 When enabled, Flymake displays its status in the mode line, which
133 provides a visual summary of diagnostic collection.  It may also hint
134 at certain exceptional situations encountered when communicating with
135 backends.
137 The following statuses are defined:
139 @multitable @columnfractions 0.25 0.75
140 @item [@var{nerrors} @var{nwarnings} ...]
141 @tab Normal operation. @var{nerrors} and @var{nwarnings} are, respectively,
142 the total number of errors and warnings found during the last buffer
143 check, for all backends. They may be followed by other totals for
144 other types of diagnostics (@pxref{Flymake error types}).
146 @item @code{Wait}
147 @tab  Some Flymake backends haven't reported since the last time they
148 where questioned.  It is reasonable to assume that this is a temporary
149 delay and Flymake will resume normal operation soon.
151 @item @code{!}
152 @tab All the configured Flymake backends have disabled themselves: Flymake
153 cannot annotate the buffer and action from the user is needed to
154 investigate and remedy the situation (@pxref{Backend exceptions}).
156 @item @code{?}
157 @tab There are no applicable Flymake backends for this buffer, thus Flymake
158 cannot annotate it.  To fix this, a user may look to extending Flymake
159 and add a new backend (@pxref{Extending Flymake}).
161 @end multitable
163 @node Backend exceptions
164 @section Backend exceptions
165 @cindex backend exceptions
167 @cindex disabled backends
168 @cindex backends, disabled
169 Some backends may take longer than others to respond or complete, and
170 some may decide to @emph{disable} themselves if they are not suitable
171 for the current buffer or encounter some unavoidable problem.  A
172 disabled backend is not tried again for future checks of the current
173 buffer.
175 @findex flymake-reporting-backends
176 @findex flymake-running-backends
177 @findex flymake-disabled-backends
178 The commands @code{flymake-reporting-backends},
179 @code{flymake-running-backends} and @code{flymake-disabled-backends}
180 show the backends currently used and those which are disabled.
182 @cindex reset disabled backends
183 Toggling @code{flymake-mode} off and on again, or invoking
184 @code{flymake-start} with a prefix argument is one way to reset the
185 disabled backend list, so that they will be tried again in the next check.
187 @cindex logging
188 @cindex flymake logging
189 Flymake also uses a simple logging facility for indicating important
190 points in the control flow.  The logging facility sends logging
191 messages to the @file{*Flymake log*} buffer.  The information logged
192 can be used for resolving various problems related to Flymake.  For
193 convenience, a shortcut to this buffer can be found in Flymake's menu,
194 accessible from the top menu bar or just left of the status indicator.
196 @vindex warning-minimum-log-level
197 @vindex warning-minimum-level
198 Logging output is controlled by the Emacs @code{warning-minimum-log-level}
199 and @code{warning-minimum-level} variables.
201 @node Customizable variables
202 @section Customizable variables
203 @cindex customizable variables
204 @cindex variables for customizing flymake
206 This section summarizes customization variables used for the
207 configuration of the Flymake user interface.
209 @vtable @code
210 @item flymake-no-changes-timeout
211 If any changes are made to the buffer, syntax check is automatically
212 started after this many seconds, unless the user makes another change,
213 which resets the timer.
215 @item flymake-start-syntax-check-on-newline
216 A boolean flag indicating whether to start syntax check immediately
217 after a newline character is inserted into the buffer.
219 @item flymake-start-on-flymake-mode
220 A boolean flag indicating whether to start syntax check immediately
221 after enabling @code{flymake-mode}.
223 @item flymake-error
224 A custom face for highlighting regions for which an error has been
225 reported.
227 @item flymake-warning
228 A custom face for highlighting regions for which a warning has been
229 reported.
231 @item flymake-note
232 A custom face for highlighting regions for which a note has been
233 reported.
235 @item flymake-error-bitmap
236 A bitmap used in the fringe to mark lines for which an error has
237 been reported.
239 @item flymake-warning-bitmap
240 A bitmap used in the fringe to mark lines for which a warning has
241 been reported.
243 @item flymake-fringe-indicator-position
244 Which fringe (if any) should show the warning/error bitmaps.
246 @item flymake-wrap-around
247 If non-nil, moving to errors with @code{flymake-goto-next-error} and
248 @code{flymake-goto-prev-error} wraps around buffer boundaries.
249 @end vtable
251 @node Extending Flymake
252 @chapter Extending Flymake
253 @cindex extending flymake
255 Flymake can primarily be extended in one of two ways:
257 @enumerate
258 @item
259 By changing the look and feel of the annotations produced by the
260 different backends.
262 @item
263 By adding a new buffer-checking backend.
264 @end enumerate
266 The following sections discuss each approach in detail.
268 @menu
269 * Flymake error types::
270 * Backend functions::
271 @end menu
273 @node Flymake error types
274 @section Customizing Flymake error types
275 @cindex customizing error types
276 @cindex error types, customization
278 @vindex flymake-diagnostic-types-alist
279 The variable @code{flymake-diagnostic-types-alist} is looked up by
280 Flymake every time an annotation for a diagnostic is created in the
281 buffer.  Specifically, this variable holds a table of correspondence
282 between symbols designating diagnostic types and an additional
283 sub-table of properties pertaining to each diagnostic type.
285 Both tables are laid out in association list (@pxref{Association
286 Lists,,, elisp, The Emacs Lisp Reference Manual}) format, and thus can
287 be conveniently accessed with the functions of the @code{assoc}
288 family.
290 You can use any symbol-value association in the properties sub-table,
291 but some symbols have special meaning as to where and how Flymake
292 presents the diagnostic:
294 @itemize
296 @item
297 @cindex bitmap of diagnostic
298 @code{bitmap}, an image displayed in the fringe according to
299 @code{flymake-fringe-indicator-position}.  The value actually follows
300 the syntax of @code{flymake-error-bitmap} (@pxref{Customizable
301 variables}).  It is overridden by any @code{before-string} overlay
302 property.
304 @item
305 @cindex severity of diagnostic
306 @code{severity} is a non-negative integer specifying the diagnostic's
307 severity.  The higher the value, the more serious is the error.  If
308 the overlay property @code{priority} is not specified, @code{severity}
309 is used to set it and help sort overlapping overlays.
311 @item
312 Every property pertaining to overlays (@pxref{Overlay Properties,,,
313 elisp, The Emacs Lisp Reference Manual}), except @code{category} and
314 @code{evaporate}.  These properties are used to affect the appearance
315 of Flymake annotations.
317 As an example, here's how to make errors (diagnostics of the type
318 @code{:error}) stand out even more prominently in the buffer, by
319 raising the characters using a @code{display} overlay property.
321 @example
322 (push '(display . (raise 1.2))
323       (cdr (assoc :error flymake-diagnostic-types-alist)))
324 @end example
326 @item
327 @vindex flymake-category
328 @code{flymake-category} is a symbol whose property list is considered
329 the default for missing values of any other properties.
330 @end itemize
332 @cindex predefined diagnostic types
333 @vindex flymake-error
334 @vindex flymake-warning
335 @vindex flymake-note
336 Three default diagnostic types, @code{:error}, @code{:warning} and
337 @code{:note} are predefined in
338 @code{flymake-diagnostic-types-alist}.  By default each lists a single
339 @code{flymake-category} property whose value is, respectively, the
340 symbols @code{flymake-error}, @code{flymake-warning} and
341 @code{flymake-note}.
343 These category symbols' plists is where the values of customizable
344 variables and faces such as @code{flymake-error-bitmap} are found.
345 Thus, if you change their plists, Flymake may stop honoring these
346 user customizations.
348 The @code{flymake-category} special property is also especially useful
349 for backends which create diagnostics objects with non-default
350 types that differ from an existing type by only a few properties
351 (@pxref{Flymake utility functions}).
353 As an example, consider configuring a new diagnostic type
354 @code{:low-priority-note} that behaves much like the @code{:note}
355 priority but without an overlay face.
357 @example
358 (add-to-list
359  'flymake-diagnostic-types-alist
360  `(:low-priority-note . ((face . nil)
361                          (flymake-category . flymake-note))))
362 @end example
364 @vindex flymake-diagnostics
365 @vindex flymake-diagnostic-backend
366 @vindex flymake-diagnostic-buffer
367 @vindex flymake-diagnostic-text
368 @vindex flymake-diagnostic-beg
369 @vindex flymake-diagnostic-end
370 As you might have guessed, Flymake's annotations are implemented as
371 overlays (@pxref{Overlays,,, elisp, The Emacs Lisp Reference Manual}).
372 Along with the properties that you specify for the specific type of
373 diagnostic, Flymake adds the property @code{flymake-diagnostic} to
374 these overlays, and sets it to the object that the backend created
375 with @code{flymake-make-diagnostic}.
377 Since overlays also support arbitrary keymaps, you can use this along
378 with the functions @code{flymake-diagnostics} and
379 @code{flymake-diagnostic-text} (@pxref{Flymake utility functions}) to
380 create interactive annotations, such as in the following example of
381 binding a @code{mouse-3} event (middle mouse button click) to an
382 Internet search for the text of a @code{:warning} or @code{:error}.
384 @example
385 (defun my-search-for-message (event)
386   (interactive "e")
387   (let* ((diags (flymake-diagnostics (posn-point (event-start event))))
388          (topmost-diag (car diags)))
389     (eww-browse-url
390        (concat
391         "https://duckduckgo.com/?q="
392         (replace-regexp-in-string " "
393                                   "+"
394                                   (flymake-diagnostic-text topmost-diag)))
395        t)))
397 (dolist (type '(:warning :error))
398   (let ((a (assoc type flymake-diagnostic-types-alist)))
399     (setf (cdr a)
400           (append `((mouse-face . highlight)
401                     (keymap . ,(let ((map (make-sparse-keymap)))
402                                  (define-key map [mouse-2]
403                                    'my-search-for-message)
404                                  map)))
405                   (cdr a)))))
406 @end example
408 @node Backend functions
409 @section Backend functions
410 @cindex backend functions
412 @vindex flymake-diagnostic-functions
413 Flymake backends are Lisp functions placed in the special hook
414 @code{flymake-diagnostic-functions}.
416 A backend's responsibility is to diagnose the contents of a buffer for
417 problems, registering the problem's positions, type, and summary
418 description.  This information is collected in the form of diagnostic
419 objects created by the function @code{flymake-make-diagnostic}
420 (@pxref{Flymake utility functions}), and
421 then handed over to Flymake, which proceeds to annotate the
422 buffer.
424 A request for a buffer check, and the subsequent delivery of
425 diagnostics, are two key events of the interaction between Flymake
426 and backend.  Each such event corresponds to a well-defined function
427 calling convention: one for calls made by Flymake into the backend via
428 the backend function, the other in the reverse direction via a
429 callback.  To be usable, backends must adhere to both.
431 Backend functions must accept an arbitrary number of arguments:
433 @itemize
434 @item
435 the first argument is always @var{report-fn}, a callback function
436 detailed below;
438 @item
439 the remaining arguments are keyword-value pairs of the
440 form @w{@code{(@var{:key} @var{value} @var{:key2} @var{value2}...)}}.  Currently,
441 Flymake provides no such arguments, but backend functions must be
442 prepared to accept (and possibly ignore) any number of them.
443 @end itemize
445 Whenever Flymake or the user decide to re-check the buffer, backend
446 functions are called as detailed above, and are expected to initiate
447 this check, but aren't in any way required to complete it before
448 exiting: if the computation involved is expensive, as
449 is often the case with large buffers, that slower task should be
450 scheduled for the future using asynchronous sub-processes
451 (@pxref{Asynchronous Processes,,, elisp, The Emacs Lisp reference
452 manual}) or other asynchronous mechanisms.
454 In any case, backend functions are expected to return quickly or
455 signal an error, in which case the backend is disabled
456 (@pxref{Backend exceptions}).
458 If the function returns, Flymake considers the backend to be
459 @dfn{running}.  If it has not done so already, the backend is expected
460 to call the function @var{report-fn} passed to it, at which point
461 Flymake considers the backend to be @dfn{reporting}.  Backends call
462 @var{report-fn} by passing it a single argument @var{report-action}
463 followed by an optional list of keyword-value pairs of the form
464 @w{@code{(@var{:report-key} @var{value} @var{:report-key2} @var{value2}...)}}.
466 Currently accepted values for @var{report-action} are:
468 @itemize
469 @item
470 A (possibly empty) list of diagnostic objects created by
471 @code{flymake-make-diagnostic}, causing Flymake to annotate the
472 buffer with this information.
474 A backend may call @var{report-fn} repeatedly in this manner, but only
475 until Flymake considers that the most recently requested buffer check
476 is now obsolete, because, say, buffer contents have changed in the
477 meantime.  The backend is only given notice of this via a renewed call
478 to the backend function.  Thus, to prevent making obsolete reports and
479 wasting resources, backend functions should first cancel any ongoing
480 processing from previous calls.
482 @item
483 The symbol @code{:panic}, signaling that the backend has encountered
484 an exceptional situation and should be disabled.
485 @end itemize
487 Currently accepted @var{report-key} arguments are:
489 @itemize
490 @item
491 @code{:explanation}, whose value should give user-readable
492 details of the situation encountered, if any.
494 @item
495 @code{:force}, whose value should be a boolean suggesting
496 that Flymake consider the report even if it was somehow
497 unexpected.
498 @end itemize
500 @menu
501 * Flymake utility functions::
502 * An annotated example backend::
503 @end menu
505 @node Flymake utility functions
506 @subsection Flymake utility functions
507 @cindex utility functions
509 @cindex create diagnostic object
510 Before delivering them to Flymake, backends create diagnostic objects
511 by calling the function @code{flymake-make-diagnostic}.
513 @deffn Function flymake-make-diagnostic buffer beg end type text
514 Make a Flymake diagnostic for @var{buffer}'s region from @var{beg} to
515 @var{end}.  @var{type} is a key to
516 @code{flymake-diagnostic-types-alist} and @var{text} is a description
517 of the problem detected in this region.
518 @end deffn
520 @cindex access diagnostic object
521 These objects' properties can be accessed with the functions
522 @code{flymake-diagnostic-backend}, @code{flymake-diagnostic-buffer},
523 @code{flymake-diagnostic-text}, @code{flymake-diagnostic-beg},
524 @code{flymake-diagnostic-end} and @code{flymake-diagnostic-type}.
526 Additionally, the function @code{flymake-diagnostics} will collect
527 such objects in the region you specify.
529 @cindex collect diagnostic objects
530 @deffn Function flymake-diagnostics beg end
531 Get a list of Flymake diagnostics in the region determined by
532 @var{beg} and @var{end}.  If neither @var{beg} or @var{end} is
533 supplied, use the whole buffer, otherwise if @var{beg} is
534 non-@code{nil} and @var{end} is @code{nil}, consider only diagnostics
535 at @var{beg}.
536 @end deffn
538 @cindex buffer position from line and column number
539 It is often the case with external syntax tools that a diagnostic's
540 position is reported in terms of a line number, and sometimes a column
541 number.  To convert this information into a buffer position, backends
542 can use the following function:
544 @deffn Function flymake-diag-region buffer line &optional col
545 Compute @var{buffer}'s region (@var{beg} .  @var{end}) corresponding
546 to @var{line} and @var{col}.  If @var{col} is @code{nil}, return a
547 region just for @var{line}.  Return @code{nil} if the region is
548 invalid.
549 @end deffn
551 @cindex add a log message
552 For troubleshooting purposes, backends may record arbitrary
553 exceptional or erroneous situations into the Flymake log
554 buffer (@pxref{Backend exceptions}):
556 @deffn Macro flymake-log level msg &optional args
557 Log, at level @var{level}, the message @var{msg} formatted with
558 @var{args}.  @var{level} is passed to @code{display-warning}
559 (@pxref{Warning Basics,,, elisp, The Emacs Lisp reference Manual}), which is
560 used to display the warning in Flymake's log buffer.
561 @end deffn
563 @node An annotated example backend
564 @subsection An annotated example backend
565 @cindex example of backend
566 @cindex backend, annotated example
568 This section presents an annotated example of a complete working
569 Flymake backend.  The example illustrates the process of writing a
570 backend as outlined above.
572 The backend in question is used for checking Ruby source files.  It
573 uses asynchronous sub-processes (@pxref{Asynchronous Processes,,, elisp,
574 The Emacs Lisp Reference Manual}), a common technique for performing
575 parallel processing in Emacs.
577 The following code needs lexical binding (@pxref{Using Lexical
578 Binding,,, elisp, The Emacs Lisp Reference Manual}) to be active.
580 @example
581 ;;; ruby-flymake.el --- A ruby Flymake backend  -*- lexical-binding: t; -*-
582 (defvar-local ruby--flymake-proc nil)
584 (defun ruby-flymake (report-fn &rest _args)
585   ;; Not having a ruby interpreter is a serious problem which should cause
586   ;; the backend to disable itself, so an @code{error} is signaled.
587   ;;
588   (unless (executable-find
589            "ruby") (error "Cannot find a suitable ruby"))
590   ;; If a live process launched in an earlier check was found, that
591   ;; process is killed.  When that process's sentinel eventually runs,
592   ;; it will notice its obsoletion, since it have since reset
593   ;; `ruby-flymake-proc' to a different value
594   ;;
595   (when (process-live-p ruby--flymake-proc)
596     (kill-process ruby--flymake-proc))
598   ;; Save the current buffer, the narrowing restriction, remove any
599   ;; narrowing restriction.
600   ;;
601   (let ((source (current-buffer)))
602     (save-restriction
603       (widen)
604       ;; Reset the `ruby--flymake-proc' process to a new process
605       ;; calling the ruby tool.
606       ;;
607       (setq
608        ruby--flymake-proc
609        (make-process
610         :name "ruby-flymake" :noquery t :connection-type 'pipe
611         ;; Make output go to a temporary buffer.
612         ;;
613         :buffer (generate-new-buffer " *ruby-flymake*")
614         :command '("ruby" "-w" "-c")
615         :sentinel
616         (lambda (proc _event)
617           ;; Check that the process has indeed exited, as it might
618           ;; be simply suspended.
619           ;;
620           (when (eq 'exit (process-status proc))
621             (unwind-protect
622                 ;; Only proceed if `proc' is the same as
623                 ;; `ruby--flymake-proc', which indicates that
624                 ;; `proc' is not an obsolete process.
625                 ;;
626                 (if (with-current-buffer source (eq proc ruby--flymake-proc))
627                     (with-current-buffer (process-buffer proc)
628                       (goto-char (point-min))
629                       ;; Parse the output buffer for diagnostic's
630                       ;; messages and locations, collect them in a list
631                       ;; of objects, and call `report-fn'.
632                       ;;
633                       (cl-loop
634                        while (search-forward-regexp
635                               "^\\(?:.*.rb\\|-\\):\\([0-9]+\\): \\(.*\\)$"
636                               nil t)
637                        for msg = (match-string 2)
638                        for (beg . end) = (flymake-diag-region
639                                           source
640                                           (string-to-number (match-string 1)))
641                        for type = (if (string-match "^warning" msg)
642                                       :warning
643                                     :error)
644                        collect (flymake-make-diagnostic source
645                                                         beg
646                                                         end
647                                                         type
648                                                         msg)
649                        into diags
650                        finally (funcall report-fn diags)))
651                   (flymake-log :warning "Canceling obsolete check %s"
652                                proc))
653               ;; Cleanup the temporary buffer used to hold the
654               ;; check's output.
655               ;;
656               (kill-buffer (process-buffer proc)))))))
657       ;; Send the buffer contents to the process's stdin, followed by
658       ;; an EOF.
659       ;;
660       (process-send-region ruby--flymake-proc (point-min) (point-max))
661       (process-send-eof ruby--flymake-proc))))
663 (defun ruby-setup-flymake-backend ()
664   (add-hook 'flymake-diagnostic-functions 'ruby-flymake nil t))
666 (add-hook 'ruby-mode-hook 'ruby-setup-flymake-backend)
667 @end example
669 @node The legacy Proc backend
670 @chapter The legacy ``Proc'' backend
671 @cindex legacy proc backend
673 @menu
674 * Proc customization variables::
675 * Adding support for a new syntax check tool::
676 * Implementation overview::
677 * Making a temporary copy::
678 * Locating a master file::
679 * Getting the include directories::
680 * Locating the buildfile::
681 * Starting the syntax check process::
682 * Parsing the output::
683 * Interaction with other modes::
684 @end menu
686 @findex flymake-proc-legacy-backend
687 The backend @code{flymake-proc-legacy-backend} was originally designed
688 to be extended for supporting new syntax check tools and error message
689 patterns.  It is also controlled by its own set of customization variables
691 @node Proc customization variables
692 @section Customization variables for the Proc backend
693 @cindex proc backend customization variables
695 @vtable @code
696 @item flymake-proc-allowed-file-name-masks
697 A list of @code{(filename-regexp, init-function, cleanup-function
698 getfname-function)} for configuring syntax check tools.  @xref{Adding
699 support for a new syntax check tool}.
701 @item flymake-proc-master-file-dirs
702 A list of directories for searching a master file.  @xref{Locating a
703 master file}.
705 @item flymake-proc-get-project-include-dirs-function
706 A function used for obtaining a list of project include dirs (C/C++
707 specific).  @xref{Getting the include directories}.
709 @item flymake-proc-master-file-count-limit
710 @itemx flymake-proc-check-file-limit
711 Used when looking for a master file.  @xref{Locating a master file}.
713 @item flymake-proc-err-line-patterns
714 Patterns for error/warning messages in the form @code{(regexp file-idx
715 line-idx col-idx err-text-idx)}.  @xref{Parsing the output}.
717 @item flymake-proc-diagnostic-type-pred
718 A function to classify a diagnostic text as particular type of
719 error.  Should be a function taking an error text and returning one of
720 the symbols indexing @code{flymake-diagnostic-types-alist}.  If non-nil
721 is returned but there is no such symbol in that table, a warning is
722 assumed.  If nil is returned, an error is assumed.  Can also be a
723 regular expression that should match only warnings.  This variable
724 replaces the old @code{flymake-warning-re} and
725 @code{flymake-warning-predicate}.
727 @item flymake-proc-compilation-prevents-syntax-check
728 A flag indicating whether compilation and syntax check of the same
729 file cannot be run simultaneously.  @xref{Interaction with other modes}.
730 @end vtable
732 @node Adding support for a new syntax check tool
733 @section Adding support for a new syntax check tool
734 @cindex adding support for a new syntax check tool
736 @menu
737 * Example---Configuring a tool called directly::
738 * Example---Configuring a tool called via make::
739 @end menu
741 Syntax check tools are configured using the
742 @code{flymake-proc-allowed-file-name-masks} list.  Each item of this list
743 has the following format:
745 @lisp
746 (filename-regexp, init-function, cleanup-function, getfname-function)
747 @end lisp
749 @table @code
750 @item filename-regexp
751 This field is used as a key for locating init/cleanup/getfname
752 functions for the buffer.  Items in
753 @code{flymake-proc-allowed-file-name-masks} are searched sequentially.
754 The first item with @code{filename-regexp} matching buffer filename is
755 selected.  If no match is found, @code{flymake-mode} is switched off.
757 @item init-function
758 @code{init-function} is required to initialize the syntax check,
759 usually by creating a temporary copy of the buffer contents.  The
760 function must return @code{(list cmd-name arg-list)}.  If
761 @code{init-function} returns null, syntax check is aborted, but
762 @code{flymake-mode} is not switched off.
764 @item cleanup-function
765 @code{cleanup-function} is called after the syntax check process is
766 complete and should take care of proper deinitialization, which is
767 usually deleting a temporary copy created by the @code{init-function}.
769 @item getfname-function
770 This function is used for translating filenames reported by the syntax
771 check tool into ``real'' filenames.  Filenames reported by the tool
772 will be different from the real ones, as actually the tool works with
773 the temporary copy.  In most cases, the default implementation
774 provided by Flymake, @code{flymake-proc-get-real-file-name}, can be
775 used as @code{getfname-function}.
776 @end table
778 To add support for a new syntax check tool, write the corresponding
779 @code{init-function} and, optionally, @code{cleanup-function} and
780 @code{getfname-function}.  If the format of error messages reported by
781 the new tool is not yet supported by Flymake, add a new entry to
782 the @code{flymake-proc-err-line-patterns} list.
784 The following sections contain some examples of configuring Flymake
785 support for various syntax check tools.
787 @node Example---Configuring a tool called directly
788 @subsection Example---Configuring a tool called directly
789 @cindex adding support for perl
791 In this example, we will add support for @command{perl} as a syntax check
792 tool.  @command{perl} supports the @option{-c} option which does syntax
793 checking.
795 First, we write the @code{init-function}:
797 @lisp
798 (defun flymake-proc-perl-init ()
799   (let* ((temp-file (flymake-proc-init-create-temp-buffer-copy
800                      'flymake-proc-create-temp-inplace))
801          (local-file (file-relative-name
802                       temp-file
803                       (file-name-directory buffer-file-name))))
804     (list "perl" (list "-wc " local-file))))
805 @end lisp
807 @code{flymake-proc-perl-init} creates a temporary copy of the buffer
808 contents with the help of
809 @code{flymake-proc-init-create-temp-buffer-copy}, and builds an appropriate
810 command line.
812 Next, we add a new entry to the
813 @code{flymake-proc-allowed-file-name-masks}:
815 @lisp
816 (setq flymake-proc-allowed-file-name-masks
817       (cons '(".+\\.pl$"
818               flymake-proc-perl-init
819               flymake-proc-simple-cleanup
820               flymake-proc-get-real-file-name)
821             flymake-proc-allowed-file-name-masks))
822 @end lisp
824 Note that we use standard @code{cleanup-function} and
825 @code{getfname-function}.
827 Finally, we add an entry to @code{flymake-proc-err-line-patterns}:
829 @lisp
830 (setq flymake-proc-err-line-patterns
831       (cons '("\\(.*\\) at \\([^ \n]+\\) line \\([0-9]+\\)[,.\n]"
832               2 3 nil 1)
833             flymake-proc-err-line-patterns))
834 @end lisp
836 @node Example---Configuring a tool called via make
837 @subsection Example---Configuring a tool called via make
838 @cindex adding support for C (gcc+make)
840 In this example we will add support for C files syntax checked by
841 @command{gcc} called via @command{make}.
843 We're not required to write any new functions, as Flymake already has
844 functions for @command{make}.  We just add a new entry to the
845 @code{flymake-proc-allowed-file-name-masks}:
847 @lisp
848 (setq flymake-proc-allowed-file-name-masks
849       (cons '(".+\\.c$"
850               flymake-proc-simple-make-init
851               flymake-proc-simple-cleanup
852               flymake-proc-get-real-file-name)
853             flymake-proc-allowed-file-name-masks))
854 @end lisp
856 @code{flymake-proc-simple-make-init} builds the following @command{make}
857 command line:
859 @lisp
860 (list "make"
861       (list "-s" "-C"
862             base-dir
863             (concat "CHK_SOURCES=" source)
864             "SYNTAX_CHECK_MODE=1"
865             "check-syntax"))
866 @end lisp
868 @code{base-dir} is a directory containing the @file{Makefile}, see
869 @ref{Locating the buildfile}.
871 Thus, @file{Makefile} must contain the @code{check-syntax} target.  In
872 our case this target might look like this:
874 @verbatim
875 check-syntax:
876         gcc -o /dev/null -S ${CHK_SOURCES} || true
877 @end verbatim
879 @noindent
880 The format of error messages reported by @command{gcc} is already
881 supported by Flymake, so we don't have to add a new entry to
882 @code{flymake-err-line-patterns}.  Note that if you are using
883 Automake, you may want to replace @code{gcc} with the standard
884 Automake variable @code{COMPILE}:
886 @verbatim
887 check-syntax:
888         $(COMPILE) -o /dev/null -S ${CHK_SOURCES} || true
889 @end verbatim
891 @node Implementation overview
892 @section Implementation overview
893 @cindex syntax check models
894 @cindex master file
896 @code{flymake-proc-legacy-backend} saves a copy of the buffer in a
897 temporary file in the buffer's directory (or in the system temporary
898 directory, for Java files), creates a syntax check command and
899 launches a process with this command.  The output is parsed using a
900 list of error message patterns, and error information (file name, line
901 number, type and text) is saved.  After the process has finished,
902 Flymake highlights erroneous lines in the buffer using the accumulated
903 error information.
905 Syntax check is considered possible if there's an entry in
906 @code{flymake-proc-allowed-file-name-masks} matching buffer's filename and
907 its @code{init-function} returns non-@code{nil} value.
909 Two syntax check modes are distinguished:
911 @enumerate
913 @item
914 Buffer can be syntax checked in a standalone fashion, that is, the
915 file (its temporary copy, in fact) can be passed over to the compiler to
916 do the syntax check.  Examples are C/C@t{++} sources (@file{.c},
917 @file{.cpp}) and Java (@file{.java}).
919 @item
920 Buffer can be syntax checked, but additional file, called master file,
921 is required to perform this operation.  A master file is a file that
922 includes the current file, so that running a syntax check tool on it
923 will also check syntax in the current file.  Examples are C/C@t{++}
924 headers (@file{.h}, @file{.hpp}).
926 @end enumerate
928 These modes are handled inside init/cleanup/getfname functions, see
929 @ref{Adding support for a new syntax check tool}.
931 The Proc backend contains implementations of all functionality
932 required to support different syntax check modes described above
933 (making temporary copies, finding master files, etc.), as well as some
934 tool-specific (routines for Make, Ant, etc.)@: code.
937 @node Making a temporary copy
938 @section Making a temporary copy
939 @cindex temporary copy of the buffer
941 After the possibility of the syntax check has been determined, a
942 temporary copy of the current buffer is made so that the most recent
943 unsaved changes could be seen by the syntax check tool.  Making a copy
944 is quite straightforward in a standalone case (mode @code{1}), as it's
945 just saving buffer contents to a temporary file.
947 Things get trickier, however, when master file is involved, as it
948 requires to
950 @itemize @bullet
951 @item
952 locate a master file
953 @item
954 patch it to include the current file using its new (temporary) name.
955 @end itemize
957 Locating a master file is discussed in the following section.
959 Patching just changes all appropriate lines of the master file so that they
960 use the new (temporary) name of the current file.  For example, suppose current
961 file name is @code{file.h}, the master file is @code{file.cpp}, and
962 it includes current file via @code{#include "file.h"}.  Current file's copy
963 is saved to file @code{file_flymake.h}, so the include line must be
964 changed to @code{#include "file_flymake.h"}.  Finally, patched master file
965 is saved to @code{file_flymake_master.cpp}, and the last one is passed to
966 the syntax check tool.
968 @node Locating a master file
969 @section Locating a master file
970 @cindex locating a master file
971 @cindex master file, locating
973 Master file is located in two steps.
975 First, a list of possible master files is built.  A simple name
976 matching is used to find the files.  For a C++ header @file{file.h},
977 the Proc backend searches for all @file{.cpp} files in the directories
978 whose relative paths are stored in a customizable variable
979 @code{flymake-proc-master-file-dirs}, which usually contains something
980 like @code{("." "./src")}.  No more than
981 @code{flymake-proc-master-file-count-limit} entries is added to the
982 master file list.  The list is then sorted to move files with names
983 @file{file.cpp} to the top.
985 Next, each master file in a list is checked to contain the appropriate
986 include directives.  No more than @code{flymake-proc-check-file-limit} of each
987 file are parsed.
989 For @file{file.h}, the include directives to look for are
990 @code{#include "file.h"}, @code{#include "../file.h"}, etc.  Each
991 include is checked against a list of include directories
992 (see @ref{Getting the include directories}) to be sure it points to the
993 correct @file{file.h}.
995 First matching master file found stops the search.  The master file is then
996 patched and saved to disk.  In case no master file is found, syntax check is
997 aborted, and corresponding status (@samp{!}) is reported in the mode line.
998 @xref{Syntax check statuses}.
1000 @node Getting the include directories
1001 @section Getting the include directories
1002 @cindex include directories (C/C++ specific)
1004 Two sets of include directories are distinguished: system include directories
1005 and project include directories.  The former is just the contents of the
1006 @code{INCLUDE} environment variable.  The latter is not so easy to obtain,
1007 and the way it can be obtained can vary greatly for different projects.
1008 Therefore, a customizable variable
1009 @code{flymake-proc-get-project-include-dirs-function} is used to provide the
1010 way to implement the desired behavior.
1012 The default implementation, @code{flymake-proc-get-project-include-dirs-imp},
1013 uses a @command{make} call.  This requires a correct base directory, that is, a
1014 directory containing a correct @file{Makefile}, to be determined.
1016 As obtaining the project include directories might be a costly operation, its
1017 return value is cached in the hash table.  The cache is cleared in the beginning
1018 of every syntax check attempt.
1020 @node Locating the buildfile
1021 @section Locating the buildfile
1022 @cindex locating the buildfile
1023 @cindex buildfile, locating
1024 @cindex Makefile, locating
1026 The Proc backend can be configured to use different tools for
1027 performing syntax checks.  For example, it can use direct compiler
1028 call to syntax check a perl script or a call to @command{make} for a
1029 more complicated case of a C/C@t{++} source.  The general idea is
1030 that simple files, like Perl scripts and @acronym{HTML} pages, can be checked by
1031 directly invoking a corresponding tool.  Files that are usually more
1032 complex and generally used as part of larger projects, might require
1033 non-trivial options to be passed to the syntax check tool, like
1034 include directories for C@t{++}.  The latter files are syntax checked
1035 using some build tool, like Make or Ant.
1037 All Make configuration data is usually stored in a file called
1038 @file{Makefile}.  To allow for future extensions, Flymake uses a notion of
1039 buildfile to reference the @dfn{project configuration} file.
1041 @findex flymake-proc-find-buildfile
1042 Special function, @code{flymake-proc-find-buildfile} is provided for locating buildfiles.
1043 Searching for a buildfile is done in a manner similar to that of searching
1044 for possible master files.
1045 @ignore
1046 A customizable variable
1047 @code{flymake-proc-buildfile-dirs} holds a list of relative paths to the
1048 buildfile.  They are checked sequentially until a buildfile is found.
1049 @end ignore
1050 In case there's no build file, the syntax check is aborted.
1052 Buildfile values are also cached.
1054 @node Starting the syntax check process
1055 @section Starting the syntax check process
1056 @cindex syntax check process, legacy proc backend
1058 The command line (command name and the list of arguments) for
1059 launching a process is returned by the initialization function.  The
1060 Proc backend then just starts an asynchronous process and configures a
1061 process filter and sentinel, which are used for processing the output
1062 of the syntax check tool.  When exiting Emacs, running processes will
1063 be killed without prompting the user.
1065 @node Parsing the output
1066 @section Parsing the output
1067 @cindex parsing the output, legacy proc backend
1069 The output generated by the syntax check tool is parsed in the process
1070 filter/sentinel using the error message patterns stored in the
1071 @code{flymake-proc-err-line-patterns} variable.  This variable contains a
1072 list of items of the form @w{@code{(regexp file-idx line-idx
1073 err-text-idx)}}, used to determine whether a particular line is an
1074 error message and extract file name, line number and error text,
1075 respectively.  Error type (error/warning) is also guessed by matching
1076 error text with the @samp{^[wW]arning} pattern.  Anything that was not
1077 classified as a warning is considered an error.  Type is then used to
1078 sort error menu items, which shows error messages first.
1080 The Proc backend is also able to interpret error message patterns
1081 missing err-text-idx information.  This is done by merely taking the
1082 rest of the matched line (@code{(substring line (match-end 0))}) as
1083 error text.  This trick allows making use of a huge collection of
1084 error message line patterns from @file{compile.el}.  All these error
1085 patterns are appended to the end of
1086 @code{flymake-proc-err-line-patterns}.
1088 The error information obtained is saved in a buffer local
1089 variable.  The buffer for which the process output belongs is
1090 determined from the process-id@w{}->@w{}buffer mapping updated
1091 after every process launch/exit.
1093 @node Interaction with other modes
1094 @section Interaction with other modes
1095 @cindex interaction with other modes, legacy proc backend
1096 @cindex interaction with compile mode, legacy proc backend
1098 The only mode the Proc backend currently knows about is
1099 @code{compile}.
1101 The Proc backend can be configured to not start syntax check if it
1102 thinks the compilation is in progress, by testing the
1103 @code{compilation-in-progress} variable.  The reason why this might be
1104 useful is saving CPU time in case both syntax check and compilation
1105 are very CPU intensive.  The original reason for adding this feature,
1106 though, was working around a locking problem with MS Visual C++
1107 compiler.  The variable in question is
1108 @code{flymake-proc-compilation-prevents-syntax-check}.
1110 @findex flymake-proc-compile
1111 The Proc backend also provides an alternative command for starting
1112 compilation, @code{flymake-proc-compile}.  It just kills all the active
1113 syntax check processes before calling @code{compile}.
1115 @node GNU Free Documentation License
1116 @appendix GNU Free Documentation License
1117 @include doclicense.texi
1119 @node Index
1120 @unnumbered Index
1122 @printindex cp
1124 @bye