summaryrefslogtreecommitdiff
path: root/gmi2html.sh
blob: d40226866d36a358b6ba6f21b4102585072d2555 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env bash

function err {
    echo "$@" >&2
}

if [ $# -ne 1 ]; then
    err "./gmi2html.sh /path/to/gmi"
    exit 1;
fi

# main method
GMI=$1
list=0
pre=0
quote=0

while read line; do

    # if in pre-mode and not closing - print and skip
    if [ $pre -eq 1 ]; then
	if [ ! -n "$(sed -nE '/^[`]{3}/p' <<< $line)" ]; then
	    echo "$line"
	    continue;
	fi
    fi


    # quotes
    if [ -n "$(sed -nE '/^[>] .+/p' <<< $line)" ]; then
	if [ $quote -eq 0 ]; then
	    echo "<figure><blockquote>"
	fi
       	quote=1;
	text=$(sed -E 's/^[>] (.+)$/\1/g' <<< $line)
	echo "<p>$text</p>"
	continue
    else
	if [ $quote -eq 1 ]; then
	    if [ -z "$(sed -E '/^[#`*]/d' <<< $line)" ]; then
		echo "</blockquote></figure>"
		quote=0
	    fi
	fi
    fi

    if [ -n "$(sed -nE '/^[`]{3}/p' <<< $line)" ]; then
	if [ $pre -eq 0 ]; then
	    echo "<pre>"
	    pre=1
	else
	    echo "</pre>"
	    pre=0
	fi
	continue;
    fi
    
    # lists
    if [ -n "$(sed -nE '/^[*] .+/p' <<< "$line")" ]; then
	if [ $list -eq 0 ]; then
	    echo "<ul>"
	fi
       	list=1;
	text=$(sed -E 's/^[*] (.+)$/\1/g' <<< "$line")
	echo "<li>${text}</li>"
	continue
    else
	if [ $list -eq 1 ]; then
	    echo "</ul>"
	fi
	list=0;
    fi
    
    # single line modifiers
    if [ -n "$(sed -nE '/^# .+/p' <<< $line)" ]; then
	text=$(sed -E 's/^# (.+)$/\1/g' <<< $line)
	echo "<h1>$text</h1>"
	continue
    fi
    if [ -n "$(sed -nE '/^## .+/p' <<< $line)" ]; then
	text=$(sed -E 's/^## (.+)$/\1/g' <<< $line)
	echo "<h2>$text</h2>"
	continue
    fi
    if [ -n "$(sed -nE '/^### .+/p' <<< $line)" ]; then
	text=$(sed -E 's/^### (.+)$/\1/g' <<< $line)
	echo "<h3>$text</h3>"
	continue
    fi
    if [ -n "$(sed -nE '/^=> .+/p' <<< "$line")" ]; then
	href=$(sed -E 's/^=> ([^ ]+)([ ]?.*)/\1/g' <<< "$line")
	if [ -n "$(sed -nE '/^=> [^ ]+ .+$/p' <<< "$line")" ]; then
	    text=$(sed -E 's/^=> [^ ]+ (.+)$/\1/g' <<< "$line")
	else
	    text=$href
	fi

	if [ $quote -eq 1 ]; then
	    echo "<cite>— <a href='${href}' rel='noopener' target='_blank'>$text</a></cite>"
	else
	    echo "<p><a href='${href}' rel='noopener' target='_blank'>$text</a></p>"
	fi
	continue
    fi
    
    # skip blank lines
    if [ -z "$line" ]; then
	continue
    fi

    # default paragraphs
    if [ $quote -eq 1 ]; then
	echo "<cite>— $line</cite>"
    else
	echo "<p>$line</p>"
    fi
    
done < $GMI