grapho/md2tex

150 lines
2.7 KiB
Plaintext
Raw Normal View History

2021-11-28 18:26:47 +01:00
#!/usr/bin/awk -f
BEGIN {
headed = 0
stack_pos = 0
tag("documentclass[a4paper]{article}")
# tag("special{papersize=210mm,297mm}")
tag("usepackage[margin=1in]{geometry}")
2022-07-02 22:55:45 +02:00
tag("usepackage[utf8]{inputenc}")
tag("setlength{\\parskip}{\\baselineskip}%")
tag("setlength{\\parindent}{0pt}%")
2021-11-28 18:26:47 +01:00
tag("usepackage{listings}")
tag("lstset{basicstyle=\\ttfamily\\footnotesize,breaklines=true}")
tag("usepackage{hyperref}")
tag("usepackage{graphicx}")
tag("sloppy")
tag("parindent0mm")
}
function tag(val) {
printf("\\%s\n", val)
}
function push(what, arg) {
stack[stack_pos++] = what;
tag("begin{" what "}" arg)
}
function peek() {
return stack[stack_pos-1]
}
function pop() {
tag("end{" stack[--stack_pos] "}")
}
function inline(text) {
gsub(/\\/, "\\textbackslash ", text)
gsub(/\{/, "\\{", text)
gsub(/\}/, "\\}", text)
gsub(/~/, "\\textasciitilde ", text)
gsub(/\$/, "\\$", text)
gsub(/_/, "\\_", text)
gsub(/#/, "\\#", text)
gsub(/%/, "\\%", text)
gsub(/&/, "\\\\&", text)
2021-11-28 18:26:47 +01:00
gsub(/\^/, "\\textasciicircum ", text)
gsub(/\.{3,}/, "\\ldots", text)
text = gensub(/\*\*([^\*]*)\*\*/, "\\textbf{\\1}", "g", text)
text = gensub(/\*([^\*]*)\*/, "\\emph{\\1}", "g", text)
text = gensub(/`([^`]*)`/, "\\texttt{\\1}", "g", text)
# links
text = gensub(/\[(.*)\]\((.*)\)/, "\\href{\\2}{\\1}\\footnote{\\url{\\2}}", "g", text)
return text
}
/^---$/ {
parse_meta = !parse_meta
next
}
{
if(parse_meta) {
split($0, r, ": ")
gsub(/(^"|"$)/, "", r[2])
meta[r[1]]=r[2]
next
}
}
/^# / {
gsub(/^#* /, "", $0)
if (!meta["title"]) meta["title"] = $0
next
}
{
if (!headed) {
if (meta["title"]) tag("title{" meta["title"] "}")
if (meta["author"]) tag("author{" meta["author"] "}")
push("document")
tag("maketitle")
headed = 1
}
}
2022-07-02 22:55:45 +02:00
/^##* / {
d=length($1)
t="section"
for (i=3; i<=d; i++) t="sub"t
2021-11-28 18:26:47 +01:00
gsub(/^#* /, "", $0)
tag(t"{" inline($0) "}")
2021-11-28 18:26:47 +01:00
next
}
/^### / {
gsub(/^#* /, "", $0)
tag("subsection{" inline($0) "}")
2021-11-28 18:26:47 +01:00
next
}
/^```$/ {
if (peek() == "lstlisting") {
pop()
} else {
push("lstlisting")
}
next
}
{
if (peek() == "lstlisting") {
print($0)
next
}
}
/^$/ {
while(peek() && peek() != "document") pop()
}
/^!\[.*\]\(.*\)$/ {
txt = $0
filenam = $0
gsub(/(^!\[|\].*$)/, "", txt)
gsub(/(^!.*\(|\)$)/, "", filenam)
gsub(/\.(jpg|png|gif|jpeg)$/, "", filenam)
2022-04-07 18:34:57 +02:00
push("figure", "[htp]")
2021-11-28 18:26:47 +01:00
tag("includegraphics[width=\\textwidth]{" filenam "}")
tag("caption{" inline(txt) "}")
next
}
/^- / {
gsub(/^- /, "", $0)
if (peek() != "itemize") push("itemize")
tag("item")
print(inline($0))
next
}
{
print(inline($0))
}
END {
while (peek()) {
pop()
}
}