about summary refs log tree commit diff stats
path: root/et
blob: 0e03aa37dfd1a8fe23379e78bca2fbfcf9306ee1 (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
#!/bin/sh
{ excitable="text" "exec" "awk" "-f" "$0" "$@"; } # -*- awk -*-
# usage: et <file> | sh

BEGIN {
	xend = xend ? xend : "...end...shexpand..."
	dend = dend ? dend : "...end...document..."
	# We shell out to sed for this because awk doesn't do capture groups ;-;
	shellfix = "sed -E" \
		" -e 's/`/\\\\`/g'" \
		" -e 's/(^|[^\\$])\\$([^\\$]|$)/\\1\\\\$\\2/g'" \
		" -e 's/(^|[^\\$])\\$(\\$+)([^\\$]|$)/\\1\\2\\3/g'"
	htmlfix = "sed -E" \
		" -e 's#([^\\\\]|^)&#\\1\\&amp;#g;'" \
		" -e 's#([^\\\\]|^)<#\\1\\&lt;#g;'" \
		" -e 's#([^\\\\]|^)>#\\1\\&gt;#g;'" \
		" -e 's#\\\\([&<>])#\\1#g;'"
	true = 1 ; false = 0
	print "shexpand()(eval \"$(echo \"cat<<'"xend"'\";cat;echo "xend")\")"
	print "shellfix()(" shellfix ")"
	print "htmlfix()(" htmlfix ")"
}

end[endn] && $0 == end[endn] {
	par = par "\n" end[endn--] "\n)"
	printpar()
	subdocp = false
	next
}

/\\$/ {
	getline nl
	sub(/\\$/,"")
	$0 = $0 " " nl
}

/^\.\.\./ {
	printpar()
	docp = !docp
	docend = $2 ? $2 : dend
	if (docp)
		print "shexpand<<" docend
	else
		print docend "\n"
	next
}

/^\.\./ && docp {
	subdocp = true
	end[++endn] = (match($0,"<<") ? substr($0,RSTART+RLENGTH) : "..")
	command = substr($0, 3, RSTART ? RSTART - 2 : length)
	$0 = "$$(" (command ? command : "cat") "<<" end[endn]
}

/^\./ && docp {
	specialp = 2
	gsub(/"/,"\\\\&")
	ln = "$$(" substr($1, 2)
	for (f=2;f<=NF;f++)
		ln = ln " \"" $f "\""
	ln = ln ")"
	$0 = ln
}

/^$/ {
	if (!par) next
	printpar()
}

{ par = par (par?"\n":"") $0 }
{ if (--specialp < 0) specialp = 0 }

END {
	if (par) printpar()
	if (docp) print docend
}

function printpar() {
	specialp = specialp || (match(par, /^[ 	]*</))
	if (docp) {
		if (!subdocp && !specialp)
			par = "<p>" par "</p>"
		print par | shellfix
		print ""
		close(shellfix)
	} else
		print par
	par = ""
}