2

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?

8

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.")
  • magit -> magic mistyped – alex_1948511 Apr 3 '18 at 8:24
3

N.B. See npostav's answer for a better solution.

Sounds like you're looking for find-file-hook:

find-file-hook is a variable defined in files.el.

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 nil

This variable may be risky if used as a file-local variable.

Documentation:

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)
  • 1
    Note that if the file would normally be in Javascript mode by default, rather than add to find-file-hook a better option might be to add it to js-mode-hook. – Stefan Oct 14 '17 at 16:35

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.