bollux/typeset_gemini.awk

123 lines
2.5 KiB
Awk

BEGIN {
pre = 0
margin = margin ? margin : 4
# Core lines
txs = "" # text style
lns = "\033[1m" # link number style
lus = "\033[36m" # link url style
lts = "\033[4m" # link text style
pfs = "" # preformatted style
# Advanced lines
h1s = "\033[1;4m" # h1 style
h2s = "\033[1m" # h2 style
h3s = "\033[3m" # h3 style
lis = "" # list item style
# Reset
res = "\033[0m" # reset style
}
/```/ {
pre = ! pre
next
}
pre {
mark = "```"
fmt = pfs "%s" res
text = $0
}
/^#/ {
match($0, /#+/)
mark = substr($0, RSTART, RLENGTH)
sub(/#+[[:space:]]*/, "", $0)
level = length(mark)
if (level == 1) {
fmt = h1s "%s" res
} else if (level == 2) {
fmt = h2s "%s" res
} else {
fmt = h3s "%s" res
}
}
/^=>/ {
mark = "=>"
sub(/=>[[:space:]]*/, "", $0)
desc = $1
text = ""
for (w = 2; w <= NF; w++) {
text = text (text ? " " : "") $w
}
fmt = lns "[" (++ln) "]" res " " lts "%s" res "\t" lus "%s" res
}
/^\*[[:space:]]/ {
mark = "*"
sub(/\*[[:space:]]*/, "", $0)
fmt = lis "%s" res
}
{
mark = mark ? mark : mark
fmt = fmt ? fmt : "%s"
text = text ? text : fold($0, " ")
desc = desc ? desc : ""
printf "%-" margin "s" fmt "\n", mark, text, desc
mark = fmt = text = desc = ""
}
function fold(str, sep, cols, out, cmd, i, j, len, chars, c, last, f, first)
{
if (! cols) {
# checks if stdout is a tty
if (system("test -t 1")) {
cols = 80
} else {
cmd = "tput cols"
cmd | getline cols
close(cmd)
}
}
# squeeze tabs and newlines to spaces
gsub(/[\t\n]/, " ", str)
# if "sep" is empty, just fold on cols with substr
if (! length(sep)) {
len = length(str)
out = substr(str, 1, cols)
for (i = cols + 1; i <= len; i += cols) {
out = out "\n"
for (j = 1; j < margin; j++) {
out = out " "
}
out = out substr(str, i, cols)
}
return out
# otherwise, we have to loop over every character (can't split() on sep, it
# would destroy the existing separators)
} else {
# split string into char array
len = split(str, chars, "")
# set boolean, used to assign the first line differently
first = 1
for (i = 1; i <= len; i += last) {
f = 0
for (c = i + cols - 1; c >= i; c--) {
if (index(sep, chars[c])) {
last = c - i + 1
f = 1
break
}
}
if (! f) {
last = cols
}
if (first) {
out = substr(str, i, last)
first = 0
} else {
out = out "\n"
for (j = 0; j < margin; j++) {
out = out " "
}
out = out substr(str, i, cols)
}
}
}
# return the output
return out
}