SirVer / ultisnips

UltiSnips - The ultimate snippet solution for Vim. Send pull requests to SirVer/ultisnips!
GNU General Public License v3.0
7.55k stars 691 forks source link

VISUAL in post_jump - can we access? How #1524

Open JoseConseco opened 1 year ago

JoseConseco commented 1 year ago

I see no discussion section on ultisnips page, so I post my question here: how do I access VISUAL (or vim yank register) from post_jump event?

I want snippet for extracting variable e.g. - a+b: something(a + b) selecting content of bracket and running snipped would generate:

new_var = a+b
something(new_war)

I tried to access snip.v.text or snip.visual_text in post_jump : post_jump "if snip.tabstop == 0: insert_method_call(snip.tabstops[1].current_text, snip.visual_text)"

But ultisnips complains about snip not having v or visual_text props.

My Code

global !p
def post(var_name, visual):
    snip.buffer[snip.snippet_start[0]:snip.snippet_start[0]] = [var_name + ' = ' + visual] 
endglobal
post_jump "if snip.tabstop == 0: post(snip.tabstops[1].current_text, snip.visual_text)"
snippet var "extract var" b
$1
endsnippet 

I also tried to use ${VISUAL} in expand_anon, but no luck.

Finally there is vim - getreg() : vim.command(":call append(line('.')-1, '"+ var_name + " = '.getreg('+'))") But then Ultisnip complains about modifying buffer using vim.command.

SirVer commented 1 year ago

This is currently not supported I think, a patch + test case would be very welcome

paulfioravanti commented 1 year ago

My workaround for this is to store the snip.visual_text in the context, to then be accessed later during post_jump. Here is an example:

global !p

def store_visual_text(snip):
    return {"visual": snip.visual_text}

def use_visual_text(snip):
    visual = snip.context["visual"].strip(" \t\n\r")
    snip.expand_anon("Visual was: ${1:" + visual + "}")

endglobal

context "store_visual_text(snip)"
post_jump "use_visual_text(snip)"
snippet visual "test post_jump visual output"
$0
endsnippet

In my own snippets, I've extracted this kind of storing the visual text into a global helper, then use it in a snippet that helps me build html tags with attributes, with this line being where the visual text gets extracted from the context.

KirtiPriya07 commented 8 months ago

is it still open?

SirVer commented 7 months ago

Yes, still open.