当Yasnippet宏可以触发时,我该如何触发事件?

12

我很喜欢yasnippet,但需要时间来记忆。我想做的是,在可以扩展宏的点上改变光标颜色(当没有宏时再改回来)。但是,从我对yasnippet工作原理的记忆来看,这可能并不完全高效。

一位朋友建议我需要一个“yasnippet-can-fire-p”,但我仍然不确定最佳实现方法。实现这个功能的最干净路径是什么,不会使我的系统崩溃?


2
下面的解决方案看起来足够好,但我认为最好的做法是使用与自动完成或公司模式等完成包集成的yasnippet。当Emacs处于空闲状态时,它们会显示完成内容,并且除了指示可以扩展外,它们还将显示它将扩展到什么。实际上,auto-complete已经有了yasnippet的源。不过我还没有尝试过。 - Dmitry
使用Yasnippet可以不必记忆任何内容。清晰的“name:”属性对于yasnippet搜索自动完成非常有帮助。 - BinaryButterfly
1个回答

14

找到检查是否可以扩展的功能花了一些时间,但最终还是“幸运”地找到了。

关键在于这个函数通常会扩展,否则就执行回退行为。我克隆了这个函数,并在那些地方设置了光标颜色。

令人惊讶的是,它实际上并没有减慢速度。

;; It will test whether it can expand, if yes, cursor color -> green.
(defun yasnippet-can-fire-p (&optional field)
  (interactive)
  (setq yas--condition-cache-timestamp (current-time))
  (let (templates-and-pos)
    (unless (and yas-expand-only-for-last-commands
                 (not (member last-command yas-expand-only-for-last-commands)))
      (setq templates-and-pos (if field
                                  (save-restriction
                                    (narrow-to-region (yas--field-start field)
                                                      (yas--field-end field))
                                    (yas--current-key))
                                (yas--current-key))))

  (set-cursor-color (if (and templates-and-pos (first templates-and-pos)) 
                        "green" "red"))))

; As pointed out by Dmitri, this will make sure it will update color when needed.
(add-hook 'post-command-hook 'yasnippet-can-fire-p)

我把这个加入到我的Lisp收藏中了(实际上我认为这也很有用)。


更新:在最新版本的yasnippet [2014年8月,从0.8.1开始]中,yas--current-key函数已被重命名为yas--templates-for-key-at-point。请参见问题


1
在这里使用post-self-insert-hook甚至是post-command-hook而不是advice会更好。您可以将它们限定为特定的缓冲区,如果使用后者,则可以在除了self-insert-command之外的命令之后触发光标更改。 - Dmitry
你可以将最后4行简化为(set-cursor-color (if (and templates-and-pos (first templates-and-pos)) "green" "red")))) - Stefan
@Stefan 谢谢,我已经采纳了你的建议! - PascalVKooten
@Dualinity:你也可以将 unless 移到 let 绑定中,去掉 setq(let ((templates-and-pos (unless (foo) (if field ...)))) (set-cursor-color ...)) - Stefan
@PascalvKooten 不用谢。 :) (将此推送到 yasnippets 本身可能是个好主意,但那不在我的掌握范围内) - AdrieanKhisbe
显示剩余4条评论

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