File: vim_autopep8.py

package info (click to toggle)
autopep8 1.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,216 kB
  • sloc: python: 13,333; makefile: 131; sh: 16
file content (55 lines) | stat: -rw-r--r-- 1,149 bytes parent folder | download | duplicates (2)
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
"""Run autopep8 on the selected buffer in Vim.

map <C-I> :pyfile <path_to>/vim_autopep8.py<CR>

Replace ":pyfile" with ":py3file" if Vim is built with Python 3 support.

"""

from __future__ import unicode_literals

import sys

import vim


ENCODING = vim.eval('&fileencoding')


def encode(text):
    if sys.version_info.major >= 3:
        return text
    else:
        return text.encode(ENCODING)


def decode(text):
    if sys.version_info.major >= 3:
        return text
    else:
        return text.decode(ENCODING)


def main():
    if vim.eval('&syntax') != 'python':
        return

    source = '\n'.join(decode(line)
                        for line in vim.current.buffer) + '\n'

    import autopep8
    formatted = autopep8.fix_code(
        source,
        options={'line_range': [1 + vim.current.range.start,
                                1 + vim.current.range.end]})

    if source != formatted:
        if formatted.endswith('\n'):
            formatted = formatted[:-1]

        vim.current.buffer[:] = [encode(line)
                                 for line in formatted.splitlines()]


if __name__ == '__main__':
    main()