Reputation: 8512
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
Upvotes: 4
Views: 863
Reputation: 125
This should work:
# -*- mode: snippet -*-
# name: foo
# key: foo
# --
`(delete-backward-char 1)`~bar$0
but usually throws a warning that a snippet modified the buffer which can be avoided by including
(add-to-list 'warning-suppress-types '(yasnippet backquote-change))
in your config.el
.
Upvotes: 0
Reputation: 17707
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 " "))))}
Upvotes: 1
Reputation: 3995
Looks like you can embed some lisp code into your templates using `. So I guess you could do something like:
`(if (string= " " (string (preceding-char))) (backward-delete-char))`
Upvotes: 2