custom directory completion appends whitespace

The simplest solution I've found so far is to generate completions that look like this:

COMPREPLY=( $( compgen -W "file1 file2 file3 dir1/ dir2/ dir3/" ) )

and add this line just before returning

[[ $COMPREPLY == */ ]] && compopt -o nospace

This sets the nospace option whenever the completion may fill in until the slash so that the user ends up with:

cmd dir1/<cursorhere>

instead of:

cmd dir1/ <cursorhere>

and it doesn't set the nospace option whenever the completion may fill in until a full filename so that the user ends up with:

cmd file1 <cursorhere>

instead of:

cmd file1<cursorhere>

If I understand correctly, you want to bash-autocomplete a directory name, and not have the extra space? (That's what I was looking for when I got to this page).

If so, when you register the completion function, use "-o nospace".

complete -o nospace -F _cdw cdw

I don't know if nospace works on compgen.


How about something like this:

COMPREPLY=( $(cdw; compgen -W "$(for d in ${cur}* ${cur}*/*; do [[ -d "$d" ]] && echo $d/; done)" -- ${cur}) )

(I'm not sure if you can call your shell function from here or not, otherwise you may have to duplicate it a bit.)

This also gets rid of your perl hack :-)