bash-completion icon indicating copy to clipboard operation
bash-completion copied to clipboard

Extending python -m completions?

Open shachargluska opened this issue 4 years ago • 1 comments
trafficstars

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 -<TAB> 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

shachargluska avatar Oct 19 '21 17:10 shachargluska

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).

scop avatar Oct 20 '21 20:10 scop