按名称插入yasnippet

6
我想在emacs-lisp函数中插入特定的yasnippet。有没有办法做到这一点? 唯一似乎相关的命令是yas/insert-snippet,但它只是打开一个带有所有选项的弹出窗口,文档没有说明如何通过指定片段名称来绕过弹出窗口。
4个回答

5

yas/insert-snippet 实际上只是在交互式使用时对 yas/expand-snippet 进行了简单的包装。然而,内部结构非常有趣。从源代码判断,当我想要在 elisp-mode 中展开 "defun" 代码段时,以下代码适用于我:

(yas/expand-snippet
  (yas/template-content (cdar (mapcan #'(lambda (table)
                                          (yas/fetch table "defun"))
                                      (yas/get-snippet-tables)))))

4

作为yasnippet的作者,我认为您不想依赖于yasnippet有趣的数据结构的内部细节,因为这些细节可能会在将来更改。我建议根据yas/insert-snippetyas/prompt-functions的文档来进行操作:

(defun yas/insert-by-name (name)
  (flet ((dummy-prompt
          (prompt choices &optional display-fn)
          (declare (ignore prompt))
          (or (find name choices :key display-fn :test #'string=)
              (throw 'notfound nil))))
    (let ((yas/prompt-functions '(dummy-prompt)))
      (catch 'notfound
        (yas/insert-snippet t)))))

(yas/insert-by-name "defun")

2
也许将其添加到软件包中会是一个值得的补充? - phils
其实,我很想了解数据结构,但我认为这个回答/评论不是合适的地方。 - Malabarba

2

我刚开始接触yasnippet,想在某些模式下自动插入我的代码片段。我找到了这里,但是我提供了一个稍微不同的解决方案。以下是另一种选择:("new-shell"是我个人提供新Shell脚本模板的代码片段的名称

(defun jsm/new-file-snippet (key)
  "Call particular yasnippet template for newly created
files. Use by adding a lambda function to the particular mode
hook passing the correct yasnippet key"
  (interactive)
  (if (= (buffer-size) 0)
      (progn
        (insert key)
        (call-interactively 'yas-expand))))

(add-hook 'sh-mode-hook '(lambda () (jsm/new-file-snippet "new-shell")))

在我看来,我的解决方案比较不容易受到yasnippet剧变的影响。


1

现在是2022年,所以我们可以简单地执行以下操作:

(yas-expand-snippet (yas-lookup-snippet "name-of-your-snippet"))

查看文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接