Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 962
benhsu Avatar asked Oct 06 '12 03:10

benhsu


People also ask

How to run a file on Emac?

To execute a file of Emacs Lisp code, use M-x load-file . This command reads a file name using the minibuffer and then executes the contents of that file as Lisp code. It is not necessary to visit the file first; in any case, this command reads the file as found on disk, not text in an Emacs buffer.

How do I compile in Emacs?

To compile a program in Emacs, type Escape followed by x followed by compile, or use the pull down "tool" menu and select compile.

How do I run a program in Emacs?

Start up Emacs and type the following sequence of keys: M-x (which means hold the "Alt" key and hit "x"). At the bottom of the emacs window "M-x" should appear. Type the command "run-scheme".


1 Answers

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.

like image 161
Daimrod Avatar answered Oct 26 '22 17:10

Daimrod