How can I configure emacs to recognize the file alone as a PHP file:
- regardless of the extension and
- only for the session
As major modes are just functions, you can enable any
major-mode, whenever you like, in whichever buffer you like, by simply invoking its corresponding command. In your case, assuming the desired mode is called
php-mode, you would invoke
M-x php-mode RET in the buffer in question. There is usually nothing persistent about changing
major-mode (unless a particular mode writes data to disk when enabled or similar), so the file would not automatically be detected as PHP the next time you read it.
If the file was the only file with that extension in the session how would I set the mode by the extension?
This is normally achieved by modifying the variable
auto-mode-alist, which maps filename patterns in the form of Elisp regular expressions to corresponding major modes. See the Emacs manual node on Choosing Modes and the variable's documentation (
C-h v auto-mode-alist RET or
M-x describe-variable RET auto-mode-alist RET) for more information.
For example, assuming the file's extension is
.drupal and the desired
php-mode, you could write
(add-to-list 'auto-mode-alist '("\\.drupal\\'" . php-mode))
Note that in Elisp, file extensions are usually terminated by the pattern
\' instead of the more mainstream
$. Emacs interprets the former as "end of string" and the latter as "end of line", so using the former avoids the theoretical possibility of failing to match a filename containing newlines. See the Emacs manual node on Regexps for more information on their usage and syntax.