2012-01-14 64 views
6

自從我切換到Emacs後,有一件事糾纏我,那就是我只能在C代碼中正確地突出顯示十進制數。例如,這些號碼是否正確強調:Emacs C模式 - 你如何語法突出顯示十六進制數字?

1234 
1234l 
1234.5f 

然而,這些數字不正確,強調:

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

是否有可能有Emacs的顏色在這些數字相同的每一個人物?更好的,如果無效的數字(如019或0x0g)可以不同的顏色,使他們脫穎而出。

+0

Emacs有幾個不同的高亮包; 'font-lock-mode'和'hilit19'等等。你在用哪個? – 2012-01-14 04:15:28

+0

我懷疑迄今爲止從未聽說過的標準C模式使用hilit19。字體鎖定更有可能。 – Tom 2012-01-14 06:51:02

+0

我不知道如何說 - 我會想象我仍在使用默認設置。 – Malvineous 2012-01-14 07:18:08

回答

6

感謝指針米沙Arefiev,它讓我找對了地方。這是我想出來的,它涵蓋了我所有的原始要求。我現在所知道的唯一的限制是,它會突出顯示無效的數字後綴,就好像它是正確的(例如「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) 
    )) 
)) 

任何建議/最佳化/修復的歡迎!

編輯:停止突出顯示評論內的數字。

+0

似乎這將突出顯示在'a.0'中的'0'作爲一個有效的數字,'a [0] .a'中的'0] .a'作爲一個無效的數字? (也'f(0).a'與'a [0] .a'有相同的問題) – yuyichao 2012-07-07 13:51:19

+0

@yuyichao:不幸的是,它的確如此。請告知,如果你知道如何解決! – Malvineous 2012-07-09 11:41:29

+0

我試過這樣做,一個不完整的版本在這裏https://github.com/yuyichao/emacsrc/blob/master/script/c-cpp.el。但是,它不會突出顯示無效浮動,並且它也不突出顯示二進制數(如果我有時間,建議welcome = D可能會完成它) – yuyichao 2012-07-09 14:31:57

1

也許這將工作:

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

我們可以使用Emacs正則表達式

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

匹配十六進制數和

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

匹配任何整數/浮點/科學號碼。它們應按順序應用,即首先註冊十六進制數字表達式。這些對我來說很好,現在已經很長時間了。查看完整的Lisp代碼this post,該代碼還添加了C++ 11關鍵字。

相關問題