Thursday, May 16, 2013

Emacs Word Commands in C and Java Modes


The Problem
You use the Emacs commands:

CommandAction
M-fMove forward by one word
M-bMove backward by one word
M-dDelete word ahead of the cursor
M-DELDelete word behind cursor
M-tTranspose words
M-@Mark word
M-uUpcase word
M-lDowncase word
M-cCapitalize word

They work beautifully with ordinary text but not so great in C or Java modes. For example, the arrows in the image below show where the cursor will skip to if you use M-f to skip forward starting at the first arrow.




The problem here is that C-mode doesn't recognize "_" as part of a "word".

The Solution
There is an easy fix for this: simply add the following lines to your .emacs file:
01 (add-hook 'c-mode-common-hook
02        (lambda ()
03          (modify-syntax-entry ?_ "w" c-mode-syntax-table)))
04 (add-hook 'java-mode-hook
05        (lambda ()
06          (modify-syntax-entry ?_ "w" java-mode-syntax-table)))
The image below shows where the cursor will skip to after the hook is installed.




All word-related commands will recognize "_" as part of a "word" in C and Java modes.

Problem solved.

No comments:

Post a Comment