如何在不影响其他完成脚本的情况下重置 COMP_WORDBREAKS? [英] How to reset COMP_WORDBREAKS without affecting other completion script?
问题描述
当我实现一个 bash 自动完成功能时,有些东西让我感到困惑,我会把它放在 /etc/bash_completion.d/
There is something confuse me when I implement a bash auto-completion function which I'll put it in /etc/bash_completion.d/
为了实现某些功能,我想从变量 $COMP_WORDBREAKS
中删除分词符冒号 (:
) 并添加斜线 (/
) 在 $COMP_WORDBREAKS
的开头.
In order to achieve some feature, I want to remove the word break characters colon (:
) from variable $COMP_WORDBREAKS
and add a slash (/
) at begin of $COMP_WORDBREAKS
.
COMP_WORDBREAKS=" /'><=;|&("
_mytool()
{
local cur=${COMP_WORDS[COMP_CWORD]}
compopt -o nospace
# my implement here
COMPREPLY=( $(compgen ..........my_implement......... -- $cur) )
}
complete -F _mytool mytool
但是,我无法直接重置 COMP_WORDBREAKS
,因为该值与其他完成脚本共享.当完成函数被调用时,变量 COMP_WORDS
数组已经被填充,所以本地更改 COMP_WORDBREAKS
没有任何影响.
However, I can't reset COMP_WORDBREAKS
directly because the value is shared with other completion scripts. By the time the completion function gets called, variable COMP_WORDS
array has already been populated, so locally changes COMP_WORDBREAKS
have no effect.
是否有任何解决方案可以在一个完成脚本中更改 COMP_WORDBREAKS
而对其他脚本没有影响?
Is there any solution for changing COMP_WORDBREAKS
in one completion script and no effect to other script?
$ echo $BASH_VERSION
4.2.10(1)-release
推荐答案
在完成脚本中修改 $COMP_WORDBREAKS
不是推荐的方式(因为它是一个全局变量,它可能会影响其他完成脚本 - 例如 ssh).
Modifying $COMP_WORDBREAKS
in your completion script is not the recommended way (as it is a global variable and it could affect the behavior of other completion scripts - for example ssh).
但是,bash 补全提供了一些辅助方法,您可以使用它们来实现目标.
However, bash completion offers some helper methods which you can use to achieve your goal.
在完成词中处理非断字字符的推荐方法是使用两种辅助方法:
The recommended way to handle non-word-breaking characters in completion words is by using the two helper methods:
_get_comp_words_by_ref
带有-n EXCLUDE
选项- 在不将 EXCLUDE 中的字符视为分词符的情况下获取完整单词
- 从 COMPREPLY 项目中删除包含前缀的冒号
(http://tiswww.case.edu/php/chet/bash/FAQ 的解决方法 -E13)
- removes colon containing prefix from COMPREPLY items
(a workaround for http://tiswww.case.edu/php/chet/bash/FAQ - E13)
所以,这里有一个基本示例,说明如何处理完成词中的冒号 (:):
So, here is a basic example of how to a handle a colon (:) in completion words:
_mytool() { local cur _get_comp_words_by_ref -n : cur # my implementation here COMPREPLY=( $(compgen ..........my_implement......... -- $cur) ) __ltrim_colon_completions "$cur" } complete -F _mytool mytool
作为最后一个提示,辅助方法位于
/etc/bash_completion
.看看里面,阅读每个方法的详细说明,发现更多的辅助方法.As a final tip, the helper methods are located in
/etc/bash_completion
. Take a look inside to read a detailed description of each method and to discover more helper methods.这篇关于如何在不影响其他完成脚本的情况下重置 COMP_WORDBREAKS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!