1

I would like to use YASnippet template system to expand abbreviations. (I don't want to use abbrev-mode which use space or symbols for expansion.)

It is not convenient to create a new file for each of my abbreviation. Could I define yasnippet templates using elisp (in init.el) instead of using the YASnippet files structure?

2
  • You might be interested in github.com/Kungsgeten/yankpad
    – npostavs
    Aug 12 '17 at 10:46
  • Thank for the pointer. It looks good, but I found a simpler approach recently. So I will answer my question below.
    – AhLeung
    Sep 2 '17 at 23:25
2

Source: https://web.archive.org/web/20080319085637/http://code.google.com/p/yasnippet/wiki/HowtoDefineSnippet

You can use yas-define-snippets to define a bunch of snippet for a mode at a time. The basic syntax is:

(yas-define-snippets MODE SNIPPETS)

Here's an example:

(yas-define-snippets 'text-mode
  '(("email" "`user-mail-address`" "User's email address")
    ("time" "`(current-time-string)`" "Current Time")
    ("foo" "blablablabla")))
3
  • That web page is obsolete, yas/define no longer exists, and the syntax for yas-define-snippets is different
    – npostavs
    Sep 3 '17 at 2:06
  • Let me remove yas/define. Thanks. Btw, I am using (yas-define-snippets ...) which still works for me.
    – AhLeung
    Sep 3 '17 at 5:09
  • Oh you are right, the definition of yas-define-snippets is different. I updated my answer.
    – AhLeung
    Sep 3 '17 at 5:11
1
(use-package yasnippet-snippets
  :defer 2
  :hook (prog-mode . yas-minor-mode)
  :config
  (yas-define-snippets 'js-mode
                       '(("clg" "console.log('$1: %s (%s)',$2);" "pX console.log()")
                         ("cle" "console.error('$1: %s (%s)',$2);" "pX console.error()")
                         ("Js" "JSON.stringify($1)" "pX JSON Stringification")
                         ("i" "if ($1) {\n$2\n\t} else {\n$3\n\t}\n" "Standard if")
                         ("time" "`(current-time-string)`" "Current Time")
                         ("if" "if ($1) {\n\t$2\n}" "pX if")))
  (yas-define-snippets 'sh-mode
                       '(("if" "if [ $1 ] ; then\n\t$2\nelse\n\t$3\nfi " "pX if"))))

Optional:

(use-package company
  :defer 2
  :after prog-mode
  :hook (prog-mode . company-mode)
  :bind (:map company-active-map
          ([(tab)] . company-auto-complete))
  :custom
  (company-dabbrev-ignore-case t)
  (company-etags-ignore-case t)
  (company-selection-wrap-around t)
  (company-minimum-prefix-length 1)
  (company-idle-delay 0.0)
  :config
  (eval-after-load 'company
    '(add-to-list 'company-backends '(company-yasnippet company-dabbrev-code company-capf))))

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.