如何在 Vim 中为命令创建别名?

发布于 2024-09-26 10:22:02 字数 397 浏览 1 评论 0原文

Vim 是我编程时首选的文本编辑器,因此我总是遇到一个特别烦人的问题。

通常,当我快速需要保存缓冲区并继续执行其他杂项任务时,我会执行典型的操作。

:w

但是,我总是 ——似乎超过 50% 的时间 ——设法利用这一点 :w。自然地,Vim 对我大喊大叫,因为 W 是一个无效命令:

E492: Not an editor command: W

我的问题是如何在 Vim 中为冒号命令起别名。特别是,您能否举例说明如何将 W 别名为 w

我知道将按键映射到某些命令的过程,但这不是我想要的。

Vim is my preferred text editor when I program, and thus I always run into a particularly annoying issue.

Frequently, when I quickly need to save the buffer and continue on to some other miscellaneous task, I do the typical

:w

However, I always — what seems to be like more than 50% of the time — manage to capitalize that :w. Naturally, Vim yells at me because W is an invalid command:

E492: Not an editor command: W

My question is how can one alias colon-commands in Vim. Particularly, could you exemplify how to alias W to w.

I am aware of the process to map keys to certain commands, but that is not what I’m looking for.

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

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

发布评论

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

评论(8

泪冰清 2024-10-03 10:22:08

最安全和最简单的是插件,例如 cmdalias.vim 或我最近的更新它的 vim-alias 考虑了

  • 前面的空格或修饰符,例如:sil(ent)(!):redi(r)
  • 范围修饰符,例如当前的 '<,'>视觉选择,
  • 转义特殊字符(例如引号),并
  • 检查所选别名是否是有效的命令行缩写。

Safest and easiest is a plugin such as cmdalias.vim or my recent update vim-alias of it that take into account

  • preceding blanks or modifiers such as :sil(ent)(!) or :redi(r),
  • range modifiers such as '<,'> for the current visual selection,
  • escape special characters such as quotes, and
  • check if the chosen alias is a valid command line abbreviation.
旧时浪漫 2024-10-03 10:22:08

我认为@ZyX的答案很好,但是如果您使用的是较新版本的neovim(0.5+),您可能想使用lua来定义函数。这是一种方法:

function _G.abbreviate_or_noop(input, output)
  local cmdtype = vim.fn.getcmdtype()
  local cmdline = vim.fn.getcmdline()

  if (cmdtype == ":" and cmdline == input) then 
    return output
  else
    return input
  end
end

function SetupCommandAlias(input, output)
  vim.api.nvim_command("cabbrev <expr> " .. input .. " " .. "v:lua.abbreviate_or_noop('" .. input .. "', '" .. output .. "')")
end

然后,您可以从 call SetupCommandAlias("pg", "postgres://") 中删除 call 并仅使用该函数像这样:SetupCommandAlias("pg", "postgres://")

注意:如果从 .vim 文件而不是 .lua 文件使用它,则需要在函数调用前加上 lua 前缀,即lua SetupCommandAlias("pg", "postgres://")

I think @ZyX's answer is great, but if you're using a newer version of neovim (0.5+), you might want to define the function using lua instead. Here's one way you could do it:

function _G.abbreviate_or_noop(input, output)
  local cmdtype = vim.fn.getcmdtype()
  local cmdline = vim.fn.getcmdline()

  if (cmdtype == ":" and cmdline == input) then 
    return output
  else
    return input
  end
end

function SetupCommandAlias(input, output)
  vim.api.nvim_command("cabbrev <expr> " .. input .. " " .. "v:lua.abbreviate_or_noop('" .. input .. "', '" .. output .. "')")
end

Then, you'd drop the call from call SetupCommandAlias("pg", "postgres://") and just use the function like this: SetupCommandAlias("pg", "postgres://").

n.b. If using it from a .vim file instead of a .lua file, you'd need to prefix the function call with lua, i.e. lua SetupCommandAlias("pg", "postgres://").

旧夏天 2024-10-03 10:22:07

也许您想将功能键之一 (F1..F12) 映射到 :w ?然后将其放入您的 .vimrc 中:(

noremap  <f1> :w<return>
inoremap <f1> <c-o>:w<return>

插入模式下的 ctrl-o 暂时切换到正常模式)。

Maybe you would like to map one of your function keys (F1..F12) to :w ? Then put this into your .vimrc:

noremap  <f1> :w<return>
inoremap <f1> <c-o>:w<return>

(ctrl-o in insert mode switches temporarily to normal mode).

铃予 2024-10-03 10:22:06

最好的解决方案包括 编写自定义函数 用于处理仅出现在命令栏开头的缩写。

为此,请在 vimrc 文件或其他任何位置添加以下内容。

" cabs - less stupidity                                                      {{{
fu! Single_quote(str)
  return "'" . substitute(copy(a:str), "'", "''", 'g') . "'"
endfu
fu! Cabbrev(key, value)
  exe printf('cabbrev <expr> %s (getcmdtype() == ":" && getcmdpos() <= %d) ? %s : %s',
    \ a:key, 1+len(a:key), Single_quote(a:value), Single_quote(a:key))
endfu
"}}}

 

" use this custom function for cabbrevations. This makes sure that they only
" apply in the beginning of a command. Else we might end up with stuff like
"   :%s/\vfoo/\v/\vbar/
" if we happen to move backwards in the pattern.

" For example:
call Cabbrev('W', 'w')

一些源材料中的有用缩写我在哪里找到这个东西:

call Cabbrev('/',   '/\v')
call Cabbrev('?',   '?\v')

call Cabbrev('s/',  's/\v')
call Cabbrev('%s/', '%s/\v')

call Cabbrev('s#',  's#\v')
call Cabbrev('%s#', '%s#\v')

call Cabbrev('s@',  's@\v')
call Cabbrev('%s@', '%s@\v')

call Cabbrev('s!',  's!\v')
call Cabbrev('%s!', '%s!\v')

call Cabbrev('s%',  's%\v')
call Cabbrev('%s%', '%s%\v')

call Cabbrev("'<,'>s/", "'<,'>s/\v")
call Cabbrev("'<,'>s#", "'<,'>s#\v")
call Cabbrev("'<,'>s@", "'<,'>s@\v")
call Cabbrev("'<,'>s!", "'<,'>s!\v")

The best solution involves writing a custom function for handling abbreviations that only take place in the beginning of the command bar.

For this, add the following your vimrc file or anywhere else.

" cabs - less stupidity                                                      {{{
fu! Single_quote(str)
  return "'" . substitute(copy(a:str), "'", "''", 'g') . "'"
endfu
fu! Cabbrev(key, value)
  exe printf('cabbrev <expr> %s (getcmdtype() == ":" && getcmdpos() <= %d) ? %s : %s',
    \ a:key, 1+len(a:key), Single_quote(a:value), Single_quote(a:key))
endfu
"}}}

" use this custom function for cabbrevations. This makes sure that they only
" apply in the beginning of a command. Else we might end up with stuff like
"   :%s/\vfoo/\v/\vbar/
" if we happen to move backwards in the pattern.

" For example:
call Cabbrev('W', 'w')

A few useful abbreviations from the source material where I found this stuff:

call Cabbrev('/',   '/\v')
call Cabbrev('?',   '?\v')

call Cabbrev('s/',  's/\v')
call Cabbrev('%s/', '%s/\v')

call Cabbrev('s#',  's#\v')
call Cabbrev('%s#', '%s#\v')

call Cabbrev('s@',  's@\v')
call Cabbrev('%s@', '%s@\v')

call Cabbrev('s!',  's!\v')
call Cabbrev('%s!', '%s!\v')

call Cabbrev('s%',  's%\v')
call Cabbrev('%s%', '%s%\v')

call Cabbrev("'<,'>s/", "'<,'>s/\v")
call Cabbrev("'<,'>s#", "'<,'>s#\v")
call Cabbrev("'<,'>s@", "'<,'>s@\v")
call Cabbrev("'<,'>s!", "'<,'>s!\v")
鸵鸟症 2024-10-03 10:22:06

假设你想在 gvim 中为 tabnew 命令添加别名。您只需在 .vimrc 文件中键入以下命令(如果不在主文件夹中,则创建一个)

cabbrev t tabnew

Suppose you want to add alias for tabnew command in gvim. you can simply type the following command in your .vimrc file (if not in home folder than create one)

cabbrev t tabnew
厌味 2024-10-03 10:22:05

我发现将 ; 键映射到 : 将是一个更好的解决方案,并且可以提高您键入其他命令的效率。

nnoremap ; :
vnoremap ; :

I find that mapping the ; key to : would be a better solution, and would make you more productive for typing other commands.

nnoremap ; :
vnoremap ; :
嗼ふ静 2024-10-03 10:22:04

要保持完成不变,请尝试使用

cnoreabbrev W w

它将命令行中的W替换为w,但前提是它后面或前面都没有单词字符,所以:W 将替换为 :w,但 :Write 不会。 (请注意,这会影响任何匹配的命令,包括您可能不期望的命令。例如,命令 :saveas W Z 将替换为 :saveas w Z,因此请小心这一点。)

更新

这是我现在的编写方式:

cnoreabbrev <expr> W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))

