How to use bash completion-functions that are defined on-the-fly?
Asked Answered
B

1

5

I try to add a completion for the alias: alias m='man'.
So, I added complete -F _man m to my .bashrc.

The problem is that the function _man used for completing, isn't defined at the start of the bash session but is defined when performing the first tab-competition on the $ man command.
So: $ complete -p | grep _man can either return nothing, or return:

complete -F _man man
complete -F _man apropos
complete -F _man whatis

Therefore, when I try to tab-complete on $ m command, I can get:

$ m -bash: completing : function « _man » not found
$ m

And I have the same problem with the functions _aptitude and _apt-get


What I would like, is to use my .bashrc to force the creation of the functions _man, _aptitude, _apt-get as soon as bash starts.
Maybe it is possible using compgen builtin.

My bash version is:
GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu)

Thanks for reading.


Edit: In fact, a similar question already exists and has been answered:
- bash-completion - completion function defined the first time a command is invoked -

Bonilla answered 17/11, 2013 at 15:54 Comment(1)
But the answer here is better than the ones in #15858771 :) I'm going to add the answer there as well.Omnivorous
B
7

You have in your .bashrc:

alias m='man'
complete -F _man m

Just add :

_completion_loader man

Then your completions on $ m will work fine, even without performing tab-completion on $ man before.

_completion_loader may not be defined in your distribution. Here's a copy of the code found in a .bashrc of Ubuntu 14.04:

_completion_loader () 
{ 
    local compfile=./completions;
    [[ $BASH_SOURCE == */* ]] && compfile="${BASH_SOURCE%/*}/completions";
    compfile+="/${1##*/}";
    [[ -f "$compfile" ]] && . "$compfile" &> /dev/null && return 124;
    complete -F _minimal "$1" && return 124
}

Actually, to avoid generating the _man function twice, you should also change the line
complete -F _man m to
complete -F _man man m.

Bonilla answered 17/11, 2013 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.