Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/awk -f
# usage: unexpand.awk [-v ts=4] [inputfile ...] < input
BEGIN {
if (!ts) {
ts = 8
}
split(" , , , , , , , ", spc_tbl, ",")
spc_tbl[0] = ""
tab_tbl[0] = ""
}
function repeat_spc(n,
r, tmp) {
if (n in spc_tbl) {
return spc_tbl[n]
} else {
r = n % 2
tmp = repeat_spc((n - r) / 2)
tmp = tmp tmp ( r ? " " : "" )
spc_tbl[n] = tmp
return tmp
}
}
function repeat_tab(n,
r, tmp) {
if (n in tab_tbl) {
return tab_tbl[n]
} else {
r = n % 2
tmp = repeat_tab((n - r) / 2)
tmp = tmp tmp ( r ? "\t" : "" )
tab_tbl[n] = tmp
return tmp
}
}
function expand(s, tab_stop,
pos, buf, idx, c, r, w) {
pos = 0
buf = ""
for (idx = 1; idx <= length(s); ++idx) {
c = substr(s, idx, 1)
if (c == " ") {
pos += 1
buf = buf c
} else if (c == "\t") {
r = pos % tab_stop
w = tab_stop - r
pos += w
buf = buf repeat_spc(w)
} else {
exit 1
}
}
return buf
}
function unexpand(s, tab_stop,
len, q, r) {
len = length(s)
q = int(len / tab_stop)
r = len - q * tab_stop
return repeat_tab(q) repeat_spc(r)
}
{
match($0, /^[ \t]*/)
head = substr($0, 1, RLENGTH)
rest = substr($0, RLENGTH+1)
head = expand(head, ts)
head = unexpand(head, ts)
print head rest
}
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment