1
0
Fork 0
mirror of synced 2024-12-25 08:13:20 -05:00

add vim-jsx, vim-javascript

This commit is contained in:
Chris Hu 2016-08-18 08:41:38 +08:00 committed by Huaishun Hu
parent 35f23c0128
commit db2bf731a3
15 changed files with 1209 additions and 0 deletions

View file

@ -0,0 +1,18 @@
## Contributing
This project uses the [git
flow](http://nvie.com/posts/a-successful-git-branching-model/) model for
development. There's [a handy git module for git
flow](//github.com/nvie/gitflow). If you'd like to be added as a contributor,
the price of admission is 1 pull request. Please follow the general code style
guides (read the code) and in your pull request explain the reason for the
proposed change and how it is valuable.
## Pull Requests
Please make your pull requests against the `develop` branch; we stage changes
for testing there to avoid unexpected breakages for our users. :)
## Bug report
Report a bug on [GitHub Issues](https://github.com/pangloss/vim-javascript/issues).

View file

@ -0,0 +1,119 @@
# vim-javascript
JavaScript bundle for vim, this bundle provides syntax highlighting and
improved indentation.
## Installation
### Install with [Vundle](https://github.com/gmarik/vundle)
Add to vimrc:
Plugin 'pangloss/vim-javascript'
And install it:
:so ~/.vimrc
:PluginInstall
### Install with [vim-plug](https://github.com/junegunn/vim-plug)
Add to vimrc:
Plug 'pangloss/vim-javascript'
And install it:
:so ~/.vimrc
:PlugInstall
### Install with [pathogen](https://github.com/tpope/vim-pathogen)
git clone https://github.com/pangloss/vim-javascript.git ~/.vim/bundle/vim-javascript
## Configuration Variables
The following variables control certain syntax highlighting plugins. You can
add them to your `.vimrc` to enable their features.
-----------------
```
let g:javascript_plugin_jsdoc = 1
```
Enables syntax highlighting for [JSDocs](http://usejsdoc.org/).
Default Value: 0
-----------------
```
let g:javascript_plugin_ngdoc = 1
```
Enables some additional syntax highlighting for NGDocs. Requires JSDoc plugin
to be enabled as well.
Default Value: 0
-----------------
```
let g:javascript_plugin_flow = 1
```
Enables syntax highlighting for [Flow](https://flowtype.org/).
Default Value: 0
-----------------
```
set foldmethod=syntax
```
Enables code folding based on our syntax file.
Please note this can have a dramatic effect on performance and because it is a
global vim option, we do not set it ourselves.
## Concealing Characters
You can customize concealing characters by defining one or more of the following
variables:
let g:javascript_conceal_function = "ƒ"
let g:javascript_conceal_null = "ø"
let g:javascript_conceal_this = "@"
let g:javascript_conceal_return = "⇚"
let g:javascript_conceal_undefined = "¿"
let g:javascript_conceal_NaN = ""
let g:javascript_conceal_prototype = "¶"
let g:javascript_conceal_static = "•"
let g:javascript_conceal_super = "Ω"
let g:javascript_conceal_arrow_function = "⇒"
## Contributing
This project uses the [git
flow](http://nvie.com/posts/a-successful-git-branching-model/) model for
development. There's [a handy git module for git
flow](//github.com/nvie/gitflow). If you'd like to be added as a contributor,
the price of admission is 1 pull request. Please follow the general code style
guides (read the code) and in your pull request explain the reason for the
proposed change and how it is valuable.
## Bug Reports
Report a bug on [GitHub Issues](https://github.com/pangloss/vim-javascript/issues).
## License
Distributed under the same terms as Vim itself. See `:help license`.

View file

@ -0,0 +1,8 @@
" Vim filetype plugin file
" Language: JavaScript
" Maintainer: vim-javascript community
" URL: https://github.com/pangloss/vim-javascript
setlocal iskeyword+=$ suffixesadd+=.js
let b:undo_ftplugin .= ' | setlocal iskeyword< suffixesadd<'

View file

@ -0,0 +1,8 @@
--langdef=js
--langmap=js:.js
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\{/\1/,object/
--regex-js=/([A-Za-z0-9._$()]+)[ \t]*[:=][ \t]*function[ \t]*\(/\1/,function/
--regex-js=/function[ \t]+([A-Za-z0-9._$]+)[ \t]*([^)])/\1/,function/
--regex-js=/([A-Za-z0-9._$]+)[ \t]*[:=][ \t]*\[/\1/,array/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^"]'[^']*/\1/,string/
--regex-js=/([^= ]+)[ \t]*=[ \t]*[^']"[^"]*/\1/,string/

View file

@ -0,0 +1,87 @@
syntax region jsFlowDefinition contained start=/:/ end=/\%(\s*[,=;)\n]\)\@=/ contains=@jsFlowCluster containedin=jsParen
syntax region jsFlowArgumentDef contained start=/:/ end=/\%(\s*[,)]\|=>\@!\)\@=/ contains=@jsFlowCluster
syntax region jsFlowArray contained matchgroup=jsFlowNoise start=/\[/ end=/\]/ contains=@jsFlowCluster
syntax region jsFlowObject contained matchgroup=jsFlowNoise start=/{/ end=/}/ contains=@jsFlowCluster
syntax region jsFlowParens contained matchgroup=jsFlowNoise start=/(/ end=/)/ contains=@jsFlowCluster
syntax match jsFlowNoise contained /[:;,<>]/
syntax keyword jsFlowType contained boolean number string null void any mixed JSON array function object array bool class
syntax keyword jsFlowTypeof contained typeof skipempty skipempty nextgroup=jsFlowTypeCustom,jsFlowType
syntax match jsFlowTypeCustom contained /\k*/ skipwhite skipempty nextgroup=jsFlowGroup
syntax region jsFlowGroup contained matchgroup=jsFlowNoise start=/</ end=/>/ contains=@jsFlowCluster
syntax region jsFlowArrowArguments contained matchgroup=jsFlowNoise start=/(/ end=/)\%(\s*=>\)\@=/ oneline skipwhite skipempty nextgroup=jsFlowArrow contains=@jsFlowCluster
syntax match jsFlowArrow contained /=>/ skipwhite skipempty nextgroup=jsFlowType,jsFlowTypeCustom,jsFlowParens
syntax match jsFlowMaybe contained /?/ skipwhite skipempty nextgroup=jsFlowType,jsFlowTypeCustom,jsFlowParens,jsFlowArrowArguments
syntax match jsFlowObjectKey contained /[0-9a-zA-Z_$?]*\(\s*:\)\@=/ contains=jsFunctionKey,jsFlowMaybe skipwhite skipempty nextgroup=jsObjectValue containedin=jsObject
syntax match jsFlowOrOperator contained /|/ skipwhite skipempty nextgroup=@jsFlowCluster
syntax match jsFlowReturn contained /:\s*/ contains=jsFlowNoise skipwhite skipempty nextgroup=@jsFlowReturnCluster
syntax region jsFlowReturnObject contained matchgroup=jsFlowNoise start=/{/ end=/}/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsFuncBlock,jsFlowReturnOrOp
syntax region jsFlowReturnArray contained matchgroup=jsFlowNoise start=/\[/ end=/\]/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsFuncBlock,jsFlowReturnOrOp
syntax region jsFlowReturnParens contained matchgroup=jsFlowNoise start=/(/ end=/)/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsFuncBlock,jsFlowReturnOrOp
syntax match jsFlowReturnKeyword contained /\k\+/ contains=jsFlowType,jsFlowTypeCustom skipwhite skipempty nextgroup=jsFlowReturnGroup,jsFuncBlock,jsFlowReturnOrOp
syntax match jsFlowReturnMaybe contained /?/ skipwhite skipempty nextgroup=jsFlowReturnKeyword
syntax region jsFlowReturnGroup contained matchgroup=jsFlowNoise start=/</ end=/>/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsFuncBlock,jsFlowReturnOrOp
syntax match jsFlowReturnOrOp contained /\s*|\s*/ skipwhite skipempty nextgroup=@jsFlowReturnCluster
syntax region jsFlowFunctionGroup contained matchgroup=jsFlowNoise start=/</ end=/>/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsFuncArgs
syntax region jsFlowClassGroup contained matchgroup=jsFlowNoise start=/</ end=/>/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsClassBlock
syntax region jsFlowTypeStatement start=/type/ end=/=\@=/ contains=jsFlowTypeOperator oneline skipwhite skipempty nextgroup=jsFlowTypeValue keepend
syntax region jsFlowTypeValue contained start=/=/ end=/[;\n]/ contains=@jsExpression,jsFlowGroup,jsFlowMaybe
syntax match jsFlowTypeOperator contained /=/
syntax keyword jsFlowTypeKeyword contained type
syntax keyword jsFlowDeclare declare skipwhite skipempty nextgroup=jsFlowTypeStatement,jsClassDefinition,jsStorageClass,jsFlowModule,jsFlowInterface
syntax match jsFlowClassProperty contained /\<[0-9a-zA-Z_$]*\>:\@=/ skipwhite skipempty nextgroup=jsFlowClassDef containedin=jsClassBlock
syntax region jsFlowClassDef contained start=/:/ end=/\%(\s*[,=;)\n]\)\@=/ contains=@jsFlowCluster skipwhite skipempty nextgroup=jsClassValue
syntax region jsFlowModule contained start=/module/ end=/{\@=/ skipempty skipempty nextgroup=jsFlowDeclareBlock contains=jsString
syntax region jsFlowInterface contained start=/interface/ end=/{\@=/ skipempty skipempty nextgroup=jsFlowInterfaceBlock contains=@jsFlowCluster
syntax region jsFlowDeclareBlock contained matchgroup=jsFlowNoise start=/{/ end=/}/ contains=jsFlowDeclare,jsFlowNoise
syntax region jsFlowInterfaceBlock contained matchgroup=jsFlowNoise start=/{/ end=/}/ contains=jsObjectKey,jsObjectKeyString,jsObjectKeyComputed,jsObjectSeparator,jsObjectFuncName,jsObjectMethodType,jsGenerator,jsComment,jsObjectStringKey,jsSpreadExpression,jsFlowNoise keepend
syntax cluster jsFlowReturnCluster contains=jsFlowNoise,jsFlowReturnObject,jsFlowReturnArray,jsFlowReturnKeyword,jsFlowReturnGroup,jsFlowReturnMaybe,jsFlowReturnOrOp
syntax cluster jsFlowCluster contains=jsFlowArray,jsFlowObject,jsFlowNoise,jsFlowTypeof,jsFlowType,jsFlowGroup,jsFlowArrowArguments,jsFlowMaybe,jsFlowParens,jsFlowOrOperator
if version >= 508 || !exists("did_javascript_syn_inits")
if version < 508
let did_javascript_syn_inits = 1
command -nargs=+ HiLink hi link <args>
else
command -nargs=+ HiLink hi def link <args>
endif
HiLink jsFlowDefinition PreProc
HiLink jsFlowClassDef jsFlowDefinition
HiLink jsFlowArgumentDef jsFlowDefinition
HiLink jsFlowType Type
HiLink jsFlowTypeCustom PreProc
HiLink jsFlowTypeof PreProc
HiLink jsFlowArray PreProc
HiLink jsFlowObject PreProc
HiLink jsFlowParens PreProc
HiLink jsFlowGroup PreProc
HiLink jsFlowReturn PreProc
HiLink jsFlowReturnObject jsFlowReturn
HiLink jsFlowReturnArray jsFlowArray
HiLink jsFlowReturnParens jsFlowParens
HiLink jsFlowReturnGroup jsFlowGroup
HiLink jsFlowFunctionGroup PreProc
HiLink jsFlowClassGroup PreProc
HiLink jsFlowArrowArguments PreProc
HiLink jsFlowArrow PreProc
HiLink jsFlowTypeStatement PreProc
HiLink jsFlowTypeKeyword PreProc
HiLink jsFlowTypeOperator PreProc
HiLink jsFlowMaybe PreProc
HiLink jsFlowReturnMaybe PreProc
HiLink jsFlowClassProperty jsClassProperty
HiLink jsFlowDeclare PreProc
HiLink jsFlowModule PreProc
HiLink jsFlowInterface PreProc
HiLink jsFlowNoise Noise
HiLink jsFlowObjectKey jsObjectKey
HiLink jsFlowOrOperator PreProc
HiLink jsFlowReturnOrOp jsFlowOrOperator
delcommand HiLink
endif

View file

@ -0,0 +1,39 @@
"" syntax coloring for javadoc comments (HTML)
syntax region jsComment matchgroup=jsComment start="/\*\s*" end="\*/" contains=jsDocTags,jsCommentTodo,jsCvsTag,@jsHtml,@Spell fold
" tags containing a param
syntax match jsDocTags contained "@\(alias\|api\|augments\|borrows\|class\|constructs\|default\|defaultvalue\|emits\|exception\|exports\|extends\|fires\|kind\|link\|listens\|member\|member[oO]f\|mixes\|module\|name\|namespace\|requires\|template\|throws\|var\|variation\|version\)\>" skipwhite nextgroup=jsDocParam
" tags containing type and param
syntax match jsDocTags contained "@\(arg\|argument\|cfg\|param\|property\|prop\)\>" skipwhite nextgroup=jsDocType
" tags containing type but no param
syntax match jsDocTags contained "@\(callback\|define\|enum\|external\|implements\|this\|type\|typedef\|return\|returns\)\>" skipwhite nextgroup=jsDocTypeNoParam
" tags containing references
syntax match jsDocTags contained "@\(lends\|see\|tutorial\)\>" skipwhite nextgroup=jsDocSeeTag
" other tags (no extra syntax)
syntax match jsDocTags contained "@\(abstract\|access\|accessor\|author\|classdesc\|constant\|const\|constructor\|copyright\|deprecated\|desc\|description\|dict\|event\|example\|file\|file[oO]verview\|final\|function\|global\|ignore\|inheritDoc\|inner\|instance\|interface\|license\|localdoc\|method\|mixin\|nosideeffects\|override\|overview\|preserve\|private\|protected\|public\|readonly\|since\|static\|struct\|todo\|summary\|undocumented\|virtual\)\>"
syntax region jsDocType contained matchgroup=jsDocTypeBrackets start="{" end="}" contains=jsDocTypeRecord oneline skipwhite nextgroup=jsDocParam
syntax match jsDocType contained "\%(#\|\"\|\w\|\.\|:\|\/\)\+" skipwhite nextgroup=jsDocParam
syntax region jsDocTypeRecord contained start=/{/ end=/}/ contains=jsDocTypeRecord extend
syntax region jsDocTypeRecord contained start=/\[/ end=/\]/ contains=jsDocTypeRecord extend
syntax region jsDocTypeNoParam contained start="{" end="}" oneline
syntax match jsDocTypeNoParam contained "\%(#\|\"\|\w\|\.\|:\|\/\)\+"
syntax match jsDocParam contained "\%(#\|\$\|-\|'\|\"\|{.\{-}}\|\w\|\.\|:\|\/\|\[.{-}]\|=\)\+"
syntax region jsDocSeeTag contained matchgroup=jsDocSeeTag start="{" end="}" contains=jsDocTags
if version >= 508 || !exists("did_javascript_syn_inits")
if version < 508
let did_javascript_syn_inits = 1
command -nargs=+ HiLink hi link <args>
else
command -nargs=+ HiLink hi def link <args>
endif
HiLink jsDocTags Special
HiLink jsDocSeeTag Function
HiLink jsDocType Type
HiLink jsDocTypeBrackets jsDocType
HiLink jsDocTypeRecord jsDocType
HiLink jsDocTypeNoParam Type
HiLink jsDocParam Label
delcommand HiLink
endif

View file

@ -0,0 +1,3 @@
syntax match jsDocTags contained /@\(link\|method[oO]f\|ngdoc\|ng[iI]nject\|restrict\)/ nextgroup=jsDocParam skipwhite
syntax match jsDocType contained "\%(#\|\$\|\w\|\"\|-\|\.\|:\|\/\)\+" nextgroup=jsDocParam skipwhite
syntax match jsDocParam contained "\%(#\|\$\|\w\|\"\|-\|\.\|:\|{\|}\|\/\|\[\|]\|=\)\+"

View file

@ -0,0 +1,10 @@
au BufNewFile,BufRead *.js setf javascript
au BufNewFile,BufRead *.jsm setf javascript
au BufNewFile,BufRead Jakefile setf javascript
fun! s:SelectJavascript()
if getline(1) =~# '^#!.*/bin/\%(env\s\+\)\?node\>'
set ft=javascript
endif
endfun
au BufNewFile,BufRead * call s:SelectJavascript()

View file

@ -0,0 +1,198 @@
" Vim indent file
" Language: Javascript
" Maintainer: vim-javascript community
" URL: https://github.com/pangloss/vim-javascript
" Acknowledgement: Based off of vim-ruby maintained by Nikolai Weibull http://vim-ruby.rubyforge.org
" Only load this indent file when no other was loaded.
if exists("b:did_indent")
finish
endif
let b:did_indent = 1
" Now, set up our indentation expression and keys that trigger it.
setlocal indentexpr=GetJavascriptIndent()
setlocal nolisp
setlocal indentkeys=0{,0},0),0],:,!^F,o,O,e
setlocal cinoptions+=j1,J1
let b:undo_indent = 'setlocal indentexpr< indentkeys< cinoptions<'
" Only define the function once.
if exists("*GetJavascriptIndent")
finish
endif
let s:cpo_save = &cpo
set cpo&vim
" Get shiftwidth value
if exists('*shiftwidth')
func s:sw()
return shiftwidth()
endfunc
else
func s:sw()
return &sw
endfunc
endif
let s:line_pre = '^\s*\%(\/\*.*\*\/\s*\)*'
let s:expr_case = s:line_pre . '\%(\%(case\>.*\)\|default\)\s*:\C'
" Regex of syntax group names that are or delimit string or are comments.
let s:syng_strcom = '\%(string\|regex\|special\|doc\|comment\|template\)\c'
" Regex of syntax group names that are strings or documentation.
let s:syng_comment = '\%(comment\|doc\)\c'
" Expression used to check whether we should skip a match with searchpair().
let s:skip_expr = "line('.') < (prevnonblank(v:lnum) - 2000) ? dummy : s:IsSyn(line('.'),col('.'),'')"
func s:lookForParens(start,end,flags,time)
try
return searchpair(a:start,'',a:end,a:flags,s:skip_expr,0,a:time)
catch /E118/
return searchpair(a:start,'',a:end,a:flags,0,0)
endtry
endfunc
let s:line_term = '\s*\%(\%(:\@<!\/\/.*\)\=\|\%(\/\*.*\*\/\s*\)*\)$'
" configurable regexes that define continuation lines, not including (, {, or [.
if !exists('g:javascript_opfirst')
let g:javascript_opfirst = '\%([,:?^%]\|\([-/.+]\)\%(\1\|\*\|\/\)\@!\|\*\/\@!\|=>\@!\||\|&\|in\%(stanceof\)\=\>\)\C'
endif
let g:javascript_opfirst = s:line_pre . g:javascript_opfirst
if !exists('g:javascript_continuation')
let g:javascript_continuation = '\%([*,.?:^%]\|+\@<!+\|-\@<!-\|\*\@<!\/\|=\||\|&\|\<in\%(stanceof\)\=\)\C'
endif
let g:javascript_continuation .= s:line_term
function s:Onescope(lnum,text,add)
return a:text =~ '\%(\<else\|\<do\|=>' . (a:add ? '\|\<try\|\<finally' : '' ) . '\)\C' . s:line_term ||
\ (a:add && a:text =~ s:line_pre . s:line_term && getline(s:PrevCodeLine(a:lnum - 1)) =~ ')' . s:line_term) ||
\ (cursor(a:lnum, match(a:text, ')' . s:line_term)) > -1 &&
\ s:lookForParens('(', ')', 'cbW', 100) > 0 &&
\ search((a:add ? '\%(function\*\|[A-Za-z_$][0-9A-Za-z_$]*\)\C' :
\ '\<\%(for\%(\s+each\)\=\|if\|let\|switch\|while\|with\)\C') . '\_s*\%#','bW')) &&
\ (a:add || (expand("<cword>") == 'while' ? !s:lookForParens('\<do\>\C', '\<while\>\C','bW',100) : 1))
endfunction
" Auxiliary Functions {{{2
" Check if the character at lnum:col is inside a string, comment, or is ascii.
function s:IsSyn(lnum, col, reg)
return synIDattr(synID(a:lnum, a:col, 1), 'name') =~? (a:reg != '' ? a:reg : s:syng_strcom)
endfunction
" Find line above 'lnum' that isn't empty, in a comment, or in a string.
function s:PrevCodeLine(lnum)
let lnum = prevnonblank(a:lnum)
while lnum > 0
if !s:IsSyn(lnum, matchend(getline(lnum), '^\s*[^''"]'),'')
break
endif
let lnum = prevnonblank(lnum - 1)
endwhile
return lnum
endfunction
" Check if line 'lnum' has more opening brackets than closing ones.
function s:LineHasOpeningBrackets(lnum)
let open_0 = 0
let open_2 = 0
let open_4 = 0
let line = getline(a:lnum)
let pos = match(line, '[][(){}]', 0)
let last = 0
while pos != -1
if !s:IsSyn(a:lnum, pos + 1, '')
let idx = stridx('(){}[]', line[pos])
if idx % 2 == 0
let open_{idx} = open_{idx} + 1
let last = pos
else
let open_{idx - 1} = open_{idx - 1} - 1
endif
endif
let pos = match(line, '[][(){}]', pos + 1)
endwhile
return [(open_0 > 0 ? 1 : (open_0 == 0 ? 0 : 2)) . (open_2 > 0 ? 1 : (open_2 == 0 ? 0 : 2)) .
\ (open_4 > 0 ? 1 : (open_4 == 0 ? 0 : 2)), last]
endfunction
" }}}
function GetJavascriptIndent()
if !exists('b:js_cache')
let b:js_cache = [0,0,0]
end
" Get the current line.
let line = getline(v:lnum)
" previous nonblank line number
let prevline = prevnonblank(v:lnum - 1)
" previous line of code
let lnum = s:PrevCodeLine(v:lnum - 1)
if lnum == 0
return 0
endif
" start with strings,comments,etc.{{{2
if (line !~ '^[''"`]' && s:IsSyn(v:lnum,1,'string\|template')) ||
\ (line !~ '^\s*[/*]' && s:IsSyn(v:lnum,1,s:syng_comment))
return -1
endif
if line !~ '^\%(\/\*\|\s*\/\/\)' && s:IsSyn(v:lnum,1,s:syng_comment)
return cindent(v:lnum)
endif
if (line =~ s:expr_case)
let cpo_switch = &cpo
set cpo+=%
let ind = cindent(v:lnum)
let &cpo = cpo_switch
return ind
endif
"}}}
" the containing paren, bracket, curly
let pcounts = [0]
if b:js_cache[0] >= lnum && b:js_cache[0] <= v:lnum && b:js_cache[0] &&
\ (b:js_cache[0] > lnum || map(pcounts,'s:LineHasOpeningBrackets(lnum)')[0][0] !~ '2')
let num = pcounts[0][0] =~ '1' ? lnum : b:js_cache[1]
if pcounts[0][0] =~'1'
call cursor(lnum,pcounts[0][1])
end
else
call cursor(v:lnum,1)
let syns = synIDattr(synID(v:lnum, 1, 1), 'name')
if line[0] =~ '\s' && syns != ''
let pattern = syns =~? 'funcblock' ? ['{','}'] : syns =~? 'jsparen' ? ['(',')'] : syns =~? 'jsbracket'? ['\[','\]'] :
\ ['(\|{\|\[',')\|}\|\]']
let num = s:lookForParens(pattern[0],pattern[1],'bW',2000)
else
let num = s:lookForParens('(\|{\|\[',')\|}\|\]','bW',2000)
end
end
let b:js_cache = [v:lnum,num,line('.') == v:lnum ? b:js_cache[2] : col('.')]
" most significant part
if line =~ s:line_pre . '[])}]'
return indent(num)
end
let inb = num == 0 ? 1 : s:Onescope(num, strpart(getline(num),0,b:js_cache[2] - 1),1)
let switch_offset = (!inb || num == 0) || expand("<cword>") != 'switch' ? 0 : &cino !~ ':' || !has('float') ? s:sw() :
\ float2nr(str2float(matchstr(&cino,'.*:\zs[-0-9.]*')) * (match(&cino,'.*:\zs[^,]*s') ? s:sw() : 1))
if ((line =~ g:javascript_opfirst ||
\ (getline(lnum) =~ g:javascript_continuation && getline(lnum) !~ s:expr_case)) &&
\ inb) || (s:Onescope(lnum,getline(lnum),0) && line !~ s:line_pre . '{')
return (num > 0 ? indent(num) : -s:sw()) + (s:sw() * 2) + switch_offset
elseif num > 0
return indent(num) + s:sw() + switch_offset
end
endfunction
let &cpo = s:cpo_save
unlet s:cpo_save

View file

@ -0,0 +1,354 @@
" Vim syntax file
" Language: JavaScript
" Maintainer: vim-javascript community
" URL: https://github.com/pangloss/vim-javascript
if !exists("main_syntax")
if version < 600
syntax clear
elseif exists("b:current_syntax")
finish
endif
let main_syntax = 'javascript'
endif
" Dollar sign is permitted anywhere in an identifier
if v:version > 704 || v:version == 704 && has('patch1142')
syntax iskeyword @,48-57,_,192-255,$
else
setlocal iskeyword+=$
endif
syntax sync fromstart
" TODO: Figure out what type of casing I need
" syntax case ignore
syntax case match
syntax match jsNoise /[:,\;\.]\{1}/
syntax match jsFuncCall /\k\+\%(\s*(\)\@=/
syntax match jsParensError /[)}\]]/
" Program Keywords
syntax keyword jsStorageClass const var let skipwhite skipempty nextgroup=jsDestructuringBlock,jsDestructuringArray,jsVariableDef
syntax match jsVariableDef contained /\k\+/ nextgroup=jsFlowDefinition
syntax keyword jsOperator delete instanceof typeof void new in of
syntax match jsOperator /[\!\|\&\+\-\<\>\=\%\/\*\~\^]\{1}/
syntax keyword jsBooleanTrue true
syntax keyword jsBooleanFalse false
" Modules
syntax keyword jsModuleKeywords contained import
syntax keyword jsModuleKeywords contained export skipwhite skipempty nextgroup=jsExportBlock,jsModuleDefault
syntax keyword jsModuleOperators contained from
syntax keyword jsModuleOperators contained as
syntax region jsModuleGroup contained matchgroup=jsBraces start=/{/ end=/}/ contains=jsModuleOperators,jsNoise,jsComment
syntax match jsModuleAsterisk contained /*/
syntax keyword jsModuleDefault contained default skipwhite skipempty nextgroup=@jsExpression
syntax region jsImportContainer start=/\<import\> / end="\%(;\|$\)" contains=jsModuleKeywords,jsModuleOperators,jsComment,jsString,jsTemplateString,jsNoise,jsModuleGroup,jsModuleAsterisk
syntax region jsExportContainer start=/\<export\> / end="\%(;\|$\)" contains=jsModuleKeywords,jsModuleOperators,jsStorageClass,jsModuleDefault,@jsExpression
syntax region jsExportBlock contained matchgroup=jsBraces start=/{/ end=/}/ contains=jsModuleOperators,jsNoise,jsComment
" Strings, Templates, Numbers
syntax region jsString start=+"+ skip=+\\\("\|$\)+ end=+"\|$+ contains=jsSpecial,@Spell extend
syntax region jsString start=+'+ skip=+\\\('\|$\)+ end=+'\|$+ contains=jsSpecial,@Spell extend
syntax region jsTemplateString start=+`+ skip=+\\\(`\|$\)+ end=+`+ contains=jsTemplateVar,jsSpecial extend
syntax match jsTaggedTemplate /\k\+\%(`\)\@=/ nextgroup=jsTemplateString
syntax match jsNumber /\<\d\+\%([eE][+-]\=\d\+\)\=\>\|\<0[bB][01]\+\>\|\<0[oO]\o\+\>\|\<0[xX]\x\+\>/
syntax keyword jsNumber Infinity
syntax match jsFloat /\<\%(\d\+\.\d\+\|\d\+\.\|\.\d\+\)\%([eE][+-]\=\d\+\)\=\>/
" Regular Expressions
syntax match jsSpecial contained "\v\\%(0|\\x\x\{2\}\|\\u\x\{4\}\|\c[A-Z]|.)"
syntax region jsTemplateVar contained matchgroup=jsTemplateBraces start=+${+ end=+}+ contains=@jsExpression
syntax region jsRegexpCharClass contained start=+\[+ skip=+\\.+ end=+\]+
syntax match jsRegexpBoundary contained "\v%(\<@![\^$]|\\[bB])"
syntax match jsRegexpBackRef contained "\v\\[1-9][0-9]*"
syntax match jsRegexpQuantifier contained "\v\\@<!%([?*+]|\{\d+%(,|,\d+)?})\??"
syntax match jsRegexpOr contained "\v\<@!\|"
syntax match jsRegexpMod contained "\v\(@<=\?[:=!>]"
syntax region jsRegexpGroup contained start="\\\@<!(" skip="\\.\|\[\(\\.\|[^]]\)*\]" end="\\\@<!)" contains=jsRegexpCharClass,@jsRegexpSpecial keepend
if v:version > 703 || v:version == 603 && has("patch1088")
syntax region jsRegexpString start=+\%(\%(\%(return\|case\)\s\+\)\@50<=\|\%(\%([)\]"']\|\d\|\w\)\s*\)\@50<!\)/\(\*\|/\)\@!+ skip=+\\.\|\[\%(\\.\|[^]]\)*\]+ end=+/[gimy]\{,4}+ contains=jsRegexpCharClass,jsRegexpGroup,@jsRegexpSpecial oneline keepend extend
else
syntax region jsRegexpString start=+\%(\%(\%(return\|case\)\s\+\)\@<=\|\%(\%([)\]"']\|\d\|\w\)\s*\)\@<!\)/\(\*\|/\)\@!+ skip=+\\.\|\[\%(\\.\|[^]]\)*\]+ end=+/[gimy]\{,4}+ contains=jsRegexpCharClass,jsRegexpGroup,@jsRegexpSpecial oneline keepend extend
endif
syntax cluster jsRegexpSpecial contains=jsSpecial,jsRegexpBoundary,jsRegexpBackRef,jsRegexpQuantifier,jsRegexpOr,jsRegexpMod
syntax match jsObjectKey contained /\<[0-9a-zA-Z_$]*\>\(\s*:\)\@=/ contains=jsFunctionKey skipwhite skipempty nextgroup=jsObjectValue
syntax region jsObjectKeyString contained start=+"+ skip=+\\\("\|$\)+ end=+"\|$+ contains=jsSpecial,@Spell skipwhite skipempty nextgroup=jsObjectValue
syntax region jsObjectKeyString contained start=+'+ skip=+\\\('\|$\)+ end=+'\|$+ contains=jsSpecial,@Spell skipwhite skipempty nextgroup=jsObjectValue
syntax region jsObjectKeyComputed contained matchgroup=jsBrackets start=/\[/ end=/]/ contains=@jsExpression skipwhite skipempty nextgroup=jsObjectValue,jsFuncArgs extend
syntax match jsObjectSeparator contained /,/
syntax region jsObjectValue contained start=/:/ end=/\%(,\|}\)\@=/ contains=@jsExpression extend
syntax match jsObjectFuncName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*\>[\r\n\t ]*(\@=/ skipwhite skipempty nextgroup=jsFuncArgs
syntax match jsFunctionKey contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*\>\(\s*:\s*function\s*\)\@=/
syntax match jsObjectMethodType contained /\%(get\|set\|static\|async\)\%( \k\+\)\@=/ skipwhite skipempty nextgroup=jsObjectFuncName
syntax region jsObjectStringKey contained start=+"+ skip=+\\\("\|$\)+ end=+"\|$+ contains=jsSpecial,@Spell extend skipwhite skipempty nextgroup=jsFuncArgs,jsObjectValue
syntax region jsObjectStringKey contained start=+'+ skip=+\\\('\|$\)+ end=+'\|$+ contains=jsSpecial,@Spell extend skipwhite skipempty nextgroup=jsFuncArgs,jsObjectValue
exe 'syntax keyword jsNull null '.(exists('g:javascript_conceal_null') ? 'conceal cchar='.g:javascript_conceal_null : '')
exe 'syntax keyword jsReturn return contained '.(exists('g:javascript_conceal_return') ? 'conceal cchar='.g:javascript_conceal_return : '')
exe 'syntax keyword jsUndefined undefined '.(exists('g:javascript_conceal_undefined') ? 'conceal cchar='.g:javascript_conceal_undefined : '')
exe 'syntax keyword jsNan NaN '.(exists('g:javascript_conceal_NaN') ? 'conceal cchar='.g:javascript_conceal_NaN : '')
exe 'syntax keyword jsPrototype prototype '.(exists('g:javascript_conceal_prototype') ? 'conceal cchar='.g:javascript_conceal_prototype : '')
exe 'syntax keyword jsThis this contained '.(exists('g:javascript_conceal_this') ? 'conceal cchar='.g:javascript_conceal_this : '')
exe 'syntax keyword jsSuper super contained '.(exists('g:javascript_conceal_super') ? 'conceal cchar='.g:javascript_conceal_super : '')
" Statement Keywords
syntax keyword jsStatement contained break continue with yield debugger
syntax keyword jsConditional if skipwhite skipempty nextgroup=jsParenIfElse
syntax keyword jsConditional else skipwhite skipempty nextgroup=jsCommentMisc,jsBlock
syntax keyword jsConditional switch skipwhite skipempty nextgroup=jsParenSwitch
syntax keyword jsRepeat while for skipwhite skipempty nextgroup=jsParenRepeat
syntax keyword jsDo do skipwhite skipempty nextgroup=jsBlock
syntax keyword jsLabel contained case default
syntax keyword jsTry try skipwhite skipempty nextgroup=jsTryCatchBlock
syntax keyword jsFinally contained finally skipwhite skipempty nextgroup=jsBlock
syntax keyword jsCatch contained catch skipwhite skipempty nextgroup=jsParenCatch
syntax keyword jsException throw
syntax keyword jsAsyncKeyword async await
syntax match jsSwitchColon contained /:/ skipwhite skipempty nextgroup=jsBlock
" Keywords
syntax keyword jsGlobalObjects Array Boolean Date Function Iterator Number Object Symbol Map WeakMap Set RegExp String Proxy Promise Buffer ParallelArray ArrayBuffer DataView Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray JSON Math console document window Intl Collator DateTimeFormat NumberFormat
syntax keyword jsGlobalNodeObjects module exports global process
syntax match jsGlobalNodeObjects /require/ contains=jsFuncCall
syntax keyword jsExceptions Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError
syntax keyword jsBuiltins decodeURI decodeURIComponent encodeURI encodeURIComponent eval isFinite isNaN parseFloat parseInt uneval
" DISCUSS: How imporant is this, really? Perhaps it should be linked to an error because I assume the keywords are reserved?
syntax keyword jsFutureKeys abstract enum int short boolean interface byte long char final native synchronized float package throws goto private transient implements protected volatile double public
" DISCUSS: Should we really be matching stuff like this?
" DOM2 Objects
syntax keyword jsGlobalObjects DOMImplementation DocumentFragment Document Node NodeList NamedNodeMap CharacterData Attr Element Text Comment CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction
syntax keyword jsExceptions DOMException
" DISCUSS: Should we really be matching stuff like this?
" DOM2 CONSTANT
syntax keyword jsDomErrNo INDEX_SIZE_ERR DOMSTRING_SIZE_ERR HIERARCHY_REQUEST_ERR WRONG_DOCUMENT_ERR INVALID_CHARACTER_ERR NO_DATA_ALLOWED_ERR NO_MODIFICATION_ALLOWED_ERR NOT_FOUND_ERR NOT_SUPPORTED_ERR INUSE_ATTRIBUTE_ERR INVALID_STATE_ERR SYNTAX_ERR INVALID_MODIFICATION_ERR NAMESPACE_ERR INVALID_ACCESS_ERR
syntax keyword jsDomNodeConsts ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE COMMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE
" DISCUSS: Should we really be special matching on these props?
" HTML events and internal variables
syntax keyword jsHtmlEvents onblur onclick oncontextmenu ondblclick onfocus onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup onresize
"" Code blocks
syntax region jsBracket matchgroup=jsBrackets start=/\[/ end=/\]/ contains=@jsExpression extend fold
syntax region jsParen matchgroup=jsParens start=/(/ end=/)/ contains=@jsAll extend fold
syntax region jsParenIfElse contained matchgroup=jsParens start=/(/ end=/)/ contains=@jsAll skipwhite skipempty nextgroup=jsCommentMisc,jsBlock extend fold
syntax region jsParenRepeat contained matchgroup=jsParens start=/(/ end=/)/ contains=@jsAll skipwhite skipempty nextgroup=jsCommentMisc,jsBlock extend fold
syntax region jsParenSwitch contained matchgroup=jsParens start=/(/ end=/)/ contains=@jsAll skipwhite skipempty nextgroup=jsSwitchBlock extend fold
syntax region jsParenCatch contained matchgroup=jsParens start=/(/ end=/)/ skipwhite skipempty nextgroup=jsTryCatchBlock extend fold
syntax region jsFuncArgs contained matchgroup=jsFuncParens start=/(/ end=/)/ contains=jsFuncArgCommas,jsComment,jsFuncArgExpression,jsDestructuringBlock,jsRestExpression,jsFlowArgumentDef skipwhite skipempty nextgroup=jsCommentFunction,jsFuncBlock,jsFlowReturn extend fold
syntax region jsClassBlock contained matchgroup=jsClassBraces start=/{/ end=/}/ contains=jsClassFuncName,jsClassMethodType,jsArrowFunction,jsArrowFuncArgs,jsComment,jsGenerator,jsDecorator,jsClassProperty,jsClassPropertyComputed,jsClassStringKey,jsNoise extend fold
syntax region jsFuncBlock contained matchgroup=jsFuncBraces start=/{/ end=/}/ contains=@jsAll extend fold
syntax region jsBlock contained matchgroup=jsBraces start=/{/ end=/}/ contains=@jsAll extend fold
syntax region jsTryCatchBlock contained matchgroup=jsBraces start=/{/ end=/}/ contains=@jsAll skipwhite skipempty nextgroup=jsCatch,jsFinally extend fold
syntax region jsSwitchBlock contained matchgroup=jsBraces start=/{/ end=/}/ contains=@jsAll,jsLabel,jsSwitchColon extend fold
syntax region jsDestructuringBlock contained matchgroup=jsDestructuringBraces start=/{/ end=/}/ contains=jsDestructuringProperty,jsDestructuringAssignment,jsDestructuringNoise,jsDestructuringPropertyComputed,jsSpreadExpression extend fold
syntax region jsDestructuringArray contained matchgroup=jsDestructuringBraces start=/\[/ end=/\]/ contains=jsDestructuringPropertyValue,jsNoise,jsDestructuringProperty,jsSpreadExpression extend fold
syntax region jsObject matchgroup=jsObjectBraces start=/{/ end=/}/ contains=jsObjectKey,jsObjectKeyString,jsObjectKeyComputed,jsObjectSeparator,jsObjectFuncName,jsObjectMethodType,jsGenerator,jsComment,jsObjectStringKey,jsSpreadExpression extend fold
syntax region jsTernaryIf matchgroup=jsTernaryIfOperator start=/?/ end=/\%(:\|[\}]\@=\)/ contains=@jsExpression
syntax region jsSpreadExpression contained matchgroup=jsSpreadOperator start=/\.\.\./ end=/[,}\]]\@=/ contains=@jsExpression
syntax region jsRestExpression contained matchgroup=jsRestOperator start=/\.\.\./ end=/[,)]\@=/
syntax region jsTernaryIf matchgroup=jsTernaryIfOperator start=/?/ end=/\%(:\|[\}]\@=\)/ contains=@jsExpression
syntax match jsGenerator contained /\*/ skipwhite skipempty nextgroup=jsFuncName,jsFuncArgs
syntax match jsFuncName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*\>/ skipwhite skipempty nextgroup=jsFuncArgs,jsFlowFunctionGroup
syntax region jsFuncArgExpression contained matchgroup=jsFuncArgOperator start=/=/ end=/[,)]\@=/ contains=@jsExpression extend
syntax match jsFuncArgCommas contained ','
syntax keyword jsArguments contained arguments
" Matches a single keyword argument with no parens
syntax match jsArrowFuncArgs /\k\+\s*\%(=>\)\@=/ skipwhite contains=jsFuncArgs skipwhite skipempty nextgroup=jsArrowFunction extend
" Matches a series of arguments surrounded in parens
syntax match jsArrowFuncArgs /([^()]*)\s*\(=>\)\@=/ contains=jsFuncArgs skipempty skipwhite nextgroup=jsArrowFunction extend
exe 'syntax match jsFunction /\<function\>/ skipwhite skipempty nextgroup=jsGenerator,jsFuncName,jsFuncArgs skipwhite '.(exists('g:javascript_conceal_function') ? 'conceal cchar='.g:javascript_conceal_function : '')
exe 'syntax match jsArrowFunction /=>/ skipwhite skipempty nextgroup=jsFuncBlock contains=jsFuncBraces '.(exists('g:javascript_conceal_arrow_function') ? 'conceal cchar='.g:javascript_conceal_arrow_function : '')
syntax keyword jsClassKeywords contained extends class
syntax match jsClassNoise contained /\./
syntax match jsClassMethodType contained /\%(get\|set\|static\|async\)\%( \k\+\)\@=/ skipwhite skipempty nextgroup=jsFuncName,jsClassProperty
syntax match jsClassDefinition /\<class\>\%( [a-zA-Z_$][0-9a-zA-Z_$ \n.]*\)*/ contains=jsClassKeywords,jsClassNoise skipwhite skipempty nextgroup=jsCommentClass,jsClassBlock,jsFlowClassGroup
syntax match jsDecorator contained "@" nextgroup=jsDecoratorFunction
syntax match jsDecoratorFunction contained "[a-zA-Z_][a-zA-Z0-9_.]*"
syntax match jsClassProperty contained /\<[0-9a-zA-Z_$]*\>\(\s*=\)\@=/ skipwhite skipempty nextgroup=jsClassValue
syntax region jsClassValue contained start=/=/ end=/\%(;\|}\|\n\)\@=/ contains=@jsExpression
syntax region jsClassPropertyComputed contained matchgroup=jsBrackets start=/\[/ end=/]/ contains=@jsExpression skipwhite skipempty nextgroup=jsFuncArgs,jsClassValue extend
syntax match jsClassFuncName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*\>\%(\s*(\)\@=/ skipwhite skipempty nextgroup=jsFuncArgs
syntax region jsClassStringKey contained start=+"+ skip=+\\\("\|$\)+ end=+"\|$+ contains=jsSpecial,@Spell extend skipwhite skipempty nextgroup=jsFuncArgs
syntax region jsClassStringKey contained start=+'+ skip=+\\\('\|$\)+ end=+'\|$+ contains=jsSpecial,@Spell extend skipwhite skipempty nextgroup=jsFuncArgs
" Destructuring
syntax match jsDestructuringPropertyValue contained /\<[0-9a-zA-Z_$]*\>/
syntax match jsDestructuringProperty contained /\<[0-9a-zA-Z_$]*\>\(\s*=\)\@=/ skipwhite skipempty nextgroup=jsDestructuringValue
syntax match jsDestructuringAssignment contained /\<[0-9a-zA-Z_$]*\>\(\s*:\)\@=/ skipwhite skipempty nextgroup=jsDestructuringValueAssignment
syntax region jsDestructuringValue contained start=/=/ end=/[,}\]]\@=/ contains=@jsExpression extend
syntax region jsDestructuringValueAssignment contained start=/:/ end=/[,}=]\@=/ contains=jsDestructuringPropertyValue,jsDestructuringBlock,jsNoise,jsDestructuringNoise skipwhite skipempty nextgroup=jsDestructuringValue extend
syntax match jsDestructuringNoise contained /[,\[\]]/
syntax region jsDestructuringPropertyComputed contained matchgroup=jsBrackets start=/\[/ end=/]/ contains=@jsExpression skipwhite skipempty nextgroup=jsDestructuringValue,jsDestructuringNoise extend fold
" Comments
syntax keyword jsCommentTodo contained TODO FIXME XXX TBD
syntax region jsComment start=/\/\// end=/$/ contains=jsCommentTodo,@Spell extend keepend
syntax region jsComment start=/\/\*/ end=/\*\// contains=jsCommentTodo,@Spell fold extend keepend
syntax region jsEnvComment start=/\%^#!/ end=/$/ display
" Specialized Comments - These are special comment regexes that are used in
" odd places that maintain the proper nextgroup functionality. It sucks we
" can't make jsComment a skippable type of group for nextgroup
syntax region jsCommentFunction contained start=/\/\// end=/$/ contains=jsCommentTodo,@Spell skipwhite skipempty nextgroup=jsFuncBlock,jsFlowReturn extend keepend
syntax region jsCommentFunction contained start=/\/\*/ end=/\*\// contains=jsCommentTodo,@Spell skipwhite skipempty nextgroup=jsFuncBlock,jsFlowReturn fold extend keepend
syntax region jsCommentClass contained start=/\/\// end=/$/ contains=jsCommentTodo,@Spell skipwhite skipempty nextgroup=jsClassBlock,jsFlowClassGroup extend keepend
syntax region jsCommentClass contained start=/\/\*/ end=/\*\// contains=jsCommentTodo,@Spell skipwhite skipempty nextgroup=jsClassBlock,jsFlowClassGroup fold extend keepend
syntax region jsCommentMisc contained start=/\/\// end=/$/ contains=jsCommentTodo,@Spell skipwhite skipempty nextgroup=jsBlock extend keepend
syntax region jsCommentMisc contained start=/\/\*/ end=/\*\// contains=jsCommentTodo,@Spell skipwhite skipempty nextgroup=jsBlock fold extend keepend
if exists("javascript_plugin_jsdoc")
runtime extras/jsdoc.vim
" NGDoc requires JSDoc
if exists("javascript_plugin_ngdoc")
runtime extras/ngdoc.vim
endif
endif
if exists("javascript_plugin_flow")
runtime extras/flow.vim
endif
syntax cluster jsExpression contains=jsBracket,jsParen,jsObject,jsBlock,jsTernaryIf,jsTaggedTemplate,jsTemplateString,jsString,jsRegexpString,jsNumber,jsFloat,jsOperator,jsBooleanTrue,jsBooleanFalse,jsNull,jsFunction,jsArrowFunction,jsGlobalObjects,jsExceptions,jsFutureKeys,jsDomErrNo,jsDomNodeConsts,jsHtmlEvents,jsFuncCall,jsUndefined,jsNan,jsPrototype,jsBuiltins,jsNoise,jsClassDefinition,jsArrowFunction,jsArrowFuncArgs,jsParensError,jsComment,jsArguments,jsThis,jsSuper,jsDo
syntax cluster jsAll contains=@jsExpression,jsExportContainer,jsImportContainer,jsStorageClass,jsConditional,jsRepeat,jsReturn,jsStatement,jsException,jsTry,jsAsyncKeyword
" Define the default highlighting.
" For version 5.7 and earlier: only when not done already
" For version 5.8 and later: only when an item doesn't have highlighting yet
if version >= 508 || !exists("did_javascript_syn_inits")
if version < 508
let did_javascript_syn_inits = 1
command -nargs=+ HiLink hi link <args>
else
command -nargs=+ HiLink hi def link <args>
endif
HiLink jsComment Comment
HiLink jsEnvComment PreProc
HiLink jsCommentTodo Todo
HiLink jsString String
HiLink jsObjectKeyString String
HiLink jsTemplateString String
HiLink jsObjectStringKey String
HiLink jsClassStringKey String
HiLink jsTaggedTemplate StorageClass
HiLink jsTernaryIfOperator Operator
HiLink jsRegexpString String
HiLink jsRegexpBoundary SpecialChar
HiLink jsRegexpQuantifier SpecialChar
HiLink jsRegexpOr Conditional
HiLink jsRegexpMod SpecialChar
HiLink jsRegexpBackRef SpecialChar
HiLink jsRegexpGroup jsRegexpString
HiLink jsRegexpCharClass Character
HiLink jsCharacter Character
HiLink jsPrototype Special
HiLink jsConditional Conditional
HiLink jsBranch Conditional
HiLink jsLabel Label
HiLink jsReturn Statement
HiLink jsRepeat Repeat
HiLink jsDo Repeat
HiLink jsStatement Statement
HiLink jsException Exception
HiLink jsTry Exception
HiLink jsFinally Exception
HiLink jsCatch Exception
HiLink jsAsyncKeyword Keyword
HiLink jsArrowFunction Type
HiLink jsFunction Type
HiLink jsGenerator jsFunction
HiLink jsArrowFuncArgs jsFuncArgs
HiLink jsFuncName Function
HiLink jsClassFuncName jsFuncName
HiLink jsObjectFuncName Function
HiLink jsArguments Special
HiLink jsError Error
HiLink jsParensError Error
HiLink jsOperator Operator
HiLink jsOf Operator
HiLink jsStorageClass StorageClass
HiLink jsClassKeywords Structure
HiLink jsThis Special
HiLink jsSuper Constant
HiLink jsNan Number
HiLink jsNull Type
HiLink jsUndefined Type
HiLink jsNumber Number
HiLink jsFloat Float
HiLink jsBooleanTrue Boolean
HiLink jsBooleanFalse Boolean
HiLink jsNoise Noise
HiLink jsBrackets Noise
HiLink jsParens Noise
HiLink jsBraces Noise
HiLink jsFuncBraces Noise
HiLink jsFuncParens Noise
HiLink jsClassBraces Noise
HiLink jsClassNoise Noise
HiLink jsObjectBraces Noise
HiLink jsObjectSeparator Noise
HiLink jsSpecial Special
HiLink jsTemplateVar Special
HiLink jsTemplateBraces jsBraces
HiLink jsGlobalObjects Constant
HiLink jsGlobalNodeObjects Constant
HiLink jsExceptions Constant
HiLink jsBuiltins Constant
HiLink jsModuleKeywords Include
HiLink jsModuleOperators Include
HiLink jsModuleDefault Include
HiLink jsDecorator Special
HiLink jsDecoratorFunction Special
HiLink jsFuncArgOperator jsFuncArgs
HiLink jsModuleAsterisk Noise
HiLink jsClassProperty jsObjectKey
HiLink jsSpreadOperator Operator
HiLink jsRestOperator Operator
HiLink jsRestExpression jsFuncArgs
HiLink jsSwitchColon Noise
HiLink jsClassMethodType Type
HiLink jsObjectMethodType Type
HiLink jsClassDefinition jsFuncName
HiLink jsDestructuringBraces Noise
HiLink jsDestructuringProperty jsFuncArgs
HiLink jsDestructuringAssignment jsObjectKey
HiLink jsDestructuringNoise Noise
HiLink jsCommentFunction jsComment
HiLink jsCommentClass jsComment
HiLink jsCommentMisc jsComment
HiLink jsDomErrNo Constant
HiLink jsDomNodeConsts Constant
HiLink jsDomElemAttrs Label
HiLink jsDomElemFuncs PreProc
HiLink jsHtmlEvents Special
HiLink jsHtmlElemAttrs Label
HiLink jsHtmlElemFuncs PreProc
HiLink jsCssStyles Label
delcommand HiLink
endif
" Define the htmlJavaScript for HTML syntax html.vim
syntax cluster htmlJavaScript contains=@jsAll
syntax cluster javaScriptExpression contains=@jsAll
" Vim's default html.vim highlights all javascript as 'Special'
hi! def link javaScript NONE
let b:current_syntax = "javascript"
if main_syntax == 'javascript'
unlet main_syntax
endif

