3 # Python imports insert completion
4 # Maintainer: Sergey Matveev <stargrave@stargrave.org>
5 # License: GNU General Public License version 3 of the License or later
7 # This plugin is intended for quick import-line insertion.
8 # For example you have got "from foo.bar import Baz" import somewhere in
9 # your Git-versioned code. In another file you can write "Baz" and then
10 # press <F3> in insert mode. Completion menu will show you suggestions
11 # of all import lines from your code containing Baz import.
13 # If you have Pylint or Pyflakes output in quickfix window, containing
14 # unfedined variables errors, then you can you :call python#importcompl#all()
15 # function. It will go through the quickfix list and find all possible
16 # imports, sort them and insert under current cursor position.
18 # It uses external "git grep" call and assumes that "canonical" Python
19 # import format is used (single import per line).
20 # You can use http://www.git.stargrave.org/?p=pyimportcan.git;a=blob;f=pyimportcan.pl
21 # utility to convert existing imports to that format.
23 const gitGrepCmd = "git grep -H --line-number --ignore-case --no-color "
25 export def Do(): string
27 var output = system(gitGrepCmd .. '"^from .* import .*' .. @" .. '" -- "*.py" "**/*.py"')
28 var suggestions: list<string>
30 for line in split(output, "\n")
31 if stridx(line, "unused-import") != -1 | continue | endif
32 m = matchlist(line, '^.*:\d\+:\(.*\)$')
33 if len(m) == 0 | continue | endif
34 insert(suggestions, m[1])
36 sort(suggestions, (s1: string, s2: string): number => {
37 if len(s1) == len(s2) | return 0 | endif
38 if len(s1) > len(s2) | return 1 | endif
43 complete(col("."), suggestions)
48 var output = system(gitGrepCmd .. '"^from .* import" -- "*.py" "**/*.py"')
51 for line in split(output, "\n")
52 if stridx(line, "unused-import") != -1 | continue | endif
54 '^.*:\d\+:\(from .* import \(\w\+\).*\)$',
55 '^.*:\d\+:\(from .* import \w\+ as \(\w\+\).*\)$',
57 ms = matchlist(line, regexp)
58 if len(ms) == 0 | break | endif
59 imports[ms[2]] = ms[1]
62 var lines = getloclist(winnr())
63 if len(lines) == 0 | lines = getqflist() | endif
64 var result: list<string>
67 if line.text !~ "^undefined name" | continue | endif
68 m = line.text[strridx(line.text[: -2], "'") + 1 : -2]
69 if len(m) == 0 || !has_key(imports, m) | continue | endif
70 insert(result, imports[m])