Debian Codegraph @

vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go

raw
1 package md2man
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8 "os"
9 "strings"
10
11 "github.com/russross/blackfriday/v2"
12 )
13
14 // roffRenderer implements the blackfriday.Renderer interface for creating
15 // roff format (manpages) from markdown text
16 type roffRenderer struct {
17 listCounters []int
18 firstHeader bool
19 listDepth int
20 }
21
22 const (
23 titleHeader = ".TH "
24 topLevelHeader = "\n\n.SH "
25 secondLevelHdr = "\n.SH "
26 otherHeader = "\n.SS "
27 crTag = "\n"
28 emphTag = "\\fI"
29 emphCloseTag = "\\fP"
30 strongTag = "\\fB"
31 strongCloseTag = "\\fP"
32 breakTag = "\n.br\n"
33 paraTag = "\n.PP\n"
34 hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n"
35 linkTag = "\n\\[la]"
36 linkCloseTag = "\\[ra]"
37 codespanTag = "\\fB"
38 codespanCloseTag = "\\fR"
39 codeTag = "\n.EX\n"
40 codeCloseTag = ".EE\n" // Do not prepend a newline character since code blocks, by definition, include a newline already (or at least as how blackfriday gives us on).
41 quoteTag = "\n.PP\n.RS\n"
42 quoteCloseTag = "\n.RE\n"
43 listTag = "\n.RS\n"
44 listCloseTag = ".RE\n"
45 dtTag = "\n.TP\n"
46 dd2Tag = "\n"
47 tableStart = "\n.TS\nallbox;\n"
48 tableEnd = ".TE\n"
49 tableCellStart = "T{\n"
50 tableCellEnd = "\nT}"
51 tablePreprocessor = `'\" t`
52 )
53
54 // NewRoffRenderer creates a new blackfriday Renderer for generating roff documents
55 // from markdown
56 func NewRoffRenderer() *roffRenderer {
57 return &roffRenderer{}
58 }
59
60 // GetExtensions returns the list of extensions used by this renderer implementation
61 func (*roffRenderer) GetExtensions() blackfriday.Extensions {
62 return blackfriday.NoIntraEmphasis |
63 blackfriday.Tables |
64 blackfriday.FencedCode |
65 blackfriday.SpaceHeadings |
66 blackfriday.Footnotes |
67 blackfriday.Titleblock |
68 blackfriday.DefinitionLists
69 }
70
71 // RenderHeader handles outputting the header at document start
72 func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {
73 // We need to walk the tree to check if there are any tables.
74 // If there are, we need to enable the roff table preprocessor.
75 ast.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
76 if node.Type == blackfriday.Table {
77 out(w, tablePreprocessor+"\n")
78 return blackfriday.Terminate
79 }
80 return blackfriday.GoToNext
81 })
82
83 // disable hyphenation
84 out(w, ".nh\n")
85 }
86
87 // RenderFooter handles outputting the footer at the document end; the roff
88 // renderer has no footer information
89 func (r *roffRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {
90 }
91
92 // RenderNode is called for each node in a markdown document; based on the node
93 // type the equivalent roff output is sent to the writer
94 func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
95 walkAction := blackfriday.GoToNext
96
97 switch node.Type {
98 case blackfriday.Text:
99 // Special case: format the NAME section as required for proper whatis parsing.
100 // Refer to the lexgrog(1) and groff_man(7) manual pages for details.
101 if node.Parent != nil &&
102 node.Parent.Type == blackfriday.Paragraph &&
103 node.Parent.Prev != nil &&
104 node.Parent.Prev.Type == blackfriday.Heading &&
105 node.Parent.Prev.FirstChild != nil &&
106 bytes.EqualFold(node.Parent.Prev.FirstChild.Literal, []byte("NAME")) {
107 before, after, found := bytesCut(node.Literal, []byte(" - "))
108 escapeSpecialChars(w, before)
109 if found {
110 out(w, ` \- `)
111 escapeSpecialChars(w, after)
112 }
113 } else {
114 escapeSpecialChars(w, node.Literal)
115 }
116 case blackfriday.Softbreak:
117 out(w, crTag)
118 case blackfriday.Hardbreak:
119 out(w, breakTag)
120 case blackfriday.Emph:
121 if entering {
122 out(w, emphTag)
123 } else {
124 out(w, emphCloseTag)
125 }
126 case blackfriday.Strong:
127 if entering {
128 out(w, strongTag)
129 } else {
130 out(w, strongCloseTag)
131 }
132 case blackfriday.Link:
133 // Don't render the link text for automatic links, because this
134 // will only duplicate the URL in the roff output.
135 // See https://daringfireball.net/projects/markdown/syntax#autolink
136 if !bytes.Equal(node.LinkData.Destination, node.FirstChild.Literal) {
137 out(w, string(node.FirstChild.Literal))
138 }
139 // Hyphens in a link must be escaped to avoid word-wrap in the rendered man page.
140 escapedLink := strings.ReplaceAll(string(node.LinkData.Destination), "-", "\\-")
141 out(w, linkTag+escapedLink+linkCloseTag)
142 walkAction = blackfriday.SkipChildren
143 case blackfriday.Image:
144 // ignore images
145 walkAction = blackfriday.SkipChildren
146 case blackfriday.Code:
147 out(w, codespanTag)
148 escapeSpecialChars(w, node.Literal)
149 out(w, codespanCloseTag)
150 case blackfriday.Document:
151 break
152 case blackfriday.Paragraph:
153 if entering {
154 if r.listDepth > 0 {
155 // roff .PP markers break lists
156 if node.Prev != nil { // continued paragraph
157 if node.Prev.Type == blackfriday.List && node.Prev.ListFlags&blackfriday.ListTypeDefinition == 0 {
158 out(w, ".IP\n")
159 } else {
160 out(w, crTag)
161 }
162 }
163 } else if node.Prev != nil && node.Prev.Type == blackfriday.Heading {
164 out(w, crTag)
165 } else {
166 out(w, paraTag)
167 }
168 } else {
169 if node.Next == nil || node.Next.Type != blackfriday.List {
170 out(w, crTag)
171 }
172 }
173 case blackfriday.BlockQuote:
174 if entering {
175 out(w, quoteTag)
176 } else {
177 out(w, quoteCloseTag)
178 }
179 case blackfriday.Heading:
180 r.handleHeading(w, node, entering)
181 case blackfriday.HorizontalRule:
182 out(w, hruleTag)
183 case blackfriday.List:
184 r.handleList(w, node, entering)
185 case blackfriday.Item:
186 r.handleItem(w, node, entering)
187 case blackfriday.CodeBlock:
188 out(w, codeTag)
189 escapeSpecialChars(w, node.Literal)
190 out(w, codeCloseTag)
191 case blackfriday.Table:
192 r.handleTable(w, node, entering)
193 case blackfriday.TableHead:
194 case blackfriday.TableBody:
195 case blackfriday.TableRow:
196 // no action as cell entries do all the nroff formatting
197 return blackfriday.GoToNext
198 case blackfriday.TableCell:
199 r.handleTableCell(w, node, entering)
200 case blackfriday.HTMLSpan:
201 // ignore other HTML tags
202 case blackfriday.HTMLBlock:
203 if bytes.HasPrefix(node.Literal, []byte("<!--")) {
204 break // ignore comments, no warning
205 }
206 fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String())
207 default:
208 fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String())
209 }
210 return walkAction
211 }
212
213 func (r *roffRenderer) handleHeading(w io.Writer, node *blackfriday.Node, entering bool) {
214 if entering {
215 switch node.Level {
216 case 1:
217 if !r.firstHeader {
218 out(w, titleHeader)
219 r.firstHeader = true
220 break
221 }
222 out(w, topLevelHeader)
223 case 2:
224 out(w, secondLevelHdr)
225 default:
226 out(w, otherHeader)
227 }
228 }
229 }
230
231 func (r *roffRenderer) handleList(w io.Writer, node *blackfriday.Node, entering bool) {
232 openTag := listTag
233 closeTag := listCloseTag
234 if (entering && r.listDepth == 0) || (!entering && r.listDepth == 1) {
235 openTag = crTag
236 closeTag = ""
237 }
238 if node.ListFlags&blackfriday.ListTypeDefinition != 0 {
239 // tags for definition lists handled within Item node
240 openTag = ""
241 closeTag = ""
242 }
243 if entering {
244 r.listDepth++
245 if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
246 r.listCounters = append(r.listCounters, 1)
247 }
248 out(w, openTag)
249 } else {
250 if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
251 r.listCounters = r.listCounters[:len(r.listCounters)-1]
252 }
253 out(w, closeTag)
254 r.listDepth--
255 }
256 }
257
258 func (r *roffRenderer) handleItem(w io.Writer, node *blackfriday.Node, entering bool) {
259 if entering {
260 if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
261 out(w, fmt.Sprintf(".IP \"%3d.\" 5\n", r.listCounters[len(r.listCounters)-1]))
262 r.listCounters[len(r.listCounters)-1]++
263 } else if node.ListFlags&blackfriday.ListTypeTerm != 0 {
264 // DT (definition term): line just before DD (see below).
265 out(w, dtTag)
266 } else if node.ListFlags&blackfriday.ListTypeDefinition != 0 {
267 // DD (definition description): line that starts with ": ".
268 //
269 // We have to distinguish between the first DD and the
270 // subsequent ones, as there should be no vertical
271 // whitespace between the DT and the first DD.
272 if node.Prev != nil && node.Prev.ListFlags&(blackfriday.ListTypeTerm|blackfriday.ListTypeDefinition) == blackfriday.ListTypeDefinition {
273 if node.Prev.Type == blackfriday.Item &&
274 node.Prev.LastChild != nil &&
275 node.Prev.LastChild.Type == blackfriday.List &&
276 node.Prev.LastChild.ListFlags&blackfriday.ListTypeDefinition == 0 {
277 out(w, ".IP\n")
278 } else {
279 out(w, dd2Tag)
280 }
281 }
282 } else {
283 out(w, ".IP \\(bu 2\n")
284 }
285 }
286 }
287
288 func (r *roffRenderer) handleTable(w io.Writer, node *blackfriday.Node, entering bool) {
289 if entering {
290 out(w, tableStart)
291 // call walker to count cells (and rows?) so format section can be produced
292 columns := countColumns(node)
293 out(w, strings.Repeat("l ", columns)+"\n")
294 out(w, strings.Repeat("l ", columns)+".\n")
295 } else {
296 out(w, tableEnd)
297 }
298 }
299
300 func (r *roffRenderer) handleTableCell(w io.Writer, node *blackfriday.Node, entering bool) {
301 if entering {
302 var start string
303 if node.Prev != nil && node.Prev.Type == blackfriday.TableCell {
304 start = "\t"
305 }
306 if node.IsHeader {
307 start += strongTag
308 } else if nodeLiteralSize(node) > 30 {
309 start += tableCellStart
310 }
311 out(w, start)
312 } else {
313 var end string
314 if node.IsHeader {
315 end = strongCloseTag
316 } else if nodeLiteralSize(node) > 30 {
317 end = tableCellEnd
318 }
319 if node.Next == nil {
320 // Last cell: need to carriage return if we are at the end of the header row.
321 end += crTag
322 }
323 out(w, end)
324 }
325 }
326
327 func nodeLiteralSize(node *blackfriday.Node) int {
328 total := 0
329 for n := node.FirstChild; n != nil; n = n.FirstChild {
330 total += len(n.Literal)
331 }
332 return total
333 }
334
335 // because roff format requires knowing the column count before outputting any table
336 // data we need to walk a table tree and count the columns
337 func countColumns(node *blackfriday.Node) int {
338 var columns int
339
340 node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
341 switch node.Type {
342 case blackfriday.TableRow:
343 if !entering {
344 return blackfriday.Terminate
345 }
346 case blackfriday.TableCell:
347 if entering {
348 columns++
349 }
350 default:
351 }
352 return blackfriday.GoToNext
353 })
354 return columns
355 }
356
357 func out(w io.Writer, output string) {
358 io.WriteString(w, output) //nolint:errcheck
359 }
360
361 func escapeSpecialChars(w io.Writer, text []byte) {
362 scanner := bufio.NewScanner(bytes.NewReader(text))
363
364 // count the number of lines in the text
365 // we need to know this to avoid adding a newline after the last line
366 n := bytes.Count(text, []byte{'\n'})
367 idx := 0
368
369 for scanner.Scan() {
370 dt := scanner.Bytes()
371 if idx < n {
372 idx++
373 dt = append(dt, '\n')
374 }
375 escapeSpecialCharsLine(w, dt)
376 }
377
378 if err := scanner.Err(); err != nil {
379 panic(err)
380 }
381 }
382
383 func escapeSpecialCharsLine(w io.Writer, text []byte) {
384 for i := 0; i < len(text); i++ {
385 // escape initial apostrophe or period
386 if len(text) >= 1 && (text[0] == '\'' || text[0] == '.') {
387 out(w, "\\&")
388 }
389
390 // directly copy normal characters
391 org := i
392
393 for i < len(text) && text[i] != '\\' {
394 i++
395 }
396 if i > org {
397 w.Write(text[org:i]) //nolint:errcheck
398 }
399
400 // escape a character
401 if i >= len(text) {
402 break
403 }
404
405 w.Write([]byte{'\\', text[i]}) //nolint:errcheck
406 }
407 }
408
409 // bytesCut is a copy of [bytes.Cut] to provide compatibility with go1.17
410 // and older. We can remove this once we drop support for go1.17 and older.
411 func bytesCut(s, sep []byte) (before, after []byte, found bool) {
412 if i := bytes.Index(s, sep); i >= 0 {
413 return s[:i], s[i+len(sep):], true
414 }
415 return s, nil, false
416 }