简体   繁体   English

在 elisp 中通过 function arguments

[英]passing function arguments in elisp

I have a function defined in my init.el :我在我的 init.el 中定义了一个init.el

(defun bind-key (keymap)
    (evil-define-key '(normal insert) keymap (kbd "C-=") 'some-function))

(bind-key 'c++-mode-map)

But evil-define-key does not bind the C-= to some-function in keymap .但是evil-define-key不会将C-=绑定到keymap中的某些功能。

However, invoke evil-define-key directly is ok:但是,直接调用evil-define-key是可以的:

(evil-define-key '(normal insert) c++-mode-map (kbd "C-=") 'some-function)

I have tried:我努力了:

(bind-key 'c++-mode-map)
(bind-key c++-mode-map)

Neither works.两者都不起作用。

I have googled for passing keymaps to a function, but found no solution.我搜索了将键盘映射传递给 function,但没有找到解决方案。 Then, I noticed evil-define-key is a macro.然后,我注意到evil-define-key是一个宏。 But I can not found solutions in this situation.但在这种情况下我找不到解决方案。

How can I get bind-key to work?我怎样才能让bind-key工作? By passing a keymap to it, the function binds C-= to some-function in in the keymap?通过将键盘映射传递给它,function 将C-=绑定到键盘映射中的某个函数?

As you've noticed, this is trickier than it looks because evil-define-key is a macro (defined here ).正如您所注意到的,这比看起来更棘手,因为evil-define-key是一个宏( 在此处定义)。 It takes a symbol that names a keymap variable, and binds the key once that variable has been defined.它采用一个命名键映射变量的符号,并在定义该变量后绑定键。 However, in this case it gets the symbol keymap instead of c++-mode-map , since a macro invocation receives as arguments the literal values in the call.但是,在这种情况下,它获取的是符号键keymap而不是c++-mode-map ,因为宏调用将调用中的文字值作为 arguments 接收。

You can get around this by changing your own function into a macro.您可以通过将自己的 function 更改为宏来解决此问题。 That means that instead of just running some code, it needs to return some code that then gets evaluated.这意味着它不仅需要运行一些代码,还需要返回一些然后被评估的代码。 Like this:像这样:

(defmacro bind-key (keymap)
  `(evil-define-key '(normal insert) ,keymap (kbd "C-=") 'some-function))

The backquote introduces a form that gets returned verbatim, except for values inside it preceded by a comma.反引号引入了一种逐字返回的形式,除了其中的值以逗号开头。

Invoke it with (bind-key c++-mode-map) , and it should be equivalent to your explicit call to evil-define-key .使用(bind-key c++-mode-map)调用它,它应该等同于您对evil-define-key的显式调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM