如何使 Vim 在运行 `vim` 命令时不报错并以 `--remote-silent` 模式打开文件?

4

为了在现有的Vim实例(我的情况是MacVim)中打开文件,我采用了Derek Wyatt的建议,并将以下内容添加到我的bash_profile中:

alias mvim='mvim --remote-silent'

只要我传递一个参数给mvim(mvim myFilemvim .等),这个命令就可以工作。但是如果我只运行mvim,就会出现错误:Argument missing after: "--remote-silent"
因此,我用以下函数替换了上面的别名:
function mvim() {
  if [ $# > 0 ] ; then
    command mvim --remote-silent "$@"
  else
    command mvim
  fi
}

现在,如果我不带参数运行 mvim 命令,我会得到同样的错误信息一个名为0的文件被写入了当前目录。如果我传递参数给mvim,则一切正常。
我错过了什么?如何处理这个问题?
感谢Ingo Karkat澄清。如果有人感兴趣,这是我现在的处理方式:
function ivim {
  if [ -n "$1" ] ; then
    command mvim --remote-silent "$@"
  elif [ -n "$( mvim --serverlist )" ] ; then
    command mvim --remote-send ":call foreground()<CR>:enew<CR>:<BS>"
  else
    command mvim
  fi
}

elif分支末尾的:<BS>只是为了清除命令行。这感觉有点hacky,但我不知道还有什么其他方法可以实现这一点。

2个回答

4
在 Bash 中,这个测试表达式是不正确的:[ $# > 0 ];你正在将标准输出(>)重定向到文件 0。相反地,请使用旧样式的 -gt "greater than" 运算符。
[ $# -gt 0 ]

或者使用较新的[[内置条件命令:
[[ $# > 0 ]]

1
[[ $# > 0 ]] 不是算术运算符“大于”。你可能想要使用 (( $# > 0 )) - Dmitry Alexandrov

0
如果你想把函数命名为mvim而不是其他名称(因为你已经习惯了输入mvim或其他原因),这里有一个简单的解决方法。
function mvim {
  if [ -n "$1" ] ; then
    command mvim --remote-silent "$@"
  elif [ -n "$( command mvim --serverlist )" ] ; then
    command mvim --remote-send ":call foreground()<CR>:enew<CR>:<BS>"
  else
    command mvim
  fi
}

请注意在elif中调用mvim之前添加的command

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