作为函数:

fun! SetupCommandAlias(from, to)
  exec 'cnoreabbrev <expr> '.a:from
        \ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
        \ .'? ("'.a:to.'") : ("'.a:from.'"))'
endfun
call SetupCommandAlias("W","w")

这会检查命令类型是否为并且命令是否为W,所以它比 cnoreabbrev W w 更安全。

To leave completion untouched, try using

cnoreabbrev W w

It will replace W in command line with w, but only if it is neither followed nor preceded by word character, so :W<CR> will be replaced with :w<CR>, but :Write won’t. (Note that this affects any commands that match, including ones that you might not expect. For example, the command :saveas W Z will be replaced by :saveas w Z, so be careful with this.)

Update

Here is how I would write it now:

cnoreabbrev <expr> W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))

As a function:

fun! SetupCommandAlias(from, to)
  exec 'cnoreabbrev <expr> '.a:from
        \ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
        \ .'? ("'.a:to.'") : ("'.a:from.'"))'
endfun
call SetupCommandAlias("W","w")

This checks that the command type is : and the command is W, so it’s safer than just cnoreabbrev W w.

半﹌身腐败 2024-10-03 10:22:04

通过补充搜索,我发现有人问了几乎相同的问题 正如我

:command <AliasName> <string of command to be aliased>

会做的那样。

请注意,正如 Richo 指出的那样,用户命令必须以大写字母开头。 >

With supplementary searching, I've found that someone asked nearly the same question as I.

:command <AliasName> <string of command to be aliased>

will do the trick.

Please be aware that, as Richo points out, the user command must begin with a capital letter.

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