Skip to content

Instantly share code, notes, and snippets.

@komeda-shinji
Created July 7, 2017 07:33
Show Gist options
  • Save komeda-shinji/c74561c2c300a8db7265ce50276b9e94 to your computer and use it in GitHub Desktop.
Save komeda-shinji/c74561c2c300a8db7265ce50276b9e94 to your computer and use it in GitHub Desktop.
括弧の対応を表示
showmatch()
{
parens=''
expect=''
str="$1"
paired=''
echo "showmatch $str" >&2
while [ -n "$str" ]
do
match=$(expr "$str" : '\([^][}{)(]*[][}{)(]\).*')
if [ -n "$match" ]; then
# strip { }
prefix=$(expr "$match" : '\([^][}{)(]*\)[][}{)(]')
# get { }
paren=$(expr "$match" : '[^][}{)(]*\([][}{)(]\)')
remain=$(expr "$str" : '[^][}{)(]*[][}{)(]\(.*\)')
case "$paren" in
'['|'{'|'(')
paired="$paired$prefix$paren"
parens="$parens$paren"
expect=$(pairof "$paren")
;;
']'|'}'|')')
if [ "$expect" = "$paren" ]; then
paired="$paired$prefix$paren"
parens=$(expr "$parens" : '\(.*\).')
expect=$(pairof $(expr "$parens" : '.*\(.\)$'))
if [ -z "$parens" ]; then
echo "$paired"
paired=""
fi
else
echo "unbalanced: $paired$prefix$paren"
paired="$paired$prefix$paren"
fi
;;
esac
else
break
fi
str="$remain"
done
if [ -n "$parens" ]; then
echo "unbalanced: $paired"
else
[ -n "$paired" ] && echo "$paired"
fi
if [ -n "$str" ]; then
echo "remain: $str"
fi
}
pairof()
{
case "$1" in
'[') echo ']';;
'{') echo '}';;
'(') echo ')';;
')') echo '(';;
'}') echo '{';;
')') echo '(';;
esac
}
str="000{abc[def] [1234] {xyz}}"
showmatch "$str"
str="000{abc[def}} [1234] {xyz}"
showmatch "$str"
str="000{abc{def"
showmatch "$str"
str="000{abc{def}gh{ij{kl{mn}o}}pq{rst}u{v}{w}xy}z"
showmatch "$str"
str="000{abc{def}gh{ij{kl{mn}o}}pq{rst}u{v}{w}xy*z"
showmatch "$str"
str="000{abc{def}gh*ij{kl{mn}o}}pq{rst}u{v}{w}xy}z"
showmatch "$str"
str="000{abc{def}gh*}*ij{kl{mn}o}}pq{rst}u{v}{w}xy}z"
showmatch "$str"
str='\index{\mbox{ABC}\mbox{DEF}{X}\kern.5em{Y}\kern-.2em{Z}}\index{\mbox{GHI}\mbox{JKL}{U}\kern.5em{V}\kern-.2em{W}}'
showmatch "$str"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment