javascript.vim 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. " Vim indent file
  2. " Language: Javascript
  3. " Maintainer: Chris Paul ( https://github.com/bounceme )
  4. " URL: https://github.com/pangloss/vim-javascript
  5. " Last Change: December 4, 2017
  6. " Only load this indent file when no other was loaded.
  7. if exists('b:did_indent')
  8. finish
  9. endif
  10. let b:did_indent = 1
  11. " Now, set up our indentation expression and keys that trigger it.
  12. setlocal indentexpr=GetJavascriptIndent()
  13. setlocal autoindent nolisp nosmartindent
  14. setlocal indentkeys+=0],0)
  15. " Testable with something like:
  16. " vim -eNs "+filetype plugin indent on" "+syntax on" "+set ft=javascript" \
  17. " "+norm! gg=G" '+%print' '+:q!' testfile.js \
  18. " | diff -uBZ testfile.js -
  19. let b:undo_indent = 'setlocal indentexpr< smartindent< autoindent< indentkeys<'
  20. " Only define the function once.
  21. if exists('*GetJavascriptIndent')
  22. finish
  23. endif
  24. let s:cpo_save = &cpo
  25. set cpo&vim
  26. " indent correctly if inside <script>
  27. " vim/vim@690afe1 for the switch from cindent
  28. " overridden with b:html_indent_script1
  29. call extend(g:,{'html_indent_script1': 'inc'},'keep')
  30. " Regex of syntax group names that are or delimit string or are comments.
  31. let s:bvars = {
  32. \ 'syng_strcom': 'string\|comment\|regex\|special\|doc\|template\%(braces\)\@!',
  33. \ 'syng_str': 'string\|template\|special' }
  34. " template strings may want to be excluded when editing graphql:
  35. " au! Filetype javascript let b:syng_str = '^\%(.*template\)\@!.*string\|special'
  36. " au! Filetype javascript let b:syng_strcom = '^\%(.*template\)\@!.*string\|comment\|regex\|special\|doc'
  37. function s:GetVars()
  38. call extend(b:,extend(s:bvars,{'js_cache': [0,0,0]}),'keep')
  39. endfunction
  40. " Get shiftwidth value
  41. if exists('*shiftwidth')
  42. function s:sw()
  43. return shiftwidth()
  44. endfunction
  45. else
  46. function s:sw()
  47. return &l:shiftwidth ? &l:shiftwidth : &l:tabstop
  48. endfunction
  49. endif
  50. " Performance for forwards search(): start search at pos rather than masking
  51. " matches before pos.
  52. let s:z = has('patch-7.4.984') ? 'z' : ''
  53. " Expression used to check whether we should skip a match with searchpair().
  54. let s:skip_expr = "s:SynAt(line('.'),col('.')) =~? b:syng_strcom"
  55. let s:in_comm = s:skip_expr[:-14] . "'comment\\|doc'"
  56. let s:rel = has('reltime')
  57. " searchpair() wrapper
  58. if s:rel
  59. function s:GetPair(start,end,flags,skip)
  60. return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,s:l1,a:skip ==# 's:SkipFunc()' ? 2000 : 200)
  61. endfunction
  62. else
  63. function s:GetPair(start,end,flags,skip)
  64. return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,s:l1)
  65. endfunction
  66. endif
  67. function s:SynAt(l,c)
  68. let byte = line2byte(a:l) + a:c - 1
  69. let pos = index(s:synid_cache[0], byte)
  70. if pos == -1
  71. let s:synid_cache[:] += [[byte], [synIDattr(synID(a:l, a:c, 0), 'name')]]
  72. endif
  73. return s:synid_cache[1][pos]
  74. endfunction
  75. function s:ParseCino(f)
  76. let [divider, n, cstr] = [0] + matchlist(&cino,
  77. \ '\%(.*,\)\=\%(\%d'.char2nr(a:f).'\(-\)\=\([.s0-9]*\)\)\=')[1:2]
  78. for c in split(cstr,'\zs')
  79. if c == '.' && !divider
  80. let divider = 1
  81. elseif c ==# 's'
  82. if n !~ '\d'
  83. return n . s:sw() + 0
  84. endif
  85. let n = str2nr(n) * s:sw()
  86. break
  87. else
  88. let [n, divider] .= [c, 0]
  89. endif
  90. endfor
  91. return str2nr(n) / max([str2nr(divider),1])
  92. endfunction
  93. " Optimized {skip} expr, only callable from the search loop which
  94. " GetJavascriptIndent does to find the containing [[{(] (side-effects)
  95. function s:SkipFunc()
  96. if s:top_col == 1
  97. throw 'out of bounds'
  98. elseif s:check_in
  99. if eval(s:skip_expr)
  100. return 1
  101. endif
  102. let s:check_in = 0
  103. elseif getline('.') =~ '\%<'.col('.').'c\/.\{-}\/\|\%>'.col('.').'c[''"]\|\\$'
  104. if eval(s:skip_expr)
  105. return 1
  106. endif
  107. elseif search('\m`\|\${\|\*\/','nW'.s:z,s:looksyn)
  108. if eval(s:skip_expr)
  109. let s:check_in = 1
  110. return 1
  111. endif
  112. else
  113. let s:synid_cache[:] += [[line2byte('.') + col('.') - 1], ['']]
  114. endif
  115. let [s:looksyn, s:top_col] = getpos('.')[1:2]
  116. endfunction
  117. function s:AlternatePair()
  118. let [pat, l:for] = ['[][(){};]', 2]
  119. while s:SearchLoop(pat,'bW','s:SkipFunc()')
  120. if s:LookingAt() == ';'
  121. if !l:for
  122. if s:GetPair('{','}','bW','s:SkipFunc()')
  123. return
  124. endif
  125. break
  126. else
  127. let [pat, l:for] = ['[{}();]', l:for - 1]
  128. endif
  129. else
  130. let idx = stridx('])}',s:LookingAt())
  131. if idx == -1
  132. return
  133. elseif !s:GetPair(['\[','(','{'][idx],'])}'[idx],'bW','s:SkipFunc()')
  134. break
  135. endif
  136. endif
  137. endwhile
  138. throw 'out of bounds'
  139. endfunction
  140. function s:Nat(int)
  141. return a:int * (a:int > 0)
  142. endfunction
  143. function s:LookingAt()
  144. return getline('.')[col('.')-1]
  145. endfunction
  146. function s:Token()
  147. return s:LookingAt() =~ '\k' ? expand('<cword>') : s:LookingAt()
  148. endfunction
  149. function s:PreviousToken(...)
  150. let [l:pos, tok] = [getpos('.'), '']
  151. if search('\m\k\{1,}\|\S','ebW')
  152. if getline('.')[col('.')-2:col('.')-1] == '*/'
  153. if eval(s:in_comm) && !s:SearchLoop('\S\ze\_s*\/[/*]','bW',s:in_comm)
  154. call setpos('.',l:pos)
  155. else
  156. let tok = s:Token()
  157. endif
  158. else
  159. let two = a:0 || line('.') != l:pos[1] ? strridx(getline('.')[:col('.')],'//') + 1 : 0
  160. if two && eval(s:in_comm)
  161. call cursor(0,two)
  162. let tok = s:PreviousToken(1)
  163. if tok is ''
  164. call setpos('.',l:pos)
  165. endif
  166. else
  167. let tok = s:Token()
  168. endif
  169. endif
  170. endif
  171. return tok
  172. endfunction
  173. function s:Pure(f,...)
  174. return eval("[call(a:f,a:000),cursor(a:firstline,".col('.').")][0]")
  175. endfunction
  176. function s:SearchLoop(pat,flags,expr)
  177. return s:GetPair(a:pat,'\_$.',a:flags,a:expr)
  178. endfunction
  179. function s:ExprCol()
  180. if getline('.')[col('.')-2] == ':'
  181. return 1
  182. endif
  183. let bal = 0
  184. while s:SearchLoop('[{}?:]','bW',s:skip_expr)
  185. if s:LookingAt() == ':'
  186. if getline('.')[col('.')-2] == ':'
  187. call cursor(0,col('.')-1)
  188. continue
  189. endif
  190. let bal -= 1
  191. elseif s:LookingAt() == '?'
  192. if getline('.')[col('.'):col('.')+1] =~ '^\.\d\@!'
  193. continue
  194. elseif !bal
  195. return 1
  196. endif
  197. let bal += 1
  198. elseif s:LookingAt() == '{'
  199. return !s:IsBlock()
  200. elseif !s:GetPair('{','}','bW',s:skip_expr)
  201. break
  202. endif
  203. endwhile
  204. endfunction
  205. " configurable regexes that define continuation lines, not including (, {, or [.
  206. let s:opfirst = '^' . get(g:,'javascript_opfirst',
  207. \ '\C\%([<>=,.?^%|/&]\|\([-:+]\)\1\@!\|\*\+\|!=\|in\%(stanceof\)\=\>\)')
  208. let s:continuation = get(g:,'javascript_continuation',
  209. \ '\C\%([<=,.~!?/*^%|&:]\|+\@<!+\|-\@<!-\|=\@<!>\|\<\%(typeof\|new\|delete\|void\|in\|instanceof\|await\)\)') . '$'
  210. function s:Continues()
  211. let tok = matchstr(strpart(getline('.'),col('.')-15,15),s:continuation)
  212. if tok =~ '[a-z:]'
  213. return tok == ':' ? s:ExprCol() : s:PreviousToken() != '.'
  214. elseif tok !~ '[/>]'
  215. return tok isnot ''
  216. endif
  217. return s:SynAt(line('.'),col('.')) !~? (tok == '>' ? 'jsflow\|^html' : 'regex')
  218. endfunction
  219. " Check if line 'lnum' has a balanced amount of parentheses.
  220. function s:Balanced(lnum,line)
  221. let l:open = 0
  222. let pos = match(a:line, '[][(){}]')
  223. while pos != -1
  224. if s:SynAt(a:lnum,pos + 1) !~? b:syng_strcom
  225. let l:open += match(' ' . a:line[pos],'[[({]')
  226. if l:open < 0
  227. return
  228. endif
  229. endif
  230. let pos = match(a:line, !l:open ? '[][(){}]' : '()' =~ a:line[pos] ?
  231. \ '[()]' : '{}' =~ a:line[pos] ? '[{}]' : '[][]', pos + 1)
  232. endwhile
  233. return !l:open
  234. endfunction
  235. function s:OneScope()
  236. if s:LookingAt() == ')' && s:GetPair('(', ')', 'bW', s:skip_expr)
  237. let tok = s:PreviousToken()
  238. return (count(split('for if let while with'),tok) ||
  239. \ tok =~# '^await$\|^each$' && s:PreviousToken() ==# 'for') &&
  240. \ s:Pure('s:PreviousToken') != '.' && !(tok == 'while' && s:DoWhile())
  241. elseif s:Token() =~# '^else$\|^do$'
  242. return s:Pure('s:PreviousToken') != '.'
  243. elseif strpart(getline('.'),col('.')-2,2) == '=>'
  244. call cursor(0,col('.')-1)
  245. if s:PreviousToken() == ')'
  246. return s:GetPair('(', ')', 'bW', s:skip_expr)
  247. endif
  248. return 1
  249. endif
  250. endfunction
  251. function s:DoWhile()
  252. let cpos = searchpos('\m\<','cbW')
  253. while s:SearchLoop('\C[{}]\|\<\%(do\|while\)\>','bW',s:skip_expr)
  254. if s:LookingAt() =~ '\a'
  255. if s:Pure('s:IsBlock')
  256. if s:LookingAt() ==# 'd'
  257. return 1
  258. endif
  259. break
  260. endif
  261. elseif s:LookingAt() != '}' || !s:GetPair('{','}','bW',s:skip_expr)
  262. break
  263. endif
  264. endwhile
  265. call call('cursor',cpos)
  266. endfunction
  267. " returns total offset from braceless contexts. 'num' is the lineNr which
  268. " encloses the entire context, 'cont' if whether a:firstline is a continued
  269. " expression, which could have started in a braceless context
  270. function s:IsContOne(cont)
  271. let [l:num, b_l] = [b:js_cache[1] + !b:js_cache[1], 0]
  272. let pind = b:js_cache[1] ? indent(b:js_cache[1]) + s:sw() : 0
  273. let ind = indent('.') + !a:cont
  274. while line('.') > l:num && ind > pind || line('.') == l:num
  275. if indent('.') < ind && s:OneScope()
  276. let b_l += 1
  277. elseif !a:cont || b_l || ind < indent(a:firstline)
  278. break
  279. else
  280. call cursor(0,1)
  281. endif
  282. let ind = min([ind, indent('.')])
  283. if s:PreviousToken() is ''
  284. break
  285. endif
  286. endwhile
  287. return b_l
  288. endfunction
  289. function s:IsSwitch()
  290. call call('cursor',b:js_cache[1:])
  291. return search('\m\C\%#.\_s*\%(\%(\/\/.*\_$\|\/\*\_.\{-}\*\/\)\@>\_s*\)*\%(case\|default\)\>','nWc'.s:z)
  292. endfunction
  293. " https://github.com/sweet-js/sweet.js/wiki/design#give-lookbehind-to-the-reader
  294. function s:IsBlock()
  295. let tok = s:PreviousToken()
  296. if join(s:stack) =~? 'xml\|jsx' && s:SynAt(line('.'),col('.')-1) =~? 'xml\|jsx'
  297. let s:in_jsx = 1
  298. return tok != '{'
  299. elseif tok =~ '\k'
  300. if tok ==# 'type'
  301. return s:Pure('eval',"s:PreviousToken() !~# '^\\%(im\\|ex\\)port$' || s:PreviousToken() == '.'")
  302. elseif tok ==# 'of'
  303. return s:Pure('eval',"!s:GetPair('[[({]','[])}]','bW',s:skip_expr) || s:LookingAt() != '(' ||"
  304. \ ."s:{s:PreviousToken() ==# 'await' ? 'Previous' : ''}Token() !=# 'for' || s:PreviousToken() == '.'")
  305. endif
  306. return index(split('return const let import export extends yield default delete var await void typeof throw case new in instanceof')
  307. \ ,tok) < (line('.') != a:firstline) || s:Pure('s:PreviousToken') == '.'
  308. elseif tok == '>'
  309. return getline('.')[col('.')-2] == '=' || s:SynAt(line('.'),col('.')) =~? 'jsflow\|^html'
  310. elseif tok == '*'
  311. return s:Pure('s:PreviousToken') == ':'
  312. elseif tok == ':'
  313. return s:Pure('eval',"s:PreviousToken() =~ '^\\K\\k*$' && !s:ExprCol()")
  314. elseif tok == '/'
  315. return s:SynAt(line('.'),col('.')) =~? 'regex'
  316. elseif tok !~ '[=~!<,.?^%|&([]'
  317. return tok !~ '[-+]' || line('.') != a:firstline && getline('.')[col('.')-2] == tok
  318. endif
  319. endfunction
  320. function GetJavascriptIndent()
  321. call s:GetVars()
  322. let s:synid_cache = [[],[]]
  323. let l:line = getline(v:lnum)
  324. " use synstack as it validates syn state and works in an empty line
  325. let s:stack = [''] + map(synstack(v:lnum,1),"synIDattr(v:val,'name')")
  326. " start with strings,comments,etc.
  327. if s:stack[-1] =~? 'comment\|doc'
  328. if l:line =~ '^\s*\*'
  329. return cindent(v:lnum)
  330. elseif l:line !~ '^\s*\/[/*]'
  331. return -1
  332. endif
  333. elseif s:stack[-1] =~? b:syng_str
  334. if b:js_cache[0] == v:lnum - 1 && s:Balanced(v:lnum-1,getline(v:lnum-1))
  335. let b:js_cache[0] = v:lnum
  336. endif
  337. return -1
  338. endif
  339. let s:l1 = max([0,prevnonblank(v:lnum) - (s:rel ? 2000 : 1000),
  340. \ get(get(b:,'hi_indent',{}),'blocklnr')])
  341. call cursor(v:lnum,1)
  342. if s:PreviousToken() is ''
  343. return
  344. endif
  345. let [l:lnum, pline] = [line('.'), getline('.')[:col('.')-1]]
  346. let l:line = substitute(l:line,'^\s*','','')
  347. let l:line_raw = l:line
  348. if l:line[:1] == '/*'
  349. let l:line = substitute(l:line,'^\%(\/\*.\{-}\*\/\s*\)*','','')
  350. endif
  351. if l:line =~ '^\/[/*]'
  352. let l:line = ''
  353. endif
  354. " the containing paren, bracket, or curly. Many hacks for performance
  355. call cursor(v:lnum,1)
  356. let idx = index([']',')','}'],l:line[0])
  357. if b:js_cache[0] > l:lnum && b:js_cache[0] < v:lnum ||
  358. \ b:js_cache[0] == l:lnum && s:Balanced(l:lnum,pline)
  359. call call('cursor',b:js_cache[1:])
  360. else
  361. let [s:looksyn, s:top_col, s:check_in, s:l1] = [v:lnum - 1,0,0,
  362. \ max([s:l1, &smc ? search('\m^.\{'.&smc.',}','nbW',s:l1 + 1) + 1 : 0])]
  363. try
  364. if idx != -1
  365. call s:GetPair(['\[','(','{'][idx],'])}'[idx],'bW','s:SkipFunc()')
  366. elseif getline(v:lnum) !~ '^\S' && s:stack[-1] =~? 'block\|^jsobject$'
  367. call s:GetPair('{','}','bW','s:SkipFunc()')
  368. else
  369. call s:AlternatePair()
  370. endif
  371. catch /^\Cout of bounds$/
  372. call cursor(v:lnum,1)
  373. endtry
  374. let b:js_cache[1:] = line('.') == v:lnum ? [0,0] : getpos('.')[1:2]
  375. endif
  376. let [b:js_cache[0], num] = [v:lnum, b:js_cache[1]]
  377. let [num_ind, is_op, b_l, l:switch_offset, s:in_jsx] = [s:Nat(indent(num)),0,0,0,0]
  378. if !num || s:LookingAt() == '{' && s:IsBlock()
  379. let ilnum = line('.')
  380. if num && !s:in_jsx && s:LookingAt() == ')' && s:GetPair('(',')','bW',s:skip_expr)
  381. if ilnum == num
  382. let [num, num_ind] = [line('.'), indent('.')]
  383. endif
  384. if idx == -1 && s:PreviousToken() ==# 'switch' && s:IsSwitch()
  385. let l:switch_offset = &cino !~ ':' ? s:sw() : s:ParseCino(':')
  386. if pline[-1:] != '.' && l:line =~# '^\%(default\|case\)\>'
  387. return s:Nat(num_ind + l:switch_offset)
  388. elseif &cino =~ '='
  389. let l:case_offset = s:ParseCino('=')
  390. endif
  391. endif
  392. endif
  393. if idx == -1 && pline[-1:] !~ '[{;]'
  394. call cursor(l:lnum, len(pline))
  395. let sol = matchstr(l:line,s:opfirst)
  396. if sol is '' || sol == '/' && s:SynAt(v:lnum,
  397. \ 1 + len(getline(v:lnum)) - len(l:line)) =~? 'regex'
  398. if s:Continues()
  399. let is_op = s:sw()
  400. endif
  401. elseif num && sol =~# '^\%(in\%(stanceof\)\=\|\*\)$' &&
  402. \ s:LookingAt() == '}' && s:GetPair('{','}','bW',s:skip_expr) &&
  403. \ s:PreviousToken() == ')' && s:GetPair('(',')','bW',s:skip_expr) &&
  404. \ (s:PreviousToken() == ']' || s:LookingAt() =~ '\k' &&
  405. \ s:{s:PreviousToken() == '*' ? 'Previous' : ''}Token() !=# 'function')
  406. return num_ind + s:sw()
  407. else
  408. let is_op = s:sw()
  409. endif
  410. call cursor(l:lnum, len(pline))
  411. let b_l = s:Nat(s:IsContOne(is_op) - (!is_op && l:line =~ '^{')) * s:sw()
  412. endif
  413. elseif idx.s:LookingAt().&cino =~ '^-1(.*(' && (search('\m\S','nbW',num) || s:ParseCino('U'))
  414. let pval = s:ParseCino('(')
  415. if !pval
  416. let [Wval, vcol] = [s:ParseCino('W'), virtcol('.')]
  417. if search('\m\S','W',num)
  418. return s:ParseCino('w') ? vcol : virtcol('.')-1
  419. endif
  420. return Wval ? s:Nat(num_ind + Wval) : vcol
  421. endif
  422. return s:Nat(num_ind + pval + searchpair('\m(','','\m)','nbrmW',s:skip_expr,num) * s:sw())
  423. endif
  424. " main return
  425. if l:line =~ '^[])}]\|^|}'
  426. if l:line_raw[0] == ')'
  427. if s:ParseCino('M')
  428. return indent(l:lnum)
  429. elseif num && &cino =~# 'm' && !s:ParseCino('m')
  430. return virtcol('.') - 1
  431. endif
  432. endif
  433. return num_ind
  434. elseif num
  435. return s:Nat(num_ind + get(l:,'case_offset',s:sw()) + l:switch_offset + b_l + is_op)
  436. endif
  437. let nest = get(get(b:, 'hi_indent', {}), 'blocklnr')
  438. if nest
  439. return indent(nextnonblank(nest + 1)) + b_l + is_op
  440. endif
  441. return b_l + is_op
  442. endfunction
  443. let &cpo = s:cpo_save
  444. unlet s:cpo_save