Y.Khurshid
Y.Khurshid

Reputation: 21

Dynamics keys for yasnippet

I'm currently learning to define yasnippets but there seems to be a use case that I can't figure out how to use. For example, let's say I want to define a ruby snippet that expands the key 'def' into a standard function definition. This is very easy to do but suppose I want to make the number of parameters of the generated function depend on the key, like if I expand the key 'def>n', I want a function defintion with n number of parameters. How would I accomplish this?

edit

Basically I want to make dynamics snippets that have behaviour that the HTML plugin Emmet possesses. Just as in how the following abbrev 'p*3>div*2' with Emmet creates 3 pairs of p tags with two div pairs within each, I would like it to be possible to make 'def*3>2' to generate 3 function definitions with 2 arguments each. That's just an example but basically I want quantifier and nesting properties.

Upvotes: 1

Views: 226

Answers (1)

Jules
Jules

Reputation: 973

To try to help out I wrote the snippet for you that does what the html does that you were talking about. You should be able to edit it to change it so that it does what you want but it wouldn't be much fun if all of the work were done for you ;).

First thing I did was define the function that does the transformation from

"p*3>div*2"

to

<p>
<div>
</div>
<div>
</div>
</p>
<p>
<div>
</div>
<div>
</div>
</p>
<p>
<div>
</div>
<div>
</div>
</p>

That function is:

(defun crushlist (my-list)
  (if my-list
      (let* ((elem (car my-list))
             (char (first (split-string elem "*")))
             (num (string-to-int(second (split-string elem "*")))))
        (apply 'concat
               (cl-loop for i from 1 to num
                        collect (concat "<" char ">
" (crushlist (cdr my-list)) "</" char ">
"))))
    ""))

The snippet then is:

${1:$$(when yas-moving-away-p (move-beginning-of-line nil) (kill-line) (insert (crushlist (split-string yas-text ">"))))}

I feel like the snippet should be:

${1:$$(when yas-moving-away-p (crushlist (split-string yas-text ">")))}

but that didn't work for me for some reason (if you find out please let me know!)

If you have any questions on how to implement your actual snippet, leave me a comment and I'll try to help.

Upvotes: 1

Related Questions