Created
March 22, 2019 23:11
-
-
Save weilbith/be0edc55b1e42edf6a6363d4cbccf300 to your computer and use it in GitHub Desktop.
Secure empty lines before and after completed snippets with UltiSnips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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