Vim地图不起作用

时间:2016-06-23 05:22:51

标签: vim

我编写了一个vim命令来帮助我在ruby代码中找到方法定义。 它接受光标下的单词并搜索具有该名称的方法定义。

:silent execute "normal! /\\v\\s*def (self.)?".expand('<cword>')."\<cr>"

它工作正常,但现在我想将它映射到一个键命令。

:nnoremap \m :silent execute "normal! /\\v\\s*def (self.)?".expand('<cword>')."\<cr>"

由于某种原因,这不起作用。 当我将光标放在方法名称上并键入\m时,我收到以下错误消息

E114: Missing quote: "\
E15: Invalid expression: "normal! /\\v\\s*def (self.)?".expand('<cword>')."\

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

问题是map本身会扩展<cr>,因此它尝试运行的命令是

:silent execute "normal! /\\v\\s*def (self.)?".expand('<cword>')."\
"

第一行触发错误,因为末尾有未终止的字符串。

要解决此问题,请尝试

nnoremap <silent> \m :silent execute "normal! /\\v\\s*def (self.)?".expand('<cword>')."\n"<cr>
  • 我添加了<silent>以使整个映射无声(否则vim将回显它在运行\m时扩展到的命令)
  • 而不是\<cr>您可以在字符串中简单地写\n,因此地图将不再使用
  • 您需要在映射结束时使用<cr>,否则命令将无法运行(它只会坐在那里等待您按Enter键)

答案 1 :(得分:1)

@melpomene correctly debugged this mapping and pointed out the need to escape <cr> in your mapping. You can also use <lt> to fix your mapping:

nnoremap \m :silent execute 'normal! /\v\s*def (self.)?'.expand('<cword>')."\<lt>cr>"<cr>

I have also used single quotes to reduce the escaping in part of the mapping.

However this mapping can be greatly simplified with the use of <c-r><c-w> to get the current word under the cursor. This means we can avoid using :execute, :normal, and expand(). Meaning we do not need to do any escaping at all.

nnoremap <silent> \m /\v\s*def (self.)?<c-r><c-w><cr>

You may want to take this further by using \zs to start the match at the word under the cursor instead at the start of the line:

nnoremap <silent> \m /\v\s*def (self.)?\zs<c-r><c-w><cr>

For more help see:

:h <>
:h literal-string
:h c_CTRL-R_CTRL-W
:h /\zs