1;;; make-mode.el --- makefile editing commands for Emacs
2
3;; Copyright (C) 1992, 1994, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4;; Free Software Foundation, Inc.
5
6;; Author: Thomas Neumann <tom@smart.bo.open.de>
7;;	Eric S. Raymond <esr@snark.thyrsus.com>
8;; Maintainer: FSF
9;; Adapted-By: ESR
10;; Keywords: unix, tools
11
12;; This file is part of GNU Emacs.
13
14;; GNU Emacs is free software; you can redistribute it and/or modify
15;; it under the terms of the GNU General Public License as published by
16;; the Free Software Foundation; either version 2, or (at your option)
17;; any later version.
18
19;; GNU Emacs is distributed in the hope that it will be useful,
20;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22;; GNU General Public License for more details.
23
24;; You should have received a copy of the GNU General Public License
25;; along with GNU Emacs; see the file COPYING.  If not, write to the
26;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27;; Boston, MA 02110-1301, USA.
28
29;;; Commentary:
30
31;; A major mode for editing makefiles.  The mode knows about Makefile
32;; syntax and defines M-n and M-p to move to next and previous productions.
33;;
34;; The keys $, =, : and . are electric; they try to help you fill in a
35;; macro reference, macro definition, ordinary target name, or special
36;; target name, respectively.  Such names are completed using a list of
37;; targets and macro names parsed out of the makefile.  This list is
38;; automatically updated, if necessary, whenever you invoke one of
39;; these commands.  You can force it to be updated with C-c C-p.
40;;
41;; The command C-c C-f adds certain filenames in the current directory
42;; as targets.  You can filter out filenames by setting the variable
43;; makefile-ignored-files-in-pickup-regex.
44;;
45;; The command C-c C-u grinds for a bit, then pops up a report buffer
46;; showing which target names are up-to-date with respect to their
47;; prerequisites, which targets are out-of-date, and which have no
48;; prerequisites.
49;;
50;; The command C-c C-b pops up a browser window listing all target and
51;; macro names.  You can mark or unmark items with C-c SPC, and insert
52;; all marked items back in the Makefile with C-c TAB.
53;;
54;; The command C-c TAB in the makefile buffer inserts a GNU make builtin.
55;; You will be prompted for the builtin's args.
56;;
57;; There are numerous other customization variables.
58
59;;
60;; To Do:
61;;
62;; * Add missing doc strings, improve terse doc strings.
63;; * Eliminate electric stuff entirely.
64;; * It might be nice to highlight targets differently depending on
65;;   whether they are up-to-date or not.  Not sure how this would
66;;   interact with font-lock.
67;; * Would be nice to edit the commands in ksh-mode and have
68;;   indentation and slashification done automatically.  Hard.
69;; * Consider removing browser mode.  It seems useless.
70;; * ":" should notice when a new target is made and add it to the
71;;   list (or at least set makefile-need-target-pickup).
72;; * Make browser into a major mode.
73;; * Clean up macro insertion stuff.  It is a mess.
74;; * Browser entry and exit is weird.  Normalize.
75;; * Browser needs to be rewritten.  Right now it is kind of a crock.
76;;   Should at least:
77;;    * Act more like dired/buffer menu/whatever.
78;;    * Highlight as mouse traverses.
79;;    * B2 inserts.
80;; * Update documentation above.
81;; * Update texinfo manual.
82;; * Update files.el.
83
84
85
86;;; Code:
87
88;; Sadly we need this for a macro.
89(eval-when-compile
90  (require 'imenu)
91  (require 'dabbrev)
92  (require 'add-log))
93
94;;; ------------------------------------------------------------
95;;; Configurable stuff
96;;; ------------------------------------------------------------
97
98(defgroup makefile nil
99  "Makefile editing commands for Emacs."
100  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
101  :group 'tools
102  :prefix "makefile-")
103
104(defface makefile-space
105  '((((class color)) (:background  "hotpink"))
106    (t (:reverse-video t)))
107  "Face to use for highlighting leading spaces in Font-Lock mode."
108  :group 'makefile)
109(put 'makefile-space-face 'face-alias 'makefile-space)
110
111(defface makefile-targets
112  ;; This needs to go along both with foreground and background colors (i.e. shell)
113  '((t (:inherit font-lock-function-name-face)))
114  "Face to use for additionally highlighting rule targets in Font-Lock mode."
115  :group 'makefile
116  :version "22.1")
117
118(defface makefile-shell
119  ()
120  ;;'((((class color) (min-colors 88) (background light)) (:background  "seashell1"))
121  ;;  (((class color) (min-colors 88) (background dark)) (:background  "seashell4")))
122  "Face to use for additionally highlighting Shell commands in Font-Lock mode."
123  :group 'makefile
124  :version "22.1")
125
126(defface makefile-makepp-perl
127  '((((class color) (background light)) (:background  "LightBlue1")) ; Camel Book
128    (((class color) (background dark)) (:background  "DarkBlue"))
129    (t (:reverse-video t)))
130  "Face to use for additionally highlighting Perl code in Font-Lock mode."
131  :group 'makefile
132  :version "22.1")
133
134(defcustom makefile-browser-buffer-name "*Macros and Targets*"
135  "*Name of the macro- and target browser buffer."
136  :type 'string
137  :group 'makefile)
138
139(defcustom makefile-target-colon ":"
140  "*String to append to all target names inserted by `makefile-insert-target'.
141\":\" or \"::\" are common values."
142  :type 'string
143  :group 'makefile)
144
145(defcustom makefile-macro-assign " = "
146  "*String to append to all macro names inserted by `makefile-insert-macro'.
147The normal value should be \" = \", since this is what
148standard make expects.  However, newer makes such as dmake
149allow a larger variety of different macro assignments, so you
150might prefer to use \" += \" or \" := \" ."
151  :type 'string
152  :group 'makefile)
153
154(defcustom makefile-electric-keys nil
155  "*If non-nil, Makefile mode should install electric keybindings.
156Default is nil."
157  :type 'boolean
158  :group 'makefile)
159
160(defcustom makefile-use-curly-braces-for-macros-p nil
161  "*Controls the style of generated macro references.
162Non-nil means macro references should use curly braces, like `${this}'.
163nil means use parentheses, like `$(this)'."
164  :type 'boolean
165  :group 'makefile)
166
167(defcustom makefile-tab-after-target-colon t
168  "*If non-nil, insert a TAB after a target colon.
169Otherwise, a space is inserted.
170The default is t."
171  :type 'boolean
172  :group 'makefile)
173
174(defcustom makefile-browser-leftmost-column 10
175  "*Number of blanks to the left of the browser selection mark."
176  :type 'integer
177  :group 'makefile)
178
179(defcustom makefile-browser-cursor-column 10
180  "*Column the cursor goes to when it moves up or down in the Makefile browser."
181  :type 'integer
182  :group 'makefile)
183
184(defcustom makefile-backslash-column 48
185  "*Column in which `makefile-backslash-region' inserts backslashes."
186  :type 'integer
187  :group 'makefile)
188
189(defcustom makefile-backslash-align t
190  "*If non-nil, `makefile-backslash-region' will align backslashes."
191  :type 'boolean
192  :group 'makefile)
193
194(defcustom makefile-browser-selected-mark "+  "
195  "*String used to mark selected entries in the Makefile browser."
196  :type 'string
197  :group 'makefile)
198
199(defcustom makefile-browser-unselected-mark "   "
200  "*String used to mark unselected entries in the Makefile browser."
201  :type 'string
202  :group 'makefile)
203
204(defcustom makefile-browser-auto-advance-after-selection-p t
205  "*If non-nil, cursor will move after item is selected in Makefile browser."
206  :type 'boolean
207  :group 'makefile)
208
209(defcustom makefile-pickup-everything-picks-up-filenames-p nil
210  "*If non-nil, `makefile-pickup-everything' picks up filenames as targets.
211This means it calls `makefile-pickup-filenames-as-targets'.
212Otherwise filenames are omitted."
213  :type 'boolean
214  :group 'makefile)
215
216(defcustom makefile-cleanup-continuations nil
217  "*If non-nil, automatically clean up continuation lines when saving.
218A line is cleaned up by removing all whitespace following a trailing
219backslash.  This is done silently.
220IMPORTANT: Please note that enabling this option causes Makefile mode
221to MODIFY A FILE WITHOUT YOUR CONFIRMATION when \"it seems necessary\"."
222  :type 'boolean
223  :group 'makefile)
224
225(defcustom makefile-mode-hook nil
226  "*Normal hook run by `makefile-mode'."
227  :type 'hook
228  :group 'makefile)
229
230(defvar makefile-browser-hook '())
231
232;;
233;; Special targets for DMake, Sun's make ...
234;;
235(defcustom makefile-special-targets-list
236  '(("DEFAULT")      ("DONE")        ("ERROR")        ("EXPORT")
237    ("FAILED")       ("GROUPEPILOG") ("GROUPPROLOG")  ("IGNORE")
238    ("IMPORT")       ("INCLUDE")     ("INCLUDEDIRS")  ("INIT")
239    ("KEEP_STATE")   ("MAKEFILES")   ("MAKE_VERSION") ("NO_PARALLEL")
240    ("PARALLEL")     ("PHONY")       ("PRECIOUS")     ("REMOVE")
241    ("SCCS_GET")     ("SILENT")      ("SOURCE")       ("SUFFIXES")
242    ("WAIT")         ("c.o")         ("C.o")          ("m.o")
243    ("el.elc")       ("y.c")         ("s.o"))
244  "*List of special targets.
245You will be offered to complete on one of those in the minibuffer whenever
246you enter a \".\" at the beginning of a line in `makefile-mode'."
247  :type '(repeat (list string))
248  :group 'makefile)
249(put 'makefile-special-targets-list 'risky-local-variable t)
250
251(defcustom makefile-runtime-macros-list
252  '(("@") ("&") (">") ("<") ("*") ("^") ("+") ("?") ("%") ("$"))
253  "*List of macros that are resolved by make at runtime.
254If you insert a macro reference using `makefile-insert-macro-ref', the name
255of the macro is checked against this list.  If it can be found its name will
256not be enclosed in { } or ( )."
257  :type '(repeat (list string))
258  :group 'makefile)
259
260;; Note that the first big subexpression is used by font lock.  Note
261;; that if you change this regexp you might have to fix the imenu
262;; index in makefile-imenu-generic-expression.
263(defvar makefile-dependency-regex
264  ;; Allow for two nested levels $(v1:$(v2:$(v3:a=b)=c)=d)
265  "^\\(\\(?:\\$\\(?:[({]\\(?:\\$\\(?:[({]\\(?:\\$\\(?:[^({]\\|.[^\n$#})]+?[})]\\)\\|[^\n$#)}]\\)+?[})]\\|[^({]\\)\\|[^\n$#)}]\\)+?[})]\\|[^({]\\)\\|[^\n$#:=]\\)+?\\)\\(:\\)\\(?:[ \t]*$\\|[^=\n]\\(?:[^#\n]*?;[ \t]*\\(.+\\)\\)?\\)"
266  "Regex used to find dependency lines in a makefile.")
267
268(defconst makefile-bsdmake-dependency-regex
269  (progn (string-match (regexp-quote "\\(:\\)") makefile-dependency-regex)
270	 (replace-match "\\([:!]\\)" t t makefile-dependency-regex))
271  "Regex used to find dependency lines in a BSD makefile.")
272
273(defvar makefile-dependency-skip "^:"
274  "Characters to skip to find a line that might be a dependency.")
275
276(defvar makefile-rule-action-regex
277  "^\t[ \t]*\\([-@]*\\)[ \t]*\\(\\(?:.*\\\\\n\\)*.*\\)"
278  "Regex used to highlight rule action lines in font lock mode.")
279
280(defconst makefile-makepp-rule-action-regex
281  ;; Don't care about initial tab, but I don't know how to font-lock correctly without.
282  "^\t[ \t]*\\(\\(?:\\(?:noecho\\|ignore[-_]error\\|[-@]+\\)[ \t]*\\)*\\)\\(\\(&\\S +\\)?\\(?:.*\\\\\n\\)*.*\\)"
283  "Regex used to highlight makepp rule action lines in font lock mode.")
284
285(defconst makefile-bsdmake-rule-action-regex
286  (progn (string-match "-@" makefile-rule-action-regex)
287	 (replace-match "-+@" t t makefile-rule-action-regex))
288  "Regex used to highlight BSD rule action lines in font lock mode.")
289
290;; Note that the first and second subexpression is used by font lock.  Note
291;; that if you change this regexp you might have to fix the imenu index in
292;; makefile-imenu-generic-expression.
293(defconst makefile-macroassign-regex
294  ;; We used to match not just the varname but also the whole value
295  ;; (spanning potentially several lines).
296  ;; "^ *\\([^ \n\t][^:#= \t\n]*\\)[ \t]*\\(?:!=[ \t]*\\(\\(?:.+\\\\\n\\)*.+\\)\\|[*:+]?[:?]?=[ \t]*\\(\\(?:.*\\\\\n\\)*.*\\)\\)"
297  ;; What about the define statement?  What about differentiating this for makepp?
298  "\\(?:^\\|^export\\|^override\\|:\\|: *override\\) *\\([^ \n\t][^:#= \t\n]*\\)[ \t]*\\(?:!=\\|[*:+]?[:?]?=\\)"
299  "Regex used to find macro assignment lines in a makefile.")
300
301(defconst makefile-var-use-regex
302  "[^$]\\$[({]\\([-a-zA-Z0-9_.]+\\|[@%<?^+*][FD]?\\)"
303  "Regex used to find $(macro) uses in a makefile.")
304
305(defconst makefile-ignored-files-in-pickup-regex
306  "\\(^\\..*\\)\\|\\(.*~$\\)\\|\\(.*,v$\\)\\|\\(\\.[chy]\\)"
307  "Regex for filenames that will NOT be included in the target list.")
308
309(defvar makefile-space 'makefile-space
310  "Face to use for highlighting leading spaces in Font-Lock mode.")
311
312;; These lists were inspired by the old solution.  But they are silly, because
313;; you can't differentiate what follows.  They need to be split up.
314(defconst makefile-statements '("include")
315  "List of keywords understood by standard make.")
316
317(defconst makefile-automake-statements
318  `("if" "else" "endif" ,@makefile-statements)
319  "List of keywords understood by automake.")
320
321(defconst makefile-gmake-statements
322  `("-sinclude" "sinclude" "vpath"	; makefile-makepp-statements takes rest
323    "ifdef" "ifndef" "ifeq" "ifneq" "-include" "define" "endef" "export"
324    "override define" "override" "unexport"
325    ,@(cdr makefile-automake-statements))
326  "List of keywords understood by gmake.")
327
328;; These are even more silly, because you can have more spaces in between.
329(defconst makefile-makepp-statements
330  `("and ifdef" "and ifndef" "and ifeq" "and ifneq" "and ifperl"
331    "and ifmakeperl" "and ifsys" "and ifnsys" "build_cache" "build_check"
332    "else ifdef" "else ifndef" "else ifeq" "else ifneq" "else ifperl"
333    "else ifmakeperl" "else ifsys" "else ifnsys" "enddef" "global"
334    "load_makefile" "ifperl" "ifmakeperl" "ifsys" "ifnsys" "_include"
335    "makeperl" "makesub" "no_implicit_load" "perl" "perl-begin" "perl_begin"
336    "perl-end" "perl_end" "prebuild" "or ifdef" "or ifndef" "or ifeq"
337    "or ifneq" "or ifperl" "or ifmakeperl" "or ifsys" "or ifnsys"
338    "override export" "override global" "register_command_parser"
339    "register_scanner" "repository" "runtime" "signature" "sub"
340    ,@(nthcdr 3 makefile-gmake-statements))
341  "List of keywords understood by gmake.")
342
343(defconst makefile-bsdmake-statements
344  `(".elif" ".elifdef" ".elifmake" ".elifndef" ".elifnmake" ".else" ".endfor"
345    ".endif" ".for" ".if" ".ifdef" ".ifmake" ".ifndef" ".ifnmake" ".undef")
346  "List of keywords understood by BSD make.")
347
348(defun makefile-make-font-lock-keywords (var keywords space
349					     &optional negation
350					     &rest font-lock-keywords)
351  `(;; Do macro assignments.  These get the "variable-name" face.
352    (,makefile-macroassign-regex
353     (1 font-lock-variable-name-face)
354     ;; This is for after !=
355     (2 'makefile-shell prepend t)
356     ;; This is for after normal assignment
357     (3 'font-lock-string-face prepend t))
358
359    ;; Rule actions.
360    (makefile-match-action
361     (1 font-lock-type-face)
362     (2 'makefile-shell prepend)
363     ;; Only makepp has builtin commands.
364     (3 font-lock-builtin-face prepend t))
365
366    ;; Variable references even in targets/strings/comments.
367    (,var 1 font-lock-variable-name-face prepend)
368
369    ;; Automatic variable references and single character variable references,
370    ;; but not shell variables references.
371    ("[^$]\\$\\([@%<?^+*_]\\|[a-zA-Z0-9]\\>\\)"
372     1 font-lock-constant-face prepend)
373    ("[^$]\\(\\$[@%*]\\)"
374     1 'makefile-targets append)
375
376    ;; Fontify conditionals and includes.
377    (,(concat "^\\(?: [ \t]*\\)?"
378	      (regexp-opt keywords t)
379	      "\\>[ \t]*\\([^: \t\n#]*\\)")
380     (1 font-lock-keyword-face) (2 font-lock-variable-name-face))
381
382    ,@(if negation
383	  `((,negation (1 font-lock-negation-char-face prepend)
384		       (2 font-lock-negation-char-face prepend t))))
385
386    ,@(if space
387	  '(;; Highlight lines that contain just whitespace.
388	    ;; They can cause trouble, especially if they start with a tab.
389	    ("^[ \t]+$" . makefile-space)
390
391	    ;; Highlight shell comments that Make treats as commands,
392	    ;; since these can fool people.
393	    ("^\t+#" 0 makefile-space t)
394
395	    ;; Highlight spaces that precede tabs.
396	    ;; They can make a tab fail to be effective.
397	    ("^\\( +\\)\t" 1 makefile-space)))
398
399    ,@font-lock-keywords
400
401    ;; Do dependencies.
402    (makefile-match-dependency
403     (1 'makefile-targets prepend)
404     (3 'makefile-shell prepend t))))
405
406(defconst makefile-font-lock-keywords
407  (makefile-make-font-lock-keywords
408   makefile-var-use-regex
409   makefile-statements
410   t))
411
412(defconst makefile-automake-font-lock-keywords
413  (makefile-make-font-lock-keywords
414   makefile-var-use-regex
415   makefile-automake-statements
416   t))
417
418(defconst makefile-gmake-font-lock-keywords
419  (makefile-make-font-lock-keywords
420   makefile-var-use-regex
421   makefile-gmake-statements
422   t
423   "^\\(?: [ \t]*\\)?if\\(n\\)\\(?:def\\|eq\\)\\>"
424
425   '("[^$]\\(\\$[({][@%*][DF][})]\\)"
426     1 'makefile-targets append)
427
428   ;; $(function ...) ${function ...}
429   '("[^$]\\$[({]\\([-a-zA-Z0-9_.]+\\s \\)"
430     1 font-lock-function-name-face prepend)
431
432   ;; $(shell ...) ${shell ...}
433   '("[^$]\\$\\([({]\\)shell[ \t]+"
434     makefile-match-function-end nil nil
435     (1 'makefile-shell prepend t))))
436
437(defconst makefile-makepp-font-lock-keywords
438  (makefile-make-font-lock-keywords
439   makefile-var-use-regex
440   makefile-makepp-statements
441   nil
442   "^\\(?: [ \t]*\\)?\\(?:and[ \t]+\\|else[ \t]+\\|or[ \t]+\\)?if\\(n\\)\\(?:def\\|eq\\|sys\\)\\>"
443
444   '("[^$]\\(\\$[({]\\(?:output\\|stem\\|target\\)s?\\_>.*?[})]\\)"
445     1 'makefile-targets append)
446
447   ;; Colon modifier keywords.
448   '("\\(:\\s *\\)\\(build_c\\(?:ache\\|heck\\)\\|env\\(?:ironment\\)?\\|foreach\\|signature\\|scanner\\|quickscan\\|smartscan\\)\\>\\([^:\n]*\\)"
449     (1 font-lock-type-face t)
450     (2 font-lock-keyword-face t)
451     (3 font-lock-variable-name-face t))
452
453   ;; $(function ...) $((function ...)) ${function ...} ${{function ...}}
454   '("[^$]\\$\\(?:((?\\|{{?\\)\\([-a-zA-Z0-9_.]+\\s \\)"
455     1 font-lock-function-name-face prepend)
456
457   ;; $(shell ...) $((shell ...)) ${shell ...} ${{shell ...}}
458   '("[^$]\\$\\(((?\\|{{?\\)shell\\(?:[-_]\\(?:global[-_]\\)?once\\)?[ \t]+"
459     makefile-match-function-end nil nil
460     (1 'makefile-shell prepend t))
461
462   ;; $(perl ...) $((perl ...)) ${perl ...} ${{perl ...}}
463   '("[^$]\\$\\(((?\\|{{?\\)makeperl[ \t]+"
464     makefile-match-function-end nil nil
465     (1 'makefile-makepp-perl prepend t))
466   '("[^$]\\$\\(((?\\|{{?\\)perl[ \t]+"
467     makefile-match-function-end nil nil
468     (1 'makefile-makepp-perl t t))
469
470   ;; Can we unify these with (if (match-end 1) 'prepend t)?
471   '("ifmakeperl\\s +\\(.*\\)" 1 'makefile-makepp-perl prepend)
472   '("ifperl\\s +\\(.*\\)" 1 'makefile-makepp-perl t)
473
474   ;; Perl block single- or multiline, as statement or rule action.
475   ;; Don't know why the initial newline in 2nd variant of group 2 doesn't get skipped.
476   '("\\<make\\(?:perl\\|sub\\s +\\S +\\)\\s *\n?\\s *{\\(?:{\\s *\n?\\(\\(?:.*\n\\)+?\\)\\s *}\\|\\s *\\(\\(?:.*?\\|\n?\\(?:.*\n\\)+?\\)\\)\\)}"
477     (1 'makefile-makepp-perl prepend t)
478     (2 'makefile-makepp-perl prepend t))
479   '("\\<\\(?:perl\\|sub\\s +\\S +\\)\\s *\n?\\s *{\\(?:{\\s *\n?\\(\\(?:.*\n\\)+?\\)\\s *}\\|\\s *\\(\\(?:.*?\\|\n?\\(?:.*\n\\)+?\\)\\)\\)}"
480     (1 'makefile-makepp-perl t t)
481     (2 'makefile-makepp-perl t t))
482
483   ;; Statement style perl block.
484   '("perl[-_]begin\\s *\\(?:\\s #.*\\)?\n\\(\\(?:.*\n\\)+?\\)\\s *perl[-_]end\\>"
485     1 'makefile-makepp-perl t)))
486
487(defconst makefile-bsdmake-font-lock-keywords
488  (makefile-make-font-lock-keywords
489   ;; A lot more could be done for variables here:
490   makefile-var-use-regex
491   makefile-bsdmake-statements
492   t
493   "^\\(?: [ \t]*\\)?\\.\\(?:el\\)?if\\(n?\\)\\(?:def\\|make\\)?\\>[ \t]*\\(!?\\)"
494   '("^[ \t]*\\.for[ \t].+[ \t]\\(in\\)\\>" 1 font-lock-keyword-face)))
495
496(defconst makefile-imake-font-lock-keywords
497  (append
498   (makefile-make-font-lock-keywords
499    makefile-var-use-regex
500    makefile-statements
501    t
502    nil
503    '("^XCOMM.*$" . font-lock-comment-face)
504    '("XVAR\\(?:use\\|def\\)[0-9]" 0 font-lock-keyword-face prepend)
505    '("@@" . font-lock-preprocessor-face)
506    )
507   cpp-font-lock-keywords))
508
509
510(defconst makefile-font-lock-syntactic-keywords
511  ;; From sh-script.el.
512  ;; A `#' begins a comment in sh when it is unquoted and at the beginning
513  ;; of a word.  In the shell, words are separated by metacharacters.
514  ;; The list of special chars is taken from the single-unix spec of the
515  ;; shell command language (under `quoting') but with `$' removed.
516  '(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 "_")
517    ;; Change the syntax of a quoted newline so that it does not end a comment.
518    ("\\\\\n" 0 ".")))
519
520(defvar makefile-imenu-generic-expression
521  `(("Dependencies" makefile-previous-dependency 1)
522    ("Macro Assignment" ,makefile-macroassign-regex 1))
523  "Imenu generic expression for Makefile mode.  See `imenu-generic-expression'.")
524
525;;; ------------------------------------------------------------
526;;; The following configurable variables are used in the
527;;; up-to-date overview .
528;;; The standard configuration assumes that your `make' program
529;;; can be run in question/query mode using the `-q' option, this
530;;; means that the command
531;;;
532;;;    make -q foo
533;;;
534;;; should return an exit status of zero if the target `foo' is
535;;; up to date and a nonzero exit status otherwise.
536;;; Many makes can do this although the docs/manpages do not mention
537;;; it. Try it with your favourite one.  GNU make, System V make, and
538;;; Dennis Vadura's DMake have no problems.
539;;; Set the variable `makefile-brave-make' to the name of the
540;;; make utility that does this on your system.
541;;; To understand what this is all about see the function definition
542;;; of `makefile-query-by-make-minus-q' .
543;;; ------------------------------------------------------------
544
545(defcustom makefile-brave-make "make"
546  "*How to invoke make, for `makefile-query-targets'.
547This should identify a `make' command that can handle the `-q' option."
548  :type 'string
549  :group 'makefile)
550
551(defcustom makefile-query-one-target-method-function
552  'makefile-query-by-make-minus-q
553  "*Function to call to determine whether a make target is up to date.
554The function must satisfy this calling convention:
555
556* As its first argument, it must accept the name of the target to
557  be checked, as a string.
558
559* As its second argument, it may accept the name of a makefile
560  as a string.  Depending on what you're going to do you may
561  not need this.
562
563* It must return the integer value 0 (zero) if the given target
564  should be considered up-to-date in the context of the given
565  makefile, any nonzero integer value otherwise."
566  :type 'function
567  :group 'makefile)
568(defvaralias 'makefile-query-one-target-method
569  'makefile-query-one-target-method-function)
570
571(defcustom makefile-up-to-date-buffer-name "*Makefile Up-to-date overview*"
572  "*Name of the Up-to-date overview buffer."
573  :type 'string
574  :group 'makefile)
575
576;;; --- end of up-to-date-overview configuration ------------------
577
578(defvar makefile-mode-abbrev-table nil
579  "Abbrev table in use in Makefile buffers.")
580(if makefile-mode-abbrev-table
581    ()
582  (define-abbrev-table 'makefile-mode-abbrev-table ()))
583
584(defvar makefile-mode-map
585  (let ((map (make-sparse-keymap)))
586    ;; set up the keymap
587    (define-key map "\C-c:" 'makefile-insert-target-ref)
588    (if makefile-electric-keys
589	(progn
590	  (define-key map "$" 'makefile-insert-macro-ref)
591	  (define-key map ":" 'makefile-electric-colon)
592	  (define-key map "=" 'makefile-electric-equal)
593	  (define-key map "." 'makefile-electric-dot)))
594    (define-key map "\C-c\C-f" 'makefile-pickup-filenames-as-targets)
595    (define-key map "\C-c\C-b" 'makefile-switch-to-browser)
596    (define-key map "\C-c\C-c" 'comment-region)
597    (define-key map "\C-c\C-p" 'makefile-pickup-everything)
598    (define-key map "\C-c\C-u" 'makefile-create-up-to-date-overview)
599    (define-key map "\C-c\C-i" 'makefile-insert-gmake-function)
600    (define-key map "\C-c\C-\\" 'makefile-backslash-region)
601    (define-key map "\C-c\C-m\C-a" 'makefile-automake-mode)
602    (define-key map "\C-c\C-m\C-b" 'makefile-bsdmake-mode)
603    (define-key map "\C-c\C-m\C-g" 'makefile-gmake-mode)
604    (define-key map "\C-c\C-m\C-i" 'makefile-imake-mode)
605    (define-key map "\C-c\C-m\C-m" 'makefile-mode)
606    (define-key map "\C-c\C-m\C-p" 'makefile-makepp-mode)
607    (define-key map "\M-p"     'makefile-previous-dependency)
608    (define-key map "\M-n"     'makefile-next-dependency)
609    (define-key map "\e\t"     'makefile-complete)
610
611    ;; Make menus.
612    (define-key map [menu-bar makefile-mode]
613      (cons "Makefile" (make-sparse-keymap "Makefile")))
614
615    (define-key map [menu-bar makefile-mode browse]
616      '("Pop up Makefile Browser" . makefile-switch-to-browser))
617    (define-key map [menu-bar makefile-mode complete]
618      '("Complete Target or Macro" . makefile-complete))
619    (define-key map [menu-bar makefile-mode pickup]
620      '("Find Targets and Macros" . makefile-pickup-everything))
621
622    (define-key map [menu-bar makefile-mode prev]
623      '("Move to Previous Dependency" . makefile-previous-dependency))
624    (define-key map [menu-bar makefile-mode next]
625      '("Move to Next Dependency" . makefile-next-dependency))
626    map)
627  "The keymap that is used in Makefile mode.")
628
629
630(defvar makefile-browser-map
631  (let ((map (make-sparse-keymap)))
632    (define-key map "n"    'makefile-browser-next-line)
633    (define-key map "\C-n" 'makefile-browser-next-line)
634    (define-key map "p"    'makefile-browser-previous-line)
635    (define-key map "\C-p" 'makefile-browser-previous-line)
636    (define-key map " "    'makefile-browser-toggle)
637    (define-key map "i"    'makefile-browser-insert-selection)
638    (define-key map "I"    'makefile-browser-insert-selection-and-quit)
639    (define-key map "\C-c\C-m" 'makefile-browser-insert-continuation)
640    (define-key map "q"    'makefile-browser-quit)
641    ;; disable horizontal movement
642    (define-key map "\C-b" 'undefined)
643    (define-key map "\C-f" 'undefined)
644    map)
645  "The keymap that is used in the macro- and target browser.")
646
647
648(defvar makefile-mode-syntax-table
649  (let ((st (make-syntax-table)))
650    (modify-syntax-entry ?\( "()    " st)
651    (modify-syntax-entry ?\) ")(    " st)
652    (modify-syntax-entry ?\[ "(]    " st)
653    (modify-syntax-entry ?\] ")[    " st)
654    (modify-syntax-entry ?\{ "(}    " st)
655    (modify-syntax-entry ?\} "){    " st)
656    (modify-syntax-entry ?\' "\"    " st)
657    (modify-syntax-entry ?\` "\"    " st)
658    (modify-syntax-entry ?#  "<     " st)
659    (modify-syntax-entry ?\n ">     " st)
660    st))
661
662(defvar makefile-imake-mode-syntax-table (copy-syntax-table
663					  makefile-mode-syntax-table))
664(if makefile-imake-mode-syntax-table
665    ()
666  (modify-syntax-entry ?/  ". 14" makefile-imake-mode-syntax-table)
667  (modify-syntax-entry ?*  ". 23" makefile-imake-mode-syntax-table)
668  (modify-syntax-entry ?#  "'" makefile-imake-mode-syntax-table)
669  (modify-syntax-entry ?\n ". b" makefile-imake-mode-syntax-table))
670
671
672;;; ------------------------------------------------------------
673;;; Internal variables.
674;;; You don't need to configure below this line.
675;;; ------------------------------------------------------------
676
677(defvar makefile-target-table nil
678  "Table of all target names known for this buffer.")
679(put 'makefile-target-table 'risky-local-variable t)
680
681(defvar makefile-macro-table nil
682  "Table of all macro names known for this buffer.")
683(put 'makefile-macro-table 'risky-local-variable t)
684
685(defvar makefile-browser-client
686  "A buffer in Makefile mode that is currently using the browser.")
687
688(defvar makefile-browser-selection-vector nil)
689(defvar makefile-has-prereqs nil)
690(defvar makefile-need-target-pickup t)
691(defvar makefile-need-macro-pickup t)
692
693(defvar makefile-mode-hook '())
694
695;; Each element looks like '("GNU MAKE FUNCTION" "ARG" "ARG" ... )
696;; Each "ARG" is used as a prompt for a required argument.
697(defconst makefile-gnumake-functions-alist
698  '(
699    ;; Text functions
700    ("subst" "From" "To" "In")
701    ("patsubst" "Pattern" "Replacement" "In")
702    ("strip" "Text")
703    ("findstring" "Find what" "In")
704    ("filter" "Pattern" "Text")
705    ("filter-out" "Pattern" "Text")
706    ("sort" "List")
707    ;; Filename functions
708    ("dir" "Names")
709    ("notdir" "Names")
710    ("suffix" "Names")
711    ("basename" "Names")
712    ("addprefix" "Prefix" "Names")
713    ("addsuffix" "Suffix" "Names")
714    ("join" "List 1" "List 2")
715    ("word" "Index" "Text")
716    ("words" "Text")
717    ("firstword" "Text")
718    ("wildcard" "Pattern")
719    ;; Misc functions
720    ("foreach" "Variable" "List" "Text")
721    ("origin" "Variable")
722    ("shell" "Command")))
723
724
725;;; ------------------------------------------------------------
726;;; The mode function itself.
727;;; ------------------------------------------------------------
728
729;;;###autoload
730(defun makefile-mode ()
731  "Major mode for editing standard Makefiles.
732
733If you are editing a file for a different make, try one of the
734variants `makefile-automake-mode', `makefile-gmake-mode',
735`makefile-makepp-mode', `makefile-bsdmake-mode' or,
736`makefile-imake-mode'.  All but the last should be correctly
737chosen based on the file name, except if it is *.mk.  This
738function ends by invoking the function(s) `makefile-mode-hook'.
739
740It is strongly recommended to use `font-lock-mode', because that
741provides additional parsing information.  This is used for
742example to see that a rule action `echo foo: bar' is a not rule
743dependency, despite the colon.
744
745\\{makefile-mode-map}
746
747In the browser, use the following keys:
748
749\\{makefile-browser-map}
750
751Makefile mode can be configured by modifying the following variables:
752
753`makefile-browser-buffer-name':
754    Name of the macro- and target browser buffer.
755
756`makefile-target-colon':
757    The string that gets appended to all target names
758    inserted by `makefile-insert-target'.
759    \":\" or \"::\" are quite common values.
760
761`makefile-macro-assign':
762   The string that gets appended to all macro names
763   inserted by `makefile-insert-macro'.
764   The normal value should be \" = \", since this is what
765   standard make expects.  However, newer makes such as dmake
766   allow a larger variety of different macro assignments, so you
767   might prefer to use \" += \" or \" := \" .
768
769`makefile-tab-after-target-colon':
770   If you want a TAB (instead of a space) to be appended after the
771   target colon, then set this to a non-nil value.
772
773`makefile-browser-leftmost-column':
774   Number of blanks to the left of the browser selection mark.
775
776`makefile-browser-cursor-column':
777   Column in which the cursor is positioned when it moves
778   up or down in the browser.
779
780`makefile-browser-selected-mark':
781   String used to mark selected entries in the browser.
782
783`makefile-browser-unselected-mark':
784   String used to mark unselected entries in the browser.
785
786`makefile-browser-auto-advance-after-selection-p':
787   If this variable is set to a non-nil value the cursor
788   will automagically advance to the next line after an item
789   has been selected in the browser.
790
791`makefile-pickup-everything-picks-up-filenames-p':
792   If this variable is set to a non-nil value then
793   `makefile-pickup-everything' also picks up filenames as targets
794   (i.e. it calls `makefile-pickup-filenames-as-targets'), otherwise
795   filenames are omitted.
796
797`makefile-cleanup-continuations':
798   If this variable is set to a non-nil value then Makefile mode
799   will assure that no line in the file ends with a backslash
800   (the continuation character) followed by any whitespace.
801   This is done by silently removing the trailing whitespace, leaving
802   the backslash itself intact.
803   IMPORTANT: Please note that enabling this option causes Makefile mode
804   to MODIFY A FILE WITHOUT YOUR CONFIRMATION when \"it seems necessary\".
805
806`makefile-browser-hook':
807   A function or list of functions to be called just before the
808   browser is entered. This is executed in the makefile buffer.
809
810`makefile-special-targets-list':
811   List of special targets. You will be offered to complete
812   on one of those in the minibuffer whenever you enter a `.'.
813   at the beginning of a line in Makefile mode."
814
815  (interactive)
816  (kill-all-local-variables)
817  (add-hook 'write-file-functions
818	    'makefile-warn-suspicious-lines nil t)
819  (add-hook 'write-file-functions
820	    'makefile-warn-continuations nil t)
821  (add-hook 'write-file-functions
822	    'makefile-cleanup-continuations nil t)
823  (make-local-variable 'makefile-target-table)
824  (make-local-variable 'makefile-macro-table)
825  (make-local-variable 'makefile-has-prereqs)
826  (make-local-variable 'makefile-need-target-pickup)
827  (make-local-variable 'makefile-need-macro-pickup)
828
829  ;; Font lock.
830  (make-local-variable 'font-lock-defaults)
831  (setq font-lock-defaults
832	;; SYNTAX-BEGIN set to backward-paragraph to avoid slow-down
833	;; near the end of a large buffer, due to parse-partial-sexp's
834	;; trying to parse all the way till the beginning of buffer.
835 	'(makefile-font-lock-keywords
836 	  nil nil
837 	  ((?$ . "."))
838 	  backward-paragraph
839	  (font-lock-syntactic-keywords
840	   . makefile-font-lock-syntactic-keywords)))
841
842  ;; Add-log.
843  (make-local-variable 'add-log-current-defun-function)
844  (setq add-log-current-defun-function 'makefile-add-log-defun)
845
846  ;; Imenu.
847  (make-local-variable 'imenu-generic-expression)
848  (setq imenu-generic-expression makefile-imenu-generic-expression)
849
850  ;; Dabbrev.
851  (make-local-variable 'dabbrev-abbrev-skip-leading-regexp)
852  (setq dabbrev-abbrev-skip-leading-regexp "\\$")
853
854  ;; Other abbrevs.
855  (setq local-abbrev-table makefile-mode-abbrev-table)
856
857  ;; Filling.
858  (make-local-variable 'fill-paragraph-function)
859  (setq fill-paragraph-function 'makefile-fill-paragraph)
860
861  ;; Comment stuff.
862  (make-local-variable 'comment-start)
863  (setq comment-start "#")
864  (make-local-variable 'comment-end)
865  (setq comment-end "")
866  (make-local-variable 'comment-start-skip)
867  (setq comment-start-skip "#+[ \t]*")
868
869  ;; Make sure TAB really inserts \t.
870  (set (make-local-variable 'indent-line-function) 'indent-to-left-margin)
871
872  ;; become the current major mode
873  (setq major-mode 'makefile-mode)
874  (setq mode-name "Makefile")
875
876  ;; Activate keymap and syntax table.
877  (use-local-map makefile-mode-map)
878  (set-syntax-table makefile-mode-syntax-table)
879
880  ;; Real TABs are important in makefiles
881  (setq indent-tabs-mode t)
882  (run-mode-hooks 'makefile-mode-hook))
883
884;; These should do more than just differentiate font-lock.
885;;;###autoload
886(define-derived-mode makefile-automake-mode makefile-mode "Makefile.am"
887  "An adapted `makefile-mode' that knows about automake."
888  (setq font-lock-defaults
889	`(makefile-automake-font-lock-keywords ,@(cdr font-lock-defaults))))
890
891;;;###autoload
892(define-derived-mode makefile-gmake-mode makefile-mode "GNUmakefile"
893  "An adapted `makefile-mode' that knows about gmake."
894  (setq font-lock-defaults
895	`(makefile-gmake-font-lock-keywords ,@(cdr font-lock-defaults))))
896
897;;;###autoload
898(define-derived-mode makefile-makepp-mode makefile-mode "Makeppfile"
899  "An adapted `makefile-mode' that knows about makepp."
900  (set (make-local-variable 'makefile-rule-action-regex)
901       makefile-makepp-rule-action-regex)
902  (setq font-lock-defaults
903	`(makefile-makepp-font-lock-keywords ,@(cdr font-lock-defaults))
904	imenu-generic-expression
905	`(("Functions" "^[ \t]*\\(?:make\\)?sub[ \t]+\\([A-Za-z0-9_]+\\)" 1)
906	  ,@imenu-generic-expression)))
907
908;;;###autoload
909(define-derived-mode makefile-bsdmake-mode makefile-mode "BSDmakefile"
910  "An adapted `makefile-mode' that knows about BSD make."
911  (set (make-local-variable 'makefile-dependency-regex)
912       makefile-bsdmake-dependency-regex)
913  (set (make-local-variable 'makefile-dependency-skip) "^:!")
914  (set (make-local-variable 'makefile-rule-action-regex)
915       makefile-bsdmake-rule-action-regex)
916  (setq font-lock-defaults
917	`(makefile-bsdmake-font-lock-keywords ,@(cdr font-lock-defaults))))
918
919;;;###autoload
920(define-derived-mode makefile-imake-mode makefile-mode "Imakefile"
921  "An adapted `makefile-mode' that knows about imake."
922  :syntax-table makefile-imake-mode-syntax-table
923  (let ((base `(makefile-imake-font-lock-keywords ,@(cdr font-lock-defaults)))
924	new)
925    ;; Remove `font-lock-syntactic-keywords' entry from font-lock-defaults.
926    (mapc (lambda (elt)
927	    (unless (and (consp elt)
928			 (eq (car elt) 'font-lock-syntactic-keywords))
929	      (setq new (cons elt new))))
930	  base)
931    (setq font-lock-defaults (nreverse new))))
932
933
934
935;;; Motion code.
936
937(defun makefile-next-dependency ()
938  "Move point to the beginning of the next dependency line."
939  (interactive)
940  (let ((here (point)))
941    (end-of-line)
942    (if (makefile-match-dependency nil)
943	(progn (beginning-of-line) t)	; indicate success
944      (goto-char here) nil)))
945
946(defun makefile-previous-dependency ()
947  "Move point to the beginning of the previous dependency line."
948  (interactive)
949  (let ((pt (point)))
950    (beginning-of-line)
951    ;; makefile-match-dependency done backwards:
952    (catch 'found
953      (while (progn (skip-chars-backward makefile-dependency-skip)
954		    (not (bobp)))
955	(or (prog1 (eq (char-after) ?=)
956	      (backward-char))
957	    (get-text-property (point) 'face)
958	    (beginning-of-line)
959	    (if (> (point) (+ (point-min) 2))
960		(eq (char-before (1- (point))) ?\\))
961	    (if (looking-at makefile-dependency-regex)
962		(throw 'found t))))
963      (goto-char pt)
964      nil)))
965
966
967
968;;; Electric keys.  Blech.
969
970(defun makefile-electric-dot (arg)
971  "Prompt for the name of a special target to insert.
972Only does electric insertion at beginning of line.
973Anywhere else just self-inserts."
974  (interactive "p")
975  (if (bolp)
976      (makefile-insert-special-target)
977    (self-insert-command arg)))
978
979(defun makefile-insert-special-target ()
980  "Prompt for and insert a special target name.
981Uses `makefile-special-targets' list."
982  (interactive)
983  (makefile-pickup-targets)
984  (let ((special-target
985	 (completing-read "Special target: "
986			  makefile-special-targets-list nil nil nil)))
987    (if (zerop (length special-target))
988	()
989      (insert "." special-target ":")
990      (makefile-forward-after-target-colon))))
991
992(defun makefile-electric-equal (arg)
993  "Prompt for name of a macro to insert.
994Only does prompting if point is at beginning of line.
995Anywhere else just self-inserts."
996  (interactive "p")
997  (makefile-pickup-macros)
998  (if (bolp)
999      (call-interactively 'makefile-insert-macro)
1000    (self-insert-command arg)))
1001
1002(defun makefile-insert-macro (macro-name)
1003  "Prepare definition of a new macro."
1004  (interactive "sMacro Name: ")
1005  (makefile-pickup-macros)
1006  (if (not (zerop (length macro-name)))
1007      (progn
1008	(beginning-of-line)
1009	(insert macro-name makefile-macro-assign)
1010	(setq makefile-need-macro-pickup t)
1011	(makefile-remember-macro macro-name))))
1012
1013(defun makefile-insert-macro-ref (macro-name)
1014  "Complete on a list of known macros, then insert complete ref at point."
1015  (interactive
1016   (list
1017    (progn
1018      (makefile-pickup-macros)
1019      (completing-read "Refer to macro: " makefile-macro-table nil nil nil))))
1020  (makefile-do-macro-insertion macro-name))
1021
1022(defun makefile-insert-target (target-name)
1023  "Prepare definition of a new target (dependency line)."
1024  (interactive "sTarget: ")
1025  (if (not (zerop (length target-name)))
1026      (progn
1027	(beginning-of-line)
1028	(insert target-name makefile-target-colon)
1029	(makefile-forward-after-target-colon)
1030	(end-of-line)
1031	(setq makefile-need-target-pickup t)
1032	(makefile-remember-target target-name))))
1033
1034(defun makefile-insert-target-ref (target-name)
1035  "Complete on a list of known targets, then insert TARGET-NAME at point."
1036  (interactive
1037   (list
1038    (progn
1039     (makefile-pickup-targets)
1040     (completing-read "Refer to target: " makefile-target-table nil nil nil))))
1041   (if (not (zerop (length target-name)))
1042       (insert target-name " ")))
1043
1044(defun makefile-electric-colon (arg)
1045  "Prompt for name of new target.
1046Prompting only happens at beginning of line.
1047Anywhere else just self-inserts."
1048  (interactive "p")
1049  (if (bolp)
1050      (call-interactively 'makefile-insert-target)
1051    (self-insert-command arg)))
1052
1053
1054
1055;;; ------------------------------------------------------------
1056;;; Extracting targets and macros from an existing makefile
1057;;; ------------------------------------------------------------
1058
1059(defun makefile-pickup-targets ()
1060  "Notice names of all target definitions in Makefile."
1061  (interactive)
1062  (when makefile-need-target-pickup
1063    (setq makefile-need-target-pickup nil
1064	  makefile-target-table nil
1065	  makefile-has-prereqs nil)
1066    (save-excursion
1067      (goto-char (point-min))
1068      (while (makefile-match-dependency nil)
1069	(goto-char (match-beginning 1))
1070	(while (let ((target-name
1071		      (buffer-substring-no-properties (point)
1072						      (progn
1073							(skip-chars-forward "^ \t:#")
1074							(point))))
1075		     (has-prereqs
1076		      (not (looking-at ":[ \t]*$"))))
1077		 (if (makefile-remember-target target-name has-prereqs)
1078		     (message "Picked up target \"%s\" from line %d"
1079			      target-name (line-number-at-pos)))
1080		 (skip-chars-forward " \t")
1081		 (not (or (eolp) (eq (char-after) ?:)))))
1082	(forward-line)))
1083    (message "Read targets OK.")))
1084
1085(defun makefile-pickup-macros ()
1086  "Notice names of all macro definitions in Makefile."
1087  (interactive)
1088  (when makefile-need-macro-pickup
1089    (setq makefile-need-macro-pickup nil
1090	  makefile-macro-table nil)
1091    (save-excursion
1092      (goto-char (point-min))
1093      (while (re-search-forward makefile-macroassign-regex nil t)
1094	(goto-char (match-beginning 1))
1095	(let ((macro-name (buffer-substring-no-properties (point)
1096							  (progn
1097							    (skip-chars-forward "^ \t:#=*")
1098							    (point)))))
1099	  (if (makefile-remember-macro macro-name)
1100	      (message "Picked up macro \"%s\" from line %d"
1101		       macro-name (line-number-at-pos))))
1102	(forward-line)))
1103    (message "Read macros OK.")))
1104
1105(defun makefile-pickup-everything (arg)
1106  "Notice names of all macros and targets in Makefile.
1107Prefix arg means force pickups to be redone."
1108  (interactive "P")
1109  (if arg
1110      (setq makefile-need-target-pickup t
1111	    makefile-need-macro-pickup t))
1112  (makefile-pickup-macros)
1113  (makefile-pickup-targets)
1114  (if makefile-pickup-everything-picks-up-filenames-p
1115      (makefile-pickup-filenames-as-targets)))
1116
1117(defun makefile-pickup-filenames-as-targets ()
1118  "Scan the current directory for filenames to use as targets.
1119Checks each filename against `makefile-ignored-files-in-pickup-regex'
1120and adds all qualifying names to the list of known targets."
1121  (interactive)
1122  (mapc (lambda (name)
1123	  (or (file-directory-p name)
1124	      (string-match makefile-ignored-files-in-pickup-regex name)
1125	      (if (makefile-remember-target name)
1126		  (message "Picked up file \"%s\" as target" name))))
1127	(file-name-all-completions "" (or (file-name-directory (buffer-file-name)) ""))))
1128
1129
1130
1131;;; Completion.
1132
1133(defun makefile-complete ()
1134  "Perform completion on Makefile construct preceding point.
1135Can complete variable and target names.
1136The context determines which are considered."
1137  (interactive)
1138  (let* ((beg (save-excursion
1139		(skip-chars-backward "^$(){}:#= \t\n")
1140		(point)))
1141	 (try (buffer-substring beg (point)))
1142	 (do-macros nil)
1143	 (paren nil))
1144
1145    (save-excursion
1146      (goto-char beg)
1147      (let ((pc (preceding-char)))
1148	(cond
1149	 ;; Beginning of line means anything.
1150	 ((bolp)
1151	  ())
1152
1153	 ;; Preceding "$" means macros only.
1154	 ((= pc ?$)
1155	  (setq do-macros t))
1156
1157	 ;; Preceding "$(" or "${" means macros only.
1158	 ((and (or (= pc ?{)
1159		   (= pc ?\())
1160	       (progn
1161		 (setq paren pc)
1162		 (backward-char)
1163		 (and (not (bolp))
1164		      (= (preceding-char) ?$))))
1165	  (setq do-macros t)))))
1166
1167    ;; Try completion.
1168    (let* ((table (append (if do-macros
1169			      '()
1170			    makefile-target-table)
1171			  makefile-macro-table))
1172	   (completion (try-completion try table)))
1173      (cond
1174       ;; Exact match, so insert closing paren or colon.
1175       ((eq completion t)
1176	(insert (if do-macros
1177		    (if (eq paren ?{)
1178			?}
1179		      ?\))
1180		  (if (save-excursion
1181			(goto-char beg)
1182			(bolp))
1183		      ":"
1184		    " "))))
1185
1186       ;; No match.
1187       ((null completion)
1188	(message "Can't find completion for \"%s\"" try)
1189	(ding))
1190
1191       ;; Partial completion.
1192       ((not (string= try completion))
1193	;; FIXME it would be nice to supply the closing paren if an
1194	;; exact, unambiguous match were found.  That is not possible
1195	;; right now.  Ditto closing ":" for targets.
1196	(delete-region beg (point))
1197
1198	;; DO-MACROS means doing macros only.  If not that, then check
1199	;; to see if this completion is a macro.  Special insertion
1200	;; must be done for macros.
1201	(if (or do-macros
1202		(assoc completion makefile-macro-table))
1203	    (let ((makefile-use-curly-braces-for-macros-p
1204		   (or (eq paren ?{)
1205		       makefile-use-curly-braces-for-macros-p)))
1206	      (delete-backward-char 2)
1207	      (makefile-do-macro-insertion completion)
1208	      (delete-backward-char 1))
1209
1210	  ;; Just insert targets.
1211	  (insert completion)))
1212
1213       ;; Can't complete any more, so make completion list.  FIXME
1214       ;; this doesn't do the right thing when the completion is
1215       ;; actually inserted.  I don't think there is an easy way to do
1216       ;; that.
1217       (t
1218	(message "Making completion list...")
1219	(let ((list (all-completions try table)))
1220	  (with-output-to-temp-buffer "*Completions*"
1221	    (display-completion-list list try)))
1222	(message "Making completion list...done"))))))
1223
1224
1225
1226;; Backslashification.  Stolen from cc-mode.el.
1227
1228(defun makefile-backslash-region (from to delete-flag)
1229  "Insert, align, or delete end-of-line backslashes on the lines in the region.
1230With no argument, inserts backslashes and aligns existing backslashes.
1231With an argument, deletes the backslashes.
1232
1233This function does not modify the last line of the region if the region ends
1234right at the start of the following line; it does not modify blank lines
1235at the start of the region.  So you can put the region around an entire macro
1236definition and conveniently use this command."
1237  (interactive "r\nP")
1238  (save-excursion
1239    (goto-char from)
1240    (let ((column makefile-backslash-column)
1241          (endmark (make-marker)))
1242      (move-marker endmark to)
1243      ;; Compute the smallest column number past the ends of all the lines.
1244      (if makefile-backslash-align
1245	  (progn
1246	    (if (not delete-flag)
1247		(while (< (point) to)
1248		  (end-of-line)
1249		  (if (= (preceding-char) ?\\)
1250		      (progn (forward-char -1)
1251			     (skip-chars-backward " \t")))
1252		  (setq column (max column (1+ (current-column))))
1253		  (forward-line 1)))
1254	    ;; Adjust upward to a tab column, if that doesn't push
1255	    ;; past the margin.
1256	    (if (> (% column tab-width) 0)
1257		(let ((adjusted (* (/ (+ column tab-width -1) tab-width)
1258				   tab-width)))
1259		  (if (< adjusted (window-width))
1260		      (setq column adjusted))))))
1261      ;; Don't modify blank lines at start of region.
1262      (goto-char from)
1263      (while (and (< (point) endmark) (eolp))
1264        (forward-line 1))
1265      ;; Add or remove backslashes on all the lines.
1266      (while (and (< (point) endmark)
1267                  ;; Don't backslashify the last line
1268                  ;; if the region ends right at the start of the next line.
1269                  (save-excursion
1270                    (forward-line 1)
1271                    (< (point) endmark)))
1272        (if (not delete-flag)
1273            (makefile-append-backslash column)
1274          (makefile-delete-backslash))
1275        (forward-line 1))
1276      (move-marker endmark nil))))
1277
1278(defun makefile-append-backslash (column)
1279  (end-of-line)
1280  ;; Note that "\\\\" is needed to get one backslash.
1281  (if (= (preceding-char) ?\\)
1282      (progn (forward-char -1)
1283             (delete-horizontal-space)
1284             (indent-to column (if makefile-backslash-align nil 1)))
1285    (indent-to column (if makefile-backslash-align nil 1))
1286    (insert "\\")))
1287
1288(defun makefile-delete-backslash ()
1289  (end-of-line)
1290  (or (bolp)
1291      (progn
1292 	(forward-char -1)
1293 	(if (looking-at "\\\\")
1294 	    (delete-region (1+ (point))
1295 			   (progn (skip-chars-backward " \t") (point)))))))
1296
1297
1298
1299;; Filling
1300
1301(defun makefile-fill-paragraph (arg)
1302  ;; Fill comments, backslashed lines, and variable definitions
1303  ;; specially.
1304  (save-excursion
1305    (beginning-of-line)
1306    (cond
1307     ((looking-at "^#+\\s-*")
1308      ;; Found a comment.  Return nil to let normal filling take place.
1309      nil)
1310
1311     ;; Must look for backslashed-region before looking for variable
1312     ;; assignment.
1313     ((or (eq (char-before (line-end-position 1)) ?\\)
1314	  (eq (char-before (line-end-position 0)) ?\\))
1315      ;; A backslash region.  Find beginning and end, remove
1316      ;; backslashes, fill, and then reapply backslahes.
1317      (end-of-line)
1318      (let ((beginning
1319	     (save-excursion
1320	       (end-of-line 0)
1321	       (while (= (preceding-char) ?\\)
1322		 (end-of-line 0))
1323	       (forward-char)
1324	       (point)))
1325	    (end
1326	     (save-excursion
1327	       (while (= (preceding-char) ?\\)
1328		 (end-of-line 2))
1329	       (point))))
1330	(save-restriction
1331	  (narrow-to-region beginning end)
1332	  (makefile-backslash-region (point-min) (point-max) t)
1333	  (let ((fill-paragraph-function nil))
1334	    (fill-paragraph nil))
1335	  (makefile-backslash-region (point-min) (point-max) nil)
1336	  (goto-char (point-max))
1337	  (if (< (skip-chars-backward "\n") 0)
1338	      (delete-region (point) (point-max)))))
1339      ;; Return non-nil to indicate it's been filled.
1340      t)
1341
1342     ((looking-at makefile-macroassign-regex)
1343      ;; Have a macro assign.  Fill just this line, and then backslash
1344      ;; resulting region.
1345      (save-restriction
1346	(narrow-to-region (point) (line-beginning-position 2))
1347	(let ((fill-paragraph-function nil))
1348	  (fill-paragraph nil))
1349	(makefile-backslash-region (point-min) (point-max) nil))
1350      ;; Return non-nil to indicate it's been filled.
1351      t)
1352
1353     (t
1354      ;; Return non-nil so we don't fill anything else.
1355      t))))
1356
1357
1358
1359;;; ------------------------------------------------------------
1360;;; Browser mode.
1361;;; ------------------------------------------------------------
1362
1363(defun makefile-browser-format-target-line (target selected)
1364  (format
1365   (concat (make-string makefile-browser-leftmost-column ?\ )
1366	   (if selected
1367	       makefile-browser-selected-mark
1368	     makefile-browser-unselected-mark)
1369	   "%s%s")
1370   target makefile-target-colon))
1371
1372(defun makefile-browser-format-macro-line (macro selected)
1373  (format
1374   (concat (make-string makefile-browser-leftmost-column ?\ )
1375	   (if selected
1376	       makefile-browser-selected-mark
1377	     makefile-browser-unselected-mark)
1378	   (makefile-format-macro-ref macro))))
1379
1380(defun makefile-browser-fill (targets macros)
1381  (let ((inhibit-read-only t))
1382    (goto-char (point-min))
1383    (erase-buffer)
1384    (mapconcat
1385     (function
1386      (lambda (item) (insert (makefile-browser-format-target-line (car item) nil) "\n")))
1387     targets
1388     "")
1389    (mapconcat
1390     (function
1391      (lambda (item) (insert (makefile-browser-format-macro-line (car item) nil) "\n")))
1392     macros
1393     "")
1394    (sort-lines nil (point-min) (point-max))
1395    (goto-char (1- (point-max)))
1396    (delete-char 1)			; remove unnecessary newline at eob
1397    (goto-char (point-min))
1398    (forward-char makefile-browser-cursor-column)))
1399
1400;;;
1401;;; Moving up and down in the browser
1402;;;
1403
1404(defun makefile-browser-next-line ()
1405  "Move the browser selection cursor to the next line."
1406  (interactive)
1407  (if (not (makefile-last-line-p))
1408      (progn
1409	(forward-line 1)
1410	(forward-char makefile-browser-cursor-column))))
1411
1412(defun makefile-browser-previous-line ()
1413  "Move the browser selection cursor to the previous line."
1414  (interactive)
1415  (if (not (makefile-first-line-p))
1416      (progn
1417	(forward-line -1)
1418	(forward-char makefile-browser-cursor-column))))
1419
1420;;;
1421;;; Quitting the browser (returns to client buffer)
1422;;;
1423
1424(defun makefile-browser-quit ()
1425  "Leave the browser and return to the makefile buffer."
1426  (interactive)
1427  (let ((my-client makefile-browser-client))
1428    (setq makefile-browser-client nil)	; we quitted, so NO client!
1429    (set-buffer-modified-p nil)
1430    (quit-window t)
1431    (pop-to-buffer my-client)))
1432
1433;;;
1434;;; Toggle state of a browser item
1435;;;
1436
1437(defun makefile-browser-toggle ()
1438  "Toggle the selection state of the browser item at the cursor position."
1439  (interactive)
1440  (let ((this-line (count-lines (point-min) (point))))
1441    (setq this-line (max 1 this-line))
1442    (makefile-browser-toggle-state-for-line this-line)
1443    (goto-line this-line)
1444    (let ((inhibit-read-only t))
1445      (beginning-of-line)
1446      (if (makefile-browser-on-macro-line-p)
1447	  (let ((macro-name (makefile-browser-this-line-macro-name)))
1448	    (delete-region (point) (progn (end-of-line) (point)))
1449	    (insert
1450	     (makefile-browser-format-macro-line
1451		macro-name
1452		(makefile-browser-get-state-for-line this-line))))
1453	(let ((target-name (makefile-browser-this-line-target-name)))
1454	  (delete-region (point) (progn (end-of-line) (point)))
1455	  (insert
1456	   (makefile-browser-format-target-line
1457	      target-name
1458	      (makefile-browser-get-state-for-line this-line))))))
1459    (beginning-of-line)
1460    (forward-char makefile-browser-cursor-column)
1461    (if makefile-browser-auto-advance-after-selection-p
1462	(makefile-browser-next-line))))
1463
1464;;;
1465;;; Making insertions into the client buffer
1466;;;
1467
1468(defun makefile-browser-insert-continuation ()
1469  "Insert a makefile continuation.
1470In the makefile buffer, go to (end-of-line), insert a \'\\\'
1471character, insert a new blank line, go to that line and indent by one TAB.
1472This is most useful in the process of creating continued lines when copying
1473large dependencies from the browser to the client buffer.
1474\(point) advances accordingly in the client buffer."
1475  (interactive)
1476  (with-current-buffer makefile-browser-client
1477    (end-of-line)
1478    (insert "\\\n\t")))
1479
1480(defun makefile-browser-insert-selection ()
1481  "Insert all selected targets and/or macros in the makefile buffer.
1482Insertion takes place at point."
1483  (interactive)
1484  (save-excursion
1485    (goto-line 1)
1486    (let ((current-line 1))
1487      (while (not (eobp))
1488	(if (makefile-browser-get-state-for-line current-line)
1489	    (makefile-browser-send-this-line-item))
1490	(forward-line 1)
1491	(setq current-line (1+ current-line))))))
1492
1493(defun makefile-browser-insert-selection-and-quit ()
1494  (interactive)
1495  (makefile-browser-insert-selection)
1496  (makefile-browser-quit))
1497
1498(defun makefile-browser-send-this-line-item ()
1499  (if (makefile-browser-on-macro-line-p)
1500      (save-excursion
1501	(let ((macro-name (makefile-browser-this-line-macro-name)))
1502	  (set-buffer makefile-browser-client)
1503	  (insert (makefile-format-macro-ref macro-name) " ")))
1504    (save-excursion
1505      (let ((target-name (makefile-browser-this-line-target-name)))
1506	(set-buffer makefile-browser-client)
1507	(insert target-name " ")))))
1508
1509(defun makefile-browser-start-interaction ()
1510  (use-local-map makefile-browser-map)
1511  (setq buffer-read-only t))
1512
1513(defun makefile-browse (targets macros)
1514  (interactive)
1515  (if (zerop (+ (length targets) (length macros)))
1516      (progn
1517	(beep)
1518	(message "No macros or targets to browse! Consider running 'makefile-pickup-everything\'"))
1519    (let ((browser-buffer (get-buffer-create makefile-browser-buffer-name)))
1520	(pop-to-buffer browser-buffer)
1521	(makefile-browser-fill targets macros)
1522	(shrink-window-if-larger-than-buffer)
1523	(set (make-local-variable 'makefile-browser-selection-vector)
1524	     (make-vector (+ (length targets) (length macros)) nil))
1525	(makefile-browser-start-interaction))))
1526
1527(defun makefile-switch-to-browser ()
1528  (interactive)
1529  (run-hooks 'makefile-browser-hook)
1530  (setq makefile-browser-client (current-buffer))
1531  (makefile-pickup-targets)
1532  (makefile-pickup-macros)
1533  (makefile-browse makefile-target-table makefile-macro-table))
1534
1535
1536
1537;;; ------------------------------------------------------------
1538;;; Up-to-date overview buffer
1539;;; ------------------------------------------------------------
1540
1541(defun makefile-create-up-to-date-overview ()
1542  "Create a buffer containing an overview of the state of all known targets.
1543Known targets are targets that are explicitly defined in that makefile;
1544in other words, all targets that appear on the left hand side of a
1545dependency in the makefile."
1546  (interactive)
1547  (if (y-or-n-p "Are you sure that the makefile being edited is consistent? ")
1548      ;;
1549      ;; The rest of this function operates on a temporary makefile, created by
1550      ;; writing the current contents of the makefile buffer.
1551      ;;
1552      (let ((saved-target-table makefile-target-table)
1553	    (this-buffer (current-buffer))
1554	    (makefile-up-to-date-buffer
1555	     (get-buffer-create makefile-up-to-date-buffer-name))
1556	    (filename (makefile-save-temporary))
1557	    ;;
1558	    ;; Forget the target table because it may contain picked-up filenames
1559	    ;; that are not really targets in the current makefile.
1560	    ;; We don't want to query these, so get a new target-table with just the
1561	    ;; targets that can be found in the makefile buffer.
1562	    ;; The 'old' target table will be restored later.
1563	    ;;
1564	    (real-targets (progn
1565			    (makefile-pickup-targets)
1566			    makefile-target-table))
1567	    (prereqs makefile-has-prereqs)
1568	    )
1569
1570	(set-buffer makefile-up-to-date-buffer)
1571	(setq buffer-read-only nil)
1572	(erase-buffer)
1573	(makefile-query-targets filename real-targets prereqs)
1574	(if (zerop (buffer-size))		; if it did not get us anything
1575	    (progn
1576	      (kill-buffer (current-buffer))
1577	      (message "No overview created!")))
1578	(set-buffer this-buffer)
1579	(setq makefile-target-table saved-target-table)
1580	(if (get-buffer makefile-up-to-date-buffer-name)
1581	    (progn
1582	      (pop-to-buffer (get-buffer makefile-up-to-date-buffer-name))
1583	      (shrink-window-if-larger-than-buffer)
1584	      (sort-lines nil (point-min) (point-max))
1585	      (setq buffer-read-only t))))))
1586
1587(defun makefile-save-temporary ()
1588  "Create a temporary file from the current makefile buffer."
1589  (let ((filename (makefile-generate-temporary-filename)))
1590    (write-region (point-min) (point-max) filename nil 0)
1591    filename))				; return the filename
1592
1593(defun makefile-generate-temporary-filename ()
1594  "Create a filename suitable for use in `makefile-save-temporary'.
1595Be careful to allow brain-dead file systems (DOS, SYSV ...) to cope
1596with the generated name!"
1597  (let ((my-name (user-login-name))
1598	(my-uid (int-to-string (user-uid))))
1599    (concat "mktmp"
1600	  (if (> (length my-name) 3)
1601	      (substring my-name 0 3)
1602	    my-name)
1603	  "."
1604	  (if (> (length my-uid) 3)
1605	      (substring my-uid 0 3)
1606	    my-uid))))
1607
1608(defun makefile-query-targets (filename target-table prereq-list)
1609  "Fill the up-to-date overview buffer.
1610Checks each target in TARGET-TABLE using
1611`makefile-query-one-target-method-function'
1612and generates the overview, one line per target name."
1613  (insert
1614   (mapconcat
1615    (function (lambda (item)
1616		(let* ((target-name (car item))
1617		       (no-prereqs (not (member target-name prereq-list)))
1618		       (needs-rebuild (or no-prereqs
1619					  (funcall
1620					   makefile-query-one-target-method-function
1621					   target-name
1622					   filename))))
1623		  (format "\t%s%s"
1624			  target-name
1625			  (cond (no-prereqs "  .. has no prerequisites")
1626				(needs-rebuild "  .. NEEDS REBUILD")
1627				(t "  .. is up to date"))))
1628		))
1629    target-table "\n"))
1630  (goto-char (point-min))
1631  (delete-file filename))		; remove the tmpfile
1632
1633(defun makefile-query-by-make-minus-q (target &optional filename)
1634  (not (eq 0
1635	(call-process makefile-brave-make nil nil nil
1636		      "-f" filename "-q" target))))
1637
1638
1639
1640;;; ------------------------------------------------------------
1641;;; Continuation cleanup
1642;;; ------------------------------------------------------------
1643
1644(defun makefile-cleanup-continuations ()
1645  (if (eq major-mode 'makefile-mode)
1646      (if (and makefile-cleanup-continuations
1647	       (not buffer-read-only))
1648	  (save-excursion
1649	    (goto-char (point-min))
1650	    (while (re-search-forward "\\\\[ \t]+$" nil t)
1651	      (replace-match "\\" t t))))))
1652
1653
1654;;; ------------------------------------------------------------
1655;;; Warn of suspicious lines
1656;;; ------------------------------------------------------------
1657
1658(defun makefile-warn-suspicious-lines ()
1659  ;; Returning non-nil cancels the save operation
1660  (if (eq major-mode 'makefile-mode)
1661      (save-excursion
1662	(goto-char (point-min))
1663	(if (re-search-forward "^\\(\t+$\\| +\t\\)" nil t)
1664	    (not (y-or-n-p
1665		  (format "Suspicious line %d. Save anyway? "
1666			  (count-lines (point-min) (point)))))))))
1667
1668(defun makefile-warn-continuations ()
1669  (if (eq major-mode 'makefile-mode)
1670      (save-excursion
1671	(goto-char (point-min))
1672	(if (re-search-forward "\\\\[ \t]+$" nil t)
1673	    (not (y-or-n-p
1674		  (format "Suspicious continuation in line %d. Save anyway? "
1675			  (count-lines (point-min) (point)))))))))
1676
1677
1678;;; ------------------------------------------------------------
1679;;; GNU make function support
1680;;; ------------------------------------------------------------
1681
1682(defun makefile-insert-gmake-function ()
1683  "Insert a GNU make function call.
1684Asks for the name of the function to use (with completion).
1685Then prompts for all required parameters."
1686  (interactive)
1687  (let* ((gm-function-name (completing-read
1688			     "Function: "
1689			     makefile-gnumake-functions-alist
1690			     nil t nil))
1691	 (gm-function-prompts
1692	  (cdr (assoc gm-function-name makefile-gnumake-functions-alist))))
1693    (if (not (zerop (length gm-function-name)))
1694	(insert (makefile-format-macro-ref
1695		 (concat gm-function-name " "
1696			 (makefile-prompt-for-gmake-funargs
1697			    gm-function-name gm-function-prompts)))
1698		" "))))
1699
1700(defun makefile-prompt-for-gmake-funargs (function-name prompt-list)
1701  (mapconcat
1702   (function (lambda (one-prompt)
1703	       (read-string (format "[%s] %s: " function-name one-prompt)
1704			    nil)))
1705   prompt-list
1706   ","))
1707
1708
1709
1710;;; ------------------------------------------------------------
1711;;; Utility functions
1712;;; ------------------------------------------------------------
1713
1714(defun makefile-match-function-end (end)
1715  "To be called as an anchored matcher by font-lock.
1716The anchor must have matched the opening parens in the first group."
1717  (let ((s (match-string-no-properties 1)))
1718    (setq s (cond ((string= s "(") "\\(.*?\\)[ \t]*)")
1719		  ((string= s "{") "\\(.*?\\)[ \t]*}")
1720		  ((string= s "((") "\\(.*?\\)[ \t]*))")
1721		  ((string= s "{{") "\\(.*?\\)[ \t]*}}")))
1722    (if s (looking-at s))))
1723
1724(defun makefile-match-dependency (bound)
1725  "Search for `makefile-dependency-regex' up to BOUND.
1726Checks that the colon has not already been fontified, else we
1727matched in a rule action."
1728  (catch 'found
1729    (let ((pt (point)))
1730      (while (progn (skip-chars-forward makefile-dependency-skip bound)
1731		    (< (point) (or bound (point-max))))
1732	(forward-char)
1733	(or (eq (char-after) ?=)
1734	    (get-text-property (1- (point)) 'face)
1735	    (if (> (line-beginning-position) (+ (point-min) 2))
1736		(eq (char-before (line-end-position 0)) ?\\))
1737	    (when (save-excursion
1738		    (beginning-of-line)
1739		    (looking-at makefile-dependency-regex))
1740	      (save-excursion
1741		(let ((deps-end (match-end 1))
1742		      (match-data (match-data)))
1743		  (goto-char deps-end)
1744		  (skip-chars-backward " \t")
1745		  (setq deps-end (point))
1746		  (beginning-of-line)
1747		  (skip-chars-forward " \t")
1748		  ;; Alter the bounds recorded for subexp 1,
1749		  ;; which is what is supposed to match the targets.
1750		  (setcar (nthcdr 2 match-data) (point))
1751		  (setcar (nthcdr 3 match-data) deps-end)
1752		  (store-match-data match-data)))
1753	      (end-of-line)
1754	      (throw 'found (point)))))
1755      (goto-char pt))
1756    nil))
1757
1758(defun makefile-match-action (bound)
1759  (catch 'found
1760    (while (re-search-forward makefile-rule-action-regex bound t)
1761      (or (eq ?\\ (char-after (- (match-beginning 0) 2)))
1762	  (throw 'found t)))))
1763
1764(defun makefile-do-macro-insertion (macro-name)
1765  "Insert a macro reference."
1766  (if (not (zerop (length macro-name)))
1767      (if (assoc macro-name makefile-runtime-macros-list)
1768	  (insert "$" macro-name)
1769	(insert (makefile-format-macro-ref macro-name)))))
1770
1771(defun makefile-remember-target (target-name &optional has-prereqs)
1772  "Remember a given target if it is not already remembered for this buffer."
1773  (if (not (zerop (length target-name)))
1774      (progn
1775      (if (not (assoc target-name makefile-target-table))
1776	  (setq makefile-target-table
1777		(cons (list target-name) makefile-target-table)))
1778      (if has-prereqs
1779	  (setq makefile-has-prereqs
1780		(cons target-name makefile-has-prereqs))))))
1781
1782(defun makefile-remember-macro (macro-name)
1783  "Remember a given macro if it is not already remembered for this buffer."
1784  (if (not (zerop (length macro-name)))
1785      (if (not (assoc macro-name makefile-macro-table))
1786	  (setq makefile-macro-table
1787		(cons (list macro-name) makefile-macro-table)))))
1788
1789(defun makefile-forward-after-target-colon ()
1790  "Move point forward after inserting the terminating colon of a target.
1791This acts according to the value of `makefile-tab-after-target-colon'."
1792  (if makefile-tab-after-target-colon
1793      (insert "\t")
1794    (insert " ")))
1795
1796(defun makefile-browser-on-macro-line-p ()
1797  "Determine if point is on a macro line in the browser."
1798  (save-excursion
1799    (beginning-of-line)
1800    (re-search-forward "\\$[{(]" (line-end-position) t)))
1801
1802(defun makefile-browser-this-line-target-name ()
1803  "Extract the target name from a line in the browser."
1804  (save-excursion
1805    (end-of-line)
1806    (skip-chars-backward "^ \t")
1807    (buffer-substring (point) (1- (line-end-position)))))
1808
1809(defun makefile-browser-this-line-macro-name ()
1810  "Extract the macro name from a line in the browser."
1811  (save-excursion
1812    (beginning-of-line)
1813    (re-search-forward "\\$[{(]" (line-end-position) t)
1814    (let ((macro-start (point)))
1815      (skip-chars-forward "^})")
1816      (buffer-substring macro-start (point)))))
1817
1818(defun makefile-format-macro-ref (macro-name)
1819  "Format a macro reference.
1820Uses `makefile-use-curly-braces-for-macros-p'."
1821  (if (or (char-equal ?\( (string-to-char macro-name))
1822	  (char-equal ?\{ (string-to-char macro-name)))
1823      (format "$%s" macro-name)
1824    (if makefile-use-curly-braces-for-macros-p
1825	(format "${%s}" macro-name)
1826      (format "$(%s)" macro-name))))
1827
1828(defun makefile-browser-get-state-for-line (n)
1829  (aref makefile-browser-selection-vector (1- n)))
1830
1831(defun makefile-browser-set-state-for-line (n to-state)
1832  (aset makefile-browser-selection-vector (1- n) to-state))
1833
1834(defun makefile-browser-toggle-state-for-line (n)
1835  (makefile-browser-set-state-for-line n (not (makefile-browser-get-state-for-line n))))
1836
1837(defun makefile-last-line-p ()
1838  (= (line-end-position) (point-max)))
1839
1840(defun makefile-first-line-p ()
1841  (= (line-beginning-position) (point-min)))
1842
1843
1844
1845;;; Support for other packages, like add-log.
1846
1847(defun makefile-add-log-defun ()
1848  "Return name of target or variable assignment that point is in.
1849If it isn't in one, return nil."
1850  (save-excursion
1851    (let (found)
1852      (beginning-of-line)
1853      ;; Scan back line by line, noticing when we come to a
1854      ;; variable or rule definition, and giving up when we see
1855      ;; a line that is not part of either of those.
1856      (while (not (or (setq found
1857			    (when (or (looking-at makefile-macroassign-regex)
1858				      (looking-at makefile-dependency-regex))
1859			      (match-string-no-properties 1)))
1860		      ;; Don't keep looking across a blank line or comment.
1861		      (looking-at "$\\|#")
1862		      (not (zerop (forward-line -1))))))
1863      ;; Remove leading and trailing whitespace.
1864      (when found
1865	(setq found (replace-regexp-in-string "[ \t]+\\'" "" found))
1866	(setq found (replace-regexp-in-string "\\`[ \t]+" "" found)))
1867      found)))
1868
1869(provide 'make-mode)
1870
1871;; arch-tag: bd23545a-de91-44fb-b1b2-feafbb2635a0
1872;;; make-mode.el ends here
1873