1

I have a yasnippet for cperl-mode:

# -*- mode: snippet -*-
# name: print Dumper
# key: vd
# --
print Dumper($0);

I need to expand this snippet to different strings depending upon the directory of the file I'm editing:

  • if dir contains /mnt/beta/ - output "die Dumper($0);"
  • otherwise - output "print Dumper($0);"

I created the following function:

(defun print-dumper ()
  "Print certain snippet depending upon file directory"
  (interactive)
      (let ((file-name (buffer-file-name)))
            (if (string-match "/mnt/beta/" file-name)
                  (insert "die Dumper();")
                  (insert "print Dumper();")))
      (backward-char 2))

It works. But how to call it in cperl mode instead of expanding yasnippet? Is there a better way to do this?

1 Answer 1

2

You can define an abbrev that uses the function you defined:

(eval-after-load "perl-mode"
   (define-abbrev perl-mode-abbrev-table "vd" "" #'print-dumper))

Don't forget to turn on abbrev-mode as a minor mode in your perl buffers:

(add-hook 'perl-mode-hook #'abbrev-mode)

Alternatively, you can probably define conditional yasnippets using the # condition directive in the snippet's definition (although I am only slightly familiar with yasnippets, so caveat emptor). The documentation says this:

condition: snippet condition

This is a piece of Emacs-lisp code. If a snippet has a condition, then it will only be expanded when the condition code evaluate to some non-nil value.

See also yas-buffer-local-condition in Expanding snippets

The problem that I see is that you might not be able to give the same key to the two snippets and I'm not familiar enough with the expansion mechanism to say what would happen if you were able to do that. Maybe a yasnippet expert will provide an answer in that case.

Your Answer

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

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