Bash custom autocompletion triggered by key

41 Views Asked by At

I really like Bash's programmable completion, but sometimes it does not include some files I'd like to autocomplete, so I have to type them manually.

I'd like to setup an alternate key (let's say `) that when pressed triggers an alternate, simpler completion (for example just files and folders). As far as I can see, the completion I'd like is simply compgen -f [text], so I'd like to wrap it is some function and possibly bind the key so that it triggers the completion with the last typed string.

I have been looking a lot but I can't seem to find how this would be done.

1

There are 1 best solutions below

4
Socowi On

According to the bash manual, you should already have ...

  • complete-filename bound to C-x / (first ctrlx together then /).
  • possible-filename-completions bound to M-/ (in most terminals, either alt/ together, or first esc then /)

What do they do? Assume your cursor is at the end of cmd fil and you have files file1 and file2 in your working directory. The former completes the command to cmd file. When pressed again, it shows the list of possible completions: file1 file2.
The latter shows the list directly, without completing anything.

How to bind to a single key?

See bash's bind command and man readline in general.

In general, it is pretty easy: To bind the key a to filename-completion, use bind a:complete-filename. For the backtick ` you would just do bind '`:complete-filename'.
However, if your operating system is configured with a keyboard layout that has deadkeys (press ` once, nothing seems to happen, press e, you get è), then you have to press ` twice, or your terminal and bash won't even see that you pressed that key. If you go for another key or special key or key sequence, similar things can happen. E.g. ctrlc is usually processed by the terminal, before bash even sees it.