I would like to enable
rjsx-mode whenever a file I open contains a specific string, or a regex like
import.*react for example. Is there a way to do something like this in emacs?
I would like to enable [some mode] whenever a file I open contains a specific string, or a regex
This is exactly what
magic-mode-alist is for (there is also
magic-fallback-mode-alist if you want the filename mode matching to take precedence).
In your case
(add-to-list 'magic-mode-alist '("import.*react" . rjsx-mode)).
magic-mode-alist is a variable defined in ‘files.el’. Its value is nil This variable may be risky if used as a file-local variable. Documentation: Alist of buffer beginnings vs. corresponding major mode functions. Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION). After visiting a file, if REGEXP matches the text at the beginning of the buffer, or calling MATCH-FUNCTION returns non-nil, ‘normal-mode’ will call FUNCTION rather than allowing ‘auto-mode-alist’ to decide the buffer’s major mode. If FUNCTION is nil, then it is not called. (That is a way of saying "allow ‘auto-mode-alist’ to decide for these files.")
N.B. See npostav's answer for a better solution.
Sounds like you're looking for
find-file-hookis a variable defined in
Its value is
(global-eldoc-mode-check-buffers global-font-lock-mode-check-buffers epa-file-find-file-hook vc-refresh-state)
Original value was
This variable may be risky if used as a file-local variable.
List of functions to be called after a buffer is loaded from a file.
The buffer’s local variables (if any) will have been processed before the functions are called.
You can customize this variable.
This variable was introduced, or its default value was changed, in version 22.1 of Emacs.
In your case, for example:
(defun my-rjsx-mode-check-buffers () "Conditionally enable `rjsx-mode' based on file contents." (save-excursion (goto-char (point-min)) (when (re-search-forward "^import .*react" nil t) (rjsx-mode)))) (add-hook 'find-file-hook #'my-rjsx-mode-check-buffers)