Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default-directory of compilation in Emacs?

Tags:

I am coding OCaml under Emacs, I have one makefile in the working folder, and several sub-folders containing .ml files. If I launch M-x compile and make works fine on a buffer of makefile, but does not work on a buffer of a .ml file, it gives me an error:

-*- mode: compilation; default-directory: "..." -*-
Compilation started at Fri Jan 27 18:51:35

make -k
make: *** No targets specified and no makefile found.  Stop.

Compilation exited abnormally with code 2 at Fri Jan 27 18:51:35

It is understandable because the default-directory is sub-folder which does not contain makefile. Does anyone know how to set the folder of makefile always as the default-directory of compilation?

like image 850
SoftTimur Avatar asked Jan 27 '12 17:01

SoftTimur


People also ask

How do I run a compiled program in Emacs?

To run make or another compilation command, type M-x compile . This reads a shell command line using the minibuffer, and then executes the command by running a shell as a subprocess (or inferior process) of Emacs.

How do I go to a folder in Emacs?

In Emacs, type M-x dired. You will be prompted for the directory to open. Type in the directory to display, or press Return to open the default directory.


2 Answers

You can call make with the right arguments:

make -C .. -k

where .. is the path to your Makefile

like image 182
Thomas Avatar answered Oct 05 '22 03:10

Thomas


You can control this from within emacs by writing a function that (temporarily) sets default-directory and calls compile.

(defun compile-in-parent-directory ()
  (interactive)
  (let ((default-directory
          (if (string= (file-name-extension buffer-file-name) "ml")
              (concat default-directory "..")
            default-directory))))
  (call-interactively #'compile))

When using compile-in-parent-directory all ml files will be compiled in the parent directory of where they are. Of course if they are nested deeper you can change the logic to reflect that. In fact there is a version on the EmacsWiki which searches parent directories until it finds a makefile. I found this after I wrote this answer, otherwise I would have just pointed you there. sigh. The good thing about my method is that it's not specific to make so that you can use the same "trick" for other commands.

You can also change the call to compile to be non-interactive if you know exactly what you want the command to be. This would work particularly well if it's bound to a key in the appropriate mode hook.

like image 32
Ivan Andrus Avatar answered Oct 05 '22 02:10

Ivan Andrus