Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
javascript.vim489 linesDownload Raw Back to indent
1" Vim indent file2" Language: Javascript3" Maintainer: Chris Paul ( https://github.com/bounceme )4" URL: https://github.com/pangloss/vim-javascript5" Last Change: 2025 Apr 136 7" Only load this indent file when no other was loaded.8if exists('b:did_indent')9  finish10endif11let b:did_indent = 112 13" Now, set up our indentation expression and keys that trigger it.14setlocal indentexpr=GetJavascriptIndent()15setlocal autoindent nolisp nosmartindent16setlocal 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  finish27endif28 29let s:cpo_save = &cpo30set cpo&vim31 32" indent correctly if inside <script>33" vim/vim@690afe1 for the switch from cindent34" overridden with b:html_indent_script135call 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()46  call extend(b:,extend(s:bvars,{'js_cache': [0,0,0]}),'keep')47endfunction48 49" Get shiftwidth value50if exists('*shiftwidth')51  function s:sw()52    return shiftwidth()53  endfunction54else55  function s:sw()56    return &l:shiftwidth ? &l:shiftwidth : &l:tabstop57  endfunction58endif59 60" Performance for forwards search(): start search at pos rather than masking61" 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() wrapper70if s:rel71  function s:GetPair(start,end,flags,skip)72    " VIM_INDENT_TEST_TRACE_START73    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:GetPair75  endfunction76else77  function s:GetPair(start,end,flags,skip)78    return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,s:l1)79  endfunction80endif81 82function s:SynAt(l,c)83  let byte = line2byte(a:l) + a:c - 184  let pos = index(s:synid_cache[0], byte)85  if pos == -186    let s:synid_cache[:] += [[byte], [synIDattr(synID(a:l, a:c, 0), 'name')]]87  endif88  return s:synid_cache[1][pos]89endfunction90 91function 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 == '.' && !divider96      let divider = 197    elseif c ==# 's'98      if n !~ '\d'99        return n . s:sw() + 0100      endif101      let n = str2nr(n) * s:sw()102      break103    else104      let [n, divider] .= [c, 0]105    endif106  endfor107  return str2nr(n) / max([str2nr(divider),1])108endfunction109 110" Optimized {skip} expr, only callable from the search loop which111" GetJavascriptIndent does to find the containing [[{(] (side-effects)112function s:SkipFunc()113  if s:top_col == 1114    throw 'out of bounds'115  elseif s:check_in116    if eval(s:skip_expr)117      return 1118    endif119    let s:check_in = 0120  elseif getline('.') =~ '\%<'.col('.').'c\/.\{-}\/\|\%>'.col('.').'c[''"]\|\\$'121    if eval(s:skip_expr)122      return 1123    endif124  elseif search('\m`\|\${\|\*\/','nW'.s:z,s:looksyn)125    if eval(s:skip_expr)126      let s:check_in = 1127      return 1128    endif129  else130    let s:synid_cache[:] += [[line2byte('.') + col('.') - 1], ['']]131  endif132  let [s:looksyn, s:top_col] = getpos('.')[1:2]133endfunction134 135function s:AlternatePair()136  let [pat, l:for] = ['[][(){};]', 2]137  while s:SearchLoop(pat,'bW','s:SkipFunc()')138    if s:LookingAt() == ';'139      if !l:for140        if s:GetPair('{','}','bW','s:SkipFunc()')141          return142        endif143        break144      else145        let [pat, l:for] = ['[{}();]', l:for - 1]146      endif147    else148      let idx = stridx('])}',s:LookingAt())149      if idx == -1150        return151      elseif !s:GetPair(['\[','(','{'][idx],'])}'[idx],'bW','s:SkipFunc()')152        break153      endif154    endif155  endwhile156  throw 'out of bounds'157endfunction158 159function s:Nat(int)160  return a:int * (a:int > 0)161endfunction162 163function s:LookingAt()164  return getline('.')[col('.')-1]165endfunction166 167function s:Token()168  return s:LookingAt() =~ '\k' ? expand('<cword>') : s:LookingAt()169endfunction170 171function 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      else178        let tok = s:Token()179      endif180    else181      let two = a:0 || line('.') != l:pos[1] ? strridx(getline('.')[:col('.')],'//') + 1 : 0182      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        endif188      else189        let tok = s:Token()190      endif191    endif192  endif193  return tok194endfunction195 196function s:Pure(f,...)197  return eval("[call(a:f,a:000),cursor(a:firstline,".col('.').")][0]")198endfunction199 200function s:SearchLoop(pat,flags,expr)201  return s:GetPair(a:pat,'\_$.',a:flags,a:expr)202endfunction203 204function s:ExprCol()205  if getline('.')[col('.')-2] == ':'206    return 1207  endif208  let bal = 0209  while s:SearchLoop('[{}?:]','bW',s:skip_expr)210    if s:LookingAt() == ':'211      if getline('.')[col('.')-2] == ':'212        call cursor(0,col('.')-1)213        continue214      endif215      let bal -= 1216    elseif s:LookingAt() == '?'217      if getline('.')[col('.'):col('.')+1] =~ '^\.\d\@!'218        continue219      elseif !bal220        return 1221      endif222      let bal += 1223    elseif s:LookingAt() == '{'224      return !s:IsBlock()225    elseif !s:GetPair('{','}','bW',s:skip_expr)226      break227    endif228  endwhile229endfunction230 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()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  endif244  return s:SynAt(line('.'),col('.')) !~? (tok == '>' ? 'jsflow\|^html' : 'regex')245endfunction246 247" Check if line 'lnum' has a balanced amount of parentheses.248function s:Balanced(lnum,line)249  let l:open = 0250  let pos = match(a:line, '[][(){}]')251  while pos != -1252    if s:SynAt(a:lnum,pos + 1) !~? b:syng_strcom253      let l:open += match(' ' . a:line[pos],'[[({]')254      if l:open < 0255        return256      endif257    endif258    let pos = match(a:line, !l:open ? '[][(){}]' : '()' =~ a:line[pos] ?259          \ '[()]' : '{}' =~ a:line[pos] ? '[{}]' : '[][]', pos + 1)260  endwhile261  return !l:open262endfunction263 264function 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    endif277    return 1278  endif279endfunction280 281function 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 1288        endif289        break290      endif291    elseif s:LookingAt() != '}' || !s:GetPair('{','}','bW',s:skip_expr)292      break293    endif294  endwhile295  call call('cursor',cpos)296endfunction297 298" returns total offset from braceless contexts. 'num' is the lineNr which299" encloses the entire context, 'cont' if whether a:firstline is a continued300" expression, which could have started in a braceless context301function 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() : 0304  let ind = indent('.') + !a:cont305  while line('.') > l:num && ind > pind || line('.') == l:num306    if indent('.') < ind && s:OneScope()307      let b_l += 1308    elseif !a:cont || b_l || ind < indent(a:firstline)309      break310    else311      call cursor(0,1)312    endif313    let ind = min([ind, indent('.')])314    if s:PreviousToken() is ''315      break316    endif317  endwhile318  return b_l319endfunction320 321function s:IsSwitch()322  call call('cursor',b:js_cache[1:])323  return search('\m\C\%#.\_s*\%(\%(\/\/.*\_$\|\/\*\_.\{-}\*\/\)\@>\_s*\)*\%(case\|default\)\>','nWc'.s:z)324endfunction325 326" https://github.com/sweet-js/sweet.js/wiki/design#give-lookbehind-to-the-reader327function 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 = 1331    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    endif339    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] == tok351  endif352endfunction353 354function 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 line359  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 -1367    endif368  elseif s:stack[-1] =~? b:syng_str369    if b:js_cache[0] == v:lnum - 1 && s:Balanced(v:lnum-1,getline(v:lnum-1))370      let b:js_cache[0] = v:lnum371    endif372    return -1373  endif374 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    return380  endif381  let [l:lnum, pline] = [line('.'), getline('.')[:col('.')-1]]382 383  let l:line = substitute(l:line,'^\s*','','')384  let l:line_raw = l:line385  if l:line[:1] == '/*'386    let l:line = substitute(l:line,'^\%(\/\*.\{-}\*\/\s*\)*','','')387  endif388  if l:line =~ '^\/[/*]'389    let l:line = ''390  endif391 392  " the containing paren, bracket, or curly. Many hacks for performance393  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  else399    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    try402      if idx != -1403        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      else407        call s:AlternatePair()408      endif409    catch /^\Cout of bounds$/410      call cursor(v:lnum,1)411    endtry412    let b:js_cache[1:] = line('.') == v:lnum ? [0,0] : getpos('.')[1:2]413  endif414 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 == num422        let [num, num_ind] = [line('.'), indent('.')]423      endif424      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        endif431      endif432    endif433    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        endif441      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      else448        let is_op = s:sw()449      endif450      call cursor(l:lnum, len(pline))451      let b_l = s:Nat(s:IsContOne(is_op) - (!is_op && l:line =~ '^{')) * s:sw()452    endif453  elseif idx.s:LookingAt().&cino =~ '^-1(.*(' && (search('\m\S','nbW',num) || s:ParseCino('U'))454    let pval = s:ParseCino('(')455    if !pval456      let [Wval, vcol] = [s:ParseCino('W'), virtcol('.')]457      if search('\m\S','W',num)458        return s:ParseCino('w') ? vcol : virtcol('.')-1459      endif460      return Wval ? s:Nat(num_ind + Wval) : vcol461    endif462    return s:Nat(num_ind + pval + searchpair('\m(','','\m)','nbrmW',s:skip_expr,num) * s:sw())463  endif464 465  " main return466  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('.') - 1472      endif473    endif474    return num_ind475  elseif num476    return s:Nat(num_ind + get(l:,'case_offset',s:sw()) + l:switch_offset + b_l + is_op)477  endif478 479  let nest = get(get(b:, 'hi_indent', {}), 'blocklnr')480  if nest481    return indent(nextnonblank(nest + 1)) + b_l + is_op482  endif483 484  return b_l + is_op485endfunction486 487let &cpo = s:cpo_save488unlet s:cpo_save489 
codekingpro/portable-devtools · Team Ai