Emacs C mode - how do you syntax out hexadecimal numbers?

One thing that bothered me about Emacs since I switched to it is that I can only get it for syntax so that decimal numbers display correctly in C code. For example, these numbers are highlighted correctly:

1234 1234l 1234.5f 

However, these numbers are NOT highlighted correctly:

 0x1234 // x is different colour 0xabcd // no hex digits are coloured 019 // invalid digit 9 is coloured like it is correct 

Is it possible for Emacs to color each character in these numbers equally? Even better, if invalid numbers (e.g. 019 or 0x0g) can be colored differently to highlight them.

+6
source share
3 answers

Thanks for the signpost Misha Arefiev, he made me look for the right places. This is what I came up with, and it covers all my initial requirements. The only limitation that I now know about is that it will highlight an invalid number suffix, as if it were right (for example, "123ulu")

 (add-hook 'c-mode-common-hook (lambda () (font-lock-add-keywords nil '( ; Valid hex number (will highlight invalid suffix though) ("\\b0x[[:xdigit:]]+[uUlL]*\\b" . font-lock-string-face) ; Invalid hex number ("\\b0x\\(\\w\\|\\.\\)+\\b" . font-lock-warning-face) ; Valid floating point number. ("\\(\\b[0-9]+\\|\\)\\(\\.\\)\\([0-9]+\\(e[-]?[0-9]+\\)?\\([lL]?\\|[dD]?[fF]?\\)\\)\\b" (1 font-lock-string-face) (3 font-lock-string-face)) ; Invalid floating point number. Must be before valid decimal. ("\\b[0-9].*?\\..+?\\b" . font-lock-warning-face) ; Valid decimal number. Must be before octal regexes otherwise 0 and 0l ; will be highlighted as errors. Will highlight invalid suffix though. ("\\b\\(\\(0\\|[1-9][0-9]*\\)[uUlL]*\\)\\b" 1 font-lock-string-face) ; Valid octal number ("\\b0[0-7]+[uUlL]*\\b" . font-lock-string-face) ; Floating point number with no digits after the period. This must be ; after the invalid numbers, otherwise it will "steal" some invalid ; numbers and highlight them as valid. ("\\b\\([0-9]+\\)\\." (1 font-lock-string-face)) ; Invalid number. Must be last so it only highlights anything not ; matched above. ("\\b[0-9]\\(\\w\\|\\.\\)+?\\b" . font-lock-warning-face) )) )) 

Any suggestions / optimizations / corrections are welcome!

EDIT: Stop it from highlighting numbers in the comments.

+6
source

Maybe this will work:

  (font-lock-add-keywords 'c-mode '(("0x\\([0-9a-fA-F]+\\)" . font-lock-builtin-face))) 
+1
source

We can use emacs regex

 \<0[xX][0-9A-Fa-f]+ 

to match hexadecimal numbers and

 \<[\-+]*[0-9]*\.?[0-9]+\([ulUL]+\|[eE][\-+]?[0-9]+\)? 

to match any integer / float / scientific number. They must be applied sequentially, that is, register the expression of a hexadecimal number first. They work well for me now for a long time. Check out this post for full Lisp code, which also adds C ++ 11 keywords.

0
source

Source: https://habr.com/ru/post/905960/


All Articles