Ultisnips dynamic tabstop generation based on first tabstop

267 Views Asked by At

I want a Ultisnips snippet capable of dealing with the following scenario:

const [value1, value2, value3, ...valueN] = await Promise.all([
  promise1,
  promise2,
  promise3,
  ...,
  promiseN,
]);

Based on what I type inside the first square brackets, I want to generate the same amount of new tabstops for each line inside the Promise.all block.

Currently I have this approach, which almost works:

global !p
def insert_lines(txt, start = 2, generate_value = lambda i: f'val{i}'):
    count = len(txt.split(','))

    lines = ["${" + str(i) + ":" + generate_value(i+1-start) + "}," for i in range(start, count + 2)]

    snip.expand_anon("\n".join(lines))
endglobal

post_jump "if snip.tabstop == 0: insert_lines(snip.tabstops[1].current_text, start=2)"
snippet pall "await Promise.all" b
const [${1:...items}] = await Promise.all([
    $0
]);
endsnippet

The issue I'm having is that $0 there requires me to jump one time more than I would want to. For example, if I have:

const [foo, bar, baz|] = await Promise.all([
  val1,
  val2,
  val3,
]);

Jumping to the next tabstop, I get:

const [foo, bar, baz|] = await Promise.all([
 |val1,
  val2,
  val3,
]);

Then:

const [foo, bar, baz|] = await Promise.all([
  val1,
 |val2,
  val3,
]);

Then:

const [foo, bar, baz|] = await Promise.all([
  val1,
  val2,
  |val3,
]);

At this point, if I jumped to the next tabstop, I'd expect to reach the end of the snippet, however, what happens is this:

const [foo, bar, baz|] = await Promise.all([
  val1,
  val2,
  val3,|
]);

It kind of makes sense because that's the original position of $0.

Is there any other way to achieve what I want?

1

There are 1 best solutions below

0
On

I am trying to answer this because I have been involved with Ultisnips for a while and I am not reputed enough to comment.

Why don't you try to place the $0 at like ]);$0(the last line of the code you posted)?

I suppose it should resolve the issue. Let me know.

Edit: Use the stack specifically made for vim and vi related questions for such questions. You can find the site here.