Try this:
snippet guard "add guard to functions" b
if !exists('*`!p snip.rv = re.search('\S+\s+(\S+)\(', snip.v.text.splitlines()[0]).group(1)`')
${VISUAL}
endif
${0:jump here <C-j>}
endsnippet
The `!p snip.rv = ...`
part is a python interpolation. The evaluation of the expression to the right of the assignment operator after snip.rv
replaces everything between the backticks.
Here the expression is:
re.search('\S+\s+(\S+)\(', snip.v.text.splitlines()[0]).group(1)
If you make a mistake when selecting the function, the first line may not match the regex, in which case an error will be raised.
Inside the python interpolation, you can use a try
, except
construct to catch the error:
snippet guard "add guard to functions" b
if !exists('*`!p
try:
func_name = re.search('\S+\s+(\S+)\(', snip.v.text.splitlines()[0]).group(1)
except AttributeError:
func_name = ''
snip.rv = func_name
`')
${VISUAL}
endif
${0:jump here <C-j>}
endsnippet