9

Following this answer, when I type (modify-syntax-entry ?_ "w") and do M-x eval-region, it has the effect I'm looking for, albeit only for that buffer. I've put (modify-syntax-entry ?_ "w") in my .emacs file, however and after restarting, it's not having effect in my C/C++ code.

I'm using Emacs GNU Emacs 26.3 (build 1, x86_64-redhat-linux-gnu, GTK+ Version 3.24.13) of 2019-12-11. My OS is: Fedora release 31 (Thirty One).

There are questions with nearly the exact same title, but their accepted answers do not work for C/C++ mode, so this is a different question.

Swiss Frank
  • 247
  • 1
  • 10

2 Answers2

12

Each major mode has its own syntax and syntax table. If you just put (modify-syntax-entry ?_ "w") in your init file, it gets evaluated in the buffer that is current when your init file is loaded -- not in a C/C++ buffer.

To evaluate that sexp when in a C/C++ buffer you can put it in a function, which you add to the mode hook. For example (untested):

(add-hook 'c-mode-hook (lambda () (modify-syntax-entry ?_ "w")))

But it's generally better to use a named, not an anonymous, hook function. For example:

(defun foo () (modify-syntax-entry ?_ "w"))

(add-hook 'c-mode-hook 'foo)
Drew
  • 75,699
  • 9
  • 109
  • 225
5

Rather than modifying the syntax tables, you can instead use the built-in superword-mode:

Superword mode is a buffer-local minor mode. Enabling it changes the definition of words such that symbols characters are treated as parts of words: e.g., in ‘superword-mode’, "this_is_a_symbol" counts as one word.

You can enable it per mode using a a hook: (add-hook 'c++-mode-hook 'superword-mode) or globally with (global-superword-mode 1) in your .emacs

erikstokes
  • 12,686
  • 2
  • 34
  • 56
  • This helped a lot! It fixed a problem where mu4e was hanging on message replies: https://github.com/djcb/mu/issues/1779 – Anthony Scemama Nov 21 '20 at 22:45
  • I get `Wrong type argument: symbolp, ((lambda nil (set (make-local-variable (quote whitespace-line-column)) 127)))` unless I put a single quote before c++-mode-hook: `(add-hook 'c++-mode-hook 'superword-mode)` – sage Sep 02 '22 at 19:07