How to build the placeholder during python interpolation

Asked by Jeremy Cantrell

is there a way to do something like:

`!p snip.rv = "${1:"+some_var+"}"`

Question information

Language:
English Edit question
Status:
Solved
For:
UltiSnips Edit question
Assignee:
No assignee Edit question
Solved by:
Jeremy Cantrell
Solved:
Last query:
Last reply:
Revision history for this message
SirVer (sirver) said :
#1

it would be easier if you would describe what you want to do exactly.

what you write is currently not possible. It would require recursive parsing of interpolated texts. There is a feature to add a one time snippet for on the spot expansion which could maybe do what you want. See help UltiSnips_Anon.

Revision history for this message
Jeremy Cantrell (jmcantrell) said :
#2

Given these global functions:

global !p
def comment(snip, text):
    return (snip.opt("&cms") % ' '+text+' ').strip()

def comment_start(snip):
    return snip.opt("&cms").split('%s')[0]+' '

def comment_end(snip):
    s = snip.opt("&cms").split('%s')
    if len(s) == 2: return ' '+s[1]
    return ''
endglobal

I would love to do this:

snippet modeline "Modeline (filetype)" b
`!p snip.rv = comment("vim:${1:ft="+snip.filetype+"}:")`
endsnippet

But this is the closest I could get:

snippet modeline "Modeline (filetype)" b
`!p snip.rv = comment_start(snip)`vim:${1:ft=`!v &ft`}:`!p snip.rv = comment_end(snip)`
endsnippet

The only problem is that the latter leaves a trailing space. Is there any way to avoid that?

Revision history for this message
SirVer (sirver) said :
#3

I still cannot follow your problem. The code does precisely what you want programmed it to do.... What is the content of cms in your case. I assume python for my following example:
set cms=#%s

&cms.split = ['#', '']

comment_start() returns '# "
comment_end() returns ' '

I assume that you have a bug in your comment_end part. I replaced this via

def comment_end(snip):
    s = snip.opt("&cms").split('%s')
    if len(s) == 2 and s[1]: return ' '+s[1]
    return ''
endglobal

Try this and report back with further problems please.

Revision history for this message
Jeremy Cantrell (jmcantrell) said :
#4

This works. Thanks.