我想在emacs-lisp函数中插入特定的yasnippet。有没有办法做到这一点?
唯一似乎相关的命令是yas/insert-snippet,但它只是打开一个带有所有选项的弹出窗口,文档没有说明如何通过指定片段名称来绕过弹出窗口。
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)))))
作为yasnippet的作者,我认为您不想依赖于yasnippet有趣的数据结构的内部细节,因为这些细节可能会在将来更改。我建议根据yas/insert-snippet
和yas/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")
我刚开始接触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剧变的影响。