I want to write a snippet for LaTeX sum that behaves like this: I write "sum" and trigger snippet expansion. "sum" becomes "\sum_{$1}^{$2} $0", with $1 being the first entry point, $2 the second one and $0 the exit point.

If I write nothing inside $1, I want to have the "_{}" part deleted and proceed to $2. Likewise with $2.

Is such a thing possible with YASnippet or any other snippet engine? I tried putting an Elisp function that deletes the needed part if exiting with no input made but it breaks the snippet.

1 Answer 1


You can do this with an extra step (see "Nested placeholder fields" in the manual):

\sum${1:_{${2:}}}^{$3} $0

With the optional field: TAB, TAB, insert field 1, TAB, insert field 2, TAB to exit. Without the optional field: TAB, C-d, insert field 2, TAB to exit.

Another option is to use a function that deletes the empty field in case it finds one:

\sum_{$1}^{$2} ${0:$$(yas-delete-if-empty)}

(defun yas-delete-if-empty ()
    (when (re-search-backward "\\\\sum\\(_{}\\)^{.+}" (line-beginning-position) t)
      (replace-match "" t t nil 1))))
  • The first option seems nice enough, thanks! Dec 21, 2019 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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