VIM - 如何根据行是否为空为键分配不同的映射?

发布于 2024-12-28 14:13:33 字数 146 浏览 3 评论 0原文

我想根据上下文分配不同的命令。

我正在尝试做这样的事情:

if line is empty:
    map x key to y command
else
    map x key to z command

I want to assign different commands depending on context.

I'm trying to do something like this:

if line is empty:
    map x key to y command
else
    map x key to z command

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷爱 2025-01-04 14:13:33

它通常是通过 映射来实现的:

nnoremap <expr> ((empty(getline('.')))?('y'):('z'))

当您要使用 NerdCommenter 时,您被迫不使用“nore”:

nmap <expr> empty(getline('.')) ? '' : '\cc'

'' 替换为所需的代码因为我不明白你所说的“附加评论”是什么意思。

It is normally achieved by <expr> mapping:

nnoremap <expr> ((empty(getline('.')))?('y'):('z'))

As you are going to use NerdCommenter, you are forced not to use “nore”:

nmap <expr> empty(getline('.')) ? '' : '\cc'

Replace '' with the desired code as I do not understand what you mean by “appending a comment”.

小…红帽 2025-01-04 14:13:33

更好的方法是使用一个函数,其行为取决于该行的内容。那么您就不必为不同的映射而烦恼。例如:

function! LineOperation()
    let curline=getline('.')
    if curline =~ '^\s*

然后映射所需的键来调用此函数:

nnoremap <silent> x :call LineOperation()<CR>
" empty line (except for whitespace): perform y command else " perform z command endif endfunction

然后映射所需的键来调用此函数:

A better approach would be to have a single function whose behaviour depends on the contents of the line. Then you don't have to bother with different mappings. For example:

function! LineOperation()
    let curline=getline('.')
    if curline =~ '^\s*

And then map the desired key to call this function:

nnoremap <silent> x :call LineOperation()<CR>
" empty line (except for whitespace): perform y command else " perform z command endif endfunction

And then map the desired key to call this function:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文