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: March 21, 2017 6 7" Only load this indent file when no other was loaded. 8if exists('b:did_indent') 9 finish 10endif 11let b:did_indent = 1 12 13" Now, set up our indentation expression and keys that trigger it. 14setlocal indentexpr=GetJavascriptIndent() 15setlocal autoindent nolisp nosmartindent 16setlocal 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 22let b:undo_indent = 'setlocal indentexpr< smartindent< autoindent< indentkeys<' 23 24" Only define the function once. 25if exists('*GetJavascriptIndent') 26 finish 27endif 28 29let s:cpo_save = &cpo 30set cpo&vim 31 32" Get shiftwidth value 33if exists('*shiftwidth') 34 function s:sw() 35 return shiftwidth() 36 endfunction 37else 38 function s:sw() 39 return &l:shiftwidth == 0 ? &l:tabstop : &l:shiftwidth 40 endfunction 41endif 42 43" Performance for forwards search(): start search at pos rather than masking 44" matches before pos. 45let s:z = has('patch-7.4.984') ? 'z' : '' 46 47" searchpair() wrapper 48if has('reltime') 49 function s:GetPair(start,end,flags,skip,time,...) 50 return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,max([prevnonblank(v:lnum) - 2000,0] + a:000),a:time) 51 endfunction 52else 53 function s:GetPair(start,end,flags,skip,...) 54 return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,max([prevnonblank(v:lnum) - 1000,get(a:000,1)])) 55 endfunction 56endif 57 58" Regex of syntax group names that are or delimit string or are comments. 59let s:syng_strcom = 'string\|comment\|regex\|special\|doc\|template\%(braces\)\@!' 60let s:syng_str = 'string\|template\|special' 61let s:syng_com = 'comment\|doc' 62" Expression used to check whether we should skip a match with searchpair(). 63let s:skip_expr = "synIDattr(synID(line('.'),col('.'),0),'name') =~? '".s:syng_strcom."'" 64 65function s:parse_cino(f) abort 66 return float2nr(eval(substitute(substitute(join(split( 67 \ matchstr(&cino,'.*'.a:f.'\zs[^,]*'), 's',1), '*'.s:W) 68 \ , '^-\=\zs\*','',''), '^-\=\zs\.','0.',''))) 69endfunction 70 71function s:skip_func() 72 if getline('.') =~ '\%<'.col('.').'c\/.\{-}\/\|\%>'.col('.').'c[''"]\|\\$' 73 return eval(s:skip_expr) 74 elseif s:checkIn || search('\m`\|\${\|\*\/','nW'.s:z,s:looksyn) 75 let s:checkIn = eval(s:skip_expr) 76 endif 77 let s:looksyn = line('.') 78 return s:checkIn 79endfunction 80 81function s:alternatePair(stop) 82 let pos = getpos('.')[1:2] 83 let pat = '[][(){};]' 84 while search('\m'.pat,'bW',a:stop) 85 if s:skip_func() | continue | endif 86 let idx = stridx('])};',s:looking_at()) 87 if idx is 3 | let pat = '[{}()]' | continue | endif 88 if idx + 1 89 if s:GetPair(['\[','(','{'][idx], '])}'[idx],'bW','s:skip_func()',2000,a:stop) <= 0 90 break 91 endif 92 else 93 return 94 endif 95 endwhile 96 call call('cursor',pos) 97endfunction 98 99function s:save_pos(f,...) 100 let l:pos = getpos('.')[1:2] 101 let ret = call(a:f,a:000) 102 call call('cursor',l:pos) 103 return ret 104endfunction 105 106function s:syn_at(l,c) 107 return synIDattr(synID(a:l,a:c,0),'name') 108endfunction 109 110function s:looking_at() 111 return getline('.')[col('.')-1] 112endfunction 113 114function s:token() 115 return s:looking_at() =~ '\k' ? expand('<cword>') : s:looking_at() 116endfunction 117 118function s:previous_token() 119 let l:pos = getpos('.')[1:2] 120 if search('\m\k\{1,}\zs\k\|\S','bW') 121 if (getline('.')[col('.')-2:col('.')-1] == '*/' || line('.') != l:pos[0] && 122 \ getline('.') =~ '\%<'.col('.').'c\/\/') && s:syn_at(line('.'),col('.')) =~? s:syng_com 123 while search('\m\S\ze\_s*\/[/*]','bW') 124 if s:syn_at(line('.'),col('.')) !~? s:syng_com 125 return s:token() 126 endif 127 endwhile 128 else 129 return s:token() 130 endif 131 endif 132 call call('cursor',l:pos) 133 return '' 134endfunction 135 136function s:expr_col() 137 if getline('.')[col('.')-2] == ':' 138 return 1 139 endif 140 let bal = 0 141 while search('\m[{}?:;]','bW') 142 if eval(s:skip_expr) | continue | endif 143 " switch (looking_at()) 144 exe { '}': "if s:GetPair('{','}','bW',s:skip_expr,200) <= 0 | return | endif", 145 \ ';': "return", 146 \ '{': "return getpos('.')[1:2] != b:js_cache[1:] && !s:IsBlock()", 147 \ ':': "let bal -= getline('.')[max([col('.')-2,0]):col('.')] !~ '::'", 148 \ '?': "let bal += 1 | if bal > 0 | return 1 | endif" }[s:looking_at()] 149 endwhile 150endfunction 151 152" configurable regexes that define continuation lines, not including (, {, or [. 153let s:opfirst = '^' . get(g:,'javascript_opfirst', 154 \ '\C\%([<>=,?^%|*/&]\|\([-.:+]\)\1\@!\|!=\|in\%(stanceof\)\=\>\)') 155let s:continuation = get(g:,'javascript_continuation', 156 \ '\C\%([-+<>=,.~!?/*^%|&:]\|\<\%(typeof\|new\|delete\|void\|in\|instanceof\|await\)\)') . '$' 157 158function s:continues(ln,con) 159 if !cursor(a:ln, match(' '.a:con,s:continuation)) 160 let teol = s:looking_at() 161 if teol == '/' 162 return s:syn_at(line('.'),col('.')) !~? 'regex' 163 elseif teol =~ '[-+>]' 164 return getline('.')[col('.')-2] != tr(teol,'>','=') 165 elseif teol =~ '\l' 166 return s:previous_token() != '.' 167 elseif teol == ':' 168 return s:expr_col() 169 endif 170 return 1 171 endif 172endfunction 173 174" get the line of code stripped of comments and move cursor to the last 175" non-comment char. 176function s:Trim(ln) 177 let pline = substitute(getline(a:ln),'\s*$','','') 178 let l:max = max([strridx(pline,'//'), strridx(pline,'/*')]) 179 while l:max != -1 && s:syn_at(a:ln, strlen(pline)) =~? s:syng_com 180 let pline = pline[: l:max] 181 let l:max = max([strridx(pline,'//'), strridx(pline,'/*')]) 182 let pline = substitute(pline[:-2],'\s*$','','') 183 endwhile 184 return pline is '' || cursor(a:ln,strlen(pline)) ? pline : pline 185endfunction 186 187" Find line above 'lnum' that isn't empty or in a comment 188function s:PrevCodeLine(lnum) 189 let [l:pos, l:n] = [getpos('.')[1:2], prevnonblank(a:lnum)] 190 while l:n 191 if getline(l:n) =~ '^\s*\/[/*]' 192 let l:n = prevnonblank(l:n-1) 193 elseif stridx(getline(l:n), '*/') + 1 && s:syn_at(l:n,1) =~? s:syng_com 194 call cursor(l:n,1) 195 keepjumps norm! [* 196 let l:n = search('\m\S','nbW') 197 else 198 break 199 endif 200 endwhile 201 call call('cursor',l:pos) 202 return l:n 203endfunction 204 205" Check if line 'lnum' has a balanced amount of parentheses. 206function s:Balanced(lnum) 207 let l:open = 0 208 let l:line = getline(a:lnum) 209 let pos = match(l:line, '[][(){}]', 0) 210 while pos != -1 211 if s:syn_at(a:lnum,pos + 1) !~? s:syng_strcom 212 let l:open += match(' ' . l:line[pos],'[[({]') 213 if l:open < 0 214 return 215 endif 216 endif 217 let pos = match(l:line, (l:open ? 218 \ '['.escape(tr(l:line[pos],'({[]})',')}][{(').l:line[pos],']').']' : 219 \ '[][(){}]'), pos + 1) 220 endwhile 221 return !l:open 222endfunction 223 224function s:OneScope(lnum) 225 let pline = s:Trim(a:lnum) 226 let kw = 'else do' 227 if pline[-1:] == ')' && s:GetPair('(', ')', 'bW', s:skip_expr, 100) > 0 228 if s:previous_token() =~# '^\%(await\|each\)$' 229 call s:previous_token() 230 let kw = 'for' 231 else 232 let kw = 'for if let while with' 233 endif 234 endif 235 return pline[-2:] == '=>' || index(split(kw),s:token()) + 1 && 236 \ s:save_pos('s:previous_token') != '.' 237endfunction 238 239" returns braceless levels started by 'i' and above lines * &sw. 'num' is the 240" lineNr which encloses the entire context, 'cont' if whether line 'i' + 1 is 241" a continued expression, which could have started in a braceless context 242function s:iscontOne(i,num,cont) 243 let [l:i, l:num, bL] = [a:i, a:num + !a:num, 0] 244 let pind = a:num ? indent(l:num) + s:W : 0 245 let ind = indent(l:i) + (a:cont ? 0 : s:W) 246 while l:i >= l:num && (ind > pind || l:i == l:num) 247 if indent(l:i) < ind && s:OneScope(l:i) 248 let bL += s:W 249 let l:i = line('.') 250 elseif !a:cont || bL || ind < indent(a:i) 251 break 252 endif 253 let ind = min([ind, indent(l:i)]) 254 let l:i = s:PrevCodeLine(l:i - 1) 255 endwhile 256 return bL 257endfunction 258 259" https://github.com/sweet-js/sweet.js/wiki/design#give-lookbehind-to-the-reader 260function s:IsBlock() 261 if s:looking_at() == '{' 262 let l:n = line('.') 263 let char = s:previous_token() 264 if match(s:stack,'\cxml\|jsx') + 1 && s:syn_at(line('.'),col('.')-1) =~? 'xml\|jsx' 265 return char != '{' 266 elseif char =~ '\k' 267 if char ==# 'type' 268 return s:previous_token() !~# '^\%(im\|ex\)port$' 269 endif 270 return index(split('return const let import export extends yield default delete var await void typeof throw case new of in instanceof') 271 \ ,char) < (line('.') != l:n) || s:save_pos('s:previous_token') == '.' 272 elseif char == '>' 273 return getline('.')[col('.')-2] == '=' || s:syn_at(line('.'),col('.')) =~? '^jsflow' 274 elseif char == ':' 275 return !s:save_pos('s:expr_col') 276 elseif char == '/' 277 return s:syn_at(line('.'),col('.')) =~? 'regex' 278 endif 279 return char !~ '[=~!<*,?^%|&([]' && 280 \ (char !~ '[-+]' || l:n != line('.') && getline('.')[col('.')-2] == char) 281 endif 282endfunction 283 284function GetJavascriptIndent() 285 let b:js_cache = get(b:,'js_cache',[0,0,0]) 286 " Get the current line. 287 call cursor(v:lnum,1) 288 let l:line = getline('.') 289 " use synstack as it validates syn state and works in an empty line 290 let s:stack = map(synstack(v:lnum,1),"synIDattr(v:val,'name')") 291 let syns = get(s:stack,-1,'') 292 293 " start with strings,comments,etc. 294 if syns =~? s:syng_com 295 if l:line =~ '^\s*\*' 296 return cindent(v:lnum) 297 elseif l:line !~ '^\s*\/[/*]' 298 return -1 299 endif 300 elseif syns =~? s:syng_str 301 if b:js_cache[0] == v:lnum - 1 && s:Balanced(v:lnum-1) 302 let b:js_cache[0] = v:lnum 303 endif 304 return -1 305 endif 306 let l:lnum = s:PrevCodeLine(v:lnum - 1) 307 if !l:lnum 308 return 309 endif 310 311 let l:line = substitute(l:line,'^\s*','','') 312 if l:line[:1] == '/*' 313 let l:line = substitute(l:line,'^\%(\/\*.\{-}\*\/\s*\)*','','') 314 endif 315 if l:line =~ '^\/[/*]' 316 let l:line = '' 317 endif 318 319 " the containing paren, bracket, or curly. Many hacks for performance 320 let idx = index([']',')','}'],l:line[0]) 321 if b:js_cache[0] >= l:lnum && b:js_cache[0] < v:lnum && 322 \ (b:js_cache[0] > l:lnum || s:Balanced(l:lnum)) 323 call call('cursor',b:js_cache[1:]) 324 else 325 let [s:looksyn, s:checkIn, top] = [v:lnum - 1, 0, (!indent(l:lnum) && 326 \ s:syn_at(l:lnum,1) !~? s:syng_str) * l:lnum] 327 if idx + 1 328 call s:GetPair(['\[','(','{'][idx],'])}'[idx],'bW','s:skip_func()',2000,top) 329 elseif getline(v:lnum) !~ '^\S' && syns =~? 'block' 330 call s:GetPair('{','}','bW','s:skip_func()',2000,top) 331 else 332 call s:alternatePair(top) 333 endif 334 endif 335 336 let b:js_cache = [v:lnum] + (line('.') == v:lnum ? [0,0] : getpos('.')[1:2]) 337 let num = b:js_cache[1] 338 339 let [s:W, isOp, bL, switch_offset] = [s:sw(),0,0,0] 340 if !num || s:IsBlock() 341 let ilnum = line('.') 342 let pline = s:save_pos('s:Trim',l:lnum) 343 if num && s:looking_at() == ')' && s:GetPair('(', ')', 'bW', s:skip_expr, 100) > 0 344 let num = ilnum == num ? line('.') : num 345 if idx < 0 && s:previous_token() ==# 'switch' && s:previous_token() != '.' 346 if &cino !~ ':' 347 let switch_offset = s:W 348 else 349 let switch_offset = max([-indent(num),s:parse_cino(':')]) 350 endif 351 if pline[-1:] != '.' && l:line =~# '^\%(default\|case\)\>' 352 return indent(num) + switch_offset 353 endif 354 endif 355 endif 356 if idx < 0 && pline[-1:] !~ '[{;]' 357 let isOp = (l:line =~# s:opfirst || s:continues(l:lnum,pline)) * s:W 358 let bL = s:iscontOne(l:lnum,b:js_cache[1],isOp) 359 let bL -= (bL && l:line[0] == '{') * s:W 360 endif 361 elseif idx < 0 && getline(b:js_cache[1])[b:js_cache[2]-1] == '(' && &cino =~ '(' 362 let pval = s:parse_cino('(') 363 return !pval ? (s:parse_cino('w') ? 0 : -(!!search('\m\S','W'.s:z,num))) + virtcol('.') : 364 \ max([indent('.') + pval + (s:GetPair('(',')','nbrmW',s:skip_expr,100,num) * s:W),0]) 365 endif 366 367 " main return 368 if l:line =~ '^\%([])}]\||}\)' 369 return max([indent(num),0]) 370 elseif num 371 return indent(num) + s:W + switch_offset + bL + isOp 372 endif 373 return bL + isOp 374endfunction 375 376let &cpo = s:cpo_save 377unlet s:cpo_save 378