~samwhited/blogsync

ref: v0.0.1 blogsync/markdown.go -rw-r--r-- 9.4 KiB
c7d923e2Sam Whited blogsync: fix name of convert command flagset 1 year, 10 months ago
                                                                                
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright 2019 The Blog Sync Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/russross/blackfriday/v2"
)

// unwrapRenderer is a blackfriday.Renderer that generates a markdown document
// that is semantically the same as the input document except with hard wrapping
// removed from text nodes.
// We have to do this because of the jank way in which Write.as bungles even the
// core markdown standard instead of just handling newlines differently in the
// web WYSIWYG editor.
type unwrapRenderer struct {
	listLevel    int
	quoteLevel   int
	listType     blackfriday.ListType
	htmlRenderer *blackfriday.HTMLRenderer

	debug *log.Logger
}

func (*unwrapRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {}
func (*unwrapRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {}
func (rend *unwrapRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	switch node.Type {
	case blackfriday.Document:
		return blackfriday.GoToNext
	case blackfriday.List:
		return rend.renderList(w, node, entering)
	case blackfriday.Item:
		return rend.renderItem(w, node, entering)
	case blackfriday.Paragraph:
		return rend.renderPar(w, node, entering)
	case blackfriday.Heading:
		return rend.renderHeading(w, node, entering)
	case blackfriday.HorizontalRule:
		return rend.renderHR(w, node, entering)
	case blackfriday.Emph:
		return rend.renderSpan("*", w, node, entering)
	case blackfriday.Strong:
		return rend.renderSpan("**", w, node, entering)
	case blackfriday.Del:
		return rend.renderSpan("~~", w, node, entering)
	case blackfriday.Link:
		return rend.renderLink(w, node, entering)
	case blackfriday.Image:
		return rend.renderImage(w, node, entering)
	case blackfriday.BlockQuote:
		return rend.renderBlockQuote(w, node, entering)
	case blackfriday.Text:
		return rend.renderText(w, node, entering)
	case blackfriday.HTMLBlock:
		return rend.renderHTMLBlock(w, node, entering)
	case blackfriday.CodeBlock:
		return rend.renderCodeBlock(w, node, entering)
	case blackfriday.Code:
		return rend.renderCode(w, node, entering)
	case blackfriday.Hardbreak:
		return rend.renderHardBreak(w, node, entering)
	case blackfriday.HTMLSpan:
		return rend.renderHTMLSpan(w, node, entering)
	}

	// Softbreaks are not supported by blackfriday and this message should never
	// be hit for them, see: https://github.com/russross/blackfriday/issues/315
	// TODO: support tables
	rend.debug.Printf("unsupported markdown node %s found", node.Type)
	return blackfriday.GoToNext
}

func (rend *unwrapRenderer) renderLink(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	// Write.as doesn't support the footnote extension to markdown, so if this is
	// a footnote render it as HTML instead.
	if node.LinkData.NoteID != 0 {
		return rend.htmlRenderer.RenderNode(w, node, entering)
	}

	if entering {
		fmt.Fprintf(w, "[")
		return blackfriday.GoToNext
	}

	fmt.Fprintf(w, "](%s %q)", node.LinkData.Destination, node.LinkData.Title)
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderImage(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if entering {
		fmt.Fprintf(w, "![")
		return blackfriday.GoToNext
	}

	fmt.Fprintf(w, "](%s %q)", node.LinkData.Destination, node.LinkData.Title)
	return blackfriday.GoToNext
}

func (rend *unwrapRenderer) renderList(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {

	// Footnotes aren't supported by write.as, so render the remaining nodes on
	// this branch with the HTML renderer.
	if node.IsFootnotesList ||
		rend.listType&blackfriday.ListTypeTerm == blackfriday.ListTypeTerm ||
		rend.listType&blackfriday.ListTypeDefinition == blackfriday.ListTypeDefinition {
		node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
			return rend.htmlRenderer.RenderNode(w, node, entering)
		})
		return blackfriday.SkipChildren
	}

	rend.listType = node.ListData.ListFlags
	if entering {
		rend.listLevel++
		if rend.listLevel == 1 {
			io.WriteString(w, "\n")
		}
		return blackfriday.GoToNext
	}

	rend.listLevel--
	if rend.listLevel == 0 {
		io.WriteString(w, "\n")
	}
	return blackfriday.GoToNext
}

func (rend *unwrapRenderer) renderItem(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if node.IsFootnotesList ||
		rend.listType&blackfriday.ListTypeTerm == blackfriday.ListTypeTerm ||
		rend.listType&blackfriday.ListTypeDefinition == blackfriday.ListTypeDefinition {
		//node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
		//	return rend.htmlRenderer.RenderNode(w, node, entering)
		//})
		return blackfriday.SkipChildren
	}

	if !entering {
		return blackfriday.GoToNext
	}
	for i := 0; i < rend.listLevel; i++ {
		fmt.Fprintf(w, "  ")
	}
	switch {
	case rend.listType&blackfriday.ListTypeOrdered == blackfriday.ListTypeOrdered:
		fmt.Fprintf(w, "1. ")
	default:
		fmt.Fprintf(w, "* ")
	}
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderHeading(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		io.WriteString(w, "\n")
		return blackfriday.GoToNext
	}

	// Convert all headings to # style.
	// The specific style doesn't matter as far as write.as is concerned and
	// since blackfriday doesn't give us the raw header literal we just make up
	// that they're all # style to avoid having to do more work.
	for i := 0; i < node.HeadingData.Level; i++ {
		io.WriteString(w, "#")
	}
	io.WriteString(w, " ")
	return blackfriday.GoToNext
}

func (rend *unwrapRenderer) renderBlockQuote(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	io.WriteString(w, "\n")
	if !entering {
		rend.quoteLevel--
		io.WriteString(w, "\n")
		return blackfriday.GoToNext
	}

	// For the actual rendering of the ">" marker, see renderPar, this just tracks
	// the state of block quotes starting and ending. If nothing is put inside of
	// them, they don't render at all.
	rend.quoteLevel++
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderText(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		return blackfriday.GoToNext
	}

	_, err := w.Write(bytes.ReplaceAll(node.Literal, []byte{'\n'}, []byte{' '}))
	if err != nil {
		panic(fmt.Errorf("error writing markdown to buffer: %w", err))
	}
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderHardBreak(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		return blackfriday.GoToNext
	}

	// Convert double spaces at the end of lines into an actual line break which
	// is what write.as expects.
	io.WriteString(w, "\n")
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderHTMLBlock(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		return blackfriday.GoToNext
	}

	if len(node.Literal) > 0 {
		_, err := w.Write(node.Literal)
		if err != nil {
			panic(fmt.Errorf("error writing markdown to buffer: %w", err))
		}
	}
	// If a paragraph or other markdown element comes after HTML we need two line
	// breaks to make sure it's part of a new block and gets wrapped in a <p> or
	// similar. This is unlike most markdown elements which are in a paragraph and
	// thus the renderPar method will add a line break afterwards and where only a
	// single line break will suffice.
	io.WriteString(w, "\n\n")

	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderHTMLSpan(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		return blackfriday.GoToNext
	}

	if len(node.Literal) > 0 {
		_, err := w.Write(node.Literal)
		if err != nil {
			panic(fmt.Errorf("error writing markdown to buffer: %w", err))
		}
	}

	return blackfriday.GoToNext
}

func (rend *unwrapRenderer) renderPar(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		io.WriteString(w, "\n")
	}

	// If we're in a block quote, render the starting mark.
	for i := 0; i < rend.quoteLevel; i++ {
		io.WriteString(w, ">")
	}
	if rend.quoteLevel > 0 {
		io.WriteString(w, " ")
	}

	// TODO: this is jank, but I couldn't figure out how to put two lines between
	// paragraphs to make write.as happy without also adding a line after eg. the
	// paragraph in a list or heading, etc.
	// Is there any other type that should also have a newline after it?
	// Is there a more general way to do this that works regardless of what type
	// comes before the paragraph?
	if node.Prev != nil && node.Prev.Type == blackfriday.Paragraph {
		io.WriteString(w, "\n")
	}
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderSpan(wrap string, w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	io.WriteString(w, wrap)
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderHR(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	if !entering {
		return blackfriday.GoToNext
	}

	io.WriteString(w, "---\n")
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderCode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	fmt.Fprintf(w, "`%s`", node.Literal)
	return blackfriday.GoToNext
}

func (*unwrapRenderer) renderCodeBlock(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	fmt.Fprintf(w, "```%s\n%s```\n", node.CodeBlockData.Info, node.Literal)
	return blackfriday.GoToNext
}