How to write snippet condition to expand it only when it's positioned at the beginning of the line?

  • 1
    What is the use case for this? If your snippet key is key_ you need to press TAB or whatever you defined, if key_ overlaps with something else just re-name it to key1_.
    – Arktik
    Commented Sep 29, 2018 at 23:18
  • @A.Blizzard, TAB is multipurpose key, also used for indentation. When I just want to indent a line and there happen to be a valid key related to snippet behind cursor I don't want to expand it. Assuming that I have a ES6 specific snippet with key "class" which produces generic ES6 class template I don't want to expand it in accidentally somewhere in the middle of file, when my intent really was to indent some lines. Adding condition that this snippet could only be expanded when it's placed at the beginning of the line allow me to expand it easily by using key at the same time.
    – Navidot
    Commented Oct 1, 2018 at 10:19
  • I see. A bit off topic but I use TAB only in insert mode in Evil to expand snippets. I am fairly new to Emacs and have been using it only for about a year now. If you haven't already I cannot recommend high enough Evil mode, which is essentially Vim.
    – Arktik
    Commented Oct 2, 2018 at 18:24
  • @A.Blizzard, I'm using evil-mode as well. yasnippet integrates well in TAB workflow - shared between many Emacs features by default.
    – Navidot
    Commented Oct 3, 2018 at 2:40

1 Answer 1


Say your snippet has the key mysnippet_, you can use the following condition:

# condition: (looking-back "^mysnippet_" nil)

Speaking of use cases, it could make sense to have snippets for inserting org-mode headers only available when the cursor is in the first line and column:

# condition: (and (looking-back "^mysnippet_" nil) (eq 1 (line-number-at-pos)))


I first proposed to use (eq 0 (current-column)), but that's of course nonsense because the cursor is after the snippet key.

  • thanks for reply. Sorry, this is not exactly what I want to achieve. What I'm looking for is the way to conditionally expand snippet placed at the beginning of the line, so before the cursor there should be some snippet to be expanded and the condition should consider it.
    – Navidot
    Commented Oct 1, 2018 at 10:11
  • I revised my answer. Does this work for you?
    – Timm
    Commented Oct 2, 2018 at 12:02
  • Yes, it works well, thanks.
    – Navidot
    Commented Oct 18, 2020 at 17:18
  • @Timm # condition: (looking-back "^f" nil) only applies if f at the beginnig of the line. Can we also do something like allow <white-space>f too? like if there is tab or space before f still snippet could be applied. But prevent if its in between a string like "f"
    – alper
    Commented Jun 11, 2021 at 15:15

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.