All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 " PEP8 compatible Python indent file
3 " Maintainer: Hynek Schlawack <hs@ox.cx>
4 " Prev Maintainer: Eric Mc Sween <em@tomcom.de> (address invalid)
5 " Original Author: David Bustos <bustos@caltech.edu> (address invalid)
8 " vim-python-pep8-indent - A nicer Python indentation style for vim.
9 " Written in 2004 by David Bustos <bustos@caltech.edu>
10 " Maintained from 2004-2005 by Eric Mc Sween <em@tomcom.de>
11 " Maintained from 2013 by Hynek Schlawack <hs@ox.cx>
13 " To the extent possible under law, the author(s) have dedicated all copyright
14 " and related and neighboring rights to this software to the public domain
15 " worldwide. This software is distributed without any warranty.
16 " You should have received a copy of the CC0 Public Domain Dedication along
17 " with this software. If not, see
18 " <http://creativecommons.org/publicdomain/zero/1.0/>.
20 " Only load this indent file when no other was loaded.
21 if exists("b:did_indent")
29 setlocal indentexpr=GetPythonPEPIndent(v:lnum)
30 setlocal indentkeys=!^F,o,O,<:>,0),0],0},=elif,=except
32 setlocal softtabstop=4
35 if !exists('g:python_pep8_indent_multiline_string')
36 let g:python_pep8_indent_multiline_string = 0
41 \ '^\s*elif\>': ['if', 'elif'],
42 \ '^\s*except\>': ['try', 'except'],
43 \ '^\s*finally\>': ['try', 'except', 'else']
45 let s:block_rules_multiple = {
46 \ '^\s*else\>': ['if', 'elif', 'for', 'try', 'except'],
48 let s:paren_pairs = ['()', '{}', '[]']
49 if &ft == 'pyrex' || &ft == 'cython'
50 let b:control_statement = '\v^\s*(class|def|if|while|with|for|except|cdef|cpdef)>'
52 let b:control_statement = '\v^\s*(class|def|if|while|with|for|except)>'
54 let s:stop_statement = '^\s*\(break\|continue\|raise\|return\|pass\)\>'
56 " Skip strings and comments. Return 1 for chars to skip.
57 " jedi* refers to syntax definitions from jedi-vim for call signatures, which
58 " are inserted temporarily into the buffer.
59 let s:skip_special_chars = 'synIDattr(synID(line("."), col("."), 0), "name") ' .
60 \ '=~? "\\vstring|comment|jedi\\S"'
62 let s:skip_after_opening_paren = 'synIDattr(synID(line("."), col("."), 0), "name") ' .
63 \ '=~? "\\vcomment|jedi\\S"'
65 " Also ignore anything concealed.
66 " Wrapper around synconcealed for older Vim (7.3.429, used on Travis CI).
67 function! s:is_concealed(line, col)
68 let concealed = synconcealed(a:line, a:col)
69 return len(concealed) && concealed[0]
72 let s:skip_special_chars .= '|| s:is_concealed(line("."), col("."))'
76 let s:skip_search = 'synIDattr(synID(line("."), col("."), 0), "name") ' .
79 " Use 'shiftwidth()' instead of '&sw'.
80 " (Since Vim patch 7.3.629, 'shiftwidth' can be set to 0 to follow 'tabstop').
81 if exists('*shiftwidth')
91 function! s:pair_sort(x, y)
93 return a:x[1] == a:y[1] ? 0 : a:x[1] > a:y[1] ? 1 : -1
95 return a:x[0] > a:y[0] ? 1 : -1
99 " Find backwards the closest open parenthesis/bracket/brace.
100 function! s:find_opening_paren(...)
101 " optional arguments: line and column (defaults to 1) to search around
103 let view = winsaveview()
104 call cursor(a:1, a:0 > 1 ? a:2 : 1)
105 let ret = s:find_opening_paren()
106 call winrestview(view)
110 let stopline = max([0, line('.') - s:maxoff])
112 " Return if cursor is in a comment.
113 exe 'if' s:skip_search '| return [0, 0] | endif'
116 for p in s:paren_pairs
117 call add(positions, searchpairpos(
118 \ '\V'.p[0], '', '\V'.p[1], 'bnW', s:skip_special_chars, stopline))
121 " Remove empty matches and return the type with the closest match
122 call filter(positions, 'v:val[0]')
123 call sort(positions, 's:pair_sort')
125 return get(positions, -1, [0, 0])
128 " Find the start of a multi-line statement
129 function! s:find_start_of_multiline_statement(lnum)
132 if getline(lnum - 1) =~ '\\$'
133 let lnum = prevnonblank(lnum - 1)
135 let [paren_lnum, _] = s:find_opening_paren(lnum)
139 let lnum = paren_lnum
145 " Find possible indent(s) of the block starter that matches the current line.
146 function! s:find_start_of_block(lnum, types, multiple)
148 let types = copy(a:types)
149 let re = '\V\^\s\*\('.join(a:types, '\|').'\)\>'
151 let last_indent = indent(lnum) + 1
152 while lnum > 0 && last_indent > 0
153 let indent = indent(lnum)
154 if indent < last_indent
156 let re = '\v^\s*'.type.'>'
157 if getline(lnum) =~# re
161 if index(r, indent) == -1
164 " Remove any handled type, e.g. 'if'.
165 call remove(types, index(types, type))
168 let last_indent = indent(lnum)
170 let lnum = prevnonblank(lnum - 1)
175 " Is "expr" true for every position in "lnum", beginning at "start"?
176 " (optionally up to a:1 / 4th argument)
177 function! s:match_expr_on_line(expr, lnum, start, ...)
178 let text = getline(a:lnum)
179 let end = a:0 ? a:1 : len(text)
183 let save_pos = getpos('.')
185 for i in range(a:start, end)
186 call cursor(a:lnum, i)
187 if !(eval(a:expr) || text[i-1] =~ '\s')
192 call setpos('.', save_pos)
196 " Line up with open parenthesis/bracket/brace.
197 function! s:indent_like_opening_paren(lnum)
198 let [paren_lnum, paren_col] = s:find_opening_paren(a:lnum)
202 let text = getline(paren_lnum)
203 let base = indent(paren_lnum)
205 let nothing_after_opening_paren = s:match_expr_on_line(
206 \ s:skip_after_opening_paren, paren_lnum, paren_col+1)
207 let starts_with_closing_paren = getline(a:lnum) =~ '^\s*[])}]'
209 if nothing_after_opening_paren
210 if starts_with_closing_paren
213 let res = base + s:sw()
216 " Indent to match position of opening paren.
220 " If this line is the continuation of a control statement
221 " indent further to distinguish the continuation line
222 " from the next logical line.
223 if text =~# b:control_statement && res == base + s:sw()
224 return base + s:sw() * 2
230 " Match indent of first block of this type.
231 function! s:indent_like_block(lnum)
232 let text = getline(a:lnum)
233 for [multiple, block_rules] in [
234 \ [0, s:block_rules],
235 \ [1, s:block_rules_multiple]]
236 for [line_re, blocks] in items(block_rules)
241 let indents = s:find_start_of_block(a:lnum - 1, blocks, multiple)
249 " Multiple valid indents, e.g. for 'else' with both try and if.
250 let indent = indent(a:lnum)
251 if index(indents, indent) != -1
252 " The indent is valid, keep it.
255 " Fallback to the first/nearest one.
262 function! s:indent_like_previous_line(lnum)
263 let lnum = prevnonblank(a:lnum - 1)
265 " No previous line, keep current indent.
270 let text = getline(lnum)
271 let start = s:find_start_of_multiline_statement(lnum)
272 let base = indent(start)
273 let current = indent(a:lnum)
275 " Jump to last character in previous line.
276 call cursor(lnum, len(text))
277 let ignore_last_char = eval(s:skip_special_chars)
279 " Search for final colon that is not inside something to be ignored.
281 let curpos = getpos(".")[2]
282 if curpos == 1 | break | endif
283 if eval(s:skip_special_chars) || text[curpos-1] =~ '\s'
286 elseif text[curpos-1] == ':'
292 if text =~ '\\$' && !ignore_last_char
293 " If this line is the continuation of a control statement
294 " indent further to distinguish the continuation line
295 " from the next logical line.
296 if getline(start) =~# b:control_statement
297 return base + s:sw() * 2
300 " Nest (other) explicit continuations only one level deeper.
304 " If the previous statement was a stop-execution statement or a pass
305 if getline(start) =~# s:stop_statement
306 " Remove one level of indentation if the user hasn't already dedented
307 if indent(a:lnum) > base - s:sw()
310 " Otherwise, trust the user
314 if s:is_dedented_already(current, base)
318 " In all other cases, line up with the start of the previous statement.
322 " If this line is dedented and the number of indent spaces is valid
323 " (multiple of the indentation size), trust the user.
324 function! s:is_dedented_already(current, base)
325 let dedent_size = a:current - a:base
326 return (dedent_size < 0 && a:current % s:sw() == 0) ? 1 : 0
329 " Is the syntax at lnum (and optionally cnum) a python string?
330 function! s:is_python_string(lnum, ...)
331 let line = getline(a:lnum)
332 let linelen = len(line)
336 let cols = a:0 ? type(a:1) != type([]) ? [a:1] : a:1 : range(1, linelen)
338 if match(map(synstack(a:lnum, cnum),
339 \ 'synIDattr(v:val,"name")'), 'python\S*String') == -1
346 function! GetPythonPEPIndent(lnum)
347 " First line has indent 0
352 " Multilinestrings: continous, docstring or starting.
353 if s:is_python_string(a:lnum, 1)
354 \ && s:is_python_string(a:lnum-1, len(getline(a:lnum-1)))
355 " Keep existing indent.
356 if match(getline(a:lnum), '\v^\s*\S') != -1
360 if s:is_python_string(a:lnum-1)
361 " Previous line is (completely) a string.
362 return indent(a:lnum-1)
365 if match(getline(a:lnum-1), '^\s*\%("""\|''''''\)') != -1
367 return indent(a:lnum-1)
370 let indent_multi = get(b:, 'python_pep8_indent_multiline_string',
371 \ get(g:, 'python_pep8_indent_multiline_string', 0))
372 if indent_multi != -2
376 if match(getline(a:lnum-1), '\v%("""|'''''')$') != -1
377 " Opening multiline string, started in previous line.
378 return indent(a:lnum-1) + s:sw()
380 return s:indent_like_opening_paren(a:lnum)
383 " Parens: If we can find an open parenthesis/bracket/brace, line up with it.
384 let indent = s:indent_like_opening_paren(a:lnum)
389 " Blocks: Match indent of first block of this type.
390 let indent = s:indent_like_block(a:lnum)
395 return s:indent_like_previous_line(a:lnum)