-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathautoformat_python.py
More file actions
64 lines (56 loc) · 1.82 KB
/
autoformat_python.py
File metadata and controls
64 lines (56 loc) · 1.82 KB
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
#!/usr/bin/env python3
import autopep8
import yapf
from yapf.yapflib import yapf_api
import difflib
import json
import os
import subprocess
import vim
USE_AUTOPEP8 = True
USE_YAPF = False
def main():
# Get the current text.
buf = vim.current.buffer
text = '\n'.join(buf)
# Determine range to format.
lines = None
lines = [int(vim.current.range.start + 1), int(vim.current.range.end + 1)]
# Load the lines variable in vimrc if set.
if int(vim.eval('exists("l:lines")')):
lines = vim.eval('l:lines')
yapf_options = {
'unformatted_source': text,
'style_config': {
'based_on_style': 'pep8',
'coalesce_brackets': 'true',
'dedent_closing_brackets': 'false',
'each_dict_entry_on_separate_line': 'true',
'indent_dictionary_value': 'true',
'SPLIT_ALL_COMMA_SEPARATED_VALUES': 'true',
'column_limit': 79,
}
}
autopep8_options = {
'aggressive': 1,
'max_line_length': 79,
}
if (lines != 'all'):
autopep8_options['line_range'] = lines
yapf_options['lines'] = [(lines[0], lines[1] + 1)]
fixed_code = None
if USE_YAPF:
fixed_code, changed = yapf_api.FormatCode(**yapf_options)
if USE_AUTOPEP8:
fixed_code = autopep8.fix_code(text, options=autopep8_options)
if not fixed_code:
print('No output from autoformatter!')
else:
line_arr = fixed_code.split('\n')[:-1]
# Execute the sequence of changes.
sequence = difflib.SequenceMatcher(None, vim.current.buffer, line_arr)
for op in reversed(sequence.get_opcodes()):
if op[0] is not 'equal':
vim.current.buffer[op[1]:op[2]] = line_arr[op[3]:op[4]]
if __name__ == '__main__':
main()