1;;; flymake.el -- a universal on-the-fly syntax checker
2
3;; Copyright (C) 2003, 2004, 2005, 2006, 2007
4;;   Free Software Foundation, Inc.
5
6;; Author:  Pavel Kobyakov <pk_at_work@yahoo.com>
7;; Maintainer: Pavel Kobyakov <pk_at_work@yahoo.com>
8;; Version: 0.3
9;; Keywords: c languages tools
10
11;; This file is part of GNU Emacs.
12
13;; GNU Emacs is free software; you can redistribute it and/or modify
14;; it under the terms of the GNU General Public License as published by
15;; the Free Software Foundation; either version 2, or (at your option)
16;; any later version.
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
24;; along with GNU Emacs; see the file COPYING.  If not, write to the
25;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26;; Boston, MA 02110-1301, USA.
27
28;;; Commentary:
29;;
30;; Flymake is a minor Emacs mode performing on-the-fly syntax
31;; checks using the external syntax check tool (for C/C++ this
32;; is usually the compiler)
33
34;;; Bugs/todo:
35
36;; - Only uses "Makefile", not "makefile" or "GNUmakefile"
37;;   (from http://bugs.debian.org/337339).
38
39;;; Code:
40
41(eval-when-compile (require 'cl))
42(if (featurep 'xemacs) (require 'overlay))
43
44(defvar flymake-is-running nil
45  "If t, flymake syntax check process is running for the current buffer.")
46(make-variable-buffer-local 'flymake-is-running)
47
48(defvar flymake-timer nil
49  "Timer for starting syntax check.")
50(make-variable-buffer-local 'flymake-timer)
51
52(defvar flymake-last-change-time nil
53  "Time of last buffer change.")
54(make-variable-buffer-local 'flymake-last-change-time)
55
56(defvar flymake-check-start-time nil
57  "Time at which syntax check was started.")
58(make-variable-buffer-local 'flymake-check-start-time)
59
60(defvar flymake-check-was-interrupted nil
61  "Non-nil if syntax check was killed by `flymake-compile'.")
62(make-variable-buffer-local 'flymake-check-was-interrupted)
63
64(defvar flymake-err-info nil
65  "Sorted list of line numbers and lists of err info in the form (file, err-text).")
66(make-variable-buffer-local 'flymake-err-info)
67
68(defvar flymake-new-err-info nil
69  "Same as `flymake-err-info', effective when a syntax check is in progress.")
70(make-variable-buffer-local 'flymake-new-err-info)
71
72;;;; [[ cross-emacs compatibility routines
73(defsubst flymake-makehash (&optional test)
74  (if (fboundp 'make-hash-table)
75      (if test (make-hash-table :test test) (make-hash-table))
76    (with-no-warnings
77      (makehash test))))
78
79(defalias 'flymake-float-time
80  (if (fboundp 'float-time)
81      'float-time
82    (if (featurep 'xemacs)
83	(lambda ()
84	  (multiple-value-bind (s0 s1 s2) (current-time)
85	    (+ (* (float (ash 1 16)) s0) (float s1) (* 0.0000001 s2)))))))
86
87(defalias 'flymake-replace-regexp-in-string
88  (if (eval-when-compile (fboundp 'replace-regexp-in-string))
89      'replace-regexp-in-string
90    (lambda (regexp rep str)
91      (replace-in-string str regexp rep))))
92
93(defalias 'flymake-split-string
94  (if (condition-case nil (equal (split-string " bc " " " t) '("bc"))
95        (error nil))
96      (lambda (str pattern) (split-string str pattern t))
97    (lambda (str pattern)
98      "Split STR into a list of substrings bounded by PATTERN.
99Zero-length substrings at the beginning and end of the list are omitted."
100      (let ((split (split-string str pattern)))
101        (while (equal (car split) "") (setq split (cdr split)))
102        (setq split (nreverse split))
103        (while (equal (car split) "") (setq split (cdr split)))
104        (nreverse split)))))
105
106(defalias 'flymake-get-temp-dir
107  (if (fboundp 'temp-directory)
108      'temp-directory
109    (lambda () temporary-file-directory)))
110
111(defalias 'flymake-line-beginning-position
112  (if (fboundp 'line-beginning-position)
113      'line-beginning-position
114    (lambda (&optional arg) (save-excursion (beginning-of-line arg) (point)))))
115
116(defalias 'flymake-line-end-position
117  (if (fboundp 'line-end-position)
118      'line-end-position
119    (lambda (&optional arg) (save-excursion (end-of-line arg) (point)))))
120
121(defun flymake-posn-at-point-as-event (&optional position window dx dy)
122  "Return pixel position of top left corner of glyph at POSITION,
123relative to top left corner of WINDOW, as a mouse-1 click
124event (identical to the event that would be triggered by clicking
125mouse button 1 at the top left corner of the glyph).
126
127POSITION and WINDOW default to the position of point in the
128selected window.
129
130DX and DY specify optional offsets from the top left of the glyph."
131  (unless window (setq window (selected-window)))
132  (unless position (setq position (window-point window)))
133  (unless dx (setq dx 0))
134  (unless dy (setq dy 0))
135
136  (let* ((pos (posn-at-point position window))
137         (x-y (posn-x-y pos))
138         (edges (window-inside-pixel-edges window))
139         (win-x-y (window-pixel-edges window)))
140    ;; adjust for window edges
141    (setcar (nthcdr 2 pos)
142            (cons (+ (car x-y) (car  edges) (- (car win-x-y))  dx)
143                  (+ (cdr x-y) (cadr edges) (- (cadr win-x-y)) dy)))
144    (list 'mouse-1 pos)))
145
146(defun flymake-popup-menu (menu-data)
147  "Pop up the flymake menu at point, using the data MENU-DATA.
148POS is a list of the form ((X Y) WINDOW), where X and Y are
149pixels positions from the top left corner of WINDOW's frame.
150MENU-DATA is a list of error and warning messages returned by
151`flymake-make-err-menu-data'."
152  (if (featurep 'xemacs)
153      (let* ((pos         (flymake-get-point-pixel-pos))
154             (x-pos       (nth 0 pos))
155	     (y-pos       (nth 1 pos))
156	     (fake-event-props  '(button 1 x 1 y 1)))
157	(setq fake-event-props (plist-put fake-event-props 'x x-pos))
158	(setq fake-event-props (plist-put fake-event-props 'y y-pos))
159	(popup-menu (flymake-make-xemacs-menu menu-data)
160                    (make-event 'button-press fake-event-props)))
161    (x-popup-menu (if (eval-when-compile (fboundp 'posn-at-point))
162                      (flymake-posn-at-point-as-event)
163                    (list (flymake-get-point-pixel-pos) (selected-window)))
164                  (flymake-make-emacs-menu menu-data))))
165
166(defun flymake-make-emacs-menu (menu-data)
167  "Return a menu specifier using MENU-DATA.
168MENU-DATA is a list of error and warning messages returned by
169`flymake-make-err-menu-data'.
170See `x-popup-menu' for the menu specifier format."
171  (let* ((menu-title     (nth 0 menu-data))
172	 (menu-items     (nth 1 menu-data))
173	 (menu-commands  (mapcar (lambda (foo)
174                                   (cons (nth 0 foo) (nth 1 foo)))
175                                 menu-items)))
176    (list menu-title (cons "" menu-commands))))
177
178(if (featurep 'xemacs) (progn
179
180(defun flymake-nop ())
181
182(defun flymake-make-xemacs-menu (menu-data)
183  "Return a menu specifier using MENU-DATA."
184  (let* ((menu-title     (nth 0 menu-data))
185	 (menu-items     (nth 1 menu-data))
186	 (menu-commands  nil))
187    (setq menu-commands (mapcar (lambda (foo)
188				  (vector (nth 0 foo) (or (nth 1 foo) '(flymake-nop)) t))
189				menu-items))
190    (cons menu-title menu-commands)))
191
192)) ;; xemacs
193
194(unless (eval-when-compile (fboundp 'posn-at-point))
195
196(defun flymake-current-row ()
197  "Return current row number in current frame."
198  (if (fboundp 'window-edges)
199      (+ (car (cdr (window-edges))) (count-lines (window-start) (point)))
200    (count-lines (window-start) (point))))
201
202(defun flymake-selected-frame ()
203  (if (fboundp 'window-edges)
204      (selected-frame)
205    (selected-window)))
206
207(defun flymake-get-point-pixel-pos ()
208  "Return point position in pixels: (x, y)."
209  (let ((mouse-pos  (mouse-position))
210	(pixel-pos  nil)
211	(ret        nil))
212    (if (car (cdr mouse-pos))
213	(progn
214	  (set-mouse-position (flymake-selected-frame) (current-column) (flymake-current-row))
215	  (setq pixel-pos (mouse-pixel-position))
216	  (set-mouse-position (car mouse-pos) (car (cdr mouse-pos)) (cdr (cdr mouse-pos)))
217	  (setq ret (list (car (cdr pixel-pos)) (cdr (cdr pixel-pos)))))
218      (progn
219	(setq ret '(0 0))))
220    (flymake-log 3 "mouse pos is %s" ret)
221    ret))
222
223) ;; End of (unless (fboundp 'posn-at-point)
224
225;;;; ]]
226
227(defcustom flymake-log-level -1
228  "Logging level, only messages with level lower or equal will be logged.
229-1 = NONE, 0 = ERROR, 1 = WARNING, 2 = INFO, 3 = DEBUG"
230  :group 'flymake
231  :type 'integer)
232
233(defun flymake-log (level text &rest args)
234  "Log a message at level LEVEL.
235If LEVEL is higher than `flymake-log-level', the message is
236ignored.  Otherwise, it is printed using `message'.
237TEXT is a format control string, and the remaining arguments ARGS
238are the string substitutions (see `format')."
239  (if (<= level flymake-log-level)
240      (let* ((msg (apply 'format text args)))
241	(message "%s" msg)
242	;;(with-temp-buffer
243	;;    (insert msg)
244	;;   (insert "\n")
245	;;   (flymake-save-buffer-in-file "d:/flymake.log" t)  ; make log file name customizable
246	;;)
247	)))
248
249(defun flymake-ins-after (list pos val)
250  "Insert VAL into LIST after position POS."
251  (let ((tmp (copy-sequence list)))	; (???)
252    (setcdr (nthcdr pos tmp) (cons val (nthcdr (1+ pos) tmp)))
253    tmp))
254
255(defun flymake-set-at (list pos val)
256  "Set VAL at position POS in LIST."
257  (let ((tmp (copy-sequence list)))	; (???)
258    (setcar (nthcdr pos tmp) val)
259    tmp))
260
261(defvar flymake-processes nil
262  "List of currently active flymake processes.")
263
264(defvar flymake-output-residual nil)
265
266(make-variable-buffer-local 'flymake-output-residual)
267
268(defcustom flymake-allowed-file-name-masks
269  '(("\\.c\\'" flymake-simple-make-init)
270    ("\\.cpp\\'" flymake-simple-make-init)
271    ("\\.xml\\'" flymake-xml-init)
272    ("\\.html?\\'" flymake-xml-init)
273    ("\\.cs\\'" flymake-simple-make-init)
274    ("\\.pl\\'" flymake-perl-init)
275    ("\\.h\\'" flymake-master-make-header-init flymake-master-cleanup)
276    ("\\.java\\'" flymake-simple-make-java-init flymake-simple-java-cleanup)
277    ("[0-9]+\\.tex\\'" flymake-master-tex-init flymake-master-cleanup)
278    ("\\.tex\\'" flymake-simple-tex-init)
279    ("\\.idl\\'" flymake-simple-make-init)
280    ;; ("\\.cpp\\'" 1)
281    ;; ("\\.java\\'" 3)
282    ;; ("\\.h\\'" 2 ("\\.cpp\\'" "\\.c\\'")
283    ;; ("[ \t]*#[ \t]*include[ \t]*\"\\([\w0-9/\\_\.]*[/\\]*\\)\\(%s\\)\"" 1 2))
284    ;; ("\\.idl\\'" 1)
285    ;; ("\\.odl\\'" 1)
286    ;; ("[0-9]+\\.tex\\'" 2 ("\\.tex\\'")
287    ;; ("[ \t]*\\input[ \t]*{\\(.*\\)\\(%s\\)}" 1 2 ))
288    ;; ("\\.tex\\'" 1)
289    )
290  "*Files syntax checking is allowed for."
291  :group 'flymake
292  :type '(repeat (string symbol symbol symbol)))
293
294(defun flymake-get-file-name-mode-and-masks (file-name)
295  "Return the corresponding entry from `flymake-allowed-file-name-masks'."
296  (unless (stringp file-name)
297    (error "Invalid file-name"))
298  (let ((fnm flymake-allowed-file-name-masks)
299	(mode-and-masks  nil))
300    (while (and (not mode-and-masks) fnm)
301      (if (string-match (car (car fnm)) file-name)
302	  (setq mode-and-masks (cdr (car fnm))))
303      (setq fnm (cdr fnm)))
304    (flymake-log 3 "file %s, init=%s" file-name (car mode-and-masks))
305    mode-and-masks))
306
307(defun flymake-can-syntax-check-file (file-name)
308  "Determine whether we can syntax check FILE-NAME.
309Return nil if we cannot, non-nil if we can."
310  (if (flymake-get-init-function file-name) t nil))
311
312(defun flymake-get-init-function (file-name)
313  "Return init function to be used for the file."
314  (let* ((init-f  (nth 0 (flymake-get-file-name-mode-and-masks file-name))))
315    ;;(flymake-log 0 "calling %s" init-f)
316    ;;(funcall init-f (current-buffer))
317    init-f))
318
319(defun flymake-get-cleanup-function (file-name)
320  "Return cleanup function to be used for the file."
321  (or (nth 1 (flymake-get-file-name-mode-and-masks file-name))
322      'flymake-simple-cleanup))
323
324(defun flymake-get-real-file-name-function (file-name)
325  (or (nth 2 (flymake-get-file-name-mode-and-masks file-name))
326      'flymake-get-real-file-name))
327
328(defcustom flymake-buildfile-dirs '("." ".." "../.." "../../.." "../../../.." "../../../../.." "../../../../../.." "../../../../../../.." "../../../../../../../.." "../../../../../../../../.." "../../../../../../../../../.." "../../../../../../../../../../..")
329  "Dirs to look for buildfile."
330  :group 'flymake
331  :type '(repeat (string)))
332
333(defvar flymake-find-buildfile-cache (flymake-makehash 'equal))
334
335(defun flymake-get-buildfile-from-cache (dir-name)
336  (gethash dir-name flymake-find-buildfile-cache))
337
338(defun flymake-add-buildfile-to-cache (dir-name buildfile)
339  (puthash dir-name buildfile flymake-find-buildfile-cache))
340
341(defun flymake-clear-buildfile-cache ()
342  (clrhash flymake-find-buildfile-cache))
343
344(defun flymake-find-buildfile (buildfile-name source-dir-name)
345  "Find buildfile starting from current directory.
346Buildfile includes Makefile, build.xml etc.
347Return its file name if found, or nil if not found."
348  (or (flymake-get-buildfile-from-cache source-dir-name)
349      (let* ((dirs flymake-buildfile-dirs)
350             (buildfile-dir          nil)
351             (found                  nil))
352        (while (and (not found) dirs)
353          (setq buildfile-dir (concat source-dir-name (car dirs)))
354          (when (file-exists-p (expand-file-name buildfile-name buildfile-dir))
355            (setq found t))
356          (setq dirs (cdr dirs)))
357        (if found
358            (progn
359              (flymake-log 3 "found buildfile at %s/%s" buildfile-dir buildfile-name)
360              (flymake-add-buildfile-to-cache source-dir-name buildfile-dir)
361              buildfile-dir)
362          (progn
363            (flymake-log 3 "buildfile for %s not found" source-dir-name)
364            nil)))))
365
366(defun flymake-fix-file-name (name)
367  "Replace all occurrences of '\' with '/'."
368  (when name
369    (setq name (expand-file-name name))
370    (setq name (abbreviate-file-name name))
371    (setq name (directory-file-name name))
372    name))
373
374(defun flymake-same-files (file-name-one file-name-two)
375  "Check if FILE-NAME-ONE and FILE-NAME-TWO point to same file.
376Return t if so, nil if not."
377  (equal (flymake-fix-file-name file-name-one)
378	 (flymake-fix-file-name file-name-two)))
379
380(defcustom flymake-master-file-dirs '("." "./src" "./UnitTest")
381  "Dirs where to look for master files."
382  :group 'flymake
383  :type '(repeat (string)))
384
385(defcustom flymake-master-file-count-limit 32
386  "Max number of master files to check."
387  :group 'flymake
388  :type 'integer)
389
390;; This is bound dynamically to pass a parameter to a sort predicate below
391(defvar flymake-included-file-name)
392
393(defun flymake-find-possible-master-files (file-name master-file-dirs masks)
394  "Find (by name and location) all possible master files.
395Master files are .cpp and .c for and .h.  Files are searched for
396starting from the .h directory and max max-level parent dirs.
397File contents are not checked."
398  (let* ((dirs master-file-dirs)
399	 (files  nil)
400	 (done   nil))
401
402    (while (and (not done) dirs)
403      (let* ((dir (expand-file-name (car dirs) (file-name-directory file-name)))
404	     (masks masks))
405	(while (and (file-exists-p dir) (not done) masks)
406	  (let* ((mask        (car masks))
407		 (dir-files   (directory-files dir t mask)))
408
409	    (flymake-log 3 "dir %s, %d file(s) for mask %s"
410			 dir (length dir-files) mask)
411	    (while (and (not done) dir-files)
412	      (when (not (file-directory-p (car dir-files)))
413		(setq files (cons (car dir-files) files))
414		(when (>= (length files) flymake-master-file-count-limit)
415		  (flymake-log 3 "master file count limit (%d) reached" flymake-master-file-count-limit)
416		  (setq done t)))
417	      (setq dir-files (cdr dir-files))))
418	  (setq masks (cdr masks))))
419      (setq dirs (cdr dirs)))
420    (when files
421      (let ((flymake-included-file-name (file-name-nondirectory file-name)))
422	(setq files (sort files 'flymake-master-file-compare))))
423    (flymake-log 3 "found %d possible master file(s)" (length files))
424    files))
425
426(defun flymake-master-file-compare (file-one file-two)
427  "Compare two files specified by FILE-ONE and FILE-TWO.
428This function is used in sort to move most possible file names
429to the beginning of the list (File.h -> File.cpp moved to top)."
430  (and (equal (file-name-sans-extension flymake-included-file-name)
431	      (file-name-sans-extension (file-name-nondirectory file-one)))
432       (not (equal file-one file-two))))
433
434(defcustom flymake-check-file-limit 8192
435  "Max number of chars to look at when checking possible master file."
436  :group 'flymake
437  :type 'integer)
438
439(defun flymake-check-patch-master-file-buffer
440       (master-file-temp-buffer
441        master-file-name patched-master-file-name
442        source-file-name patched-source-file-name
443        include-dirs regexp)
444  "Check if MASTER-FILE-NAME is a master file for SOURCE-FILE-NAME.
445For .cpp master file this means it includes SOURCE-FILE-NAME (.h).
446If yes, patch a copy of MASTER-FILE-NAME to include PATCHED-SOURCE-FILE-NAME
447instead of SOURCE-FILE-NAME.
448Whether a buffer for MATER-FILE-NAME exists, use it as a source
449instead of reading master file from disk."
450  (let* ((source-file-nondir (file-name-nondirectory source-file-name))
451         (found                     nil)
452	 (inc-name                  nil)
453	 (search-limit              flymake-check-file-limit))
454    (setq regexp
455          (format regexp	; "[ \t]*#[ \t]*include[ \t]*\"\\(.*%s\\)\""
456                  (regexp-quote source-file-nondir)))
457    (unwind-protect
458        (with-current-buffer master-file-temp-buffer
459          (when (> search-limit (point-max))
460            (setq search-limit (point-max)))
461          (flymake-log 3 "checking %s against regexp %s"
462                       master-file-name regexp)
463          (goto-char (point-min))
464          (while (and (< (point) search-limit)
465                      (re-search-forward regexp search-limit t))
466            (let ((match-beg   (match-beginning 1))
467                  (match-end   (match-end 1)))
468
469              (flymake-log 3 "found possible match for %s" source-file-nondir)
470              (setq inc-name (match-string 1))
471              (when (eq t (compare-strings
472                           source-file-nondir nil nil
473                           inc-name (- (length inc-name)
474                                       (length source-file-nondir)) nil))
475                (flymake-log 3 "inc-name=%s" inc-name)
476                (when (flymake-check-include source-file-name inc-name
477                                             include-dirs)
478                  (setq found t)
479                  ;;  replace-match is not used here as it fails in
480                  ;; XEmacs with 'last match not a buffer' error as
481                  ;; check-includes calls replace-in-string
482                  (flymake-replace-region
483                   match-beg match-end
484                   (file-name-nondirectory patched-source-file-name))))
485              (forward-line 1)))
486          (when found
487            (flymake-save-buffer-in-file patched-master-file-name)))
488      ;;+(flymake-log 3 "killing buffer %s"
489      ;;                (buffer-name master-file-temp-buffer))
490      (kill-buffer master-file-temp-buffer))
491    ;;+(flymake-log 3 "check-patch master file %s: %s" master-file-name found)
492    (when found
493      (flymake-log 2 "found master file %s" master-file-name))
494    found))
495
496(defun flymake-replace-region (beg end rep)
497  "Replace text in BUFFER in region (BEG END) with REP."
498  (save-excursion
499    (goto-char end)
500    ;; Insert before deleting, so as to better preserve markers's positions.
501    (insert rep)
502    (delete-region beg end)))
503
504(defun flymake-read-file-to-temp-buffer (file-name)
505  "Insert contents of FILE-NAME into newly created temp buffer."
506  (let* ((temp-buffer (get-buffer-create (generate-new-buffer-name (concat "flymake:" (file-name-nondirectory file-name))))))
507    (with-current-buffer temp-buffer
508      (insert-file-contents file-name))
509    temp-buffer))
510
511(defun flymake-copy-buffer-to-temp-buffer (buffer)
512  "Copy contents of BUFFER into newly created temp buffer."
513  (with-current-buffer
514      (get-buffer-create (generate-new-buffer-name
515                          (concat "flymake:" (buffer-name buffer))))
516    (insert-buffer-substring buffer)
517    (current-buffer)))
518
519(defun flymake-check-include (source-file-name inc-name include-dirs)
520  "Check if SOURCE-FILE-NAME can be found in include path.
521Return t if it can be found via include path using INC-NAME."
522  (if (file-name-absolute-p inc-name)
523      (flymake-same-files source-file-name inc-name)
524    (while (and include-dirs
525                (not (flymake-same-files
526                      source-file-name
527                      (concat (file-name-directory source-file-name)
528                              "/" (car include-dirs)
529                              "/" inc-name))))
530      (setq include-dirs (cdr include-dirs)))
531    include-dirs))
532
533(defun flymake-find-buffer-for-file (file-name)
534  "Check if there exists a buffer visiting FILE-NAME.
535Return t if so, nil if not."
536  (let ((buffer-name (get-file-buffer file-name)))
537    (if buffer-name
538	(get-buffer buffer-name))))
539
540(defun flymake-create-master-file (source-file-name patched-source-file-name get-incl-dirs-f create-temp-f masks include-regexp)
541  "Save SOURCE-FILE-NAME with a different name.
542Find master file, patch and save it."
543  (let* ((possible-master-files     (flymake-find-possible-master-files source-file-name flymake-master-file-dirs masks))
544	 (master-file-count         (length possible-master-files))
545	 (idx                       0)
546	 (temp-buffer               nil)
547	 (master-file-name          nil)
548	 (patched-master-file-name  nil)
549	 (found                     nil))
550
551    (while (and (not found) (< idx master-file-count))
552      (setq master-file-name (nth idx possible-master-files))
553      (setq patched-master-file-name (funcall create-temp-f master-file-name "flymake_master"))
554      (if (flymake-find-buffer-for-file master-file-name)
555	  (setq temp-buffer (flymake-copy-buffer-to-temp-buffer (flymake-find-buffer-for-file master-file-name)))
556	(setq temp-buffer (flymake-read-file-to-temp-buffer master-file-name)))
557      (setq found
558	    (flymake-check-patch-master-file-buffer
559	     temp-buffer
560	     master-file-name
561	     patched-master-file-name
562	     source-file-name
563	     patched-source-file-name
564	     (funcall get-incl-dirs-f (file-name-directory master-file-name))
565	     include-regexp))
566      (setq idx (1+ idx)))
567    (if found
568	(list master-file-name patched-master-file-name)
569      (progn
570	(flymake-log 3 "none of %d master file(s) checked includes %s" master-file-count
571		     (file-name-nondirectory source-file-name))
572	nil))))
573
574(defun flymake-save-buffer-in-file (file-name)
575  (save-restriction
576    (widen)
577    (make-directory (file-name-directory file-name) 1)
578    (write-region (point-min) (point-max) file-name nil 566))
579  (flymake-log 3 "saved buffer %s in file %s" (buffer-name) file-name))
580
581(defun flymake-save-string-to-file (file-name data)
582  "Save string DATA to file FILE-NAME."
583  (write-region data nil file-name nil 566))
584
585(defun flymake-read-file-to-string (file-name)
586  "Read contents of file FILE-NAME and return as a string."
587  (with-temp-buffer
588    (insert-file-contents file-name)
589    (buffer-substring (point-min) (point-max))))
590
591(defun flymake-process-filter (process output)
592  "Parse OUTPUT and highlight error lines.
593It's flymake process filter."
594  (let ((source-buffer (process-buffer process)))
595
596    (flymake-log 3 "received %d byte(s) of output from process %d"
597                 (length output) (process-id process))
598    (when source-buffer
599      (with-current-buffer source-buffer
600        (flymake-parse-output-and-residual output)))))
601
602(defun flymake-process-sentinel (process event)
603  "Sentinel for syntax check buffers."
604  (when (memq (process-status process) '(signal exit))
605    (let* ((exit-status       (process-exit-status process))
606           (command           (process-command process))
607           (source-buffer     (process-buffer process))
608           (cleanup-f         (flymake-get-cleanup-function (buffer-file-name source-buffer))))
609
610      (flymake-log 2 "process %d exited with code %d"
611                   (process-id process) exit-status)
612      (condition-case err
613          (progn
614            (flymake-log 3 "cleaning up using %s" cleanup-f)
615            (when (buffer-live-p source-buffer)
616              (with-current-buffer source-buffer
617                (funcall cleanup-f)))
618
619            (delete-process process)
620            (setq flymake-processes (delq process flymake-processes))
621
622            (when (buffer-live-p source-buffer)
623              (with-current-buffer source-buffer
624
625                (flymake-parse-residual)
626                (flymake-post-syntax-check exit-status command)
627                (setq flymake-is-running nil))))
628        (error
629         (let ((err-str (format "Error in process sentinel for buffer %s: %s"
630                                source-buffer (error-message-string err))))
631           (flymake-log 0 err-str)
632           (with-current-buffer source-buffer
633             (setq flymake-is-running nil))))))))
634
635(defun flymake-post-syntax-check (exit-status command)
636  (setq flymake-err-info flymake-new-err-info)
637  (setq flymake-new-err-info nil)
638  (setq flymake-err-info
639        (flymake-fix-line-numbers
640         flymake-err-info 1 (flymake-count-lines)))
641  (flymake-delete-own-overlays)
642  (flymake-highlight-err-lines flymake-err-info)
643  (let (err-count warn-count)
644    (setq err-count (flymake-get-err-count flymake-err-info "e"))
645    (setq warn-count  (flymake-get-err-count flymake-err-info "w"))
646    (flymake-log 2 "%s: %d error(s), %d warning(s) in %.2f second(s)"
647		 (buffer-name) err-count warn-count
648		 (- (flymake-float-time) flymake-check-start-time))
649    (setq flymake-check-start-time nil)
650
651    (if (and (equal 0 err-count) (equal 0 warn-count))
652	(if (equal 0 exit-status)
653	    (flymake-report-status "" "")	; PASSED
654	  (if (not flymake-check-was-interrupted)
655	      (flymake-report-fatal-status "CFGERR"
656					   (format "Configuration error has occured while running %s" command))
657	    (flymake-report-status nil ""))) ; "STOPPED"
658      (flymake-report-status (format "%d/%d" err-count warn-count) ""))))
659
660(defun flymake-parse-output-and-residual (output)
661  "Split OUTPUT into lines, merge in residual if necessary."
662  (let* ((buffer-residual     flymake-output-residual)
663         (total-output        (if buffer-residual (concat buffer-residual output) output))
664         (lines-and-residual  (flymake-split-output total-output))
665         (lines               (nth 0 lines-and-residual))
666         (new-residual        (nth 1 lines-and-residual)))
667    (setq flymake-output-residual new-residual)
668    (setq flymake-new-err-info
669          (flymake-parse-err-lines
670           flymake-new-err-info lines))))
671
672(defun flymake-parse-residual ()
673  "Parse residual if it's non empty."
674  (when flymake-output-residual
675    (setq flymake-new-err-info
676          (flymake-parse-err-lines
677           flymake-new-err-info
678           (list flymake-output-residual)))
679    (setq flymake-output-residual nil)))
680
681(defun flymake-er-make-er (line-no line-err-info-list)
682  (list line-no line-err-info-list))
683
684(defun flymake-er-get-line (err-info)
685  (nth 0 err-info))
686
687(defun flymake-er-get-line-err-info-list (err-info)
688  (nth 1 err-info))
689
690(defstruct (flymake-ler
691            (:constructor nil)
692            (:constructor flymake-ler-make-ler (file line type text &optional full-file)))
693  file line type text full-file)
694
695(defun flymake-ler-set-file (line-err-info file)
696  (flymake-ler-make-ler file
697			(flymake-ler-line line-err-info)
698			(flymake-ler-type line-err-info)
699			(flymake-ler-text line-err-info)
700			(flymake-ler-full-file line-err-info)))
701
702(defun flymake-ler-set-full-file (line-err-info full-file)
703  (flymake-ler-make-ler (flymake-ler-file line-err-info)
704			(flymake-ler-line line-err-info)
705			(flymake-ler-type line-err-info)
706			(flymake-ler-text line-err-info)
707			full-file))
708
709(defun flymake-ler-set-line (line-err-info line)
710  (flymake-ler-make-ler (flymake-ler-file line-err-info)
711			line
712			(flymake-ler-type line-err-info)
713			(flymake-ler-text line-err-info)
714			(flymake-ler-full-file line-err-info)))
715
716(defun flymake-get-line-err-count (line-err-info-list type)
717  "Return number of errors of specified TYPE.
718Value of TYPE is either \"e\" or \"w\"."
719  (let* ((idx        0)
720	 (count      (length line-err-info-list))
721	 (err-count  0))
722
723    (while (< idx count)
724      (when (equal type (flymake-ler-type (nth idx line-err-info-list)))
725	(setq err-count (1+ err-count)))
726      (setq idx (1+ idx)))
727    err-count))
728
729(defun flymake-get-err-count (err-info-list type)
730  "Return number of errors of specified TYPE for ERR-INFO-LIST."
731  (let* ((idx        0)
732	 (count      (length err-info-list))
733	 (err-count  0))
734    (while (< idx count)
735      (setq err-count (+ err-count (flymake-get-line-err-count (nth 1 (nth idx err-info-list)) type)))
736      (setq idx (1+ idx)))
737    err-count))
738
739(defun flymake-fix-line-numbers (err-info-list min-line max-line)
740  "Replace line numbers with fixed value.
741If line-numbers is less than MIN-LINE, set line numbers to MIN-LINE.
742If line numbers is greater than MAX-LINE, set line numbers to MAX-LINE.
743The reason for this fix is because some compilers might report
744line number outside the file being compiled."
745  (let* ((count     (length err-info-list))
746	 (err-info  nil)
747	 (line      0))
748    (while (> count 0)
749      (setq err-info (nth (1- count) err-info-list))
750      (setq line (flymake-er-get-line err-info))
751      (when (or (< line min-line) (> line max-line))
752	(setq line (if (< line min-line) min-line max-line))
753	(setq err-info-list (flymake-set-at err-info-list (1- count)
754					    (flymake-er-make-er line
755								(flymake-er-get-line-err-info-list err-info)))))
756      (setq count (1- count))))
757  err-info-list)
758
759(defun flymake-highlight-err-lines (err-info-list)
760  "Highlight error lines in BUFFER using info from ERR-INFO-LIST."
761  (save-excursion
762    (dolist (err err-info-list)
763      (flymake-highlight-line (car err) (nth 1 err)))))
764
765(defun flymake-overlay-p (ov)
766  "Determine whether overlay OV was created by flymake."
767  (and (overlayp ov) (overlay-get ov 'flymake-overlay)))
768
769(defun flymake-make-overlay (beg end tooltip-text face mouse-face)
770  "Allocate a flymake overlay in range BEG and END."
771  (when (not (flymake-region-has-flymake-overlays beg end))
772    (let ((ov (make-overlay beg end nil t t)))
773      (overlay-put ov 'face           face)
774      (overlay-put ov 'mouse-face     mouse-face)
775      (overlay-put ov 'help-echo      tooltip-text)
776      (overlay-put ov 'flymake-overlay  t)
777      (overlay-put ov 'priority 100)
778      ;;+(flymake-log 3 "created overlay %s" ov)
779      ov)
780    (flymake-log 3 "created an overlay at (%d-%d)" beg end)))
781
782(defun flymake-delete-own-overlays ()
783  "Delete all flymake overlays in BUFFER."
784  (dolist (ol (overlays-in (point-min) (point-max)))
785    (when (flymake-overlay-p ol)
786      (delete-overlay ol)
787      ;;+(flymake-log 3 "deleted overlay %s" ol)
788      )))
789
790(defun flymake-region-has-flymake-overlays (beg end)
791  "Check if region specified by BEG and END has overlay.
792Return t if it has at least one flymake overlay, nil if no overlay."
793  (let ((ov                  (overlays-in beg end))
794	(has-flymake-overlays  nil))
795    (while (consp ov)
796      (when (flymake-overlay-p (car ov))
797	(setq has-flymake-overlays t))
798      (setq ov (cdr ov)))
799    has-flymake-overlays))
800
801(defface flymake-errline
802  ;;+   '((((class color)) (:foreground "OrangeRed" :bold t :underline t))
803  ;;+   '((((class color)) (:underline "OrangeRed"))
804  '((((class color)) (:background "LightPink"))
805    (t (:bold t)))
806  "Face used for marking error lines."
807  :group 'flymake)
808
809(defface flymake-warnline
810  '((((class color)) (:background "LightBlue2"))
811    (t (:bold t)))
812  "Face used for marking warning lines."
813  :group 'flymake)
814
815(defun flymake-highlight-line (line-no line-err-info-list)
816  "Highlight line LINE-NO in current buffer.
817Perhaps use text from LINE-ERR-INFO-LIST to enhance highlighting."
818  (goto-line line-no)
819  (let* ((line-beg (flymake-line-beginning-position))
820	 (line-end (flymake-line-end-position))
821	 (beg      line-beg)
822	 (end      line-end)
823	 (tooltip-text (flymake-ler-text (nth 0 line-err-info-list)))
824	 (face     nil))
825
826    (goto-char line-beg)
827    (while (looking-at "[ \t]")
828      (forward-char))
829
830    (setq beg (point))
831
832    (goto-char line-end)
833    (while (and (looking-at "[ \t\r\n]") (> (point) 1))
834      (backward-char))
835
836    (setq end (1+ (point)))
837
838    (when (<= end beg)
839      (setq beg line-beg)
840      (setq end line-end))
841
842    (when (= end beg)
843      (goto-char end)
844      (forward-line)
845      (setq end (point)))
846
847    (if (> (flymake-get-line-err-count line-err-info-list "e") 0)
848	(setq face 'flymake-errline)
849      (setq face 'flymake-warnline))
850
851    (flymake-make-overlay beg end tooltip-text face nil)))
852
853(defun flymake-parse-err-lines (err-info-list lines)
854  "Parse err LINES, store info in ERR-INFO-LIST."
855  (let* ((count              (length lines))
856	 (idx                0)
857	 (line-err-info      nil)
858	 (real-file-name     nil)
859	 (source-file-name   buffer-file-name)
860	 (get-real-file-name-f (flymake-get-real-file-name-function source-file-name)))
861
862    (while (< idx count)
863      (setq line-err-info (flymake-parse-line (nth idx lines)))
864      (when line-err-info
865	(setq real-file-name (funcall get-real-file-name-f
866                                      (flymake-ler-file line-err-info)))
867	(setq line-err-info (flymake-ler-set-full-file line-err-info real-file-name))
868
869	(if (flymake-same-files real-file-name source-file-name)
870	    (setq line-err-info (flymake-ler-set-file line-err-info nil))
871	  (setq line-err-info (flymake-ler-set-file line-err-info (file-name-nondirectory real-file-name))))
872
873	(setq err-info-list (flymake-add-err-info err-info-list line-err-info)))
874      (flymake-log 3 "parsed '%s', %s line-err-info" (nth idx lines) (if line-err-info "got" "no"))
875      (setq idx (1+ idx)))
876    err-info-list))
877
878(defun flymake-split-output (output)
879  "Split OUTPUT into lines.
880Return last one as residual if it does not end with newline char.
881Returns ((LINES) RESIDUAL)."
882  (when (and output (> (length output) 0))
883    (let* ((lines (flymake-split-string output "[\n\r]+"))
884	   (complete (equal "\n" (char-to-string (aref output (1- (length output))))))
885	   (residual nil))
886      (when (not complete)
887	(setq residual (car (last lines)))
888	(setq lines (butlast lines)))
889      (list lines residual))))
890
891(defun flymake-reformat-err-line-patterns-from-compile-el (original-list)
892  "Grab error line patterns from ORIGINAL-LIST in compile.el format.
893Convert it to flymake internal format."
894  (let* ((converted-list '()))
895    (dolist (item original-list)
896      (setq item (cdr item))
897      (let ((regexp (nth 0 item))
898	    (file (nth 1 item))
899	    (line (nth 2 item))
900	    (col (nth 3 item)))
901	(if (consp file)	(setq file (car file)))
902	(if (consp line)	(setq line (car line)))
903	(if (consp col)	(setq col (car col)))
904
905	(when (not (functionp line))
906	  (setq converted-list (cons (list regexp file line col) converted-list)))))
907    converted-list))
908
909(require 'compile)
910
911(defvar flymake-err-line-patterns ; regexp file-idx line-idx col-idx (optional) text-idx(optional), match-end to end of string is error text
912  (append
913   '(
914     ;; MS Visual C++ 6.0
915     ("\\(\\([a-zA-Z]:\\)?[^:(\t\n]+\\)(\\([0-9]+\\)) \: \\(\\(error\\|warning\\|fatal error\\) \\(C[0-9]+\\):[ \t\n]*\\(.+\\)\\)"
916      1 3 nil 4)
917     ;; jikes
918     ("\\(\\([a-zA-Z]:\\)?[^:(\t\n]+\\)\:\\([0-9]+\\)\:[0-9]+\:[0-9]+\:[0-9]+\: \\(\\(Error\\|Warning\\|Caution\\|Semantic Error\\):[ \t\n]*\\(.+\\)\\)"
919      1 3 nil 4)
920     ;; MS midl
921     ("midl[ ]*:[ ]*\\(command line error .*\\)"
922      nil nil nil 1)
923     ;; MS C#
924     ("\\(\\([a-zA-Z]:\\)?[^:(\t\n]+\\)(\\([0-9]+\\),[0-9]+)\: \\(\\(error\\|warning\\|fatal error\\) \\(CS[0-9]+\\):[ \t\n]*\\(.+\\)\\)"
925      1 3 nil 4)
926     ;; perl
927     ("\\(.*\\) at \\([^ \n]+\\) line \\([0-9]+\\)[,.\n]" 2 3 nil 1)
928     ;; LaTeX warnings (fileless) ("\\(LaTeX \\(Warning\\|Error\\): .*\\) on input line \\([0-9]+\\)" 20 3 nil 1)
929     ;; ant/javac
930     (" *\\(\\[javac\\]\\)? *\\(\\([a-zA-Z]:\\)?[^:(\t\n]+\\)\:\\([0-9]+\\)\:[ \t\n]*\\(.+\\)"
931      2 4 nil 5))
932   ;; compilation-error-regexp-alist)
933   (flymake-reformat-err-line-patterns-from-compile-el compilation-error-regexp-alist-alist))
934  "Patterns for matching error/warning lines.  Each pattern has the form
935\(REGEXP FILE-IDX LINE-IDX COL-IDX ERR-TEXT-IDX).
936Use `flymake-reformat-err-line-patterns-from-compile-el' to add patterns
937from compile.el")
938
939;;(defcustom flymake-err-line-patterns
940;;  '(
941;;    ; MS Visual C++ 6.0
942;;    ("\\(\\([a-zA-Z]:\\)?[^:(\t\n]+\\)(\\([0-9]+\\)) \: \\(\\(error\\|warning\\|fatal error\\) \\(C[0-9]+\\):[ \t\n]*\\(.+\\)\\)"
943;;       1 3 4)
944;;   ; jikes
945;;   ("\\(\\([a-zA-Z]:\\)?[^:(\t\n]+\\)\:\\([0-9]+\\)\:[0-9]+\:[0-9]+\:[0-9]+\: \\(\\(Error\\|Warning\\|Caution\\):[ \t\n]*\\(.+\\)\\)"
946;;       1 3 4))
947;;    "patterns for matching error/warning lines, (regexp file-idx line-idx err-text-idx)"
948;;   :group 'flymake
949;;   :type '(repeat (string number number number))
950;;)
951
952(defun flymake-parse-line (line)
953  "Parse LINE to see if it is an error or warning.
954Return its components if so, nil otherwise."
955  (let ((raw-file-name nil)
956	(line-no 0)
957	(err-type "e")
958	(err-text nil)
959	(patterns flymake-err-line-patterns)
960	(matched nil))
961    (while (and patterns (not matched))
962      (when (string-match (car (car patterns)) line)
963	(let* ((file-idx (nth 1 (car patterns)))
964	       (line-idx (nth 2 (car patterns))))
965
966	  (setq raw-file-name (if file-idx (match-string file-idx line) nil))
967	  (setq line-no       (if line-idx (string-to-number (match-string line-idx line)) 0))
968	  (setq err-text      (if (> (length (car patterns)) 4)
969				  (match-string (nth 4 (car patterns)) line)
970				(flymake-patch-err-text (substring line (match-end 0)))))
971	  (or err-text (setq err-text "<no error text>"))
972	  (if (and err-text (string-match "^[wW]arning" err-text))
973	      (setq err-type "w")
974	    )
975	  (flymake-log 3 "parse line: file-idx=%s line-idx=%s file=%s line=%s text=%s" file-idx line-idx
976		       raw-file-name line-no err-text)
977	  (setq matched t)))
978      (setq patterns (cdr patterns)))
979    (if matched
980	(flymake-ler-make-ler raw-file-name line-no err-type err-text)
981      ())))
982
983(defun flymake-find-err-info (err-info-list line-no)
984  "Find (line-err-info-list pos) for specified LINE-NO."
985  (if err-info-list
986      (let* ((line-err-info-list  nil)
987	     (pos       0)
988	     (count     (length err-info-list)))
989
990	(while (and (< pos count) (< (car (nth pos err-info-list)) line-no))
991	  (setq pos (1+ pos)))
992	(when (and (< pos count) (equal (car (nth pos err-info-list)) line-no))
993	  (setq line-err-info-list (flymake-er-get-line-err-info-list (nth pos err-info-list))))
994	(list line-err-info-list pos))
995    '(nil 0)))
996
997(defun flymake-line-err-info-is-less-or-equal (line-one line-two)
998  (or (string< (flymake-ler-type line-one) (flymake-ler-type line-two))
999      (and (string= (flymake-ler-type line-one) (flymake-ler-type line-two))
1000	   (not (flymake-ler-file line-one)) (flymake-ler-file line-two))
1001      (and (string= (flymake-ler-type line-one) (flymake-ler-type line-two))
1002	   (or (and      (flymake-ler-file line-one)       (flymake-ler-file line-two))
1003	       (and (not (flymake-ler-file line-one)) (not (flymake-ler-file line-two)))))))
1004
1005(defun flymake-add-line-err-info (line-err-info-list line-err-info)
1006  "Update LINE-ERR-INFO-LIST with the error LINE-ERR-INFO.
1007For the format of LINE-ERR-INFO, see `flymake-ler-make-ler'.
1008The new element is inserted in the proper position, according to
1009the predicate `flymake-line-err-info-is-less-or-equal'.
1010The updated value of LINE-ERR-INFO-LIST is returned."
1011  (if (not line-err-info-list)
1012      (list line-err-info)
1013    (let* ((count  (length line-err-info-list))
1014	   (idx    0))
1015      (while (and (< idx count) (flymake-line-err-info-is-less-or-equal (nth idx line-err-info-list) line-err-info))
1016	(setq idx (1+ idx)))
1017      (cond ((equal 0     idx)    (setq line-err-info-list (cons line-err-info line-err-info-list)))
1018	    (t                    (setq line-err-info-list (flymake-ins-after line-err-info-list (1- idx) line-err-info))))
1019      line-err-info-list)))
1020
1021(defun flymake-add-err-info (err-info-list line-err-info)
1022  "Update ERR-INFO-LIST with the error LINE-ERR-INFO, preserving sort order.
1023Returns the updated value of ERR-INFO-LIST.
1024For the format of ERR-INFO-LIST, see `flymake-err-info'.
1025For the format of LINE-ERR-INFO, see `flymake-ler-make-ler'."
1026  (let* ((line-no             (if (flymake-ler-file line-err-info) 1 (flymake-ler-line line-err-info)))
1027	 (info-and-pos        (flymake-find-err-info err-info-list line-no))
1028	 (exists              (car info-and-pos))
1029	 (pos                 (nth 1 info-and-pos))
1030	 (line-err-info-list  nil)
1031	 (err-info            nil))
1032
1033    (if exists
1034	(setq line-err-info-list (flymake-er-get-line-err-info-list (car (nthcdr pos err-info-list)))))
1035    (setq line-err-info-list (flymake-add-line-err-info line-err-info-list line-err-info))
1036
1037    (setq err-info (flymake-er-make-er line-no line-err-info-list))
1038    (cond (exists             (setq err-info-list (flymake-set-at err-info-list pos err-info)))
1039	  ((equal 0 pos)      (setq err-info-list (cons err-info err-info-list)))
1040	  (t                  (setq err-info-list (flymake-ins-after err-info-list (1- pos) err-info))))
1041    err-info-list))
1042
1043(defun flymake-get-project-include-dirs-imp (basedir)
1044  "Include dirs for the project current file belongs to."
1045  (if (flymake-get-project-include-dirs-from-cache basedir)
1046      (progn
1047	(flymake-get-project-include-dirs-from-cache basedir))
1048    ;;else
1049    (let* ((command-line  (concat "make -C "
1050				  (shell-quote-argument basedir)
1051				  " DUMPVARS=INCLUDE_DIRS dumpvars"))
1052	   (output        (shell-command-to-string command-line))
1053	   (lines         (flymake-split-string output "\n"))
1054	   (count         (length lines))
1055	   (idx           0)
1056	   (inc-dirs      nil))
1057      (while (and (< idx count) (not (string-match "^INCLUDE_DIRS=.*" (nth idx lines))))
1058	(setq idx (1+ idx)))
1059      (when (< idx count)
1060	(let* ((inc-lines  (flymake-split-string (nth idx lines) " *-I"))
1061	       (inc-count  (length inc-lines)))
1062	  (while (> inc-count 0)
1063	    (when (not (string-match "^INCLUDE_DIRS=.*" (nth (1- inc-count) inc-lines)))
1064	      (push (flymake-replace-regexp-in-string "\"" "" (nth (1- inc-count) inc-lines)) inc-dirs))
1065	    (setq inc-count (1- inc-count)))))
1066      (flymake-add-project-include-dirs-to-cache basedir inc-dirs)
1067      inc-dirs)))
1068
1069(defcustom flymake-get-project-include-dirs-function 'flymake-get-project-include-dirs-imp
1070  "Function used to get project include dirs, one parameter: basedir name."
1071  :group 'flymake
1072  :type 'function)
1073
1074(defun flymake-get-project-include-dirs (basedir)
1075  (funcall flymake-get-project-include-dirs-function basedir))
1076
1077(defun flymake-get-system-include-dirs ()
1078  "System include dirs - from the 'INCLUDE' env setting."
1079  (let* ((includes (getenv "INCLUDE")))
1080    (if includes (flymake-split-string includes path-separator) nil)))
1081
1082(defvar flymake-project-include-dirs-cache (flymake-makehash 'equal))
1083
1084(defun flymake-get-project-include-dirs-from-cache (base-dir)
1085  (gethash base-dir flymake-project-include-dirs-cache))
1086
1087(defun flymake-add-project-include-dirs-to-cache (base-dir include-dirs)
1088  (puthash base-dir include-dirs flymake-project-include-dirs-cache))
1089
1090(defun flymake-clear-project-include-dirs-cache ()
1091  (clrhash flymake-project-include-dirs-cache))
1092
1093(defun flymake-get-include-dirs (base-dir)
1094  "Get dirs to use when resolving local file names."
1095  (let* ((include-dirs (append '(".") (flymake-get-project-include-dirs base-dir) (flymake-get-system-include-dirs))))
1096    include-dirs))
1097
1098;; (defun flymake-restore-formatting ()
1099;;   "Remove any formatting made by flymake."
1100;;   )
1101
1102;; (defun flymake-get-program-dir (buffer)
1103;;   "Get dir to start program in."
1104;;   (unless (bufferp buffer)
1105;;     (error "Invalid buffer"))
1106;;   (with-current-buffer buffer
1107;;     default-directory))
1108
1109(defun flymake-safe-delete-file (file-name)
1110  (when (and file-name (file-exists-p file-name))
1111    (delete-file file-name)
1112    (flymake-log 1 "deleted file %s" file-name)))
1113
1114(defun flymake-safe-delete-directory (dir-name)
1115  (condition-case err
1116      (progn
1117	(delete-directory dir-name)
1118	(flymake-log 1 "deleted dir %s" dir-name))
1119    (error
1120     (flymake-log 1 "Failed to delete dir %s, error ignored" dir-name))))
1121
1122(defcustom flymake-compilation-prevents-syntax-check t
1123  "If non-nil, syntax check won't be started in case compilation is running."
1124  :group 'flymake
1125  :type 'boolean)
1126
1127(defun flymake-start-syntax-check ()
1128  "Start syntax checking for current buffer."
1129  (interactive)
1130  (flymake-log 3 "flymake is running: %s" flymake-is-running)
1131  (when (and (not flymake-is-running)
1132             (flymake-can-syntax-check-file buffer-file-name))
1133    (when (or (not flymake-compilation-prevents-syntax-check)
1134              (not (flymake-compilation-is-running))) ;+ (flymake-rep-ort-status buffer "COMP")
1135      (flymake-clear-buildfile-cache)
1136      (flymake-clear-project-include-dirs-cache)
1137
1138      (setq flymake-check-was-interrupted nil)
1139
1140      (let* ((source-file-name  buffer-file-name)
1141             (init-f (flymake-get-init-function source-file-name))
1142             (cleanup-f (flymake-get-cleanup-function source-file-name))
1143             (cmd-and-args (funcall init-f))
1144             (cmd          (nth 0 cmd-and-args))
1145             (args         (nth 1 cmd-and-args))
1146             (dir          (nth 2 cmd-and-args)))
1147        (if (not cmd-and-args)
1148            (progn
1149              (flymake-log 0 "init function %s for %s failed, cleaning up" init-f source-file-name)
1150              (funcall cleanup-f))
1151          (progn
1152            (setq flymake-last-change-time nil)
1153            (flymake-start-syntax-check-process cmd args dir)))))))
1154
1155(defun flymake-start-syntax-check-process (cmd args dir)
1156  "Start syntax check process."
1157  (let* ((process nil))
1158    (condition-case err
1159	(progn
1160	  (when dir
1161	    (let ((default-directory dir))
1162	      (flymake-log 3 "starting process on dir %s" default-directory)))
1163	  (setq process (apply 'start-process "flymake-proc" (current-buffer) cmd args))
1164	  (set-process-sentinel process 'flymake-process-sentinel)
1165	  (set-process-filter process 'flymake-process-filter)
1166          (push process flymake-processes)
1167
1168          (setq flymake-is-running t)
1169          (setq flymake-last-change-time nil)
1170          (setq flymake-check-start-time (flymake-float-time))
1171
1172	  (flymake-report-status nil "*")
1173	  (flymake-log 2 "started process %d, command=%s, dir=%s"
1174		       (process-id process) (process-command process)
1175                       default-directory)
1176	  process)
1177      (error
1178       (let* ((err-str (format "Failed to launch syntax check process '%s' with args %s: %s"
1179			       cmd args (error-message-string err)))
1180	      (source-file-name buffer-file-name)
1181	      (cleanup-f        (flymake-get-cleanup-function source-file-name)))
1182	 (flymake-log 0 err-str)
1183	 (funcall cleanup-f)
1184	 (flymake-report-fatal-status "PROCERR" err-str))))))
1185
1186(defun flymake-kill-process (proc)
1187  "Kill process PROC."
1188  (kill-process proc)
1189  (let* ((buf (process-buffer proc)))
1190    (when (buffer-live-p buf)
1191      (with-current-buffer buf
1192	(setq flymake-check-was-interrupted t))))
1193  (flymake-log 1 "killed process %d" (process-id proc)))
1194
1195(defun flymake-stop-all-syntax-checks ()
1196  "Kill all syntax check processes."
1197  (interactive)
1198  (while flymake-processes
1199    (flymake-kill-process (pop flymake-processes))))
1200
1201(defun flymake-compilation-is-running ()
1202  (and (boundp 'compilation-in-progress)
1203       compilation-in-progress))
1204
1205(defun flymake-compile ()
1206  "Kill all flymake syntax checks, start compilation."
1207  (interactive)
1208  (flymake-stop-all-syntax-checks)
1209  (call-interactively 'compile))
1210
1211(defcustom flymake-no-changes-timeout 0.5
1212  "Time to wait after last change before starting compilation."
1213  :group 'flymake
1214  :type 'number)
1215
1216(defun flymake-on-timer-event (buffer)
1217  "Start a syntax check for buffer BUFFER if necessary."
1218  (when (buffer-live-p buffer)
1219    (with-current-buffer buffer
1220      (when (and (not flymake-is-running)
1221		 flymake-last-change-time
1222		 (> (- (flymake-float-time) flymake-last-change-time)
1223                    flymake-no-changes-timeout))
1224
1225	(setq flymake-last-change-time nil)
1226	(flymake-log 3 "starting syntax check as more than 1 second passed since last change")
1227	(flymake-start-syntax-check)))))
1228
1229(defun flymake-current-line-no ()
1230  "Return number of current line in current buffer."
1231  (count-lines (point-min) (if (eobp) (point) (1+ (point)))))
1232
1233(defun flymake-count-lines ()
1234  "Return number of lines in buffer BUFFER."
1235  (count-lines (point-min) (point-max)))
1236
1237(defun flymake-display-err-menu-for-current-line ()
1238  "Display a menu with errors/warnings for current line if it has errors and/or warnings."
1239  (interactive)
1240  (let* ((line-no             (flymake-current-line-no))
1241	 (line-err-info-list  (nth 0 (flymake-find-err-info flymake-err-info line-no)))
1242	 (menu-data           (flymake-make-err-menu-data line-no line-err-info-list))
1243	 (choice              nil))
1244    (if menu-data
1245	(progn
1246	  (setq choice (flymake-popup-menu menu-data))
1247	  (flymake-log 3 "choice=%s" choice)
1248	  (when choice
1249	    (eval choice)))
1250      (flymake-log 1 "no errors for line %d" line-no))))
1251
1252(defun flymake-make-err-menu-data (line-no line-err-info-list)
1253  "Make a (menu-title (item-title item-action)*) list with errors/warnings from LINE-ERR-INFO-LIST."
1254  (let* ((menu-items  nil))
1255    (when line-err-info-list
1256      (let* ((count           (length line-err-info-list))
1257	     (menu-item-text  nil))
1258	(while (> count 0)
1259	  (setq menu-item-text (flymake-ler-text (nth (1- count) line-err-info-list)))
1260	  (let* ((file       (flymake-ler-file (nth (1- count) line-err-info-list)))
1261		 (full-file  (flymake-ler-full-file (nth (1- count) line-err-info-list)))
1262		 (line       (flymake-ler-line (nth (1- count) line-err-info-list))))
1263	    (if file
1264		(setq menu-item-text (concat menu-item-text " - " file "(" (format "%d" line) ")")))
1265	    (setq menu-items (cons (list menu-item-text
1266					 (if file (list 'flymake-goto-file-and-line full-file line) nil))
1267				   menu-items)))
1268	  (setq count (1- count)))
1269	(flymake-log 3 "created menu-items with %d item(s)" (length menu-items))))
1270    (if menu-items
1271	(let* ((menu-title  (format "Line %d: %d error(s), %d warning(s)" line-no
1272				    (flymake-get-line-err-count line-err-info-list "e")
1273				    (flymake-get-line-err-count line-err-info-list "w"))))
1274	  (list menu-title menu-items))
1275      nil)))
1276
1277(defun flymake-goto-file-and-line (file line)
1278  "Try to get buffer for FILE and goto line LINE in it."
1279  (if (not (file-exists-p file))
1280      (flymake-log 1 "file %s does not exists" file)
1281    (progn
1282      (find-file file)
1283      (goto-line line))))
1284
1285;; flymake minor mode declarations
1286(defvar flymake-mode-line nil)
1287
1288(make-variable-buffer-local 'flymake-mode-line)
1289
1290(defvar flymake-mode-line-e-w nil)
1291
1292(make-variable-buffer-local 'flymake-mode-line-e-w)
1293
1294(defvar flymake-mode-line-status nil)
1295
1296(make-variable-buffer-local 'flymake-mode-line-status)
1297
1298(defun flymake-report-status (e-w &optional status)
1299  "Show status in mode line."
1300  (when e-w
1301    (setq flymake-mode-line-e-w e-w))
1302  (when status
1303    (setq flymake-mode-line-status status))
1304  (let* ((mode-line " Flymake"))
1305    (when (> (length flymake-mode-line-e-w) 0)
1306      (setq mode-line (concat mode-line ":" flymake-mode-line-e-w)))
1307    (setq mode-line (concat mode-line flymake-mode-line-status))
1308    (setq flymake-mode-line mode-line)
1309    (force-mode-line-update)))
1310
1311(defun flymake-display-warning (warning)
1312  "Display a warning to user."
1313  (message-box warning))
1314
1315(defcustom flymake-gui-warnings-enabled t
1316  "Enables/disables GUI warnings."
1317  :group 'flymake
1318  :type 'boolean)
1319
1320(defun flymake-report-fatal-status (status warning)
1321  "Display a warning and switch flymake mode off."
1322  (when flymake-gui-warnings-enabled
1323    (flymake-display-warning (format "Flymake: %s. Flymake will be switched OFF" warning))
1324    )
1325  (flymake-mode 0)
1326  (flymake-log 0 "switched OFF Flymake mode for buffer %s due to fatal status %s, warning %s"
1327               (buffer-name) status warning))
1328
1329(defcustom flymake-start-syntax-check-on-find-file t
1330  "Start syntax check on find file."
1331  :group 'flymake
1332  :type 'boolean)
1333
1334;;;###autoload
1335(define-minor-mode flymake-mode
1336  "Minor mode to do on-the-fly syntax checking.
1337When called interactively, toggles the minor mode.
1338With arg, turn Flymake mode on if and only if arg is positive."
1339  :group 'flymake :lighter flymake-mode-line
1340  (cond
1341
1342   ;; Turning the mode ON.
1343   (flymake-mode
1344    (if (not (flymake-can-syntax-check-file buffer-file-name))
1345        (flymake-log 2 "flymake cannot check syntax in buffer %s" (buffer-name))
1346      (add-hook 'after-change-functions 'flymake-after-change-function nil t)
1347      (add-hook 'after-save-hook 'flymake-after-save-hook nil t)
1348      (add-hook 'kill-buffer-hook 'flymake-kill-buffer-hook nil t)
1349      ;;+(add-hook 'find-file-hook 'flymake-find-file-hook)
1350
1351      (flymake-report-status "" "")
1352
1353      (setq flymake-timer
1354            (run-at-time nil 1 'flymake-on-timer-event (current-buffer)))
1355
1356      (when flymake-start-syntax-check-on-find-file
1357        (flymake-start-syntax-check))))
1358
1359   ;; Turning the mode OFF.
1360   (t
1361    (remove-hook 'after-change-functions 'flymake-after-change-function t)
1362    (remove-hook 'after-save-hook 'flymake-after-save-hook t)
1363    (remove-hook 'kill-buffer-hook 'flymake-kill-buffer-hook t)
1364    ;;+(remove-hook 'find-file-hook (function flymake-find-file-hook) t)
1365
1366    (flymake-delete-own-overlays)
1367
1368    (when flymake-timer
1369      (cancel-timer flymake-timer)
1370      (setq flymake-timer nil))
1371
1372    (setq flymake-is-running nil))))
1373
1374;;;###autoload
1375(defun flymake-mode-on ()
1376  "Turn flymake mode on."
1377  (flymake-mode 1)
1378  (flymake-log 1 "flymake mode turned ON for buffer %s" (buffer-name)))
1379
1380;;;###autoload
1381(defun flymake-mode-off ()
1382  "Turn flymake mode off."
1383  (flymake-mode 0)
1384  (flymake-log 1 "flymake mode turned OFF for buffer %s" (buffer-name)))
1385
1386(defcustom flymake-start-syntax-check-on-newline t
1387  "Start syntax check if newline char was added/removed from the buffer."
1388  :group 'flymake
1389  :type 'boolean)
1390
1391(defun flymake-after-change-function (start stop len)
1392  "Start syntax check for current buffer if it isn't already running."
1393  ;;+(flymake-log 0 "setting change time to %s" (flymake-float-time))
1394  (let((new-text (buffer-substring start stop)))
1395    (when (and flymake-start-syntax-check-on-newline (equal new-text "\n"))
1396      (flymake-log 3 "starting syntax check as new-line has been seen")
1397      (flymake-start-syntax-check))
1398    (setq flymake-last-change-time (flymake-float-time))))
1399
1400(defun flymake-after-save-hook ()
1401  (if (local-variable-p 'flymake-mode (current-buffer))	; (???) other way to determine whether flymake is active in buffer being saved?
1402      (progn
1403	(flymake-log 3 "starting syntax check as buffer was saved")
1404	(flymake-start-syntax-check)))) ; no more mode 3. cannot start check if mode 3 (to temp copies) is active - (???)
1405
1406(defun flymake-kill-buffer-hook ()
1407  (when flymake-timer
1408    (cancel-timer flymake-timer)
1409    (setq flymake-timer nil)))
1410
1411(defun flymake-find-file-hook ()
1412  ;;+(when flymake-start-syntax-check-on-find-file
1413  ;;+    (flymake-log 3 "starting syntax check on file open")
1414  ;;+    (flymake-start-syntax-check)
1415  ;;+)
1416  (when (and (not (local-variable-p 'flymake-mode (current-buffer)))
1417	     (flymake-can-syntax-check-file buffer-file-name))
1418    (flymake-mode)
1419    (flymake-log 3 "automatically turned ON flymake mode")))
1420
1421(defun flymake-get-first-err-line-no (err-info-list)
1422  "Return first line with error."
1423  (when err-info-list
1424    (flymake-er-get-line (car err-info-list))))
1425
1426(defun flymake-get-last-err-line-no (err-info-list)
1427  "Return last line with error."
1428  (when err-info-list
1429    (flymake-er-get-line (nth (1- (length err-info-list)) err-info-list))))
1430
1431(defun flymake-get-next-err-line-no (err-info-list line-no)
1432  "Return next line with error."
1433  (when err-info-list
1434    (let* ((count  (length err-info-list))
1435	   (idx    0))
1436      (while (and (< idx count) (>= line-no (flymake-er-get-line (nth idx err-info-list))))
1437	(setq idx (1+ idx)))
1438      (if (< idx count)
1439	  (flymake-er-get-line (nth idx err-info-list))))))
1440
1441(defun flymake-get-prev-err-line-no (err-info-list line-no)
1442  "Return previous line with error."
1443  (when err-info-list
1444    (let* ((count (length err-info-list)))
1445      (while (and (> count 0) (<= line-no (flymake-er-get-line (nth (1- count) err-info-list))))
1446	(setq count (1- count)))
1447      (if (> count 0)
1448	  (flymake-er-get-line (nth (1- count) err-info-list))))))
1449
1450(defun flymake-skip-whitespace ()
1451  "Move forward until non-whitespace is reached."
1452  (while (looking-at "[ \t]")
1453    (forward-char)))
1454
1455(defun flymake-goto-line (line-no)
1456  "Go to line LINE-NO, then skip whitespace."
1457  (goto-line line-no)
1458  (flymake-skip-whitespace))
1459
1460(defun flymake-goto-next-error ()
1461  "Go to next error in err ring."
1462  (interactive)
1463  (let ((line-no (flymake-get-next-err-line-no flymake-err-info (flymake-current-line-no))))
1464    (when (not line-no)
1465      (setq line-no (flymake-get-first-err-line-no flymake-err-info))
1466      (flymake-log 1 "passed end of file"))
1467    (if line-no
1468	(flymake-goto-line line-no)
1469      (flymake-log 1 "no errors in current buffer"))))
1470
1471(defun flymake-goto-prev-error ()
1472  "Go to previous error in err ring."
1473  (interactive)
1474  (let ((line-no (flymake-get-prev-err-line-no flymake-err-info (flymake-current-line-no))))
1475    (when (not line-no)
1476      (setq line-no (flymake-get-last-err-line-no flymake-err-info))
1477      (flymake-log 1 "passed beginning of file"))
1478    (if line-no
1479	(flymake-goto-line line-no)
1480      (flymake-log 1 "no errors in current buffer"))))
1481
1482(defun flymake-patch-err-text (string)
1483  (if (string-match "^[\n\t :0-9]*\\(.*\\)$" string)
1484      (match-string 1 string)
1485    string))
1486
1487;;;; general init-cleanup and helper routines
1488(defun flymake-create-temp-inplace (file-name prefix)
1489  (unless (stringp file-name)
1490    (error "Invalid file-name"))
1491  (or prefix
1492      (setq prefix "flymake"))
1493  (let* ((temp-name   (concat (file-name-sans-extension file-name)
1494			      "_" prefix
1495			      (and (file-name-extension file-name)
1496				   (concat "." (file-name-extension file-name))))))
1497    (flymake-log 3 "create-temp-inplace: file=%s temp=%s" file-name temp-name)
1498    temp-name))
1499
1500(defun flymake-create-temp-with-folder-structure (file-name prefix)
1501  (unless (stringp file-name)
1502    (error "Invalid file-name"))
1503
1504  (let* ((dir       (file-name-directory file-name))
1505         ;; Not sure what this slash-pos is all about, but I guess it's just
1506         ;; trying to remove the leading / of absolute file names.
1507	 (slash-pos (string-match "/" dir))
1508	 (temp-dir  (expand-file-name (substring dir (1+ slash-pos))
1509                                      (flymake-get-temp-dir))))
1510
1511    (file-truename (expand-file-name (file-name-nondirectory file-name)
1512                                     temp-dir))))
1513
1514(defun flymake-delete-temp-directory (dir-name)
1515  "Attempt to delete temp dir created by `flymake-create-temp-with-folder-structure', do not fail on error."
1516  (let* ((temp-dir    (flymake-get-temp-dir))
1517	 (suffix      (substring dir-name (1+ (length temp-dir)))))
1518
1519    (while (> (length suffix) 0)
1520      (setq suffix (directory-file-name suffix))
1521      ;;+(flymake-log 0 "suffix=%s" suffix)
1522      (flymake-safe-delete-directory
1523       (file-truename (expand-file-name suffix temp-dir)))
1524      (setq suffix (file-name-directory suffix)))))
1525
1526(defvar flymake-temp-source-file-name nil)
1527(make-variable-buffer-local 'flymake-temp-source-file-name)
1528
1529(defvar flymake-master-file-name nil)
1530(make-variable-buffer-local 'flymake-master-file-name)
1531
1532(defvar flymake-temp-master-file-name nil)
1533(make-variable-buffer-local 'flymake-temp-master-file-name)
1534
1535(defvar flymake-base-dir nil)
1536(make-variable-buffer-local 'flymake-base-dir)
1537
1538(defun flymake-init-create-temp-buffer-copy (create-temp-f)
1539  "Make a temporary copy of the current buffer, save its name in buffer data and return the name."
1540  (let*  ((source-file-name       buffer-file-name)
1541	  (temp-source-file-name  (funcall create-temp-f source-file-name "flymake")))
1542
1543    (flymake-save-buffer-in-file temp-source-file-name)
1544    (setq flymake-temp-source-file-name temp-source-file-name)
1545    temp-source-file-name))
1546
1547(defun flymake-simple-cleanup ()
1548  "Do cleanup after `flymake-init-create-temp-buffer-copy'.
1549Delete temp file."
1550  (flymake-safe-delete-file flymake-temp-source-file-name)
1551  (setq flymake-last-change-time nil))
1552
1553(defun flymake-get-real-file-name (file-name-from-err-msg)
1554  "Translate file name from error message to \"real\" file name.
1555Return full-name.  Names are real, not patched."
1556  (let* ((real-name		nil)
1557	 (source-file-name	buffer-file-name)
1558	 (master-file-name	flymake-master-file-name)
1559	 (temp-source-file-name	flymake-temp-source-file-name)
1560	 (temp-master-file-name	flymake-temp-master-file-name)
1561	 (base-dirs
1562          (list flymake-base-dir
1563                (file-name-directory source-file-name)
1564                (if master-file-name (file-name-directory master-file-name))))
1565	 (files (list (list source-file-name       source-file-name)
1566                      (list temp-source-file-name  source-file-name)
1567                      (list master-file-name       master-file-name)
1568                      (list temp-master-file-name  master-file-name))))
1569
1570    (when (equal 0 (length file-name-from-err-msg))
1571      (setq file-name-from-err-msg source-file-name))
1572
1573    (setq real-name (flymake-get-full-patched-file-name file-name-from-err-msg base-dirs files))
1574    ;; if real-name is nil, than file name from err msg is none of the files we've patched
1575    (if (not real-name)
1576	(setq real-name (flymake-get-full-nonpatched-file-name file-name-from-err-msg base-dirs)))
1577    (if (not real-name)
1578	(setq real-name file-name-from-err-msg))
1579    (setq real-name (flymake-fix-file-name real-name))
1580    (flymake-log 3 "get-real-file-name: file-name=%s real-name=%s" file-name-from-err-msg real-name)
1581    real-name))
1582
1583(defun flymake-get-full-patched-file-name (file-name-from-err-msg base-dirs files)
1584  (let* ((base-dirs-count  (length base-dirs))
1585	 (file-count       (length files))
1586	 (real-name        nil))
1587
1588    (while (and (not real-name) (> base-dirs-count 0))
1589      (setq file-count (length files))
1590      (while (and (not real-name) (> file-count 0))
1591	(let* ((this-dir        (nth (1- base-dirs-count) base-dirs))
1592	       (this-file       (nth 0 (nth (1- file-count) files)))
1593	       (this-real-name  (nth 1 (nth (1- file-count) files))))
1594	  ;;+(flymake-log 0 "this-dir=%s this-file=%s this-real=%s msg-file=%s" this-dir this-file this-real-name file-name-from-err-msg)
1595	  (when (and this-dir this-file (flymake-same-files
1596					 (expand-file-name file-name-from-err-msg this-dir)
1597					 this-file))
1598	    (setq real-name this-real-name)))
1599	(setq file-count (1- file-count)))
1600      (setq base-dirs-count (1- base-dirs-count)))
1601    real-name))
1602
1603(defun flymake-get-full-nonpatched-file-name (file-name-from-err-msg base-dirs)
1604  (let* ((real-name  nil))
1605    (if (file-name-absolute-p file-name-from-err-msg)
1606	(setq real-name file-name-from-err-msg)
1607      (let* ((base-dirs-count  (length base-dirs)))
1608	(while (and (not real-name) (> base-dirs-count 0))
1609	  (let* ((full-name (expand-file-name file-name-from-err-msg
1610					      (nth (1- base-dirs-count) base-dirs))))
1611	    (if (file-exists-p full-name)
1612		(setq real-name full-name))
1613	    (setq base-dirs-count (1- base-dirs-count))))))
1614    real-name))
1615
1616(defun flymake-init-find-buildfile-dir (source-file-name buildfile-name)
1617  "Find buildfile, store its dir in buffer data and return its dir, if found."
1618  (let* ((buildfile-dir
1619          (flymake-find-buildfile buildfile-name
1620                                  (file-name-directory source-file-name))))
1621    (if buildfile-dir
1622        (setq flymake-base-dir buildfile-dir)
1623      (flymake-log 1 "no buildfile (%s) for %s" buildfile-name source-file-name)
1624      (flymake-report-fatal-status
1625       "NOMK" (format "No buildfile (%s) found for %s"
1626                      buildfile-name source-file-name)))))
1627
1628(defun flymake-init-create-temp-source-and-master-buffer-copy (get-incl-dirs-f create-temp-f master-file-masks include-regexp)
1629  "Find master file (or buffer), create its copy along with a copy of the source file."
1630  (let* ((source-file-name       buffer-file-name)
1631	 (temp-source-file-name  (flymake-init-create-temp-buffer-copy create-temp-f))
1632	 (master-and-temp-master (flymake-create-master-file
1633				  source-file-name temp-source-file-name
1634				  get-incl-dirs-f create-temp-f
1635				  master-file-masks include-regexp)))
1636
1637    (if (not master-and-temp-master)
1638	(progn
1639	  (flymake-log 1 "cannot find master file for %s" source-file-name)
1640          (flymake-report-status "!" "")	; NOMASTER
1641          nil)
1642      (setq flymake-master-file-name (nth 0 master-and-temp-master))
1643      (setq flymake-temp-master-file-name (nth 1 master-and-temp-master)))))
1644
1645(defun flymake-master-cleanup ()
1646  (flymake-simple-cleanup)
1647  (flymake-safe-delete-file flymake-temp-master-file-name))
1648
1649;;;; make-specific init-cleanup routines
1650(defun flymake-get-syntax-check-program-args (source-file-name base-dir use-relative-base-dir use-relative-source get-cmd-line-f)
1651  "Create a command line for syntax check using GET-CMD-LINE-F."
1652  (funcall get-cmd-line-f
1653           (if use-relative-source
1654               (file-relative-name source-file-name base-dir)
1655             source-file-name)
1656           (if use-relative-base-dir
1657               (file-relative-name base-dir
1658                                   (file-name-directory source-file-name))
1659             base-dir)))
1660
1661(defun flymake-get-make-cmdline (source base-dir)
1662  (list "make"
1663	(list "-s"
1664	      "-C"
1665	      base-dir
1666	      (concat "CHK_SOURCES=" source)
1667	      "SYNTAX_CHECK_MODE=1"
1668	      "check-syntax")))
1669
1670(defun flymake-get-ant-cmdline (source base-dir)
1671  (list "ant"
1672	(list "-buildfile"
1673	      (concat base-dir "/" "build.xml")
1674	      (concat "-DCHK_SOURCES=" source)
1675	      "check-syntax")))
1676
1677(defun flymake-simple-make-init-impl (create-temp-f use-relative-base-dir use-relative-source build-file-name get-cmdline-f)
1678  "Create syntax check command line for a directly checked source file.
1679Use CREATE-TEMP-F for creating temp copy."
1680  (let* ((args nil)
1681	 (source-file-name   buffer-file-name)
1682	 (buildfile-dir      (flymake-init-find-buildfile-dir source-file-name build-file-name)))
1683    (if buildfile-dir
1684	(let* ((temp-source-file-name  (flymake-init-create-temp-buffer-copy create-temp-f)))
1685	  (setq args (flymake-get-syntax-check-program-args temp-source-file-name buildfile-dir
1686							    use-relative-base-dir use-relative-source
1687							    get-cmdline-f))))
1688    args))
1689
1690(defun flymake-simple-make-init ()
1691  (flymake-simple-make-init-impl 'flymake-create-temp-inplace t t "Makefile" 'flymake-get-make-cmdline))
1692
1693(defun flymake-master-make-init (get-incl-dirs-f master-file-masks include-regexp)
1694  "Create make command line for a source file checked via master file compilation."
1695  (let* ((make-args nil)
1696	 (temp-master-file-name (flymake-init-create-temp-source-and-master-buffer-copy
1697                                 get-incl-dirs-f 'flymake-create-temp-inplace
1698				 master-file-masks include-regexp)))
1699    (when temp-master-file-name
1700      (let* ((buildfile-dir (flymake-init-find-buildfile-dir temp-master-file-name "Makefile")))
1701	(if  buildfile-dir
1702	    (setq make-args (flymake-get-syntax-check-program-args
1703			     temp-master-file-name buildfile-dir nil nil 'flymake-get-make-cmdline)))))
1704    make-args))
1705
1706(defun flymake-find-make-buildfile (source-dir)
1707  (flymake-find-buildfile "Makefile" source-dir))
1708
1709;;;; .h/make specific
1710(defun flymake-master-make-header-init ()
1711  (flymake-master-make-init 'flymake-get-include-dirs
1712			    '("\\.cpp\\'" "\\.c\\'")
1713			    "[ \t]*#[ \t]*include[ \t]*\"\\([[:word:]0-9/\\_.]*%s\\)\""))
1714
1715;;;; .java/make specific
1716(defun flymake-simple-make-java-init ()
1717  (flymake-simple-make-init-impl 'flymake-create-temp-with-folder-structure nil nil "Makefile" 'flymake-get-make-cmdline))
1718
1719(defun flymake-simple-ant-java-init ()
1720  (flymake-simple-make-init-impl 'flymake-create-temp-with-folder-structure nil nil "build.xml" 'flymake-get-ant-cmdline))
1721
1722(defun flymake-simple-java-cleanup ()
1723  "Cleanup after `flymake-simple-make-java-init' -- delete temp file and dirs."
1724  (flymake-safe-delete-file flymake-temp-source-file-name)
1725  (when flymake-temp-source-file-name
1726    (flymake-delete-temp-directory
1727     (file-name-directory flymake-temp-source-file-name))))
1728
1729;;;; perl-specific init-cleanup routines
1730(defun flymake-perl-init ()
1731  (let* ((temp-file   (flymake-init-create-temp-buffer-copy
1732                       'flymake-create-temp-inplace))
1733	 (local-file  (file-relative-name
1734                       temp-file
1735                       (file-name-directory buffer-file-name))))
1736    (list "perl" (list "-wc " local-file))))
1737
1738;;;; tex-specific init-cleanup routines
1739(defun flymake-get-tex-args (file-name)
1740  ;;(list "latex" (list "-c-style-errors" file-name))
1741  (list "texify" (list "--pdf" "--tex-option=-c-style-errors" file-name)))
1742
1743(defun flymake-simple-tex-init ()
1744  (flymake-get-tex-args (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)))
1745
1746(defun flymake-master-tex-init ()
1747  (let* ((temp-master-file-name (flymake-init-create-temp-source-and-master-buffer-copy
1748                                 'flymake-get-include-dirs-dot 'flymake-create-temp-inplace
1749				 '("\\.tex\\'")
1750				 "[ \t]*\\input[ \t]*{\\(.*%s\\)}")))
1751    (when temp-master-file-name
1752      (flymake-get-tex-args temp-master-file-name))))
1753
1754(defun flymake-get-include-dirs-dot (base-dir)
1755  '("."))
1756
1757;;;; xml-specific init-cleanup routines
1758(defun flymake-xml-init ()
1759  (list "xml" (list "val" (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace))))
1760
1761(provide 'flymake)
1762
1763;; arch-tag: 8f0d6090-061d-4cac-8862-7c151c4a02dd
1764;;; flymake.el ends here
1765