0

I forget to enter sh-mode when I create new shell scripts in ~/.local/bin, so I want emacs to do this automatically. Because I have an advice set up to make them executable, this will have the effect of also marking them executable automatically.

I tried creating this .dir-locals.el file in the directory:

((nil . ((magic-fallback-mode-alist . (("^$" . sh-mode))))))

but although it asked me whether to apply the "risky" file-local variable magic-fallback-mode-alist, it did not work - the new buffer was still using fundamental-mode.

  • Do your scripts have an extension? If so, you can associates the extension with sh-mode in auto-mode-alist. For example: (add-to-list 'auto-mode-alist '("\\.sh\\'" . sh-mode)). This should already be the default, but if you are using another extension, you can set it this way (this will apply globally though, not just to files in that directory. – elethan Jan 13 '16 at 15:12
  • normal-mode calls (set-auto-mode) and (hack-local-variables) in that order (as indeed it needs to in order for directory local specifications to match on the major mode). This is why your .dir-locals.el does not have the desired effect. – phils Jan 13 '16 at 21:09
  • 1
    About "I have an advice set up to make them executable, this will have the effect of also marking them executable automatically.", if you have this in your config (add-hook 'after-save-hook #'executable-make-buffer-file-executable-if-script-p), any file that begins with #!, example #!/bin/sh, will be automatically made an executable when you save the file. Adding that hash-bang will also automatically set the correct sh-mode (correct flavor of sh). – Kaushal Modi Jan 14 '16 at 22:41
2

auto-insert-mode should do this for you.

  1. Follow the instructions at the beginning of the file you get when you type M-x find-library autoinsert, i.e., add (add-hook 'find-file-hook 'auto-insert) to your initialization file.
  2. Make sure you have ("/bin/.*[^/]\\'" . "Shell-Script mode magic number") in the variable auto-insert-alist. This should already be the case.
  • Oh neat. I have uses for this for sure :) – phils Jan 13 '16 at 21:29
  • @Tobias I never heard of auto-insert-mode! :) At a quick glance, it looks like header2 package. Is it? – Kaushal Modi Jan 14 '16 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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