aboutsummaryrefslogtreecommitdiffstats
path: root/bash-prompt.sh
blob: 587b6edb306ac76a438cb7d9cd1bb3eed23e7076 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# License at bottom

old_cmdno=${old_cmdno-0}
old_lines=${old_lines-0}
old_cols=${old_cols-0}

prepare_terminal()
{
  stty rows $((LINES - 1))
  printf "\n\033[1A"
  old_lines=$LINES
  old_cols=$COLUMNS
}

get_current_line()
{
  local esc=$(printf "\033")
  local response
  printf "$esc[6n" > /dev/tty
  read -s -d R response < /dev/tty
  local IFS="[;"
  set -- $response
  printf "%s\n" "$2"
}

update_status_line()
{
  local exit=$?
  local getcmdno='\#'
  local cmdno=${getcmdno@P}
  local esc=$(printf "\033")
  local pwd=$PWD
  local dots=

  [ $LINES -eq $old_lines -a $COLUMNS -eq $old_cols ] || prepare_terminal

  local status_esc="$esc[7m$esc[m"

  while true; do
    local status="$esc[7m$(date +%m-%d/%H:%M)$esc[m $HOSTNAME $dots$pwd"
    local status_len=$((${#status} - ${#status_esc}))
    [ $status_len -le $COLUMNS ] && break
    pwd=${pwd#/}
    pwd=/${pwd#*/}
    dots='...'
    [ "${pwd#/*/}" == "$pwd" ] && break
  done

  status_len=$((${#status} - ${#status_esc}))

  [ $status_len -gt $COLUMNS ] && status=

  printf "${esc}7$esc[%s;1H$esc[K%s$esc[1;%sr${esc}8" $((LINES + 1)) "$status" $LINES
  if [ $exit -ne 0 -a $cmdno -ne $old_cmdno ] ; then
    printf "!%s!\n" $exit
  fi

  local curln=$(get_current_line)

  if [ $curln -gt $LINES ]; then
    printf "$esc[%s;1H" $LINES
  fi

  old_cmdno=$cmdno
}

PROMPT_COMMAND='update_status_line'

# Copyright 2023
# Kaz Kylheku <kaz@kylheku.com>
# Vancouver, Canada
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condition is met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form need not reproduce any copyright notice.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.