Skip to content

Autocomplete fails to complete filenames with spaces #379

Closed
@Caralluin

Description

@Caralluin

When I try the autocomplete feature in bash with file names that contain spaces, the completion fails, because the parts of the name are treated separately.

So if I have a file named file with spaces.txt and type fi, then nothing happens on first TAB (despite no other file matches fi), and on the second TAB I get the list: file spaces.txt with as possible completions, which is the correctly found filename, but the parts sorted alphabetically.

It looks for me like the result of some missing quotes or something like that, but I know very few of bash autocompletion, so I don't know how to fix it.

Activity

jonasvertikal

jonasvertikal commented on Oct 31, 2024

@jonasvertikal

I believe a solution for Bash could be to replace

append("       COMPREPLY=(\$(compgen -o default -- \"\${word}\"))\n")

from the completion generator with

append("       mapfile -t COMPREPLY < <(compgen -o default -- \"\${word}\")\n")

using the approach by https://stackoverflow.com/a/26511572. This appears to properly format paths with spaces.
It does, however, introduce a dependency on mapfile which is builtin since Bash 4 from 2009.


Unintended splits on spaces is also an issue for custom completion (source).
Here's a minimal example that shows the issue:

~$ custom_kotlin() { COMPREPLY=("foo" "foo bar" "baz"); } # emulated custom generator
~$ _bad() { COMPREPLY=($(compgen -F custom_kotlin 2>/dev/null)); }
~$ _good() { mapfile -t COMPREPLY < <(compgen -F custom_kotlin 2>/dev/null); }
~$ hello() { echo "hello world"; } # target function for completion
~$ complete -F _bad hello
~$ hello # double-tab
bar  baz  foo
~$ complete -F _good hello
~$ hello # double-tab
baz      foo      foo bar
~$

A similar solution for Bash could be to replace

append("       COMPREPLY=(\$(compgen -F $fname 2>/dev/null))\n")

from here with

append("       mapfile -t COMPREPLY < <(compgen -F fname 2>/dev/null)\n")
added a commit that references this issue on Feb 9, 2025
1418237
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Autocomplete fails to complete filenames with spaces · Issue #379 · ajalt/clikt