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