5

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.

9

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)
| improve this answer | |
3

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

| improve this answer | |

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.