1 " Python imports insert completion
2 " Maintainer: Sergey Matveev <stargrave@stargrave.org>
3 " License: GNU General Public License version 3 of the License or later
5 " This plugin is intended for quick import-line insertion.
6 " For example you have got "from foo.bar import Baz" import somewhere in
7 " your Git-versioned code. In another file you can write "Baz" and then
8 " press <F3> in insert mode. Completion menu will show you suggestions
9 " of all import lines from your code containing Baz import.
11 " If you have Pylint or Pyflakes output in quickfix window, containing
12 " unfedined variables errors, then you can you :call AllImportCompl()
13 " function. It will go through the quickfix list and find all possible
14 " imports, sort them and insert under current cursor position.
16 " It uses external "git grep" call and assumes that "canonical" Python
17 " import format is used (single import per line).
18 " You can use http://www.git.stargrave.org/?p=pyimportcan.git;a=blob;f=pyimportcan.pl
19 " utility to convert existing imports to that format.
21 let s:git_grep_cmd = "git grep -H --line-number --ignore-case --no-color "
23 if exists('g:loaded_importcompl') | finish | endif
24 let g:loaded_importcompl = 1
26 function! SortByLen(s1, s2)
27 if len(a:s1) == len(a:s2) | return a:s1 > a:s2 | endif
28 return 1 ? len(a:s1) > len(a:s2) : -1
31 function! ImportCompl()
33 let output = system(s:git_grep_cmd . '"^from .* import .*' . @" . '" -- "*.py" "**/*.py"')
35 for line in split(output, "\n")
36 if stridx(line, "unused-import") != -1 | continue | endif
37 let m = matchlist(line, '^.*:\d\+:\(.*\)$')
38 if len(m) == 0 | continue | endif
39 call insert(suggestions, m[1])
41 call sort(suggestions, "SortByLen")
42 call uniq(suggestions)
43 call reverse(suggestions)
44 call complete(col('.'), suggestions)
48 inoremap <F3> <C-R>=ImportCompl()<CR>
50 function! AllImportCompl()
51 let output = system(s:git_grep_cmd . '"^from .* import" -- "*.py" "**/*.py"')
53 for line in split(output, "\n")
54 if stridx(line, "unused-import") != -1 | continue | endif
56 \'^.*:\d\+:\(from .* import \(\w\+\).*\)$',
57 \'^.*:\d\+:\(from .* import \w\+ as \(\w\+\).*\)$',
59 let m = matchlist(line, regexp)
60 if len(m) == 0 | break | endif
61 let imports[m[2]] = m[1]
64 let lines = getloclist(winnr())
65 if len(lines) == 0 | let lines = getqflist() | endif
68 let m = matchlist(line.text, '\(E0602\|F821\).*' . "'" . '\(\w\+\)' . "'$")
69 if len(m) == 0 || !has_key(imports, m[2]) | continue | endif
70 call insert(result, imports[m[2]])
72 call sort(result, "i")
74 call append(".", result)