View file

@ -0,0 +1,138 @@
vim-jsx
=======
Syntax highlighting and indenting for JSX. JSX is a JavaScript syntax
transformer which translates inline XML document fragments into JavaScript
objects. It was developed by Facebook alongside [React][1].
vim-jsx is _not_ a JavaScript syntax package, so in order to use it, you will
also need to choose a base JS highlighter. [pangloss/vim-javascript][2] is the
recommended package---it is vim-jsx's "official" dependency, and the only
package against which it is regularly tested. However, vim-jsx makes a best
effort to support other JavaScript syntax packages, including:
- pangloss/vim-javascript
- jelera/vim-javascript-syntax
- othree/yajs
Notably, the system vim JavaScript syntax is _not_ supported, due to its
over-simplicity. However, the system XML syntax package is an implicit
dependency.
Vim support for inline XML in JS is remarkably similar to the same for PHP,
which you can find [here][3].
Troubleshooting
---------------
If you're experiencing incorrect highlighting or indenting in your JSX code,
please file a GitHub issue which includes the following:
- A brief affirmation that you've read the README and have installed one of the
supported dependencies (and the name of the one you're using).
- A minimal ~/.vimrc which repros the issue you're having, as well as both a
paste and a screenshot of the issue (a paste alone is insufficient, since it
doesn't illustrate the specific highlighting or indenting problem). To
obtain a minimal ~/.vimrc, simply bisect your ~/.vimrc by adding `finish` at
various points in the file. (You can likewise bisect your included plugins
by selectively including only half of them, then a quarter, etc.).
Most of the issues filed result from failures to install vim-javascript or
conflicts with existing JS syntax or indent files---so failing to indicate that
you've ruled those issues out may result in your issue being closed with
minimal comment.
(Please feel free to disregard all this for feature requests.)
Usage
-----
By default, JSX syntax highlighting and indenting will be enabled only for
files with the `.jsx` extension. If you would like JSX in `.js` files, add
```viml
let g:jsx_ext_required = 0
```
to your .vimrc or somewhere in your include path. If you wish to restrict JSX
to files with the pre-v0.12 `@jsx React.DOM` pragma, add
```viml
let g:jsx_pragma_required = 1
```
to your .vimrc or somewhere in your include path.
Frequently Asked Questions
--------------------------
- _How come syntax highlighting doesn't work at all?_
This is the only question I'll answer with another question---Which do you
think is more likely: (a) this package fails completely and utterly in serving
its most fundamental purpose, or (b) user error?
- _Why are my end tags colored differently than my start tags?_
vim-jsx is basically the glue that holds JavaScript and XML syntax packages
together in blissful harmony. This means that any XML syntax defaults carry
over to the XML portions of vim, and it's common for many colorschemes to
highlight start and end tags differently due to the system XML syntax defaults.
- _Syntax highlighting seems to work, but breaks highlighting and indenting
further down in the file. What's wrong?_
This often results from trying to enable XML folding in one's `~/.vimrc` (i.e.,
via `let g:xml_syntax_folding = 1`). vim-jsx does not support syntax folding,
and is not tested with either JavaScript or XML folding enabled.
Installation
------------
### Pathogen
The recommended installation method is via [Pathogen][4]. Then simply execute
cd ~/.vim/bundle
git clone https://github.com/mxw/vim-jsx.git
(You can install [vim-javascript][2] in an analogous manner.)
### Vundle
You can also add vim-jsx using [Vundle][5]---just add the following lines to
your `~/.vimrc`:
Plugin 'pangloss/vim-javascript'
Plugin 'mxw/vim-jsx'
To install from within vim, use the commands below.
:so ~/.vimrc
:PluginInstall
Alternatively, use the command below to install the plugins from the command
line.
vim +PluginInstall +qall
### Manual Installation
If you have no `~/.vim/after` directory, you can download the tarball or zip
and copy the contents to `~/.vim`.
If you have existing `~/.vim/after` files, copy the syntax and indent files
directly into their respective destinations. If you have existing after syntax
or indent files for Javascript, you'll probably want to do something like
mkdir -p ~/.vim/after/syntax/javascript
cp path/to/vim-jsx/after/syntax/jsx.vim ~/.vim/after/syntax/javascript/jsx.vim
mkdir -p ~/.vim/after/indent/javascript
cp path/to/vim-jsx/after/indent/jsx.vim ~/.vim/after/indent/javascript/jsx.vim
[1]: http://facebook.github.io/react/ "React"
[2]: https://github.com/pangloss/vim-javascript "pangloss: vim-javascript"
[3]: https://github.com/mxw/vim-xhp "mxw: vim-xhp"
[4]: https://github.com/tpope/vim-pathogen "tpope: vim-pathogen"
[5]: https://github.com/VundleVim/Vundle "VundleVim: Vundle"

View file

@ -0,0 +1,16 @@
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Vim ftplugin file
"
" Language: JSX (JavaScript)
" Maintainer: Max Wang <mxawng@gmail.com>
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" modified from html.vim
if exists("loaded_matchit")
let b:match_ignorecase = 0
let b:match_words = '(:),\[:\],{:},<:>,' .
\ '<\@<=\([^/][^ \t>]*\)[^>]*\%(>\|$\):<\@<=/\1>'
endif
setlocal suffixesadd+=.jsx

View file

@ -0,0 +1,114 @@
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Vim indent file
"
" Language: JSX (JavaScript)
" Maintainer: Max Wang <mxawng@gmail.com>
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Save the current JavaScript indentexpr.
let b:jsx_js_indentexpr = &indentexpr
" Prologue; load in XML indentation.
if exists('b:did_indent')
let s:did_indent=b:did_indent
unlet b:did_indent
endif
exe 'runtime! indent/xml.vim'
if exists('s:did_indent')
let b:did_indent=s:did_indent
endif
setlocal indentexpr=GetJsxIndent()
" JS indentkeys
setlocal indentkeys=0{,0},0),0],0\,,!^F,o,O,e
" XML indentkeys
setlocal indentkeys+=*<Return>,<>>,<<>,/
" Multiline end tag regex (line beginning with '>' or '/>')
let s:endtag = '^\s*\/\?>\s*;\='
" Get all syntax types at the beginning of a given line.
fu! SynSOL(lnum)
return map(synstack(a:lnum, 1), 'synIDattr(v:val, "name")')
endfu
" Get all syntax types at the end of a given line.
fu! SynEOL(lnum)
let lnum = prevnonblank(a:lnum)
let col = strlen(getline(lnum))
return map(synstack(lnum, col), 'synIDattr(v:val, "name")')
endfu
" Check if a syntax attribute is XMLish.
fu! SynAttrXMLish(synattr)
return a:synattr =~ "^xml" || a:synattr =~ "^jsx"
endfu
" Check if a synstack is XMLish (i.e., has an XMLish last attribute).
fu! SynXMLish(syns)
return SynAttrXMLish(get(a:syns, -1))
endfu
" Check if a synstack denotes the end of a JSX block.
fu! SynJSXBlockEnd(syns)
return get(a:syns, -1) =~ '\%(js\|javascript\)Braces' &&
\ SynAttrXMLish(get(a:syns, -2))
endfu
" Determine how many jsxRegions deep a synstack is.
fu! SynJSXDepth(syns)
return len(filter(copy(a:syns), 'v:val ==# "jsxRegion"'))
endfu
" Check whether `cursyn' continues the same jsxRegion as `prevsyn'.
fu! SynJSXContinues(cursyn, prevsyn)
let curdepth = SynJSXDepth(a:cursyn)
let prevdepth = SynJSXDepth(a:prevsyn)
" In most places, we expect the nesting depths to be the same between any
" two consecutive positions within a jsxRegion (e.g., between a parent and
" child node, between two JSX attributes, etc.). The exception is between
" sibling nodes, where after a completed element (with depth N), we return
" to the parent's nesting (depth N - 1). This case is easily detected,
" since it is the only time when the top syntax element in the synstack is
" jsxRegion---specifically, the jsxRegion corresponding to the parent.
return prevdepth == curdepth ||
\ (prevdepth == curdepth + 1 && get(a:cursyn, -1) ==# 'jsxRegion')
endfu
" Cleverly mix JS and XML indentation.
fu! GetJsxIndent()
let cursyn = SynSOL(v:lnum)
let prevsyn = SynEOL(v:lnum - 1)
" Use XML indenting iff:
" - the syntax at the end of the previous line was either JSX or was the
" closing brace of a jsBlock whose parent syntax was JSX; and
" - the current line continues the same jsxRegion as the previous line.
if (SynXMLish(prevsyn) || SynJSXBlockEnd(prevsyn)) &&
\ SynJSXContinues(cursyn, prevsyn)
let ind = XmlIndentGet(v:lnum, 0)
" Align '/>' and '>' with '<' for multiline tags.
if getline(v:lnum) =~? s:endtag
let ind = ind - &sw
endif
" Then correct the indentation of any JSX following '/>' or '>'.
if getline(v:lnum - 1) =~? s:endtag
let ind = ind + &sw
endif
else
if len(b:jsx_js_indentexpr)
" Invoke the base JS package's custom indenter. (For vim-javascript,
" e.g., this will be GetJavascriptIndent().)
let ind = eval(b:jsx_js_indentexpr)
else
let ind = cindent(v:lnum)
endif
endif
return ind
endfu

View file

@ -0,0 +1,61 @@
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Vim syntax file
"
" Language: JSX (JavaScript)
" Maintainer: Max Wang <mxawng@gmail.com>
" Depends: pangloss/vim-javascript
"
" CREDITS: Inspired by Facebook.
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Prologue; load in XML syntax.
if exists('b:current_syntax')
let s:current_syntax=b:current_syntax
unlet b:current_syntax
endif
syn include @XMLSyntax syntax/xml.vim
if exists('s:current_syntax')
let b:current_syntax=s:current_syntax
endif
" Officially, vim-jsx depends on the pangloss/vim-javascript syntax package
" (and is tested against it exclusively). However, in practice, we make some
" effort towards compatibility with other packages.
"
" These are the plugin-to-syntax-element correspondences:
"
" - pangloss/vim-javascript: jsBlock, jsExpression
" - jelera/vim-javascript-syntax: javascriptBlock
" - othree/yajs.vim: javascriptNoReserved
" JSX attributes should color as JS. Note the trivial end pattern; we let
" jsBlock take care of ending the region.
syn region xmlString contained start=+{+ end=++ contains=jsBlock,javascriptBlock
" JSX child blocks behave just like JSX attributes, except that (a) they are
" syntactically distinct, and (b) they need the syn-extend argument, or else
" nested XML end-tag patterns may end the outer jsxRegion.
syn region jsxChild contained start=+{+ end=++ contains=jsBlock,javascriptBlock
\ extend
" Highlight JSX regions as XML; recursively match.
"
" Note that we prohibit JSX tags from having a < or word character immediately
" preceding it, to avoid conflicts with, respectively, the left shift operator
" and generic Flow type annotations (http://flowtype.org/).
syn region jsxRegion
\ contains=@Spell,@XMLSyntax,jsxRegion,jsxChild,jsBlock,javascriptBlock
\ start=+\%(<\|\w\)\@<!<\z([a-zA-Z][a-zA-Z0-9:\-.]*\)+
\ skip=+<!--\_.\{-}-->+
\ end=+</\z1\_\s\{-}>+
\ end=+/>+
\ keepend
\ extend
" Add jsxRegion to the lowest-level JS syntax cluster.
syn cluster jsExpression add=jsxRegion
" Allow jsxRegion to contain reserved words.
syn cluster javascriptNoReserved add=jsxRegion

View file

@ -0,0 +1,36 @@
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Vim ftdetect file
"
" Language: JSX (JavaScript)
" Maintainer: Max Wang <mxawng@gmail.com>
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Whether the .jsx extension is required.
if !exists('g:jsx_ext_required')
let g:jsx_ext_required = 1
endif
" Whether the @jsx pragma is required.
if !exists('g:jsx_pragma_required')
let g:jsx_pragma_required = 0
endif
if g:jsx_pragma_required
" Look for the @jsx pragma. It must be included in a docblock comment before
" anything else in the file (except whitespace).
let s:jsx_pragma_pattern = '\%^\_s*\/\*\*\%(\_.\%(\*\/\)\@!\)*@jsx\_.\{-}\*\/'
let b:jsx_pragma_found = search(s:jsx_pragma_pattern, 'npw')
endif
" Whether to set the JSX filetype on *.js files.
fu! <SID>EnableJSX()
if g:jsx_pragma_required && !b:jsx_pragma_found | return 0 | endif
if g:jsx_ext_required && !exists('b:jsx_ext_found') | return 0 | endif
return 1
endfu
autocmd BufNewFile,BufRead *.jsx let b:jsx_ext_found = 1
autocmd BufNewFile,BufRead *.jsx set filetype=javascript.jsx
autocmd BufNewFile,BufRead *.js
\ if <SID>EnableJSX() | set filetype=javascript.jsx | endif