Monorepo for Tangled
tangled.org
1package extension
2
3import (
4 "github.com/yuin/goldmark"
5 gast "github.com/yuin/goldmark/ast"
6 "github.com/yuin/goldmark/parser"
7 "github.com/yuin/goldmark/text"
8 "github.com/yuin/goldmark/util"
9)
10
11type dashParser struct{}
12
13func (p *dashParser) Trigger() []byte {
14 return []byte{'-'}
15}
16
17func (p *dashParser) Parse(parent gast.Node, block text.Reader, pc parser.Context) gast.Node {
18 line, _ := block.PeekLine()
19 if len(line) < 2 || line[0] != '-' || line[1] != '-' {
20 return nil
21 }
22 node := gast.NewString([]byte("\u2014"))
23 node.SetCode(true)
24 block.Advance(2)
25 return node
26}
27
28type digitDashParser struct{}
29
30func (p *digitDashParser) Trigger() []byte {
31 return []byte{'-'}
32}
33
34func (p *digitDashParser) Parse(parent gast.Node, block text.Reader, pc parser.Context) gast.Node {
35 line, _ := block.PeekLine()
36 if len(line) < 2 {
37 return nil
38 }
39 before := block.PrecendingCharacter()
40 if before < '0' || before > '9' {
41 return nil
42 }
43 if line[1] < '0' || line[1] > '9' {
44 return nil
45 }
46 node := gast.NewString([]byte("\u2013"))
47 node.SetCode(true)
48 block.Advance(1)
49 return node
50}
51
52type dashExt struct{}
53
54// Dashes replaces "--" with an em-dash (—) and a hyphen between two digits
55// with an en-dash (–). Implemented as an inline parser so it operates on the
56// raw byte stream, unaffected by hard-wrapped source lines.
57var Dashes goldmark.Extender = &dashExt{}
58
59func (e *dashExt) Extend(m goldmark.Markdown) {
60 m.Parser().AddOptions(parser.WithInlineParsers(
61 util.Prioritized(&dashParser{}, 9990),
62 util.Prioritized(&digitDashParser{}, 9991),
63 ))
64}