benhsu
benhsu

Reputation: 5526

using the current buffer's file name in M-x compile

I would like emacs to use the current buffer's file name as part of the command passed to M-x compile. For example, if I am editing ~/foo.rb, I would like M-x compile to execute ruby ~/foo.rb

I tried setting compilation-command to (list "ruby" buffer-file-name), but apparently you can't pass an s-expression here.

Upvotes: 23

Views: 4351

Answers (1)

Daimrod
Daimrod

Reputation: 5020

1. Read the documentation of the function

C-hfcompileRET

compile is an interactive autoloaded compiled Lisp function in
`compile.el'.
[snip]
Interactively, prompts for the command if `compilation-read-command' is
non-nil; otherwise uses `compile-command'.  With prefix arg, always prompts.
Additionally, with universal prefix arg, compilation buffer will be in
comint mode, i.e. interactive.

Now that we've found what we were looking for, let's …

2. … read the documentation of the variable …

C-hvcompile-commandRET

compile-command is a variable defined in `compile.el'.
Its value is "make -k "
[snip]
Sometimes it is useful for files to supply local values for this variable.
You might also use mode hooks to specify it in certain modes, like this:

    (add-hook 'c-mode-hook
       (lambda ()
     (unless (or (file-exists-p "makefile")
             (file-exists-p "Makefile"))
       (set (make-local-variable 'compile-command)
        (concat "make -k "
            (file-name-sans-extension buffer-file-name))))))

3. … and finally adapt the example to your needs

(add-hook 'ruby-mode-hook
          (lambda ()
            (set (make-local-variable 'compile-command)
                 (concat "ruby " buffer-file-name))))

Of course you can easily customize it to use rake if there is a Rakefile.

Upvotes: 44

Related Questions