robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

zeertzjqvim-patch:cb0b4cf: Fix a few more typos (#39596)37596fcd29

master
10.2 KiB277 linesraw
1" Vim indent file
2" Language:         Rust
3" Author:           Chris Morgan <me@chrismorgan.info>
4" Last Change:      2023-09-11
5" 2024 Jul 04 by Vim Project: use shiftwidth() instead of hard-coding shifted values #15138
6" 2025 Dec 29 by Vim Project: clean up
7" 2025 Dec 31 by Vim Project: correctly indent after nested array literal #19042
8" 2026 Jan 28 by Vim Project: fix indentation when a string literal contains 'if' #19265
9" 2026 May 04 by Vim Project: fix typo
10
11" For bugs, patches and license go to https://github.com/rust-lang/rust.vim
12" Note: upstream seems umaintained: https://github.com/rust-lang/rust.vim/issues/502
13
14" Only load this indent file when no other was loaded.
15if exists("b:did_indent")
16    finish
17endif
18let b:did_indent = 1
19
20setlocal cindent
21setlocal cinoptions=L0,(s,Ws,J1,j1,m1
22setlocal cinkeys=0{,0},!^F,o,O,0[,0],0(,0)
23" Don't think cinwords will actually do anything at all... never mind
24setlocal cinwords=for,if,else,while,loop,impl,mod,unsafe,trait,struct,enum,fn,extern,macro
25
26" Some preliminary settings
27setlocal nolisp		" Make sure lisp indenting doesn't supersede us
28setlocal autoindent	" indentexpr isn't much help otherwise
29" Also do indentkeys, otherwise # gets shoved to column 0 :-/
30setlocal indentkeys=0{,0},!^F,o,O,0[,0],0(,0)
31
32setlocal indentexpr=GetRustIndent(v:lnum)
33
34let b:undo_indent = "setlocal cindent< cinoptions< cinkeys< cinwords< lisp< autoindent< indentkeys< indentexpr<"
35
36" Only define the function once.
37if exists("*GetRustIndent")
38    finish
39endif
40
41" vint: -ProhibitAbbreviationOption
42let s:save_cpo = &cpo
43set cpo&vim
44" vint: +ProhibitAbbreviationOption
45
46" Come here when loading the script the first time.
47
48function! s:get_line_trimmed(lnum)
49    " Get the line and remove a trailing comment.
50    " Use syntax highlighting attributes when possible.
51    " NOTE: this is not accurate; /* */ or a line continuation could trick it
52    let line = getline(a:lnum)
53    let line_len = strlen(line)
54    if has('syntax_items')
55        " If the last character in the line is a comment, do a binary search for
56        " the start of the comment.  synID() is slow, a linear search would take
57        " too long on a long line.
58        if synIDattr(synID(a:lnum, line_len, 1), "name") =~? 'Comment\|Todo'
59            let min = 1
60            let max = line_len
61            while min < max
62                let col = (min + max) / 2
63                if synIDattr(synID(a:lnum, col, 1), "name") =~? 'Comment\|Todo'
64                    let max = col
65                else
66                    let min = col + 1
67                endif
68            endwhile
69            let line = strpart(line, 0, min - 1)
70        endif
71        return substitute(line, "\s*$", "", "")
72    else
73        " Sorry, this is not complete, nor fully correct (e.g. string "//").
74        " Such is life.
75        return substitute(line, "\s*//.*$", "", "")
76    endif
77endfunction
78
79function! s:is_string_comment(lnum, col)
80    if has('syntax_items')
81        for id in synstack(a:lnum, a:col)
82            let synname = synIDattr(id, "name")
83            if synname ==# "rustString" || synname =~# "^rustComment"
84                return 1
85            endif
86        endfor
87    else
88        " without syntax, let's not even try
89        return 0
90    endif
91endfunction
92
93function GetRustIndent(lnum)
94    " Starting assumption: cindent (called at the end) will do it right
95    " normally. We just want to fix up a few cases.
96
97    let line = getline(a:lnum)
98
99    if has('syntax_items')
100        let synname = synIDattr(synID(a:lnum, 1, 1), "name")
101        if synname ==# "rustString"
102            " If the start of the line is in a string, don't change the indent
103            return -1
104        elseif synname =~? '\(Comment\|Todo\)'
105                    \ && line !~# '^\s*/\*'  " not /* opening line
106            if synname =~? "CommentML" " multi-line
107                if line !~# '^\s*\*' && getline(a:lnum - 1) =~# '^\s*/\*'
108                    " This is (hopefully) the line after a /*, and it has no
109                    " leader, so the correct indentation is that of the
110                    " previous line.
111                    return GetRustIndent(a:lnum - 1)
112                endif
113            endif
114            " If it's in a comment, let cindent take care of it now. This is
115            " for cases like "/*" where the next line should start " * ", not
116            " "* " as the code below would otherwise cause for module scope
117            " Fun fact: "  /*\n*\n*/" takes two calls to get right!
118            return cindent(a:lnum)
119        endif
120    endif
121
122    " cindent gets second and subsequent match patterns/struct members wrong,
123    " as it treats the comma as indicating an unfinished statement::
124    "
125    " match a {
126    "     b => c,
127    "         d => e,
128    "         f => g,
129    " };
130
131    " Search backwards for the previous non-empty line.
132    let prevlinenum = prevnonblank(a:lnum - 1)
133    let prevline = s:get_line_trimmed(prevlinenum)
134    while prevlinenum > 1 && prevline !~# '[^[:blank:]]'
135        let prevlinenum = prevnonblank(prevlinenum - 1)
136        let prevline = s:get_line_trimmed(prevlinenum)
137    endwhile
138
139    " A standalone '{', '}', or 'where'
140    let l:standalone_open = line =~# '\V\^\s\*{\s\*\$'
141    let l:standalone_close = line =~# '\V\^\s\*}\s\*\$'
142    let l:standalone_where = line =~# '\V\^\s\*where\s\*\$'
143    if l:standalone_open || l:standalone_close || l:standalone_where
144        let l:orig_line = line('.')
145        let l:orig_col = col('.')
146        let l:i = 0
147        while 1
148            " ToDo: we can search for more items than 'fn' and 'if'.
149            let [l:found_line, l:col, l:submatch] =
150                        \ searchpos('\<\(fn\|if\)\>', 'bWp')
151            if l:found_line ==# 0 || !s:is_string_comment(l:found_line, l:col)
152                break
153            endif
154            let l:i += 1
155            " Limit to 10 iterations as a failsafe against endless looping.
156            if l:i >= 10
157                let l:found_line = 0
158                break
159            endif
160        endwhile
161        call cursor(l:orig_line, l:orig_col)
162        if l:found_line !=# 0
163            " Now we count the number of '{' and '}' in between the match
164            " locations and the current line (there is probably a better
165            " way to compute this).
166            let l:i = l:found_line
167            let l:search_line = strpart(getline(l:i), l:col - 1)
168            let l:opens = 0
169            let l:closes = 0
170            while l:i < a:lnum
171                let l:search_line2 = substitute(l:search_line, '\V{', '', 'g')
172                let l:opens += strlen(l:search_line) - strlen(l:search_line2)
173                let l:search_line3 = substitute(l:search_line2, '\V}', '', 'g')
174                let l:closes += strlen(l:search_line2) - strlen(l:search_line3)
175                let l:i += 1
176                let l:search_line = getline(l:i)
177            endwhile
178            if l:standalone_open || l:standalone_where
179                if l:opens ==# l:closes
180                    return indent(l:found_line)
181                endif
182            else
183                " Expect to find just one more close than an open
184                if l:opens ==# l:closes + 1
185                    return indent(l:found_line)
186                endif
187            endif
188        endif
189    endif
190
191    " A standalone 'where' adds a shift.
192    let l:standalone_prevline_where = prevline =~# '\V\^\s\*where\s\*\$'
193    if l:standalone_prevline_where
194        return indent(prevlinenum) + shiftwidth()
195    endif
196
197    " Handle where clauses nicely: subsequent values should line up nicely.
198    if prevline[len(prevline) - 1] ==# ","
199                \ && prevline =~# '^\s*where\s'
200        return indent(prevlinenum) + 6
201    endif
202
203    let l:last_prevline_character = prevline[len(prevline) - 1]
204
205    " A line that ends with '.<expr>;' is probably an end of a long list
206    " of method operations.
207    if prevline =~# '\V\^\s\*.' && l:last_prevline_character ==# ';'
208        call cursor(a:lnum - 1, 1)
209        let l:scope_start = searchpair('{\|(', '', '}\|)', 'nbW',
210                    \ 's:is_string_comment(line("."), col("."))')
211        if l:scope_start != 0 && l:scope_start < a:lnum
212            return indent(l:scope_start) + shiftwidth()
213        endif
214    endif
215
216    " Prevent cindent from becoming confused when pairing square brackets, as
217    " in
218    "
219    " let arr = [[u8; 4]; 2] = [
220    "     [0; 4],
221    "     [1, 3, 5, 9],
222    " ];
223    "     | ← indentation placed here
224    "
225    " for which it calculates too much indentation in the line following the
226    " close of the array.
227    if prevline =~# '^\s*\]' && l:last_prevline_character ==# ';'
228                \ && line !~# '^\s*}'
229        return indent(prevlinenum)
230    endif
231
232    if l:last_prevline_character ==# ","
233                \ && s:get_line_trimmed(a:lnum) !~# '^\s*[\[\]{})]'
234                \ && prevline !~# '^\s*fn\s'
235                \ && prevline !~# '([^()]\+,$'
236                \ && s:get_line_trimmed(a:lnum) !~# '^\s*\S\+\s*=>'
237        " Oh ho! The previous line ended in a comma! I bet cindent will try to
238        " take this too far... For now, let's normally use the previous line's
239        " indent.
240
241        " One case where this doesn't work out is where *this* line contains
242        " square or curly brackets; then we normally *do* want to be indenting
243        " further.
244        "
245        " Another case where we don't want to is one like a function
246        " definition with arguments spread over multiple lines:
247        "
248        " fn foo(baz: Baz,
249        "        baz: Baz) // <-- cindent gets this right by itself
250        "
251        " Another case is similar to the previous, except calling a function
252        " instead of defining it, or any conditional expression that leaves
253        " an open paren:
254        "
255        " foo(baz,
256        "     baz);
257        "
258        " if baz && (foo ||
259        "            bar) {
260        "
261        " Another case is when the current line is a new match arm.
262        "
263        " There are probably other cases where we don't want to do this as
264        " well. Add them as needed.
265        return indent(prevlinenum)
266    endif
267
268    " Fall back on cindent, which does it mostly right
269    return cindent(a:lnum)
270endfunction
271
272" vint: -ProhibitAbbreviationOption
273let &cpo = s:save_cpo
274unlet s:save_cpo
275" vint: +ProhibitAbbreviationOption
276
277" vim: set et sw=4 sts=4 ts=8: