3

I figured the following would tell emacs to recognize files starting with "Makefile" and start makefile-mode:

(add-to-list 'auto-mode-alist '("\\`Makefile" . makefile-mode))

The \\` indicates the start of the string.

This doesn't work though. Can someone please explain why and how this can be fixed?

1 Answer 1

5

There is already an entry ("[Mm]akefile\\'" . makefile-gmake-mode) in auto-mode-alist.

(I figure that you actually wanted to delete the end \\' of the regular expression.)

The entry for xinit shows how to handle the beginning of a file name:

("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)

The main aspect here is that your regular expression must match the full absolute path of the file sans backup-suffixes and remote-file identifications.

So I propose you use something like

(add-to-list 'auto-mode-alist '("\\(/\\|\\`\\)[Mm]akefile" . makefile-gmake-mode))

You don't need to care about the existing entry for makefiles since the first matching entry is used.

If you really want to replace the existing entry even if this is not required you can also use the following statement:

(setcar (assoc-string "[Mm]akefile\\'" auto-mode-alist) "\\(/\\|\\`\\)[Mm]akefile")

Or if you are afraid that the default entry disappears some time in the future you can act in dependence of its existence in auto-mode-alist:

(let ((existing-entry (assoc-string "[Mm]akefile\\'" auto-mode-alist)))
  (if existing-entry (setcar existing-entry "\\(/\\|\\`\\)[Mm]akefile")
    (add-to-list 'auto-mode-alist '("\\(/\\|\\`\\)[Mm]akefile" . makefile-gmake-mode))))
3
  • Thanks. I understand this mean that it matches on the full path and so I have to either match on /Makefile or Makefile. Either way, emacs is giving me an error on your proposed code. Adding a quote in front of the ( fixes it. Thanks.
    – ana
    Mar 19, 2016 at 8:30
  • Thanks for the correction. It was a typo. I added the quote in the answer.
    – Tobias
    Mar 19, 2016 at 8:32
  • If I could give you a hundred upvotes, I'd do it -- this has been driving me crazy for weeks, because every time I made changes to , e.g. Makefile.Docker I would get some default mode that would "helpfully" convert my tabs to spaces.. :(
    – JVMATL
    Dec 20, 2019 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.