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