scop / bash-completion

Programmable completion functions for bash
GNU General Public License v2.0
2.95k stars 382 forks source link

Extending python -m completions? #632

Open shachargluska opened 3 years ago

shachargluska commented 3 years ago

bash-completion adds auto completions for python executable, including -m flag and the existing modules. But once a specific module is selected - is there a way to extend the completion? E.g. if I type python -m http.server - and expected to see "-h, --help, --cgi, --bind", etc...

To clarify, I don't think bash-completions should include completions for all modules. That could be generated separately by an external tool (such as shtab or argcomplete).

Is there a way to extend the existing python completions?

This is related to https://github.com/iterative/shtab/issues/55

scop commented 3 years ago

Only by modifying the current python completion code (or replacing it with some other implementation altogether). Here's an uglyish PoC:

--- a/completions/python
+++ b/completions/python
@@ -63,5 +63,14 @@ _python()

     # if -c or -m is already given, complete all kind of files.
-    if [[ ${words[*]::cword} == *\ -[cm]\ * ]]; then
+    if [[ ${words[*]::cword} =~ \ -([cm])\ +([A-Za-z0-9_.]+)? ]]; then
+        # For options after "-m foo", try to parse module help
+        if [[ $cur == -* &&
+            ${BASH_REMATCH[1]} == m && ${BASH_REMATCH[2]-} ]]; then
+            local opts=$(_parse_help "$1" "-m ${BASH_REMATCH[2]} -h")
+            if [[ ${opts-} ]]; then
+                COMPREPLY=($(compgen -W '$opts' -- "$cur"))
+                return
+            fi
+        fi
         _filedir
     elif [[ $cur != -* ]]; then

This is incomplete though. At minimum, we should additionally check if we are completing module options and skip the case blocks above entirely if we are. And this implementation doesn't have any support for module option arguments (such as --bind <TAB> for http.server), it just completes filenames for everything that doesn't look like an option. But perhaps that would already be an improvement (if the first issue would be fixed/implemented first).