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