Skip to content

Commit

Permalink
Use array PROMPT_COMMAND in Bash >= 5.1
Browse files Browse the repository at this point in the history
Bash 5.1 started to support the array form of PROMPT_COMMAND, which
can be used to register multiple PROMPT_COMMAND commands more
robustly.  We perform this in a shell function to temporarily set IFS.
  • Loading branch information
akinomyoga committed Jul 17, 2024
1 parent df3e63d commit 8ad6576
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions mcfly.bash
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,25 @@ function mcfly_initialize {
return "${exit_code}" # Restore the original exit code by returning it.
}

function mcfly_add_prompt_command {
local command=$1 IFS=$' \t\n'
if ((BASH_VERSINFO[0] > 5 || BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 1)); then
# Bash 5.1 supports array PROMPT_COMMAND, where we register our prompt
# command to a new element PROMPT_COMMAND[i] (with i >= 1) to avoid
# conflicts with other frameworks.
if [[ " ${PROMPT_COMMAND[*]-} " != *" $command "* ]]; then
PROMPT_COMMAND[0]=${PROMPT_COMMAND[0]:-}
PROMPT_COMMAND+=("$command")
fi
elif [[ -z ${PROMPT_COMMAND-} ]]; then
PROMPT_COMMAND="$command"
elif [[ $PROMPT_COMMAND != *"mcfly_prompt_command"* ]]; then
PROMPT_COMMAND="$command;${PROMPT_COMMAND#;}"
fi
}
# Set $PROMPT_COMMAND run mcfly_prompt_command, preserving any existing $PROMPT_COMMAND.
mcfly_add_prompt_command "mcfly_prompt_command"

function mcfly_search_with_tiocsti {
local LAST_EXIT_CODE=$?
# shellcheck disable=SC2145
Expand Down Expand Up @@ -107,15 +126,6 @@ function mcfly_initialize {
return "$LAST_EXIT_CODE"
}

# Set $PROMPT_COMMAND run mcfly_prompt_command, preserving any existing $PROMPT_COMMAND.
if [ -z "${PROMPT_COMMAND-}" ]
then
PROMPT_COMMAND="mcfly_prompt_command"
elif [[ ! "$PROMPT_COMMAND" =~ "mcfly_prompt_command" ]]
then
PROMPT_COMMAND="mcfly_prompt_command;${PROMPT_COMMAND#;}"
fi

# Take ownership of ctrl-r.
if [[ ${BASH_VERSINFO[0]} -ge 4 ]]; then
# shellcheck disable=SC2016
Expand Down

0 comments on commit 8ad6576

Please sign in to comment.