Zsh prompt: refine shrunken path algorithm

- Allow short elements
- Try to keep last element
  - Shorten mid-section if not possible
This commit is contained in:
tastytea 2022-04-22 23:05:21 +02:00
parent 2e4cfd99e0
commit a170e34344
Signed by: tastytea
SSH Key Fingerprint: SHA256:FBkvrOlhq5use1XEttyUGT4bUTDVA1ar9SgIc9P03cM

View File

@ -90,24 +90,37 @@ else
fi
# Reduce directory elements to first letter until directory path is reasonably
# short. Never shrink first element.
# short. Never shrink first element. Don't shrink relatively short elements. Try
# to not shrink last element.
function _shrunkpwd()
{
local dir=${(D)PWD}
local -i maxwidth=$(( ${COLUMNS} / 3 ))
if [[ ${#dir} -le ${maxwidth} ]]; then
local -i max_width=$(( ${COLUMNS} / 3 ))
if [[ ${#dir} -le ${max_width} ]]; then
print -n ${dir}
return
fi
local -a shortdir=(${(s:/:)dir})
for index in {2..${#shortdir}}; do
if [[ ${#${(j:/:)shortdir}} -gt ${maxwidth} ]]; then
shortdir[index]=${shortdir[index][1]}
# Maybe shorten all elements but the first and last
local -a short_dir=(${(s:/:)dir})
local -i allowed_element_width=$(( ${max_width} / ${#short_dir} -1 ))
for index in {2..$(( ${#short_dir} - 1 ))}; do
if [[ ${#short_dir[index]} -gt ${allowed_element_width} ]] && \
[[ ${#${(j:/:)short_dir}} -gt ${max_width} ]]; then
short_dir[index]=${short_dir[index][1]}
fi
done
local out=${(j:/:)shortdir}
# If the last element is too long, replace the mid-section with …
if [[ ${#short_dir[-1]} -gt ${allowed_element_width} ]]; then
local -i current_width=${#${(j:/:)short_dir}}
if [[ ${current_width} -gt ${max_width} ]]; then
local -i half_length=$(( ( ${max_width} - ( ${current_width} - ${#short_dir[-1]} ) ) / 2 - 1 ))
short_dir[-1]=${short_dir[-1][1,${half_length}]}"…"${short_dir[-1][$(( ${half_length} * -1 )),-1]}
fi
fi
local out=${(j:/:)short_dir}
[[ ${out[1]} != '~' ]] && out[1]="/${out[1]}"
print -n ${out}
}