summaryrefslogtreecommitdiffstats
path: root/runtime/indent/context.vim
blob: 762c5c16a106f5427ed6ffaefb2c79a51af61b5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
vim9script

# Language:           ConTeXt typesetting engine
# Maintainer:         Nicola Vitacolonna <nvitacolonna@gmail.com>
# Former Maintainers: Nikolai Weibull <now@bitwi.se>
# Latest Revision:    2022 Aug 12

if exists("b:did_indent")
  finish
endif

# Load MetaPost indentation script (this will also set b:did_indent)
runtime! indent/mp.vim

setlocal indentexpr=ConTeXtIndent()

b:undo_indent = "setl indentexpr<"

def PrevNotComment(l: number): number
  var prevlnum = prevnonblank(l)

  while prevlnum > 0 && getline(prevlnum) =~# '^\s*%'
    prevlnum = prevnonblank(prevlnum - 1)
  endwhile

  return prevlnum
enddef

def FindPair(pstart: string, pmid: string, pend: string): number
  cursor(v:lnum, 1)
  return indent(searchpair(pstart, pmid, pend, 'bWn',
    'synIDattr(synID(line("."), col("."), 0), "name") =~? "string\\|comment"'))
enddef

def ConTeXtIndent(): number
  # Use MetaPost rules inside MetaPost graphic environments
  if len(synstack(v:lnum, 1)) > 0 &&
    synIDattr(synstack(v:lnum, 1)[0], "name") ==# 'contextMPGraphic'
    return g:MetaPostIndent()
  endif

  const prevlnum = PrevNotComment(v:lnum - 1)
  const prevind  = indent(prevlnum)
  const prevline = getline(prevlnum)
  const currline = getline(v:lnum)

  # If the current line starts with ], match indentation.
  if currline =~# '^\s*\]'
    return FindPair('\[', '', '\]')
  endif

  # If the current line starts with }, match indentation.
  if currline =~# '^\s*}'
    return FindPair('{', '', '}')
  endif

  # If the previous line ends with [ or { (possibly followed by a comment) then indent.
  if prevline =~# '[{[]\s*\%(%.*\)\=$'
    return prevind + shiftwidth()
  endif

  return -1
enddef

# vim: sw=2 fdm=marker