summaryrefslogtreecommitdiffstats
path: root/resize
blob: d132a91cb3346c5e74d7da509dcef6ae31b7984b (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
#!/bin/sh

#
# resize - script to detect actual terminal window size
#          and set the appropriate tty kernel params
#          similarly to the 20+ year old resize program from X11.
#
# Kaz Kylheku <kkylheku@gmail.com>
# October 2006
#
# LICENSE: Permission is granted to use or redistribute this program in
# original or modified form, provided the copyright notice is kept intact. Use
# of this program consititutes agreement that the author is not to be held
# liable for the consequences of any problem imagined to be connected to
# this program, under any theory of liability.
#

if [ $# -ne 0 ] ; then
    echo This is not the X11 resize program, but a shell script imitation.
    echo It does not process any arguments.
    exit 1
fi

# put tty in raw mode
saved_tty=$(stty -g)
stty raw isig -echo

# Save cursor position
printf "\0337" > /dev/tty

# Position the cursor to location 999,999
printf "\033[999;999H" > /dev/tty

# Query the actual cursor position
printf "\033[6n" > /dev/tty

# read tty response
# We use dd to read character by character
# until encountering the R letter,
# The response syntax is ESC[<row>;<col>R
while true; do
    char=$(dd bs=1 count=1 2> /dev/null)
    if [ "$char" = "R" ] ; then
        break;
    fi
    tty_response="$tty_response$char"
done

# Restore cursor position
printf "\0338" > /dev/tty

# restore tty
stty $saved_tty

# Set up tty
set_tty_params()
{
    stty rows $2 columns $3
    cat <<!
COLUMNS=$3;
LINES=$2;
export COLUMNS LINES;
!
}

# Trick: use IFS to parse the VT100 response.
# Since [ ; and R are delimiters, this means
# that the ESC, <row> and <col> will be
# extracted as tokens, and passed to the
# function as $1, $2 and $3.
IFS='[;R'
set_tty_params $tty_response