A very simple Makefile:

        gcc -o hello hello.c

And I already set:

(add-hook 'before-save-hook
      '(lambda ()
         ;; indent the whole buffer before-save
         (when (derived-mode-p 'prog-mode)
           (indent-region (point-min) (point-max)))))

in my init.el, so if I C-x C-s in this Makefile file, it will become:

gcc -o hello hello.c

Is there a way I can make Emacs recognize that the lines under : symbol should be indented with one TAB?

BTW: Typing TAB in the gcc... line will keep inserting tabs, is there a way that typing TAB indents this line like doing it in C code and TAB again won't do anything like inserting another tab)?

  • Indentation is a makefile is not deterministic, as in emacs can't know whether or not that line should or shouldn't be indented. This applies to other whitespace dependent language like python, take a line of python and improperly indent it, there could be many levels of indentation that are syntactically correct for a given line, but emacs has no way to know which one is correct without understanding the context of your application. However, for simple makefiles, you could write your own indent-line-function that always indents lines with one tab if they come after a make target. – Jordon Biondo Mar 25 '15 at 16:58
  • @JordonBiondo How can I exclude makefile-mode from '(derived-mode-p 'prog-mode)' then? – CodyChan Mar 26 '15 at 12:22
  • Check against the major-mode variable. So something like: (unless (eq major-mode 'makefile-mode) ...). Note that there are actually a number of makefile major modes, so you'll need check whether or not any of them are the major mode like (unless (member major-mode the-list-of-makefile-major-modes) ...) – Jordon Biondo Mar 26 '15 at 13:13
  • gist.github.com/jordonbiondo/dc4482f07c48cf9ee59a. I won't post this as answer for now, hoping that someone chimes with something that isn't "you can't" – Jordon Biondo Mar 26 '15 at 13:22
  • @JordonBiondo Thanks, and I modified my snippet of code a little bit, and it works as expected. – CodyChan Mar 26 '15 at 15:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.