I am using the standard (shipped) Emacs C++ mode but I have a slight itch that I am looking to ge开发者_运维技巧t scratched. How would I go about properly highlighting the types inside of a sizeof and the casts in C++?
For example:
A Cast
Type * pointer = reinterpret_cast <Type *> (original);
Sizeof
std::cout << sizeof (Type) << "\n";
Add these expressions to your .emacs
, or evaluate them with M-:
.
Sizeof (that's the easier of the two cases)
The regex highlights any combination (indicated by the bracket expression [...]
; regarding syntax, please see the note below) of alphanumeric, whitespace and asterisk within parentheses and preceded by sizeof
.
(font-lock-add-keywords 'c++-mode
'(("\\<sizeof[[:space:]]*(\\([[:alnum:][:space:]*]+\\))"
1 font-lock-type-face t)))
The number 1
tells emacs to only highlight the first subexpression (marked by \\(...\\)
) using the face font-lock-type-face
; t
means overriding any previous highlighting.
You can see and change the available faces with M-x customize group [RET] font-lock-faces [RET]
.
C++ style casts
I'm not sure which typename you want to be highlighted – the “original” or the one to cast into. This highlighter marks both:
(font-lock-add-keywords 'c++-mode
'(("\\<[[:alnum:]]+_cast[[:space:]]*<\\([[:alnum:][:space:]*]+\\)>[[:space:]]*(\\([[:alnum:][:space:]*]+\\))"
(1 font-lock-type-face t)
(2 font-lock-type-face t))))
Again, '1and
2` select the corresponding subexpressions.
Please note: The regexes for the typenames do not perfectly conform to C++ syntax. For example, emacs will happily highlight nonsense like sizeof(int * 32)
.
Also, my solution doesn't take into account the problem Pavel mentioned in the comment on your question; that you could also use sizeof
on variables, which would need different highlighting. I don't think this possible, short of implementing a complete C parser in the font lock code.
精彩评论