Skip to content

Instantly share code, notes, and snippets.

@d0c-s4vage
Created November 10, 2016 20:36
Show Gist options
  • Save d0c-s4vage/11240a1e96d2afddbbb4a0b7e5e97033 to your computer and use it in GitHub Desktop.
Save d0c-s4vage/11240a1e96d2afddbbb4a0b7e5e97033 to your computer and use it in GitHub Desktop.
Short vim script that maps CTRL+j in normal and insert mode to add a new import (and sort the imports) in a Python file.
function! PythonAddImportInsertLeave(insert_mode)
execute "normal! V/import.*$\\n\\s*\\n\<CR>"
execute "normal! !sort\<CR>"
execute "normal! `mzz"
" remove import auto-cmd
autocmd! PythonAddImport *
if a:insert_mode
call feedkeys("a")
endif
endfunction
function! PythonAddImport(insert_mode)
if &filetype != "python"
return
endif
execute "normal! mmgg/import\<CR>Oimport\<space>"
augroup PythonAddImport
execute "autocmd InsertLeave <buffer> :call PythonAddImportInsertLeave(". a:insert_mode .")"
augroup end
startinsert!
endfunction
nnoremap <C-j> :call PythonAddImport(0)<CR>
inoremap <C-j> <ESC>:call PythonAddImport(1)<CR>
@d0c-s4vage
Copy link
Author

import_python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment