Display text in the middle of the screen (pass -c
to centre every line). Useful for reading e-books, man-pages (hint: col -bx
) etc.
middle.awk
#!/usr/bin/awk -f
#
# Display text of each FILE in the middle of the screen.
# With `-c', centre each line.
#
# Usage: middle.awk [-- -c] [FILE...]
function getcols( a, cmd, col, s) {
col = ENVIRON["COLUMNS"] + 0
if (col > 0) # user override
return col
cmd = "stty -f /dev/tty size 2>/dev/null"
cmd | getline s
close(cmd)
split(s, a)
col = a[2] + 0
return (col > 0) ? col : 80
}
function strip(str, s) {
s = str
sub(/^[[:blank:]]+/, "", s) # leading blanks
sub(/[[:blank:]]+$/, "", s) # trailing "
return s
}
function len(str, a, i, ln, n) { # compute length of str,
# accounting for backspace.
n = split(str, a, "")
for (i = 1; i <= n; i++)
(a[i] == "\b") ? ln-- : ln++
if (ln < 0) ln = 0
return ln
}
function pr(L, N, i, n) {
for (i = 1; i <= N; i++) {
n = COLS/2 - LL/2
if (n < 0) n = 0 # hopeless: line len. > scr. width
printf "%*s%s\n", n, "", L[i]
}
}
BEGIN {
STYLE = "middle" # default
if (ARGV[1] == "-c") {
STYLE = "centre"
ARGV[1] = ""
}
COLS = getcols()
}
{
if (STYLE == "middle") {
if (FN != FILENAME) { # new file
FN = FILENAME
pr(L, N) # print saved prev. file
LL = N = 0 # reset
}
if ((n = len($0)) > LL) LL = n
L[++N] = $0
} else { # STYLE == "centre"
s = strip($0)
n = COLS/2 + length(s)/2
printf "%*s\n", n, s
}
}
END {
if (STYLE == "middle")
pr(L, N)
}