2

I created a yasnippet that calls a function:

# -*- mode: snippet -*-
# name: print
# key: pr
# --
`(cperl-print)`

The function code:

(defun cperl-print ()
  (interactive)
  (let* ((current (point))
          (end (line-end-position)))
    (if (< current end)
      (insert "print")
      (progn
        (insert "print ;")
        (backward-char 1))
      )))

Unfortunately, backward-char doesn't produce any effect when called from inside yasnippet. When the function is called directly, it works. Is there any way to fix this?

3
  • The snippet writing tutorial expressly discourages the use of insert within backquotes... Per the snippet writing tutorial joaotavora.github.io/yasnippet/snippet-development.html : "Note: backquote expressions should not modify the buffer. Please note that the lisp forms in backquotes should not modify the buffer, doing so will trigger a warning. For example, instead of doing ..."
    – lawlist
    Oct 6, 2021 at 13:52
  • @lawlistWhat to do if I need to insert different text depending upon the environment? His example is too primitive.
    – user4035
    Oct 6, 2021 at 15:40
  • In older versions of yasnippet, it was possible to return a string with a place holder of where to end such as "print$0;" and that would have solved your problem -- along with there being no need to use (insert "...."), i.e., just return the string itself. However, that previous solution no longer works because there is an args out of range error. If @npostavs is still active on this forum, then he may have a solution for you. If a satisfactory answer is not forthcoming in a reasonable period of time, then you may wish to consider submitting an Issue on Github to obtain some guidance.
    – lawlist
    Oct 7, 2021 at 3:35

1 Answer 1

0

According to the documentation, there is type directive:

If the type directive is set to command, the body of the snippet is interpreted as lisp code to be evaluated when the snippet is triggered.

So, I just used it and it worked.

# -*- mode: snippet -*-
# name: print
# key: pr
# type: command
# --
(let* ((current (point))
        (end (line-end-position)))
  (if (< current end)
    (insert "print")
    (progn
      (insert "print ;")
      (backward-char 1))))

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.