Bash completion with space key only if the line is empty

84 views Asked by At

I have the following bash script

cmd_complete () {
    make run
    echo -n "${PS1@P}" # print prompt again
}

complete -F cmd_complete -E

bind "Space:complete"

This script does the following:

  • When pressing space in the terminal it triggers the terminal completion
  • The terminal complete will execute the function cmd_complete
  • The cmd_complete will run make run command then prints bash prompt again.

What is wrong:

  • When typing a word in the terminal and press space it'll not print space
  • this is because space is bound to complete function whether the bash line is empty or not.

What I would like to achieve is:

  • To run cmd_complete when pressing space ONLY when the line is empty.

Documentation I checked but couldn't find what I need:

1

There are 1 answers

0
jhnc On BEST ANSWER
my_cmd(){
    # short variable names are easier to read
    local -n ln=READLINE_LINE pt=READLINE_POINT

    # if line is not empty, just insert a space
    if [[ -n $ln ]]; then
        ln="${ln:0:pt} ${ln:pt}"
        (( pt++ ))
        return
    fi

    # do stuff here
    make run

    # no need to re-print the prompt
}

bind -x '" ":my_cmd'