Vim 文件第一行的语法区域

Vim syntax region on the first lines of a file

我尝试为我的笔记创建语法定义。

这是一个例子:

=Title of the note (it's the very first line)
@context (mandatory)
!action (mandatory)
#tag-1 (optional)
#tag-2 (optional)
#tag-n (optional)
>attached-files (optional)

My note come after the first blank line
and continue until the end of the file...

No matter any additional empty line

我想创建语法来突出显示这些不同的匹配项。在我的笔记中,我可以写一些看起来像标题(=这样)或标签(#this-way)的行,它们不必突出显示。我尝试为我的笔记元数据创建一个区域,从第一行到第一空行。

我试过了,但我遇到了问题(突出显示似乎不错,但如果我删除空行之后的所有行(包括空行),那么它就不再起作用了...

augroup gtd

    autocmd!

    autocmd BufRead,BufNewFile *.gtd set filetype=gtd

    autocmd FileType gtd syntax region gtdTags start="\%1l" end="^\s*$" fold transparent contains=gtdTitle,gtdContext,gtdStatus,gtdHashtags,gtdAttachedFiles
    autocmd FileType gtd syntax match gtdTitle '^=.*' contained
    autocmd FileType gtd syntax match gtdContext '^@\S\+$' contained
    autocmd FileType gtd syntax match gtdStatus '^!\S\+$' contained
    autocmd FileType gtd syntax match gtdHashtags '^#\S\+$' contained
    autocmd FileType gtd syntax match gtdAttachedFiles '^>attached-files$' contained

    autocmd FileType gtd syntax match gtdSubtitle '^\s*\*\* .*'
    autocmd FileType gtd syntax keyword gtdTodo TODO WAITING SOMEDAY SCHEDULED

    autocmd FileType gtd highlight gtdTitle guifg=white guibg=NONE gui=bold
    autocmd FileType gtd highlight gtdContext guifg=yellow
    autocmd FileType gtd highlight gtdStatus guifg=red gui=NONE
    autocmd FileType gtd highlight gtdHashtags guifg=grey gui=italic
    autocmd FileType gtd highlight gtdAttachedFiles guifg=red guibg=white gui=bold

    autocmd FileType gtd highlight gtdSubtitle guifg=black guibg=lightgrey gui=bold
    autocmd FileType gtd highlight gtdTodo guifg=white guibg=red gui=NONE

augroup END

如何停止第一个 empty/blank 行或文件末尾的区域,关于第一个即将到来的区域?

您可以在区域结尾的模式中包含表示文件结尾的特殊原子:end="^\s*$\|\@$";但是,这不是必需的。 Vim alwaysstart 模式匹配时开始语法区域;它不检查 end 模式,正如 :help syn-region 解释的那样:

Note: The decision to start a region is only based on a matching start pattern. There is no check for a matching end pattern.

因此,即使 end 模式没有匹配项,所有区域都隐式地结束于缓冲区的末尾。事实上,你的语法对我来说很好用。

我认为您感到困惑,因为您没有定义正确的语法脚本,而是选择了 autocmd FileType gtd 前缀。此外,缺少 syntax clear

将您的 :syntax 命令放入 ~/.vim/syntax/gtd.vim 中的单独文件中,并遵守 :help 44.12 中描述的格式。您还可以查看 Vim.

附带的 $VIMRUNTIME/syntax/*.vim 中的各种语法脚本之一