Last week I finally modernized my PHP emacs setup. I did so by selecting two powerful modes (php-mode and web-mode) and implementing a bit of code to easily toggle between the two. I included this comment in my blog post:
At some point, I could codify this so that files in the snippets directory, for example, always open in web-mode, whereas files loaded from under lib start off in php-mode.
When I wrote the above statement I assumed that I'd need to dust off the o'l emacs lisp manual and would need to write some code to analyze the directory of the file being opened. Turns out, I was vastly over-thinking this.
The standard way to associate a mode with a file is by using the elisp variable auto-mode-alist. This is Emacs 101 stuff, and is something I've been doing for 20+ years. In my emacs config file I had this line:
(add-to-list 'auto-mode-alist '("[.]php$" . php-mode))
Which says too open .php files in php-mode. What I'd never done, nor considered, is that you don't have to limit yourself to matching the base filename. The auto-mode-alist is matched against the entire path. To open up ‘snippet’ files in web-mode is trivial. I just put the above code in my .emacs file:
(add-to-list 'auto-mode-alist '("[.]php$" . php-mode)) (add-to-list 'auto-mode-alist '("\\(pages\\|snippets\\|templates\\)/.*[.]php?$" . web-mode))
The order is key here. add-to-list pushes new items to the front of the list. So the first line adds a general rule to open up all .php files in php-mode, and the second line adds a specific rule: if the full path to the file contains the the word pages or snippets or templates, then open the file in web-mode. It's not perfect, but files matching this path convention are far more likely to be in the right mode for me.
While I'm a bonehead for not seeing this sooner, I sure do appreciate trivial solutions.
No comments:
Post a Comment