Skip to content

Commit

Permalink
Python imports
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewRadev committed Oct 26, 2012
1 parent 51b8f12 commit 37f45e8
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
40 changes: 40 additions & 0 deletions autoload/sj/python.vim
Expand Up @@ -82,6 +82,46 @@ function! sj#python#JoinTuple()
return s:JoinList('([^)]*\s*$', '(')
endfunction

function! sj#python#SplitImport()
let import_pattern = '^from \%(.*\) import \zs.*$'

normal! 0
if search(import_pattern, 'Wc', line('.')) <= 0
return 0
endif

let import_list = sj#GetMotion('vg_')

if stridx(import_list, ',') < 0
return 0
endif

let imports = split(import_list, ',\s*')

call sj#ReplaceMotion('vg_', join(imports, ",\\\n"))
return 1
endfunction

function! sj#python#JoinImport()
let import_pattern = '^from \%(.*\) import .*\\\s*$'

if getline('.') !~ import_pattern
return 0
endif

let start_lineno = line('.')
let current_lineno = nextnonblank(start_lineno + 1)

while getline(current_lineno) =~ '\\\s*$' && current_lineno < line('$')
let current_lineno = nextnonblank(current_lineno + 1)
endwhile

let end_lineno = current_lineno

exe start_lineno.','.end_lineno.'s/,\\\n\s*/, /e'
return 1
endfunction

function! s:SplitList(regex, opening_char, closing_char)
if sj#SearchUnderCursor(a:regex) <= 0
return 0
Expand Down
5 changes: 5 additions & 0 deletions examples/test.py
@@ -1,3 +1,8 @@
from foo import bar, baz
from foo import one,\
two,\
three

knights = {'gallahad': 'the pure', 'robin': 'the brave'}

spam = {'spam': [1, 2, 3], 'spam, spam': { 'one': 'two' }, "spam, spam, spam...": ('spam', 'eggs')}
Expand Down
6 changes: 4 additions & 2 deletions ftplugin/python/splitjoin.vim
Expand Up @@ -3,7 +3,8 @@ if !exists('b:splitjoin_split_callbacks')
\ 'sj#python#SplitDict',
\ 'sj#python#SplitArray',
\ 'sj#python#SplitTuple',
\ 'sj#python#SplitStatement'
\ 'sj#python#SplitStatement',
\ 'sj#python#SplitImport'
\ ]
endif

Expand All @@ -12,6 +13,7 @@ if !exists('b:splitjoin_join_callbacks')
\ 'sj#python#JoinDict',
\ 'sj#python#JoinArray',
\ 'sj#python#JoinTuple',
\ 'sj#python#JoinStatement'
\ 'sj#python#JoinStatement',
\ 'sj#python#JoinImport'
\ ]
endif

0 comments on commit 37f45e8

Please sign in to comment.