[英]vim: How do I syntax highlight a line so that one part of it is formatted as A and the other part is formatted as B?
我今天已經在這幾個小時,在線研究和閱讀vim手冊。 我的智慧結束了。 我想格式化帶有時間戳的行,以便它們具有綠色文本,同時加粗時間戳本身。 例如,如果我有以下4行:
1 [ 20:42:57 20190601 ] Apple car truck a whole bunch of other nonsense
2 ball baby zebra more nonsense
3 [ 20:43:12 20190601 ] dog blah blah blah
4 circle mouse rat up down left right b a b a select start
然后包含時間戳(第2行和第4行)的兩行都有綠色文本,時間戳本身( [ 20:42:57 20190601 ]
和[ 20:43:12 20190601 ]
)將是粗體。
我的第一個想法是只使用正則表達式模式來匹配所有帶有時間戳的行並將它們着色為綠色,然后使用另一個正則表達式模式僅用於時間戳本身並使它們變為粗體,如下所示:
syntax match timestampline "\[ \([0-9]\{2}\:\)\{2}[0-9]\{2} [0-9]\{8} \].*$"
highlight timestampline ctermfg=green ctermbg=NONE
syntax match timestamponly "\[ \([0-9]\{2}\:\)\{2}[0-9]\{2} [0-9]\{8} \]"
highlight timestamponly cterm=bold
但這只會導致時間戳在任何地方都沒有綠色文字。
然后我想也許我需要告訴每個語法停止或開始匹配,如下所示:
syntax match timestampline "\[ \([0-9]\{2}\:\)\{2}[0-9]\{2} [0-9]\{8} \]\{-}\zs.*$"
highlight timestampline ctermfg=green ctermbg=NONE
syntax match timestamponly "\[ \([0-9]\{2}\:\)\{2}[0-9]\{2} [0-9]\{8} \]\ze"
highlight timestamponly ctermfg=green ctermbg=NONE cterm=bold
但這只會導致時間戳為綠色和粗體,其他所有內容都未格式化。
我不明白我做錯了什么。 為什么第二個重點聲明完全否定了第一個? 他們不應該只是格式化他們匹配的東西而不影響他們不匹配的東西嗎?
:help :syn-priority
:
當多個語法項可能匹配時,將使用以下規則:
- 當多個匹配或區域項目在同一位置開始時,最后定義的項目具有優先級。
所以在你的代碼中, timestamponly
總是獲勝,而timestampline
永遠不會被使用。
你可以得到你想要的效果:
syntax match timestampline /.*$/ contained
highlight timestampline ctermfg=green
syntax match timestamponly /\[ \d\{2}:\d\{2}:\d\{2} \d\{8} \]/ nextgroup=timestampline
highlight timestamponly ctermfg=green cterm=bold
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.