; Macros for editing makefiles
; Created by Jorge Stolfi on 93-04-02
; Last edited on 2001-09-30 19:28:47 by stolfi

(defvar last-make-command nil
  "The last `make' command that was executed")

(defvar mkm-run-make-command "make -f %s %s"
  "Command to run `make' on the makefile that is open in the current buffer")

(defvar mkm-keymap nil
  "Keymap used in makefile-mode.")

(if mkm-keymap 
  ()
  (let ((map (make-sparse-keymap)))
    (define-key map "\C-c\C-c" 'mkm-run-make)
    (define-key map "\C-c\C-a" 'mkm-run-make-all)
    (define-key map "\C-c\C-i" 'mkm-run-make-install)
    (define-key map "\C-c\C-t" 'mkm-run-make-tests)
    (define-key map "\C-c`" 'next-error)      ; also (usually) on "\C-x`"
    (setq mkm-keymap map)
  )
)

(defun makefile-mode ()
"This is a mode for editing makefiles.
\\{mkm-keymap}
   mkm-run-make-command holds the command to run `make' on the current buffer."
  (interactive)
  (kill-all-local-variables)
  ; (setq debug-on-error t) ; DEBUG
  (use-local-map mkm-keymap)
  (setq major-mode 'makefile-mode)
  (setq mode-name "Makefile")
  (setq indent-tabs-mode nil)
  (make-local-variable 'require-final-newline)
  (setq require-final-newline t)
  (make-local-variable 'comment-start)
  (setq comment-start "# ")
  (make-local-variable 'comment-end)
  (setq comment-end "")
  (make-local-variable 'comment-column)
  (setq comment-column 1)
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip "\\*+ *")
  (make-local-variable 'comment-indent-hook)
  (setq comment-indent-hook 'c-comment-indent)
  (make-local-variable 'parse-sexp-ignore-comments)
  (setq parse-sexp-ignore-comments t)
  (run-hooks 'makefile-mode-hook))

(defun mkm-run-make (what &optional save)
  "Runs `make WHAT' on the current buffer"
  (interactive "s")
  (let 
    (
      (filename (file-name-nondirectory (buffer-file-name)))
      (command (format mkm-run-make-command filename what))
    )
    (if save (setq last-make-command command))
    (compile command)
  )
)

(defun mkm-run-make-all ()
  "Runs `make all' on the current buffer"
  (interactive)
  (mkm-run-make "all" t)
)

(defun mkm-run-make-install ()
  "Runs `make install' on the current buffer"
  (interactive)
  (mkm-run-make "install" nil)
)

(defun mkm-run-make-tests ()
  "Runs `make tests' on the current buffer"
  (interactive)
  (mkm-run-make "tests" nil)
)