spmenu-wiki/Contextual completions.md

1.6 KiB

Contextual completions

xprompt is a prompt for X providing one notable feature over dmenu: contextual completions. Contextual completions can be achieved with spmenu as well by using the -r flag and reading from file.

printf "Type 'git' and it will autocomplete." > /tmp/git-complete-file
printf "" > /tmp/f

func() {
    while true; do
        case "$(tail -n 1 /tmp/f)" in
            "git ")
                printf "git clone\ngit pull\ngit fetch\n" > /tmp/git-complete-file
            ;;
            "git clone ")
                printf "git clone https://git.speedie.site/speedie/spmenu\n" > /tmp/git-complete-file
            ;;
        esac
    done
}

func &

spmenu -lf /tmp/git-complete-file -r >> /tmp/f

tail -n 1 /tmp/f

This is an example of a script which allows you to autocomplete some Git arguments. If you type in git, git clone, git pull and git fetch will be displayed as matching options. If you type in git clone, git clone will be displayed as a match with the spmenu Git repository. Of course, this is a super basic script, which should give you an idea of how this works.

Importantly, -r is passed to spmenu. This will print the text typed into spmenu every single time a key is pressed. We need to output this to a file, so the case statement can get the last line. The last line is always the typed/matched text. If -r is not passed, spmenu will not output anything until enter is pressed, and therefore we can't check the input while spmenu is running.

The function func is a while loop which does the checking and writing of /tmp/git-complete-file. spmenu reads items from /tmp/git-complete-file.