I'm writing an XML document where I frequently produce markup like this:

We can exit Terminal mode by pressing <keystroke>&lt;C-\&gt;&lt;C-n&gt;</keystroke>.

I'd like to define an UltiSnips snippet to help with producing <keystroke> tags like this. Ideally, I'd be able to type (where <tab> expands the snippet, and <C-j> jumps to the next tabstop):


and have it output:


Is it possible to create a snippet for UltiSnips that behaves this way?


Using regular expression snippet it's possible to achieve this. Following snippet works almost ideally:

snippet "keystroke([^>]\S+)?" "Adds keystroke" r
<keystroke>`!p snip.rv = (match.group(1) or "").replace("<", "&lt;").replace(">", "&gt;")`</keystroke>$0

It works after you enter all the key sequences, for example: keystroke<C-\><C-n>Tab will result in:


with the cursor position after </keystroke>

  • Edited the answer. Enclosed match.group(1) in () and added empty string as a fallback – grodzik May 11 '17 at 9:42
  • This snippet works nicely, thanks. I wonder if it's also possible to do the substitution in a post_expand action? – nelstrom May 11 '17 at 10:49
  • I had to do it this way, because UltiSnips prevents and makes it very troublesome to edit current line, so anything after snippet was expanded makes it hard to change, mainly because this particular snippet is contained in just one line – grodzik May 11 '17 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.