vim 支持 nginx 配置文件语法高亮

配置nginx服务器的时候,语法高亮看的更清晰,也不容易出错。让vim支持nginx的语法高亮,需要两个步骤。

指定文件类型

au BufRead,BufNewFile /etc/nginx/* set ft=nginx

添加文件 ~/.vim/syntax/nginx.vim

最新的文件通过 nginx.org 下载源码解压后,可以获得。

比如: nginx-1.21.3\contrib\vim\syntax\nginx.vim

" Vim syntax file
" Language: nginx.conf

if exists("b:current_syntax")
  finish
end

setlocal iskeyword+=.
setlocal iskeyword+=/
setlocal iskeyword+=:

syn match ngxVariable '\$\w\w*'
syn match ngxVariableBlock '\$\w\w*' contained
syn match ngxVariableString '\$\w\w*' contained
syn region ngxBlock start=+^+ end=+{+ contains=ngxComment,ngxDirectiveBlock,ngxVariableBlock,ngxString oneline
syn region ngxString start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=ngxVariableString oneline
syn region ngxString start=+'+ end=+'+ skip=+\\\\\|\\'+ contains=ngxVariableString oneline
syn match ngxComment '\s*#.*$'

syn keyword ngxBoolean on
syn keyword ngxBoolean off

syn keyword ngxDirectiveBlock http         contained
syn keyword ngxDirectiveBlock mail         contained
syn keyword ngxDirectiveBlock events       contained
syn keyword ngxDirectiveBlock server       contained
syn keyword ngxDirectiveBlock types        contained
syn keyword ngxDirectiveBlock location     contained
syn keyword ngxDirectiveBlock upstream     contained
syn keyword ngxDirectiveBlock charset_map  contained
syn keyword ngxDirectiveBlock limit_except contained
syn keyword ngxDirectiveBlock if           contained
syn keyword ngxDirectiveBlock geo          contained
syn keyword ngxDirectiveBlock map          contained

syn keyword ngxDirectiveImportant include
syn keyword ngxDirectiveImportant root
syn keyword ngxDirectiveImportant server
syn keyword ngxDirectiveImportant server_name
syn keyword ngxDirectiveImportant listen
syn keyword ngxDirectiveImportant internal
syn keyword ngxDirectiveImportant proxy_pass
syn keyword ngxDirectiveImportant memcached_pass
syn keyword ngxDirectiveImportant fastcgi_pass
syn keyword ngxDirectiveImportant try_files