blob: 8e4c60322eb0ba17cbd154a6d1647676f4c2f082 [file] [log] [blame]
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001" Vim indent file
2" Language: Julia
3" Maintainer: Carlo Baldassi <carlobaldassi@gmail.com>
4" Homepage: https://github.com/JuliaEditorSupport/julia-vim
Bram Moolenaard592deb2022-06-17 15:42:40 +01005" Last Change: 2022 Jun 14
Bram Moolenaar6aa57292021-08-14 21:25:52 +02006" Notes: originally based on Bram Molenaar's indent file for vim
7
Bram Moolenaard592deb2022-06-17 15:42:40 +01008" Only load this indent file when no other was loaded.
9if exists("b:did_indent")
10 finish
11endif
12let b:did_indent = 1
13
Bram Moolenaar6aa57292021-08-14 21:25:52 +020014setlocal autoindent
15
16setlocal indentexpr=GetJuliaIndent()
17setlocal indentkeys+==end,=else,=catch,=finally,),],}
18setlocal indentkeys-=0#
19setlocal indentkeys-=:
20setlocal indentkeys-=0{
21setlocal indentkeys-=0}
22setlocal nosmartindent
23
24" Only define the function once.
25if exists("*GetJuliaIndent")
26 finish
27endif
28
29let s:skipPatternsBasic = '\<julia\%(Comment\%([LM]\|Delim\)\)\>'
30let s:skipPatterns = '\<julia\%(Comprehension\%(For\|If\)\|RangeKeyword\|Comment\%([LM]\|Delim\)\|\%([bs]\|Shell\|Printf\|Doc\)\?String\|StringPrefixed\|DocStringM\(Raw\)\?\|RegEx\|SymbolS\?\|Macro\|Dotted\)\>'
31
32function JuliaMatch(lnum, str, regex, st, ...)
33 let s = a:st
34 let e = a:0 > 0 ? a:1 : -1
35 let basic_skip = a:0 > 1 ? a:2 : 'all'
36 let skip = basic_skip ==# 'basic' ? s:skipPatternsBasic : s:skipPatterns
37 while 1
38 let f = match(a:str, '\C' . a:regex, s)
39 if e >= 0 && f >= e
40 return -1
41 endif
42 if f >= 0
43 let attr = synIDattr(synID(a:lnum,f+1,1),"name")
44 let attrT = synIDattr(synID(a:lnum,f+1,0),"name")
45 if attr =~# skip || attrT =~# skip
46 let s = f+1
47 continue
48 endif
49 endif
50 break
51 endwhile
52 return f
53endfunction
54
55function GetJuliaNestingStruct(lnum, ...)
56 " Auxiliary function to inspect the block structure of a line
57 let line = getline(a:lnum)
58 let s = a:0 > 0 ? a:1 : 0
59 let e = a:0 > 1 ? a:2 : -1
60 let blocks_stack = []
61 let num_closed_blocks = 0
62 while 1
63 let fb = JuliaMatch(a:lnum, line, '\<\%(if\|else\%(if\)\?\|while\|for\|try\|catch\|finally\|\%(staged\)\?function\|macro\|begin\|mutable\s\+struct\|\%(mutable\s\+\)\@<!struct\|\%(abstract\|primitive\)\s\+type\|let\|\%(bare\)\?module\|quote\|do\)\>', s, e)
64 let fe = JuliaMatch(a:lnum, line, '\<end\>', s, e)
65
66 if fb < 0 && fe < 0
67 " No blocks found
68 break
69 end
70
71 if fb >= 0 && (fb < fe || fe < 0)
72 " The first occurrence is an opening block keyword
73 " Note: some keywords (elseif,else,catch,finally) are both
74 " closing blocks and opening new ones
75
76 let i = JuliaMatch(a:lnum, line, '\<if\>', s)
77 if i >= 0 && i == fb
78 let s = i+1
79 call add(blocks_stack, 'if')
80 continue
81 endif
82 let i = JuliaMatch(a:lnum, line, '\<elseif\>', s)
83 if i >= 0 && i == fb
84 let s = i+1
85 if len(blocks_stack) > 0 && blocks_stack[-1] == 'if'
86 let blocks_stack[-1] = 'elseif'
87 elseif (len(blocks_stack) > 0 && blocks_stack[-1] != 'elseif') || len(blocks_stack) == 0
88 call add(blocks_stack, 'elseif')
89 let num_closed_blocks += 1
90 endif
91 continue
92 endif
93 let i = JuliaMatch(a:lnum, line, '\<else\>', s)
94 if i >= 0 && i == fb
95 let s = i+1
96 if len(blocks_stack) > 0 && blocks_stack[-1] =~# '\<\%(else\)\=if\>'
97 let blocks_stack[-1] = 'else'
98 else
99 call add(blocks_stack, 'else')
100 let num_closed_blocks += 1
101 endif
102 continue
103 endif
104
105 let i = JuliaMatch(a:lnum, line, '\<try\>', s)
106 if i >= 0 && i == fb
107 let s = i+1
108 call add(blocks_stack, 'try')
109 continue
110 endif
111 let i = JuliaMatch(a:lnum, line, '\<catch\>', s)
112 if i >= 0 && i == fb
113 let s = i+1
114 if len(blocks_stack) > 0 && blocks_stack[-1] == 'try'
115 let blocks_stack[-1] = 'catch'
116 else
117 call add(blocks_stack, 'catch')
118 let num_closed_blocks += 1
119 endif
120 continue
121 endif
122 let i = JuliaMatch(a:lnum, line, '\<finally\>', s)
123 if i >= 0 && i == fb
124 let s = i+1
125 if len(blocks_stack) > 0 && (blocks_stack[-1] == 'try' || blocks_stack[-1] == 'catch')
126 let blocks_stack[-1] = 'finally'
127 else
128 call add(blocks_stack, 'finally')
129 let num_closed_blocks += 1
130 endif
131 continue
132 endif
133
134 let i = JuliaMatch(a:lnum, line, '\<\%(bare\)\?module\>', s)
135 if i >= 0 && i == fb
136 let s = i+1
137 if i == 0
138 call add(blocks_stack, 'col1module')
139 else
140 call add(blocks_stack, 'other')
141 endif
142 continue
143 endif
144
145 let i = JuliaMatch(a:lnum, line, '\<\%(while\|for\|function\|macro\|begin\|\%(mutable\s\+\)\?struct\|\%(abstract\|primitive\)\s\+type\|let\|quote\|do\)\>', s)
146 if i >= 0 && i == fb
147 if match(line, '\C\<\%(mutable\|abstract\|primitive\)', i) != -1
148 let s = i+11
149 else
150 let s = i+1
151 endif
152 call add(blocks_stack, 'other')
153 continue
154 endif
155
156 " Note: it should be impossible to get here
157 break
158
159 else
160 " The first occurrence is an 'end'
161
162 let s = fe+1
163 if len(blocks_stack) == 0
164 let num_closed_blocks += 1
165 else
166 call remove(blocks_stack, -1)
167 endif
168 continue
169
170 endif
171
172 " Note: it should be impossible to get here
173 break
174 endwhile
175 let num_open_blocks = len(blocks_stack) - count(blocks_stack, 'col1module')
176 return [num_open_blocks, num_closed_blocks]
177endfunction
178
179function GetJuliaNestingBrackets(lnum, c)
180 " Auxiliary function to inspect the brackets structure of a line
181 let line = getline(a:lnum)[0 : (a:c - 1)]
182 let s = 0
183 let brackets_stack = []
184 let last_closed_bracket = -1
185 while 1
186 let fb = JuliaMatch(a:lnum, line, '[([{]', s)
187 let fe = JuliaMatch(a:lnum, line, '[])}]', s)
188
189 if fb < 0 && fe < 0
190 " No brackets found
191 break
192 end
193
194 if fb >= 0 && (fb < fe || fe < 0)
195 " The first occurrence is an opening bracket
196
197 let i = JuliaMatch(a:lnum, line, '(', s)
198 if i >= 0 && i == fb
199 let s = i+1
200 call add(brackets_stack, ['par',i])
201 continue
202 endif
203
204 let i = JuliaMatch(a:lnum, line, '\[', s)
205 if i >= 0 && i == fb
206 let s = i+1
207 call add(brackets_stack, ['sqbra',i])
208 continue
209 endif
210
211 let i = JuliaMatch(a:lnum, line, '{', s)
212 if i >= 0 && i == fb
213 let s = i+1
214 call add(brackets_stack, ['curbra',i])
215 continue
216 endif
217
218 " Note: it should be impossible to get here
219 break
220
221 else
222 " The first occurrence is a closing bracket
223
224 let i = JuliaMatch(a:lnum, line, ')', s)
225 if i >= 0 && i == fe
226 let s = i+1
227 if len(brackets_stack) > 0 && brackets_stack[-1][0] == 'par'
228 call remove(brackets_stack, -1)
229 else
230 let last_closed_bracket = i + 1
231 endif
232 continue
233 endif
234
235 let i = JuliaMatch(a:lnum, line, ']', s)
236 if i >= 0 && i == fe
237 let s = i+1
238 if len(brackets_stack) > 0 && brackets_stack[-1][0] == 'sqbra'
239 call remove(brackets_stack, -1)
240 else
241 let last_closed_bracket = i + 1
242 endif
243 continue
244 endif
245
246 let i = JuliaMatch(a:lnum, line, '}', s)
247 if i >= 0 && i == fe
248 let s = i+1
249 if len(brackets_stack) > 0 && brackets_stack[-1][0] == 'curbra'
250 call remove(brackets_stack, -1)
251 else
252 let last_closed_bracket = i + 1
253 endif
254 continue
255 endif
256
257 " Note: it should be impossible to get here
258 break
259
260 endif
261
262 " Note: it should be impossible to get here
263 break
264 endwhile
265 let first_open_bracket = -1
266 let last_open_bracket = -1
267 let infuncargs = 0
268 if len(brackets_stack) > 0
269 let first_open_bracket = brackets_stack[0][1]
270 let last_open_bracket = brackets_stack[-1][1]
271 if brackets_stack[-1][0] == 'par' && IsFunctionArgPar(a:lnum, last_open_bracket+1)
272 let infuncargs = 1
273 endif
274 endif
275 return [first_open_bracket, last_open_bracket, last_closed_bracket, infuncargs]
276endfunction
277
278let s:bracketBlocks = '\<julia\%(\%(\%(Printf\)\?Par\|SqBra\%(Idx\)\?\|CurBra\)Block\|ParBlockInRange\|StringVars\%(Par\|SqBra\|CurBra\)\|Dollar\%(Par\|SqBra\)\|QuotedParBlockS\?\)\>'
279
280function IsInBrackets(lnum, c)
281 let stack = map(synstack(a:lnum, a:c), 'synIDattr(v:val, "name")')
282 call filter(stack, 'v:val =~# s:bracketBlocks')
283 return len(stack) > 0
284endfunction
285
286function IsInDocString(lnum)
287 let stack = map(synstack(a:lnum, 1), 'synIDattr(v:val, "name")')
288 call filter(stack, 'v:val =~# "\\<juliaDocString\\(Delim\\|M\\\(Raw\\)\\?\\)\\?\\>"')
289 return len(stack) > 0
290endfunction
291
292function IsInContinuationImportLine(lnum)
293 let stack = map(synstack(a:lnum, 1), 'synIDattr(v:val, "name")')
294 call filter(stack, 'v:val =~# "\\<juliaImportLine\\>"')
295 if len(stack) == 0
296 return 0
297 endif
298 return JuliaMatch(a:lnum, getline(a:lnum), '\<\%(import\|using\|export\)\>', indent(a:lnum)) == -1
299endfunction
300
301function IsFunctionArgPar(lnum, c)
302 if a:c == 0
303 return 0
304 endif
305 let stack = map(synstack(a:lnum, a:c-1), 'synIDattr(v:val, "name")')
306 return len(stack) >= 2 && stack[-2] ==# 'juliaFunctionDef'
307endfunction
308
309function JumpToMatch(lnum, last_closed_bracket)
310 " we use the % command to skip back (tries to ues matchit if possible,
311 " otherwise resorts to vim's default, which is buggy but better than
312 " nothing)
313 call cursor(a:lnum, a:last_closed_bracket)
314 let percmap = maparg("%", "n")
315 if exists("g:loaded_matchit") && percmap =~# 'Match\%(it\|_wrapper\)'
316 normal %
317 else
318 normal! %
319 end
320endfunction
321
322" Auxiliary function to find a line which does not start in the middle of a
323" multiline bracketed expression, to be used as reference for block
324" indentation.
325function LastBlockIndent(lnum)
326 let lnum = a:lnum
327 let ind = 0
328 while lnum > 0
329 let ind = indent(lnum)
330 if ind == 0
331 return [lnum, 0]
332 endif
333 if !IsInBrackets(lnum, 1)
334 break
335 endif
336 let lnum = prevnonblank(lnum - 1)
337 endwhile
338 return [max([lnum,1]), ind]
339endfunction
340
341function GetJuliaIndent()
342 " Do not alter doctrings indentation
343 if IsInDocString(v:lnum)
344 return -1
345 endif
346
347 " Find a non-blank line above the current line.
348 let lnum = prevnonblank(v:lnum - 1)
349
350 " At the start of the file use zero indent.
351 if lnum == 0
352 return 0
353 endif
354
355 let ind = -1
356 let st = -1
357 let lim = -1
358
359 " Multiline bracketed expressions take precedence
360 let align_brackets = get(g:, "julia_indent_align_brackets", 1)
361 let align_funcargs = get(g:, "julia_indent_align_funcargs", 0)
362 let c = len(getline(lnum)) + 1
363 while IsInBrackets(lnum, c)
364 let [first_open_bracket, last_open_bracket, last_closed_bracket, infuncargs] = GetJuliaNestingBrackets(lnum, c)
365
366 " First scenario: the previous line has a hanging open bracket:
367 " set the indentation to match the opening bracket (plus an extra space)
368 " unless we're in a function arguments list or alignment is disabled, in
369 " which case we just add an extra indent
370 if last_open_bracket != -1
371 if (!infuncargs && align_brackets) || (infuncargs && align_funcargs)
372 let st = last_open_bracket
373 let ind = virtcol([lnum, st + 1])
374 else
375 let ind = indent(lnum) + shiftwidth()
376 endif
377
378 " Second scenario: some multiline bracketed expression was closed in the
379 " previous line. But since we know we are still in a bracketed expression,
380 " we need to find the line where the bracket was opened
381 elseif last_closed_bracket != -1
382 call JumpToMatch(lnum, last_closed_bracket)
383 if line(".") == lnum
384 " something wrong here, give up
385 let ind = indent(lnum)
386 else
387 let lnum = line(".")
388 let c = col(".") - 1
389 if c == 0
390 " uhm, give up
391 let ind = 0
392 else
393 " we skipped a bracket set, keep searching for an opening bracket
394 let lim = c
395 continue
396 endif
397 endif
398
399 " Third scenario: nothing special: keep the indentation
400 else
401 let ind = indent(lnum)
402 endif
403
404 " Does the current line start with a closing bracket? Then depending on
405 " the situation we align it with the opening one, or we let the rest of
406 " the code figure it out (the case in which we're closing a function
407 " argument list is special-cased)
408 if JuliaMatch(v:lnum, getline(v:lnum), '[])}]', indent(v:lnum)) == indent(v:lnum) && ind > 0
409 if !align_brackets && !align_funcargs
410 call JumpToMatch(v:lnum, indent(v:lnum))
411 return indent(line("."))
412 elseif (align_brackets && getline(v:lnum)[indent(v:lnum)] != ')') || align_funcargs
413 return ind - 1
414 else " must be a ')' and align_brackets==1 and align_funcargs==0
415 call JumpToMatch(v:lnum, indent(v:lnum))
416 if IsFunctionArgPar(line("."), col("."))
417 let ind = -1
418 else
419 return ind - 1
420 endif
421 endif
422 endif
423
424 break
425 endwhile
426
427 if ind == -1
428 " We are not in a multiline bracketed expression. Thus we look for a
429 " previous line to use as a reference
430 let [lnum,ind] = LastBlockIndent(lnum)
431 let c = len(getline(lnum)) + 1
432 if IsInBrackets(lnum, c)
433 let [first_open_bracket, last_open_bracket, last_closed_bracket, infuncargs] = GetJuliaNestingBrackets(lnum, c)
434 let lim = first_open_bracket
435 endif
436 end
437
438 " Analyse the reference line
439 let [num_open_blocks, num_closed_blocks] = GetJuliaNestingStruct(lnum, st, lim)
440 " Increase indentation for each newly opened block in the reference line
441 let ind += shiftwidth() * num_open_blocks
442
443 " Analyse the current line
444 let [num_open_blocks, num_closed_blocks] = GetJuliaNestingStruct(v:lnum)
445 " Decrease indentation for each closed block in the current line
446 let ind -= shiftwidth() * num_closed_blocks
447
448 " Additional special case: multiline import/using/export statements
449
450 let prevline = getline(lnum)
451 " Are we in a multiline import/using/export statement, right below the
452 " opening line?
453 if IsInContinuationImportLine(v:lnum) && !IsInContinuationImportLine(lnum)
454 if get(g:, 'julia_indent_align_import', 1)
455 " if the opening line has a colon followed by non-comments, use it as
456 " reference point
457 let cind = JuliaMatch(lnum, prevline, ':', indent(lnum), lim)
458 if cind >= 0
459 let nonwhiteind = JuliaMatch(lnum, prevline, '\S', cind+1, -1, 'basic')
460 if nonwhiteind >= 0
461 " return match(prevline, '\S', cind+1) " a bit overkill...
462 return cind + 2
463 endif
464 else
465 " if the opening line is not a naked import/using/export statement, use
466 " it as reference
467 let iind = JuliaMatch(lnum, prevline, '\<import\|using\|export\>', indent(lnum), lim)
468 if iind >= 0
469 " assuming whitespace after using... so no `using(XYZ)` please!
470 let nonwhiteind = JuliaMatch(lnum, prevline, '\S', iind+6, -1, 'basic')
471 if nonwhiteind >= 0
472 return match(prevline, '\S', iind+6)
473 endif
474 endif
475 endif
476 endif
477 let ind += shiftwidth()
478
479 " Or did we just close a multiline import/using/export statement?
480 elseif !IsInContinuationImportLine(v:lnum) && IsInContinuationImportLine(lnum)
481 " find the starting line of the statement
482 let ilnum = 0
483 for iln in range(lnum-1, 1, -1)
484 if !IsInContinuationImportLine(iln)
485 let ilnum = iln
486 break
487 endif
488 endfor
489 if ilnum == 0
490 " something went horribly wrong, give up
491 let ind = indent(lnum)
492 endif
493 let ind = indent(ilnum)
494 endif
495
496 return ind
497endfunction