如何在.bashrc中制作vim调用函数? [英] How to make the vim call function in .bashrc?
问题描述
环境:debian9 + vim7.4.
Environment: debian9+vim7.4.
cat .bashrc
add(){
echo $(expr $1 + $2)
}
现在在vim中编辑文件
Now edit a file in vim
add 1 5
在命令模式:w !bash
中运行它,发生错误.
Run it in command mode :w !bash
,an error occur.
bash: line 1: add: command not found
shell returned 127
在/etc/vim/vimrc和.bashrc和.vimrc中的
1.add set shellcmdflag=-ic
.
2.重新启动
3.vim test.sh
进入命令模式
:verbose设置shellcmdflag
1.add set shellcmdflag=-ic
in both /etc/vim/vimrc and .bashrc and .vimrc .
2.reboot
3.vim test.sh
enter into command mode
:verbose set shellcmdflag
shellcmdflag=-ic
Last set from ~/.vimrc
4.在test.sh中输入两行
4.input two lines in test.sh
ls
add 5 6
:w !bash
a1.sh test.py
bash: line 2: add: command not found
shell returned 127
如何使两行同时执行?
How to make both two lines executed?
:execute '! source ~/.bashrc; source '.expand('%:p')
可以同时运行以下两个命令:ls
和add
.
:execute '! source ~/.bashrc; source '.expand('%:p')
can make both commands: ls
and add
run.
重新启动后,
1.无法从sh test.sh
调用添加功能吗?
After rebooting,
1.add function can't be called from sh test.sh
?
sh test.sh
test.sh #it means that ls command executed
test.sh: 2: test.sh: add: not found #it means that add function can't be called from /etc/vim/vimrc or .bashrc or .vimrc.
2.add函数不能从vim !bash %
调用吗?
2.add function can't be called from vim !bash %
?
test.sh #it means that ls command executed
test.sh: line 2: add: command not found #it means that add function can't be called from /etc/vim/vimrc or .bashrc or .vimrc.
[4]+ Stopped vim test.sh
推荐答案
问题是Vim默认会调用 non-interactive shell和.bashrc
(在其中定义了add
函数)仅用于交互式外壳程序.
The problem is that Vim by default invokes a non-interactive shell, and .bashrc
(where you've defined your add
function) is only read for interactive shells.
您可以指示Vim使用交互式shell:
You can instruct Vim to use an interactive shell:
:set shellcmdflag=-ic
这可能会使外部命令的调用变慢(由于评估Bash初始化的开销).
This may make external command invocations slighly slower (due to the overhead in evaluating your Bash initializations).
或者,您可以在其他地方定义该函数,因此该函数始终可用(但没有这样简单的位置;请参见man bash
,尤其是INVOCATION
部分).或将功能转换为可从PATH访问的单独脚本(例如~/bin/add
).
Alternatively, you could define the function somewhere else, so it's always available (but there's no easy place like this; see man bash
, esp. the INVOCATION
section). Or turn the function into a separate script accessible from your PATH (e.g. ~/bin/add
).
这篇关于如何在.bashrc中制作vim调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!