Skip to content

Instantly share code, notes, and snippets.

@MikeDacre
Last active June 29, 2024 18:15
Show Gist options
  • Save MikeDacre/365d716258d13a833831 to your computer and use it in GitHub Desktop.
Save MikeDacre/365d716258d13a833831 to your computer and use it in GitHub Desktop.
UltiSnips: Add import to top of file with other imports
global !p
def first_blank_line():
""" Search current vim buffer for first blank line. If not found return current line """
b = snip.buffer
index = 0
break_index = 100
com_delim = re.compile(r'^(\s+)?(""")')
in_comment = False
for line in b:
index += 1
if index == break_index:
return -1
if com_delim.match(line):
in_comment = False if in_comment else True
if in_comment:
continue
if re.match(r'^\s*$', line):
return index
return -1
def search_imports(impt, frm='', end=True):
""" Look for first instance of import impt or from frm import impt in the currrent
vim buffer, if found return -1. If not found return start of imports, if end
is true, return end of imports instead. """
b = snip.buffer
if frm:
sch = re.compile(r'^from ' + frm + r' import ' + impt)
else:
sch = re.compile(r'^(from \w )?import ' + impt)
index = 0
start = 0
imp_found = False
break_len = 2 # Maximum number of line breaks between imports before termination
break_ind = 0
last_ind = 0
for line in b:
index += 1
if sch.match(line):
return -1
elif re.match(r'^(from \w )?import \w', line):
if not imp_found:
start = index
imp_found = True
break_ind = 0
last_ind = index
else:
if imp_found:
if not last_ind:
last_ind = index
if break_ind == break_len:
break
else:
break_ind += 1
if imp_found:
if end:
return last_ind + 1 if last_ind else index + 1
else:
return start
else:
return -2
def add_import(impt, frm='', end=True):
""" Add an import if it does not already exist, default is to add to end """
imp_loc = search_imports(impt, frm, end)
if imp_loc == -1:
return
if imp_loc == -2:
imp_loc = first_blank_line()
if imp_loc == -1:
imp_loc = vim.current.window.cursor[0]
imp_loc = imp_loc - 1
imp_string = 'from {} import {}'.format(frm, impt) if frm else 'import {}'.format(impt)
snip.buffer.append(imp_string, imp_loc)
def add_imports(impts, end=True):
""" Add a list of imports
If you want to import as from ... import ..., then use a tuple for the import:
[(import, from), import, (import, from), ...] """
for impt in impts:
if type(impt) is tuple:
add_import(*impt, end=end)
else:
add_import(impt, end=end)
endglobal
pre_expand "add_import('argparse', end=False)"
snippet firstimport "Description" b
${1:hi}
endsnippet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment