vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

vimindent.vim (39056B)


      1 vim9script
      2 
      3 # Language:     Vim script
      4 # Maintainer:   github user lacygoill
      5 # Last Change:  2025 Oct 09
      6 #
      7 # Includes changes from The Vim Project:
      8 
      9 # NOTE: Whenever you change the code, make sure the tests are still passing:
     10 #
     11 #     $ cd runtime/indent/
     12 #     $ make clean; make test || vimdiff testdir/vim.{ok,fail}
     13 
     14 # Config {{{1
     15 
     16 const TIMEOUT: number = get(g:, 'vim_indent', {})
     17     ->get('searchpair_timeout', 100)
     18 
     19 def IndentMoreInBracketBlock(): number # {{{2
     20     if get(g:, 'vim_indent', {})
     21             ->get('more_in_bracket_block', false)
     22         return shiftwidth()
     23     endif
     24     return 0
     25 enddef
     26 
     27 def IndentMoreLineContinuation(): number # {{{2
     28     var n: any = get(g:, 'vim_indent', {})
     29         # We inspect `g:vim_indent_cont` to stay backward compatible.
     30         ->get('line_continuation', get(g:, 'vim_indent_cont', shiftwidth() * 3))
     31 
     32     if n->typename() == 'string'
     33         return n->eval()
     34     endif
     35     return n
     36 enddef
     37 # }}}2
     38 
     39 # Init {{{1
     40 var patterns: list<string>
     41 # Tokens {{{2
     42 # BAR_SEPARATION {{{3
     43 
     44 const BAR_SEPARATION: string = '[^|\\]\@1<=|'
     45 
     46 # OPENING_BRACKET {{{3
     47 
     48 const OPENING_BRACKET: string = '[[{(]'
     49 
     50 # CLOSING_BRACKET {{{3
     51 
     52 const CLOSING_BRACKET: string = '[]})]'
     53 
     54 # NON_BRACKET {{{3
     55 
     56 const NON_BRACKET: string = '[^[\]{}()]'
     57 
     58 # LIST_OR_DICT_CLOSING_BRACKET {{{3
     59 
     60 const LIST_OR_DICT_CLOSING_BRACKET: string = '[]}]'
     61 
     62 # LIST_OR_DICT_OPENING_BRACKET {{{3
     63 
     64 const LIST_OR_DICT_OPENING_BRACKET: string = '[[{]'
     65 
     66 # CHARACTER_UNDER_CURSOR {{{3
     67 
     68 const CHARACTER_UNDER_CURSOR: string = '\%.c.'
     69 
     70 # INLINE_COMMENT {{{3
     71 
     72 # TODO: It is not required for an inline comment to be surrounded by whitespace.
     73 # But it might help against false positives.
     74 # To be more reliable, we should inspect the syntax, and only require whitespace
     75 # before  the `#`  comment leader.   But that  might be  too costly  (because of
     76 # `synstack()`).
     77 const INLINE_COMMENT: string = '\s[#"]\%(\s\|[{}]\{3}\)'
     78 
     79 # INLINE_VIM9_COMMENT {{{3
     80 
     81 const INLINE_VIM9_COMMENT: string = '\s#'
     82 
     83 # COMMENT {{{3
     84 
     85 # TODO: Technically, `"\s` is wrong.
     86 #
     87 # First, whitespace is not required.
     88 # Second, in Vim9, a string might appear at the start of the line.
     89 # To be sure, we should also inspect the syntax.
     90 # We can't use `INLINE_COMMENT` here. {{{
     91 #
     92 #     const COMMENT: string = $'^\s*{INLINE_COMMENT}'
     93 #                                    ^------------^
     94 #                                          ✘
     95 #
     96 # Because  `INLINE_COMMENT` asserts  the  presence of  a  whitespace before  the
     97 # comment leader.  This assertion is not satisfied for a comment starting at the
     98 # start of the line.
     99 #}}}
    100 const COMMENT: string = '^\s*\%(#\|"\\\=\s\).*$'
    101 
    102 # DICT_KEY {{{3
    103 
    104 const DICT_KEY: string = '^\s*\%('
    105     .. '\%(\w\|-\)\+'
    106     .. '\|'
    107     .. '"[^"]*"'
    108     .. '\|'
    109     .. "'[^']*'"
    110     .. '\|'
    111     .. '\[[^]]\+\]'
    112     .. '\)'
    113     .. ':\%(\s\|$\)'
    114 
    115 # END_OF_COMMAND {{{3
    116 
    117 const END_OF_COMMAND: string = $'\s*\%($\|||\@!\|{INLINE_COMMENT}\)'
    118 
    119 # END_OF_LINE {{{3
    120 
    121 const END_OF_LINE: string = $'\s*\%($\|{INLINE_COMMENT}\)'
    122 
    123 # END_OF_VIM9_LINE {{{3
    124 
    125 const END_OF_VIM9_LINE: string = $'\s*\%($\|{INLINE_VIM9_COMMENT}\)'
    126 
    127 # OPERATOR {{{3
    128 
    129 const OPERATOR: string = '\%(^\|\s\)\%([-+*/%]\|\.\.\|||\|&&\|??\|?\|<<\|>>\|\%([=!]=\|[<>]=\=\|[=!]\~\|is\|isnot\)[?#]\=\)\%(\s\|$\)\@=\%(\s*[|<]\)\@!'
    130     # assignment operators
    131     .. '\|' .. '\s\%([-+*/%]\|\.\.\)\==\%(\s\|$\)\@='
    132     # support `:` when used inside conditional operator `?:`
    133     .. '\|' .. '\%(\s\|^\):\%(\s\|$\)'
    134 
    135 # HEREDOC_OPERATOR {{{3
    136 
    137 const HEREDOC_OPERATOR: string = '\s=<<\s\@=\%(\s\+\%(trim\|eval\)\)\{,2}'
    138 
    139 # PATTERN_DELIMITER {{{3
    140 
    141 # A better regex would be:
    142 #
    143 #     [^-+*/%.:#[:blank:][:alnum:]\"|]\|->\@!\%(=\s\)\@!\|[+*/%]\%(=\s\)\@!
    144 #
    145 # But sometimes, it can be too costly and cause `E363` to be given.
    146 const PATTERN_DELIMITER: string = '[-+*/%]\%(=\s\)\@!'
    147 # }}}2
    148 # Syntaxes {{{2
    149 # BLOCKS {{{3
    150 
    151 const BLOCKS: list<list<string>> = [
    152     ['if', 'el\%[se]', 'elseif\=', 'en\%[dif]'],
    153     ['for', 'endfor\='],
    154     ['wh\%[ile]', 'endw\%[hile]'],
    155     ['try', 'cat\%[ch]', 'fina\|finally\=', 'endt\%[ry]'],
    156     ['def', 'enddef'],
    157     ['fu\%[nction](\@!', 'endf\%[unction]'],
    158     ['class', 'endclass'],
    159     ['interface', 'endinterface'],
    160     ['enum', 'endenum'],
    161     ['aug\%[roup]\%(\s\+[eE][nN][dD]\)\@!\s\+\S\+', 'aug\%[roup]\s\+[eE][nN][dD]'],
    162 ]
    163 
    164 # MODIFIERS {{{3
    165 
    166 # some keywords can be prefixed by modifiers (e.g. `def` can be prefixed by `export`)
    167 const MODIFIERS: dict<string> = {
    168     def: ['export', 'static'],
    169     class: ['export', 'abstract', 'export abstract'],
    170     interface: ['export'],
    171     enum: ['export'],
    172 }
    173 #     ...
    174 #     class: ['export', 'abstract', 'export abstract'],
    175 #     ...
    176 #     →
    177 #     ...
    178 #     class: '\%(export\|abstract\|export\s\+abstract\)\s\+',
    179 #     ...
    180 ->map((_, mods: list<string>): string =>
    181     '\%(' .. mods
    182     ->join('\|')
    183     ->substitute('\s\+', '\\s\\+', 'g')
    184     .. '\)' .. '\s\+')
    185 
    186 # HIGHER_ORDER_COMMAND {{{3
    187 
    188 patterns =<< trim eval END
    189     argdo\>!\=
    190     bufdo\>!\=
    191     [cl]f\=do\>!\=
    192     folddoc\%[losed]\>
    193     foldd\%[oopen]\>
    194     tabdo\=\>
    195     windo\>
    196     au\%[tocmd]\>!\=.*
    197     com\%[mand]\>!\=.*
    198     g\%[lobal]!\={PATTERN_DELIMITER}.*
    199     v\%[global]!\={PATTERN_DELIMITER}.*
    200 END
    201 
    202 const HIGHER_ORDER_COMMAND: string = $'\%(^\|{BAR_SEPARATION}\)\s*\<\%({patterns->join('\|')}\)\%(\s\|$\)\@='
    203 
    204 # START_MIDDLE_END {{{3
    205 
    206 # Let's derive this constant from `BLOCKS`:
    207 #
    208 #     [['if', 'el\%[se]', 'elseif\=', 'en\%[dif]'],
    209 #      ['for', 'endfor\='],
    210 #      ...,
    211 #      [...]]
    212 #     →
    213 #     {
    214 #      'for': ['for', '', 'endfor\='],
    215 #      'endfor': ['for', '', 'endfor\='],
    216 #      'if': ['if', 'el\%[se]\|elseif\=', 'en\%[dif]'],
    217 #      'else': ['if', 'el\%[se]\|elseif\=', 'en\%[dif]'],
    218 #      'elseif': ['if', 'el\%[se]\|elseif\=', 'en\%[dif]'],
    219 #      'endif': ['if', 'el\%[se]\|elseif\=', 'en\%[dif]'],
    220 #      ...
    221 #     }
    222 var START_MIDDLE_END: dict<list<string>>
    223 
    224 def Unshorten(kwd: string): string
    225     return BlockStartKeyword(kwd)
    226 enddef
    227 
    228 def BlockStartKeyword(line: string): string
    229     var kwd: string = line->matchstr('\l\+')
    230     return fullcommand(kwd, false)
    231 enddef
    232 
    233 {
    234     for kwds: list<string> in BLOCKS
    235         var [start: string, middle: string, end: string] = [kwds[0], '', kwds[-1]]
    236         if MODIFIERS->has_key(start->Unshorten())
    237             start = $'\%({MODIFIERS[start]}\)\={start}'
    238         endif
    239         if kwds->len() > 2
    240             middle = kwds[1 : -2]->join('\|')
    241         endif
    242         for kwd: string in kwds
    243             START_MIDDLE_END->extend({[kwd->Unshorten()]: [start, middle, end]})
    244         endfor
    245     endfor
    246 }
    247 
    248 START_MIDDLE_END = START_MIDDLE_END
    249     ->map((_, kwds: list<string>) =>
    250         kwds->map((_, kwd: string) => kwd == ''
    251         ? ''
    252         : $'\%(^\|{BAR_SEPARATION}\|\<sil\%[ent]\|{HIGHER_ORDER_COMMAND}\)\s*'
    253         .. $'\<\%({kwd}\)\>\%(\s\|$\|!\)\@=\%(\s*{OPERATOR}\)\@!'))
    254 
    255 lockvar! START_MIDDLE_END
    256 
    257 # ENDS_BLOCK {{{3
    258 
    259 const ENDS_BLOCK: string = '^\s*\%('
    260     .. BLOCKS
    261     ->copy()
    262     ->map((_, kwds: list<string>): string => kwds[-1])
    263     ->join('\|')
    264     .. '\|' .. CLOSING_BRACKET
    265     .. $'\){END_OF_COMMAND}'
    266 
    267 # ENDS_BLOCK_OR_CLAUSE {{{3
    268 
    269 patterns = BLOCKS
    270     ->copy()
    271     ->map((_, kwds: list<string>) => kwds[1 :])
    272     ->flattennew()
    273     # `catch` and `elseif` need to be handled as special cases
    274     ->filter((_, pat: string): bool => pat->Unshorten() !~ '^\%(catch\|elseif\)\>')
    275 
    276 const ENDS_BLOCK_OR_CLAUSE: string = '^\s*\%(' .. patterns->join('\|') .. $'\){END_OF_COMMAND}'
    277     .. $'\|^\s*cat\%[ch]\%(\s\+\({PATTERN_DELIMITER}\).*\1\)\={END_OF_COMMAND}'
    278     .. $'\|^\s*elseif\=\>\%(\s\|$\)\@=\%(\s*{OPERATOR}\)\@!'
    279 
    280 # STARTS_NAMED_BLOCK {{{3
    281 
    282 patterns = []
    283 {
    284     for kwds: list<string> in BLOCKS
    285         for kwd: string in kwds[0 : -2]
    286             if MODIFIERS->has_key(kwd->Unshorten())
    287                 patterns->add($'\%({MODIFIERS[kwd]}\)\={kwd}')
    288             else
    289                 patterns->add(kwd)
    290             endif
    291         endfor
    292     endfor
    293 }
    294 
    295 const STARTS_NAMED_BLOCK: string = $'^\s*\%(sil\%[ent]!\=\s\+\)\=\%({patterns->join('\|')}\)\>\%(\s\|$\|!\)\@='
    296 
    297 # STARTS_CURLY_BLOCK {{{3
    298 
    299 # TODO: `{` alone on a line is not necessarily the start of a block.
    300 # It  could be  a dictionary  if the  previous line  ends with  a binary/ternary
    301 # operator.  This  can cause  an issue whenever  we use  `STARTS_CURLY_BLOCK` or
    302 # `LINE_CONTINUATION_AT_EOL`.
    303 const STARTS_CURLY_BLOCK: string = '\%('
    304     .. '^\s*{'
    305     .. '\|' .. '^.*\zs\s=>\s\+{'
    306     .. '\|' ..  $'^\%(\s*\|.*{BAR_SEPARATION}\s*\)\%(com\%[mand]\|au\%[tocmd]\).*\zs\s{{'
    307     .. '\)' .. END_OF_COMMAND
    308 
    309 # STARTS_FUNCTION {{{3
    310 
    311 const STARTS_FUNCTION: string = $'^\s*\%({MODIFIERS.def}\)\=def\>!\=\s\@='
    312 
    313 # ENDS_FUNCTION {{{3
    314 
    315 const ENDS_FUNCTION: string = $'^\s*enddef\>{END_OF_COMMAND}'
    316 
    317 # ASSIGNS_HEREDOC {{{3
    318 
    319 const ASSIGNS_HEREDOC: string = $'^\%({COMMENT}\)\@!.*\%({HEREDOC_OPERATOR}\)\s\+\zs[A-Z]\+{END_OF_LINE}'
    320 
    321 # PLUS_MINUS_COMMAND {{{3
    322 
    323 # In legacy, the `:+` and `:-` commands are not required to be preceded by a colon.
    324 # As a result, when `+` or `-` is alone on a line, there is ambiguity.
    325 # It might be an operator or a command.
    326 # To not break the indentation in legacy scripts, we might need to consider such
    327 # lines as commands.
    328 const PLUS_MINUS_COMMAND: string = '^\s*[+-]\s*$'
    329 
    330 # TRICKY_COMMANDS {{{3
    331 
    332 # Some  commands  are tricky  because  they  accept  an  argument which  can  be
    333 # conflated with an operator.  Examples:
    334 #
    335 #     argdelete *
    336 #     cd -
    337 #     normal! ==
    338 #     nunmap <buffer> (
    339 #
    340 # TODO: Other commands might accept operators as argument.  Handle them too.
    341 patterns =<< trim eval END
    342     {'\'}<argd\%[elete]\s\+\*\s*$
    343     \<[lt]\=cd!\=\s\+-\s*$
    344     \<norm\%[al]!\=\s\+.*$
    345     \<reg\%[isters]\%(\s\+\S\+\)\+$
    346     \%(\<sil\%[ent]!\=\s\+\)\=\<[nvxsoilct]\=\%(nore\|un\)\=map!\=\s
    347     \<set\%(\%[global]\|\%[local]\)\>.*,$
    348     {PLUS_MINUS_COMMAND}
    349 END
    350 
    351 const TRICKY_COMMANDS: string = patterns->join('\|')
    352 # }}}2
    353 # EOL {{{2
    354 # OPENING_BRACKET_AT_EOL {{{3
    355 
    356 const OPENING_BRACKET_AT_EOL: string = OPENING_BRACKET .. END_OF_VIM9_LINE
    357 
    358 # CLOSING_BRACKET_AT_EOL {{{3
    359 
    360 const CLOSING_BRACKET_AT_EOL: string = CLOSING_BRACKET .. END_OF_VIM9_LINE
    361 
    362 # COMMA_AT_EOL {{{3
    363 
    364 const COMMA_AT_EOL: string = $',{END_OF_VIM9_LINE}'
    365 
    366 # COMMA_OR_DICT_KEY_AT_EOL {{{3
    367 
    368 const COMMA_OR_DICT_KEY_AT_EOL: string = $'\%(,\|{DICT_KEY}\){END_OF_VIM9_LINE}'
    369 
    370 # LAMBDA_ARROW_AT_EOL {{{3
    371 
    372 const LAMBDA_ARROW_AT_EOL: string = $'\s=>{END_OF_VIM9_LINE}'
    373 
    374 # LINE_CONTINUATION_AT_EOL {{{3
    375 
    376 const LINE_CONTINUATION_AT_EOL: string = '\%('
    377     .. ','
    378     .. '\|' .. OPERATOR
    379     .. '\|' .. '\s=>'
    380     .. '\|' .. '[^=]\zs[[(]'
    381     .. '\|' .. DICT_KEY
    382     # `{` is ambiguous.
    383     # It can be the start of a dictionary or a block.
    384     # We only want to match the former.
    385     .. '\|' .. $'^\%({STARTS_CURLY_BLOCK}\)\@!.*\zs{{'
    386     .. '\)\s*\%(\s#[^{].*\)\=$'
    387 # }}}2
    388 # SOL {{{2
    389 # BACKSLASH_AT_SOL {{{3
    390 
    391 const BACKSLASH_AT_SOL: string = '^\s*\%(\\\|[#"]\\ \)'
    392 
    393 # CLOSING_BRACKET_AT_SOL {{{3
    394 
    395 const CLOSING_BRACKET_AT_SOL: string = $'^\s*{CLOSING_BRACKET}'
    396 
    397 # LINE_CONTINUATION_AT_SOL {{{3
    398 
    399 const LINE_CONTINUATION_AT_SOL: string = '^\s*\%('
    400     .. '\\'
    401     .. '\|' .. '[#"]\\ '
    402     .. '\|' .. OPERATOR
    403     .. '\|' .. '->\s*\h'
    404     .. '\|' .. '->\s*(' # lambda call: ->((v) => v ? "ON" : "OFF")()
    405     .. '\|' .. '\.\h'  # dict member
    406     .. '\|' .. '|'
    407     # TODO: `}` at the start of a line is not necessarily a line continuation.
    408     # Could be the end of a block.
    409     .. '\|' .. CLOSING_BRACKET
    410     .. '\)'
    411 
    412 # RANGE_AT_SOL {{{3
    413 
    414 const RANGE_AT_SOL: string = '^\s*:\S'
    415 # }}}1
    416 # Interface {{{1
    417 export def Expr(lnum = v:lnum): number # {{{2
    418     # line which is indented
    419     var line_A: dict<any> = {text: getline(lnum), lnum: lnum}
    420     # line above, on which we'll base the indent of line A
    421     var line_B: dict<any>
    422 
    423     if line_A->AtStartOf('HereDoc')
    424         line_A->CacheHeredoc()
    425     elseif line_A.lnum->IsInside('HereDoc')
    426         return line_A.text->HereDocIndent()
    427     elseif line_A.lnum->IsRightBelow('HereDoc')
    428         var ind: number = b:vimindent.startindent
    429         unlet! b:vimindent
    430         if line_A.text =~ ENDS_BLOCK_OR_CLAUSE
    431             return ind - shiftwidth()
    432         endif
    433         return ind
    434     endif
    435 
    436     # Don't move this block after the function header one.
    437     # Otherwise, we  might clear the cache  too early if the  line following the
    438     # header is a comment.
    439     if line_A.text =~ COMMENT
    440         return CommentIndent()
    441     endif
    442 
    443     line_B = PrevCodeLine(line_A.lnum)
    444     if line_A.text =~ BACKSLASH_AT_SOL
    445         if line_B.text =~ BACKSLASH_AT_SOL
    446             return Indent(line_B.lnum)
    447         endif
    448         return Indent(line_B.lnum) + IndentMoreLineContinuation()
    449     endif
    450 
    451     if line_A->AtStartOf('FuncHeader')
    452             && !IsInInterface()
    453         line_A.lnum->CacheFuncHeader()
    454     elseif line_A.lnum->IsInside('FuncHeader')
    455         return b:vimindent.startindent + 2 * shiftwidth()
    456     elseif line_A.lnum->IsRightBelow('FuncHeader')
    457         var startindent: number = b:vimindent.startindent
    458         unlet! b:vimindent
    459         if line_A.text =~ ENDS_FUNCTION
    460             return startindent
    461         endif
    462         return startindent + shiftwidth()
    463     endif
    464 
    465     var past_bracket_block: dict<any>
    466     if exists('b:vimindent')
    467             && b:vimindent->has_key('is_BracketBlock')
    468         past_bracket_block = RemovePastBracketBlock(line_A)
    469     endif
    470     if line_A->AtStartOf('BracketBlock')
    471         line_A->CacheBracketBlock()
    472     endif
    473     if line_A.lnum->IsInside('BracketBlock')
    474         var is_in_curly_block: bool = IsInCurlyBlock()
    475         for block: dict<any> in b:vimindent.block_stack
    476             if line_A.lnum <= block.startlnum
    477                 continue
    478             endif
    479             if !block->has_key('startindent')
    480                 block.startindent = Indent(block.startlnum)
    481             endif
    482             if !is_in_curly_block
    483                 return BracketBlockIndent(line_A, block)
    484             endif
    485         endfor
    486     endif
    487     if line_A.text->ContinuesBelowBracketBlock(line_B, past_bracket_block)
    488             && line_A.text !~ CLOSING_BRACKET_AT_SOL
    489         return past_bracket_block.startindent
    490             + (past_bracket_block.startline =~ STARTS_NAMED_BLOCK ? 2 * shiftwidth() : 0)
    491     endif
    492 
    493     # Problem: If we press `==` on the line right below the start of a multiline
    494     # lambda (split after its arrow `=>`), the indent is not correct.
    495     # Solution: Indent relative to the line above.
    496     if line_B->EndsWithLambdaArrow()
    497         return Indent(line_B.lnum) + shiftwidth() + IndentMoreInBracketBlock()
    498     endif
    499     # FIXME: Similar issue here:
    500     #
    501     #     var x = []
    502     #         ->filter((_, _) =>
    503     #             true)
    504     #         ->items()
    505     #
    506     # Press `==` on last line.
    507     # Expected: The `->items()` line is indented like `->filter(...)`.
    508     # Actual: It's indented like `true)`.
    509     # Is it worth fixing? `=ip` gives  the correct indentation, because then the
    510     # cache is used.
    511 
    512     # Don't move this block before the heredoc one.{{{
    513     #
    514     # A heredoc might be assigned on the very first line.
    515     # And if it is, we need to cache some info.
    516     #}}}
    517     # Don't move it before the function header and bracket block ones either.{{{
    518     #
    519     # You could, because these blocks of code deal with construct which can only
    520     # appear  in a  Vim9  script.  And  in  a  Vim9 script,  the  first line  is
    521     # `vim9script`.  Or  maybe some legacy code/comment  (see `:help vim9-mix`).
    522     # But you  can't find a  Vim9 function header or  Vim9 bracket block  on the
    523     # first line.
    524     #
    525     # Anyway, even if you could, don't.  First, it would be inconsistent.
    526     # Second, it  could give unexpected results  while we're trying to  fix some
    527     # failing test.
    528     #}}}
    529     if line_A.lnum == 1
    530         return 0
    531     endif
    532 
    533     # Don't do that:
    534     #     if line_A.text !~ '\S'
    535     #         return -1
    536     #     endif
    537     # It would prevent  a line from being automatically indented  when using the
    538     # normal command `o`.
    539     # TODO: Can we write a test for this?
    540 
    541     if line_B.text =~ STARTS_CURLY_BLOCK
    542         return Indent(line_B.lnum) + shiftwidth() + IndentMoreInBracketBlock()
    543     endif
    544 
    545     if line_A.text =~ CLOSING_BRACKET_AT_SOL
    546         var start: number = MatchingOpenBracket(line_A)
    547         if start <= 0
    548             return -1
    549         endif
    550         return Indent(start) + IndentMoreInBracketBlock()
    551 
    552     elseif line_A.text =~ ENDS_BLOCK_OR_CLAUSE
    553             && !line_B->EndsWithLineContinuation()
    554         var kwd: string = BlockStartKeyword(line_A.text)
    555         if !START_MIDDLE_END->has_key(kwd)
    556             return -1
    557         endif
    558 
    559         # If the cursor  is after the match  for the end pattern,  we won't find
    560         # the start of the block.  Let's make sure that doesn't happen.
    561         cursor(line_A.lnum, 1)
    562 
    563         var [start: string, middle: string, end: string] = START_MIDDLE_END[kwd]
    564         var block_start: number = SearchPairStart(start, middle, end)
    565         if block_start > 0
    566             return Indent(block_start)
    567         endif
    568         return -1
    569     endif
    570 
    571     var base_ind: number
    572     if line_A->IsFirstLineOfCommand(line_B)
    573         line_A.isfirst = true
    574         line_B = line_B->FirstLinePreviousCommand()
    575         base_ind = Indent(line_B.lnum)
    576 
    577         if line_B->EndsWithCurlyBlock()
    578                 && !line_A->IsInThisBlock(line_B.lnum)
    579             return base_ind
    580         endif
    581 
    582     else
    583         line_A.isfirst = false
    584         base_ind = Indent(line_B.lnum)
    585 
    586         var line_C: dict<any> = PrevCodeLine(line_B.lnum)
    587         if !line_B->IsFirstLineOfCommand(line_C) || line_C.lnum <= 0
    588             return base_ind
    589         endif
    590     endif
    591 
    592     return base_ind + Offset(line_A, line_B)
    593 enddef
    594 
    595 def g:GetVimIndent(): number # {{{2
    596     # for backward compatibility
    597     return Expr()
    598 enddef
    599 # }}}1
    600 # Core {{{1
    601 def Offset( # {{{2
    602         # we indent this line ...
    603         line_A: dict<any>,
    604         # ... relatively to this line
    605         line_B: dict<any>,
    606         ): number
    607 
    608     if line_B->AtStartOf('FuncHeader')
    609             && IsInInterface()
    610         return 0
    611     endif
    612 
    613     # increase indentation inside a block
    614     if line_B.text =~ STARTS_NAMED_BLOCK
    615             || line_B->EndsWithCurlyBlock()
    616         # But don't indent if the line starting the block also closes it.
    617         if line_B->AlsoClosesBlock()
    618             return 0
    619         endif
    620         # Indent twice for  a line continuation in the block  header itself, so that
    621         # we can easily  distinguish the end of  the block header from  the start of
    622         # the block body.
    623         if (line_B->EndsWithLineContinuation()
    624                 && !line_A.isfirst)
    625                 || (line_A.text =~ LINE_CONTINUATION_AT_SOL
    626                 && line_A.text !~ PLUS_MINUS_COMMAND)
    627                 || line_A.text->Is_IN_KeywordForLoop(line_B.text)
    628             return 2 * shiftwidth()
    629         endif
    630         return shiftwidth()
    631     endif
    632 
    633     # increase indentation of  a line if it's the continuation  of a command which
    634     # started on a previous line
    635     if !line_A.isfirst
    636             && (line_B->EndsWithLineContinuation()
    637             || line_A.text =~ LINE_CONTINUATION_AT_SOL)
    638             && !(line_B->EndsWithComma() && line_A.lnum->IsInside('EnumBlock'))
    639         return shiftwidth()
    640     endif
    641 
    642     return 0
    643 enddef
    644 
    645 def HereDocIndent(line_A: string): number # {{{2
    646     # at the end of a heredoc
    647     if line_A =~ $'^\s*{b:vimindent.endmarker}$'
    648         # `END` must be at the very start of the line if the heredoc is not trimmed
    649         if !b:vimindent.is_trimmed
    650             # We can't invalidate the cache just yet.
    651             # The indent of `END` is meaningless;  it's always 0.  The next line
    652             # will need to be indented relative to the start of the heredoc.  It
    653             # must know where it starts; it needs the cache.
    654             return 0
    655         endif
    656         var ind: number = b:vimindent.startindent
    657         # invalidate the cache so that it's not used for the next heredoc
    658         unlet! b:vimindent
    659         return ind
    660     endif
    661 
    662     # In a non-trimmed heredoc, all of leading whitespace is semantic.
    663     # Leave it alone.
    664     if !b:vimindent.is_trimmed
    665         # But do save the indent of the assignment line.
    666         if !b:vimindent->has_key('startindent')
    667             b:vimindent.startindent = b:vimindent.startlnum->Indent()
    668         endif
    669         return -1
    670     endif
    671 
    672     # In a trimmed heredoc, *some* of the leading whitespace is semantic.
    673     # We want to preserve  it, so we can't just indent  relative to the assignment
    674     # line.  That's because we're dealing with data, not with code.
    675     # Instead, we need  to compute by how  much the indent of  the assignment line
    676     # was increased  or decreased.   Then, we  need to apply  that same  change to
    677     # every line inside the body.
    678     var offset: number
    679     if !b:vimindent->has_key('offset')
    680         var old_startindent: number = b:vimindent.startindent
    681         var new_startindent: number = b:vimindent.startlnum->Indent()
    682         offset = new_startindent - old_startindent
    683 
    684         # If all the non-empty lines in  the body have a higher indentation relative
    685         # to the assignment, there is no need to indent them more.
    686         # But if  at least one of  them does have  the same indentation level  (or a
    687         # lower one), then we want to indent it further (and the whole block with it).
    688         # This way,  we can clearly distinguish  the heredoc block from  the rest of
    689         # the code.
    690         var end: number = search($'^\s*{b:vimindent.endmarker}$', 'nW')
    691         var should_indent_more: bool = range(v:lnum, end - 1)
    692             ->indexof((_, lnum: number): bool => Indent(lnum) <= old_startindent && getline(lnum) != '') >= 0
    693         if should_indent_more
    694             offset += shiftwidth()
    695         endif
    696 
    697         b:vimindent.offset = offset
    698         b:vimindent.startindent = new_startindent
    699     endif
    700 
    701     return Indent(v:lnum) + b:vimindent.offset
    702 enddef
    703 
    704 def CommentIndent(): number # {{{2
    705     var line_B: dict<any>
    706     line_B.lnum = prevnonblank(v:lnum - 1)
    707     line_B.text = getline(line_B.lnum)
    708     if line_B.text =~ COMMENT
    709         return Indent(line_B.lnum)
    710     endif
    711 
    712     var next: number = NextCodeLine()
    713     if next == 0
    714         return 0
    715     endif
    716     var vimindent_save: dict<any> = get(b:, 'vimindent', {})->deepcopy()
    717     var ind: number = next->Expr()
    718     # The previous `Expr()` might have set or deleted `b:vimindent`.
    719     # This could  cause issues (e.g.  when indenting  2 commented lines  above a
    720     # heredoc).  Let's make sure the state of the variable is not altered.
    721     if vimindent_save->empty()
    722         unlet! b:vimindent
    723     else
    724         b:vimindent = vimindent_save
    725     endif
    726     if getline(next) =~ ENDS_BLOCK
    727         return ind + shiftwidth()
    728     endif
    729     return ind
    730 enddef
    731 
    732 def BracketBlockIndent(line_A: dict<any>, block: dict<any>): number # {{{2
    733     var ind: number = block.startindent
    734 
    735     if line_A.text =~ CLOSING_BRACKET_AT_SOL
    736         if b:vimindent.is_on_named_block_line
    737             ind += 2 * shiftwidth()
    738         endif
    739         return ind + IndentMoreInBracketBlock()
    740     endif
    741 
    742     var startline: dict<any> = {
    743         text: block.startline,
    744         lnum: block.startlnum
    745     }
    746     if startline->EndsWithComma()
    747             || startline->EndsWithLambdaArrow()
    748             || (startline->EndsWithOpeningBracket()
    749             # TODO: Is that reliable?
    750             && block.startline !~
    751             $'^\s*{NON_BRACKET}\+{LIST_OR_DICT_CLOSING_BRACKET},\s\+{LIST_OR_DICT_OPENING_BRACKET}')
    752         ind += shiftwidth() + IndentMoreInBracketBlock()
    753     endif
    754 
    755     if b:vimindent.is_on_named_block_line
    756         ind += shiftwidth()
    757     endif
    758 
    759     if block.is_dict
    760             && line_A.text !~ DICT_KEY
    761         ind += shiftwidth()
    762     endif
    763 
    764     return ind
    765 enddef
    766 
    767 def CacheHeredoc(line_A: dict<any>) # {{{2
    768     var endmarker: string = line_A.text->matchstr(ASSIGNS_HEREDOC)
    769     var endlnum: number = search($'^\s*{endmarker}$', 'nW')
    770     var is_trimmed: bool = line_A.text =~ $'.*\s\%(trim\%(\s\+eval\)\=\)\s\+[A-Z]\+{END_OF_LINE}'
    771     b:vimindent = {
    772         is_HereDoc: true,
    773         startlnum: line_A.lnum,
    774         endlnum: endlnum,
    775         endmarker: endmarker,
    776         is_trimmed: is_trimmed,
    777     }
    778     if is_trimmed
    779         b:vimindent.startindent = Indent(line_A.lnum)
    780     endif
    781     RegisterCacheInvalidation()
    782 enddef
    783 
    784 def CacheFuncHeader(startlnum: number) # {{{2
    785     var pos: list<number> = getcurpos()
    786     cursor(startlnum, 1)
    787     if search('(', 'W', startlnum) <= 0
    788         return
    789     endif
    790     var endlnum: number = SearchPair('(', '', ')', 'nW')
    791     setpos('.', pos)
    792     if endlnum == startlnum
    793         return
    794     endif
    795 
    796     b:vimindent = {
    797         is_FuncHeader: true,
    798         startindent: startlnum->Indent(),
    799         endlnum: endlnum,
    800     }
    801     RegisterCacheInvalidation()
    802 enddef
    803 
    804 def CacheBracketBlock(line_A: dict<any>) # {{{2
    805     var pos: list<number> = getcurpos()
    806     var opening: string = line_A.text->matchstr(CHARACTER_UNDER_CURSOR)
    807     var closing: string = {'[': ']', '{': '}', '(': ')'}[opening]
    808     var endlnum: number = SearchPair(opening, '', closing, 'nW')
    809     setpos('.', pos)
    810     if endlnum <= line_A.lnum
    811         return
    812     endif
    813 
    814     if !exists('b:vimindent')
    815         b:vimindent = {
    816             is_BracketBlock: true,
    817             is_on_named_block_line: line_A.text =~ STARTS_NAMED_BLOCK,
    818             block_stack: [],
    819         }
    820     endif
    821 
    822     var is_dict: bool
    823     var is_curly_block: bool
    824     if opening == '{'
    825         if line_A.text =~ STARTS_CURLY_BLOCK
    826             [is_dict, is_curly_block] = [false, true]
    827         else
    828             [is_dict, is_curly_block] = [true, false]
    829         endif
    830     endif
    831     b:vimindent.block_stack->insert({
    832         is_dict: is_dict,
    833         is_curly_block: is_curly_block,
    834         startline: line_A.text,
    835         startlnum: line_A.lnum,
    836         endlnum: endlnum,
    837     })
    838 
    839     RegisterCacheInvalidation()
    840 enddef
    841 
    842 def RegisterCacheInvalidation() # {{{2
    843     # invalidate the cache so that it's not used for the next `=` normal command
    844     autocmd_add([{
    845         cmd: 'unlet! b:vimindent',
    846         event: 'ModeChanged',
    847         group: '__VimIndent__',
    848         once: true,
    849         pattern: '*:n',
    850         replace: true,
    851     }])
    852 enddef
    853 
    854 def RemovePastBracketBlock(line_A: dict<any>): dict<any> # {{{2
    855     var stack: list<dict<any>> = b:vimindent.block_stack
    856 
    857     var removed: dict<any>
    858     if line_A.lnum > stack[0].endlnum
    859         removed = stack[0]
    860     endif
    861 
    862     stack->filter((_, block: dict<any>): bool => line_A.lnum <= block.endlnum)
    863     if stack->empty()
    864         unlet! b:vimindent
    865     endif
    866     return removed
    867 enddef
    868 # }}}1
    869 # Util {{{1
    870 # Get {{{2
    871 def Indent(lnum: number): number # {{{3
    872     if lnum <= 0
    873         # Don't  return `-1`.  It could cause `Expr()` to return a non-multiple of `'shiftwidth'`.{{{
    874         #
    875         # It would be  OK if we were always returning  `Indent()` directly.  But
    876         # we  don't.  Most  of  the  time, we  include  it  in some  computation
    877         # like  `Indent(...) + shiftwidth()`.   If  `'shiftwidth'` is  `4`,  and
    878         # `Indent()` returns `-1`, `Expr()` will end up returning `3`.
    879         #}}}
    880         return 0
    881     endif
    882     return indent(lnum)
    883 enddef
    884 
    885 def MatchingOpenBracket(line: dict<any>): number # {{{3
    886     var end: string = line.text->matchstr(CLOSING_BRACKET)
    887     var start: string = {']': '[', '}': '{', ')': '('}[end]
    888     cursor(line.lnum, 1)
    889     return SearchPairStart(start, '', end)
    890 enddef
    891 
    892 def FirstLinePreviousCommand(line: dict<any>): dict<any> # {{{3
    893     var line_B: dict<any> = line
    894 
    895     while line_B.lnum > 1
    896         var code_line_above: dict<any> = PrevCodeLine(line_B.lnum)
    897 
    898         if line_B.text =~ CLOSING_BRACKET_AT_SOL
    899             var n: number = MatchingOpenBracket(line_B)
    900 
    901             if n <= 0
    902                 break
    903             endif
    904 
    905             line_B.lnum = n
    906             line_B.text = getline(line_B.lnum)
    907             continue
    908 
    909         elseif line_B->IsFirstLineOfCommand(code_line_above)
    910             break
    911         endif
    912 
    913         line_B = code_line_above
    914     endwhile
    915 
    916     return line_B
    917 enddef
    918 
    919 def PrevCodeLine(lnum: number): dict<any> # {{{3
    920     var line: string = getline(lnum)
    921     if line =~ '^\s*[A-Z]\+$'
    922         var endmarker: string = line->matchstr('[A-Z]\+')
    923         var pos: list<number> = getcurpos()
    924         cursor(lnum, 1)
    925         var n: number = search(ASSIGNS_HEREDOC, 'bnW')
    926         setpos('.', pos)
    927         if n > 0
    928             line = getline(n)
    929             if line =~ $'{HEREDOC_OPERATOR}\s\+{endmarker}'
    930                 return {lnum: n, text: line}
    931             endif
    932         endif
    933     endif
    934 
    935     var n: number = prevnonblank(lnum - 1)
    936     line = getline(n)
    937     while line =~ COMMENT && n > 1
    938         n = prevnonblank(n - 1)
    939         line = getline(n)
    940     endwhile
    941     # If we get back to the first line, we return 1 no matter what; even if it's a
    942     # commented line.   That should not  cause an issue  though.  We just  want to
    943     # avoid a  commented line above which  there is a  line of code which  is more
    944     # relevant.  There is nothing above the first line.
    945     return {lnum: n, text: line}
    946 enddef
    947 
    948 def NextCodeLine(): number # {{{3
    949     var last: number = line('$')
    950     if v:lnum == last
    951         return 0
    952     endif
    953 
    954     var lnum: number = v:lnum + 1
    955     while lnum <= last
    956         var line: string = getline(lnum)
    957         if line != '' && line !~ COMMENT
    958             return lnum
    959         endif
    960         ++lnum
    961     endwhile
    962     return 0
    963 enddef
    964 
    965 def SearchPair( # {{{3
    966         start: string,
    967         middle: string,
    968         end: string,
    969         flags: string,
    970         stopline = 0,
    971         ): number
    972 
    973     var s: string = start
    974     var e: string = end
    975     if start == '[' || start == ']'
    976         s = s->escape('[]')
    977     endif
    978     if end == '[' || end == ']'
    979         e = e->escape('[]')
    980     endif
    981     # VIM_INDENT_TEST_TRACE_START
    982     return searchpair('\C' .. s, (middle == '' ? '' : '\C' .. middle), '\C' .. e,
    983         flags, (): bool => InCommentOrString(), stopline, TIMEOUT)
    984     # VIM_INDENT_TEST_TRACE_END dist#vimindent#SearchPair
    985 enddef
    986 
    987 def SearchPairStart( # {{{3
    988         start: string,
    989         middle: string,
    990         end: string,
    991         ): number
    992     return SearchPair(start, middle, end, 'bnW')
    993 enddef
    994 
    995 def SearchPairEnd( # {{{3
    996         start: string,
    997         middle: string,
    998         end: string,
    999         stopline = 0,
   1000         ): number
   1001     return SearchPair(start, middle, end, 'nW', stopline)
   1002 enddef
   1003 # }}}2
   1004 # Test {{{2
   1005 def AtStartOf(line_A: dict<any>, syntax: string): bool # {{{3
   1006     if syntax == 'BracketBlock'
   1007         return AtStartOfBracketBlock(line_A)
   1008     endif
   1009 
   1010     var pat: string = {
   1011         HereDoc: ASSIGNS_HEREDOC,
   1012         FuncHeader: STARTS_FUNCTION
   1013     }[syntax]
   1014     return line_A.text =~ pat
   1015         && (!exists('b:vimindent') || !b:vimindent->has_key('is_HereDoc'))
   1016 enddef
   1017 
   1018 def AtStartOfBracketBlock(line_A: dict<any>): bool # {{{3
   1019     # We  ignore bracket  blocks  while we're  indenting  a function  header
   1020     # because  it makes  the logic  simpler.  It  might mean  that we  don't
   1021     # indent correctly a  multiline bracket block inside  a function header,
   1022     # but that's  a corner case for  which it doesn't seem  worth making the
   1023     # code more complex.
   1024     if exists('b:vimindent')
   1025             && !b:vimindent->has_key('is_BracketBlock')
   1026         return false
   1027     endif
   1028 
   1029     var pos: list<number> = getcurpos()
   1030     cursor(line_A.lnum, [line_A.lnum, '$']->col())
   1031 
   1032     if SearchPair(OPENING_BRACKET, '', CLOSING_BRACKET, 'bcW', line_A.lnum) <= 0
   1033         setpos('.', pos)
   1034         return false
   1035     endif
   1036     # Don't restore the cursor position.
   1037     # It needs to be on a bracket for `CacheBracketBlock()` to work as intended.
   1038 
   1039     return line_A->EndsWithOpeningBracket()
   1040         || line_A->EndsWithCommaOrDictKey()
   1041         || line_A->EndsWithLambdaArrow()
   1042 enddef
   1043 
   1044 def ContinuesBelowBracketBlock( # {{{3
   1045         line_A: string,
   1046         line_B: dict<any>,
   1047         block: dict<any>
   1048         ): bool
   1049 
   1050     return !block->empty()
   1051         && (line_A =~ LINE_CONTINUATION_AT_SOL
   1052         || line_B->EndsWithLineContinuation())
   1053 enddef
   1054 
   1055 def IsInside(lnum: number, syntax: string): bool # {{{3
   1056     if syntax == 'EnumBlock'
   1057         var cur_pos = getpos('.')
   1058         cursor(lnum, 1)
   1059         var enum_pos = search('^\C\s*\%(export\s\)\=\s*enum\s\+\S\+', 'bnW')
   1060         var endenum_pos = search('^\C\s*endenum\>', 'bnW')
   1061         setpos('.', cur_pos)
   1062 
   1063         if enum_pos == 0 && endenum_pos == 0
   1064             return false
   1065         endif
   1066         if (enum_pos > 0 && (endenum_pos == 0 || enum_pos > endenum_pos))
   1067             return true
   1068         endif
   1069         return false
   1070     endif
   1071 
   1072     if !exists('b:vimindent')
   1073             || !b:vimindent->has_key($'is_{syntax}')
   1074         return false
   1075     endif
   1076 
   1077     if syntax == 'BracketBlock'
   1078         if !b:vimindent->has_key('block_stack')
   1079                 || b:vimindent.block_stack->empty()
   1080             return false
   1081         endif
   1082         return lnum <= b:vimindent.block_stack[0].endlnum
   1083     endif
   1084 
   1085     return lnum <= b:vimindent.endlnum
   1086 enddef
   1087 
   1088 def IsRightBelow(lnum: number, syntax: string): bool # {{{3
   1089     return exists('b:vimindent')
   1090         && b:vimindent->has_key($'is_{syntax}')
   1091         && lnum > b:vimindent.endlnum
   1092 enddef
   1093 
   1094 def IsInCurlyBlock(): bool # {{{3
   1095     return b:vimindent.block_stack
   1096         ->indexof((_, block: dict<any>): bool => block.is_curly_block) >= 0
   1097 enddef
   1098 
   1099 def IsInThisBlock(line_A: dict<any>, lnum: number): bool # {{{3
   1100     var pos: list<number> = getcurpos()
   1101     cursor(lnum, [lnum, '$']->col())
   1102     var end: number = SearchPairEnd('{', '', '}')
   1103     setpos('.', pos)
   1104 
   1105     return line_A.lnum <= end
   1106 enddef
   1107 
   1108 def IsInInterface(): bool # {{{3
   1109     return SearchPair('interface', '', 'endinterface', 'nW') > 0
   1110 enddef
   1111 
   1112 def IsFirstLineOfCommand(line_1: dict<any>, line_2: dict<any>): bool # {{{3
   1113     if line_1.text->Is_IN_KeywordForLoop(line_2.text)
   1114         return false
   1115     endif
   1116 
   1117     if line_1.text =~ RANGE_AT_SOL
   1118             || line_1.text =~ PLUS_MINUS_COMMAND
   1119         return true
   1120     endif
   1121 
   1122     if line_2.text =~ DICT_KEY
   1123             && !line_1->IsInThisBlock(line_2.lnum)
   1124         return true
   1125     endif
   1126 
   1127     var line_1_is_good: bool = line_1.text !~ COMMENT
   1128         && line_1.text !~ DICT_KEY
   1129         && line_1.text !~ LINE_CONTINUATION_AT_SOL
   1130 
   1131     var line_2_is_good: bool = !line_2->EndsWithLineContinuation()
   1132 
   1133     return line_1_is_good && line_2_is_good
   1134 enddef
   1135 
   1136 def Is_IN_KeywordForLoop(line_1: string, line_2: string): bool # {{{3
   1137     return line_2 =~ '^\s*for\s'
   1138         && line_1 =~ '^\s*in\s'
   1139 enddef
   1140 
   1141 def InCommentOrString(): bool # {{{3
   1142     return synstack('.', col('.'))
   1143         ->indexof((_, id: number): bool => synIDattr(id, 'name') =~ '\ccomment\|string\|heredoc') >= 0
   1144 enddef
   1145 
   1146 def AlsoClosesBlock(line_B: dict<any>): bool # {{{3
   1147     # We know that `line_B` opens a block.
   1148     # Let's see if it also closes that block.
   1149     var kwd: string = BlockStartKeyword(line_B.text)
   1150     if !START_MIDDLE_END->has_key(kwd)
   1151         return false
   1152     endif
   1153 
   1154     var [start: string, middle: string, end: string] = START_MIDDLE_END[kwd]
   1155     var pos: list<number> = getcurpos()
   1156     cursor(line_B.lnum, 1)
   1157     var block_end: number = SearchPairEnd(start, middle, end, line_B.lnum)
   1158     setpos('.', pos)
   1159 
   1160     return block_end > 0
   1161 enddef
   1162 
   1163 def EndsWithComma(line: dict<any>): bool # {{{3
   1164     return NonCommentedMatch(line, COMMA_AT_EOL)
   1165 enddef
   1166 
   1167 def EndsWithCommaOrDictKey(line_A: dict<any>): bool # {{{3
   1168     return NonCommentedMatch(line_A, COMMA_OR_DICT_KEY_AT_EOL)
   1169 enddef
   1170 
   1171 def EndsWithCurlyBlock(line_B: dict<any>): bool # {{{3
   1172     return NonCommentedMatch(line_B, STARTS_CURLY_BLOCK)
   1173 enddef
   1174 
   1175 def EndsWithLambdaArrow(line_A: dict<any>): bool # {{{3
   1176     return NonCommentedMatch(line_A, LAMBDA_ARROW_AT_EOL)
   1177 enddef
   1178 
   1179 def EndsWithLineContinuation(line_B: dict<any>): bool # {{{3
   1180     return NonCommentedMatch(line_B, LINE_CONTINUATION_AT_EOL)
   1181 enddef
   1182 
   1183 def EndsWithOpeningBracket(line: dict<any>): bool # {{{3
   1184     return NonCommentedMatch(line, OPENING_BRACKET_AT_EOL)
   1185 enddef
   1186 
   1187 def EndsWithClosingBracket(line: dict<any>): bool # {{{3
   1188     return NonCommentedMatch(line, CLOSING_BRACKET_AT_EOL)
   1189 enddef
   1190 
   1191 def NonCommentedMatch(line: dict<any>, pat: string): bool # {{{3
   1192     # Could happen if there is no code above us, and we're not on the 1st line.
   1193     # In that case, `PrevCodeLine()` returns `{lnum: 0, line: ''}`.
   1194     if line.lnum == 0
   1195         return false
   1196     endif
   1197 
   1198     # Technically, that's wrong.  A  line might start with a range  and end with a
   1199     # line continuation symbol.  But it's unlikely.  And it's useful to assume the
   1200     # opposite because it  prevents us from conflating a mark  with an operator or
   1201     # the start of a list:
   1202     #
   1203     #              not a comparison operator
   1204     #              v
   1205     #     :'< mark <
   1206     #     :'< mark [
   1207     #              ^
   1208     #              not the start of a list
   1209     if line.text =~ RANGE_AT_SOL
   1210         return false
   1211     endif
   1212 
   1213     #                    that's not an arithmetic operator
   1214     #                    v
   1215     #     catch /pattern /
   1216     #
   1217     # When `/` is used as a pattern delimiter, it's always present twice.
   1218     # And  usually, the  first occurrence  is  in the  middle of  a sequence  of
   1219     # non-whitespace characters.  If we can find  such a `/`, we assume that the
   1220     # trailing `/` is not an operator.
   1221     # Warning: Here, don't use a too complex pattern.{{{
   1222     #
   1223     # In particular, avoid backreferences.
   1224     # For example, this would be too costly:
   1225     #
   1226     #     if line.text =~ $'\%(\S*\({PATTERN_DELIMITER}\)\S\+\|\S\+\({PATTERN_DELIMITER}\)\S*\)'
   1227     #             .. $'\s\+\1{END_OF_COMMAND}'
   1228     #
   1229     # Sometimes, it could even give `E363`.
   1230     #}}}
   1231     var delim: string = line.text
   1232         ->matchstr($'\s\+\zs{PATTERN_DELIMITER}\ze{END_OF_COMMAND}')
   1233     if !delim->empty()
   1234         delim = $'\V{delim}\m'
   1235         if line.text =~ $'\%(\S*{delim}\S\+\|\S\+{delim}\S*\)\s\+{delim}{END_OF_COMMAND}'
   1236             return false
   1237         endif
   1238     endif
   1239     # TODO: We might still miss some corner cases:{{{
   1240     #
   1241     #                          conflated with arithmetic division
   1242     #                          v
   1243     #     substitute/pat / rep /
   1244     #         echo
   1245     #     ^--^
   1246     #      ✘
   1247     #
   1248     # A better way to handle all these corner cases, would be to inspect the top
   1249     # of the syntax stack:
   1250     #
   1251     #     :echo synID('.', col('.'), v:false)->synIDattr('name')
   1252     #
   1253     # Unfortunately, the legacy syntax plugin is not accurate enough.
   1254     # For example, it doesn't highlight a slash as an operator.
   1255     # }}}
   1256 
   1257     # `%` at the end of a line is tricky.
   1258     # It might be the modulo operator or the current file (e.g. `edit %`).
   1259     # Let's assume it's the latter.
   1260     if line.text =~ $'%{END_OF_COMMAND}'
   1261         return false
   1262     endif
   1263 
   1264     if line.text =~ TRICKY_COMMANDS
   1265         return false
   1266     endif
   1267 
   1268     var pos: list<number> = getcurpos()
   1269     cursor(line.lnum, 1)
   1270     # VIM_INDENT_TEST_TRACE_START
   1271     var match_lnum: number = search(pat, 'cnW', line.lnum, TIMEOUT, (): bool => InCommentOrString())
   1272     # VIM_INDENT_TEST_TRACE_END dist#vimindent#NonCommentedMatch
   1273     setpos('.', pos)
   1274     return match_lnum > 0
   1275 enddef
   1276 # }}}1
   1277 # vim:sw=4