Skip to content

Instantly share code, notes, and snippets.

@ubaldot
Last active August 18, 2024 22:03
Show Gist options
  • Save ubaldot/55d99dc69fac7537f2fdc812f5105421 to your computer and use it in GitHub Desktop.
Save ubaldot/55d99dc69fac7537f2fdc812f5105421 to your computer and use it in GitHub Desktop.
Markdown and Vim: quick Bold, italic and strikethough toggle.
def Surround(pre: string, post: string)
var pre_len = strlen(pre)
var post_len = strlen(post)
var [line_start, column_start] = getpos("'<")[1 : 2]
var [line_end, column_end] = getpos("'>")[1 : 2]
if line_start > line_end
var tmp = line_start
line_start = line_end
line_end = tmp
tmp = column_start
column_start = column_end
column_end = tmp
endif
if line_start == line_end && column_start > column_end
var tmp = column_start
column_start = column_end
column_end = tmp
endif
var leading_chars = strcharpart(getline(line_start), column_start - 1 - pre_len, pre_len)
var trailing_chars = strcharpart(getline(line_end), column_end, post_len)
cursor(line_start, column_start)
var offset = 0
if leading_chars == pre
execute($"normal! {pre_len}X")
offset = -pre_len
else
execute($"normal! i{pre}")
offset = pre_len
endif
# Some chars have been added if you are working on the same line
if line_start == line_end
cursor(line_end, column_end + offset)
else
cursor(line_end, column_end)
endif
if trailing_chars == post
execute($"normal! l{post_len}x")
else
execute($"normal! a{post}")
endif
enddef
xnoremap " <esc><ScriptCmd>myfunctions.Surround('"', '"')<cr>
xnoremap ' <esc><ScriptCmd>myfunctions.Surround("'", "'")<cr>
xnoremap ( <esc><ScriptCmd>myfunctions.Surround('(', ')')<cr>
xnoremap [ <esc><ScriptCmd>myfunctions.Surround('[', ']')<cr>
xnoremap { <esc><ScriptCmd>myfunctions.Surround('{', '}')<cr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment