From cec3718bdd089bcf58575740c5ae4f86b27226d1 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Sat, 14 Jan 2023 19:59:12 -0700 Subject: markdown converter --- gemtext/mdconv/convert.go | 72 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 gemtext/mdconv/convert.go (limited to 'gemtext/mdconv/convert.go') diff --git a/gemtext/mdconv/convert.go b/gemtext/mdconv/convert.go new file mode 100644 index 0000000..0c92f9f --- /dev/null +++ b/gemtext/mdconv/convert.go @@ -0,0 +1,72 @@ +package mdconv + +import ( + "fmt" + "io" + "text/template" + + "tildegit.org/tjp/gus/gemtext" +) + +func Convert(wr io.Writer, doc gemtext.Document, overrides *template.Template) error { + tmpl, err := baseTmpl.Clone() + if err != nil { + return err + } + + if overrides != nil { + for _, override := range overrides.Templates() { + tmpl, err = tmpl.AddParseTree(override.Name(), override.Tree) + if err != nil { + return err + } + } + } + + return tmpl.ExecuteTemplate(wr, "mdconv", doc) +} + +var baseTmpl = template.Must(template.New("mdconv").Parse(fmt.Sprintf((` +{{block "header" .}}{{end -}} +{{range . -}} +{{if .Type | eq %d}}{{block "textline" . -}} + {{. -}} +{{end -}} +{{else if .Type | eq %d}}{{block "linkline" . -}} + => [{{if eq .Label ""}}{{.URL}}{{else}}{{.Label}}{{end}}]({{.URL}}) +{{end -}} +{{else if .Type | eq %d}}{{block "preformattoggleline" . -}} + ` + "```" + ` +{{end -}} +{{else if .Type | eq %d}}{{block "preformattedtextline" . -}} + {{. -}} +{{end -}} +{{else if .Type | eq %d}}{{block "heading1line" . -}} + # {{.Body}} +{{end -}} +{{else if .Type | eq %d}}{{block "heading2line" . -}} + ## {{.Body}} +{{end -}} +{{else if .Type | eq %d}}{{block "heading3line" . -}} + ### {{.Body}} +{{end -}} +{{else if .Type | eq %d}}{{block "listitemline" . -}} + * {{.Body}} +{{end -}} +{{else if .Type | eq %d}}{{block "quoteline" . -}} + > {{.Body}} +{{end -}} +{{end -}} +{{end -}} +{{block "footer" .}}{{end -}} +`)[1:], + gemtext.LineTypeText, + gemtext.LineTypeLink, + gemtext.LineTypePreformatToggle, + gemtext.LineTypePreformattedText, + gemtext.LineTypeHeading1, + gemtext.LineTypeHeading2, + gemtext.LineTypeHeading3, + gemtext.LineTypeListItem, + gemtext.LineTypeQuote, +))) -- cgit v1.2.3