Skip to content

Instantly share code, notes, and snippets.

@weilbith
Created March 22, 2019 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weilbith/be0edc55b1e42edf6a6363d4cbccf300 to your computer and use it in GitHub Desktop.
Save weilbith/be0edc55b1e42edf6a6363d4cbccf300 to your computer and use it in GitHub Desktop.
Secure empty lines before and after completed snippets with UltiSnips
global !p
def on_jump(snippet, positions, function, arguments=None):
if not isinstance(positions, list):
positions = [positions]
for position in positions:
if position == "last":
position = len(snippet.tabstops) - 1
if position == snippet.tabstop:
if arguments:
function(arguments)
else:
function()
def secure_empty_line_wrap(arguments):
snippet, count_before, count_after = arguments[0:3]
force_count = arguments[3] if len(arguments) > 3 else False
last_line = len(snippet.buffer) - 1
snippet_start = snippet.snippet_start[0]
snippet_end = snippet.snippet_end[0] + 1
index_before = snippet_start - count_before
index_after = snippet_end + count_after
if snippet_start > 0:
for index in reversed(range(index_before, snippet_start)):
if snippet.buffer[index]:
missing_empty_lines = index - index_before + 1
snippet.buffer.append([''] * missing_empty_lines, index + 1)
snippet_end += missing_empty_lines
index_after += missing_empty_lines
last_line += missing_empty_lines
added_lines_before = missing_empty_lines
break
elif index == index_before and force_count:
while True:
index -= 1
if snippet.buffer[index]: break
del snippet.buffer[index]
snippet_end -= 1
index_after -= 1
last_line -= 1
if snippet_end < last_line:
for index in range(snippet_end, index_after):
if snippet.buffer[index]:
missing_empty_lines = index_after - index
snippet.buffer.append([''] * missing_empty_lines, index)
break
elif index == index_after - 1 and force_count:
index += 1
while True:
if snippet.buffer[index]: break
del snippet.buffer[index]
endglobal
# Primitive snippets to show usability.
pre_expand "snip.buffer[snip.line] = ''; snip.cursor.set(snip.line, 0)"
post_jump "on_jump(snip, 'last', secure_empty_line_wrap, [snip, 2, 1, True])"
snippet class "class" bmA
class ${1:ClassName}($2):
${3:${VISUAL}}
endsnippet
post_jump "on_jump(snip, 'last', secure_empty_line_wrap, [snip, 1, 1])"
snippet def "function" bma
def ${1:function_name}($2):
${3:${VISUAL:pass}}
endsnippet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment