Search code examples
emacscode-snippets

Replace character before expanding yasnippet


Is it possible to replace a character before a yasnippet is expanded?

Say that I have the following snippet:

# -*- mode: snippet -*-
# name: foo
# key: foo
# --
~bar$0

I write foo and press Tab to expand it and I get ~bar or explicitly illustrated where the first row is before expansion and the second after expansion:

foo[Tab]
~bar

Now, imagine that I want the snippet to delete any possible spaces directly before the cursor (that is 1-n directly preceding spaces) before the snippet is expanded.

Say that I have the following text

word word

and that I place the cursor as such

word [cursor]word

and enter the snippet key

word foo[cursor]word

now I expand the snippet by pressing Tab and I want the following to happen

word~bar[cursor]word

Notice that the space before the snippet is deleted so that the snippet is inserted directly after the first word. How can I make this happen? This does not happen with the defined snippet above. What happens is

word ~bar[cursor]word

Solution

  • This works with the latest yasnippet from here:

    # -*- mode: snippet -*-
    # name: foo
    # key: foo
    # --
    ~bar${0:$$(save-excursion (goto-char (overlay-start (yas/snippet-control-overlay (first (yas/snippets-at-point)))))
                              (delete-char (- (skip-chars-backward " "))))}