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_. Sep 29 '18 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
    Oct 1 '18 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. Oct 2 '18 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
    Oct 3 '18 at 2:40

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
    Oct 1 '18 at 10:11
  • I revised my answer. Does this work for you?
    – Timm
    Oct 2 '18 at 12:02
  • Yes, it works well, thanks.
    – Navidot
    Oct 18 '20 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
    Jun 11 at 15:15

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.