Sanitize input, fixing weird output when holding arrow keys

More info in http://unix.stackexchange.com/questions/179191/bashscript-to-detect-right-arrow-key-being-pressed/179193
This commit is contained in:
Jorge Morante 2016-07-31 19:02:21 +02:00
parent 0c16b46f0f
commit 29d424996d
2 changed files with 104 additions and 2 deletions

View File

@ -4,6 +4,7 @@ CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $CURRENT_DIR/config.sh
source $CURRENT_DIR/actions.sh
source $CURRENT_DIR/hints.sh
source $CURRENT_DIR/utils.sh
FINGERS_COPY_COMMAND=$(tmux show-option -gqv @fingers-copy-command)
@ -67,13 +68,59 @@ function copy_result() {
fi
}
function sanitize_input() {
local input=$(echo "$(str_to_ascii "$1")" | sed -r "s/ 27 91 [0-9]{2}//")
local sanitized=''
OLDIFS=$IFS
IFS=' '
for char_code in $input; do
sanitized="${sanitized}$(chr "$char_code")"
done
IFS=$OLDIFS
echo "$sanitized"
}
function is_valid_input() {
local input=$1
local is_valid=1
for (( i=0; i<${#input}; i++ )); do
char=${input:$i:1}
if [[ ! $(is_alpha $char) == "1" ]]; then
is_valid=0
break
fi
done
echo $is_valid
}
trap "handle_exit" EXIT
input=''
while read -r -s -n1 char
do
while read -rsn1 char; do
# Escape sequence, flush input
if [[ "$char" == $'\x1b' ]]; then
read -rsn1 -t 0.1 next_char
if [[ "$next_char" == "[" ]]; then
read -rsn1 -t 0.1
fi
continue
fi
if [[ ! $(is_valid_input "$char") == "1" ]]; then
continue
fi
if [[ $char == "$BACKSPACE" ]]; then
input=""
continue
else
input="$input$char"
fi

View File

@ -1,9 +1,64 @@
#!/usr/bin/env bash
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
function array_join() {
local IFS="$1"; shift; echo "$*";
}
function ord() {
LC_CTYPE=C printf '%d' "'$1"
}
function chr() {
[ "$1" -lt 256 ] || return 1
printf "\\$(printf '%03o' "$1")"
}
function is_between() {
local value=$1
local lower=$2
local upper=$3
if [[ $value -ge $lower ]] && [[ $value -le $upper ]]; then
echo 1
else
echo 0
fi
}
A_CODE=$(ord "a")
Z_CODE=$(ord "z")
CAPITAL_A_CODE=$(ord "A")
CAPITAL_Z_CODE=$(ord "Z")
function is_letter() {
echo $(is_between $(ord $1) $A_CODE $Z_CODE)
}
function is_capital_letter() {
echo $(is_between $(ord $1) $CAPITAL_A_CODE $CAPITAL_Z_CODE)
}
function is_alpha() {
if [[ $(is_letter $1) == "1" ]] || [[ $(is_capital_letter $1) == "1" ]]; then
echo 1
else
echo 0
fi
}
function str_to_ascii() {
local input=$1
local output=''
for (( i=0; i<${#input}; i++ )); do
output="${output}$(ord "${input:$i:1}") "
done
echo "${output// $//}"
}
function display_message() {
local original_display_time=$(tmux show-option -gqv display-time)
tmux set-option -g display-time $2