aboutsummaryrefslogtreecommitdiff
path: root/markdown/ast_code.go
blob: 6b949f2924c85e477cc1190b8fe84d8c5ffc503d (plain)
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
package markdown

import (
	"errors"
	"html"
	"html/template"

	"git.anhgelus.world/anhgelus/small-web/dom"
)

var (
	ErrUnknownCodeType          = errors.New("unkown code type")
	ErrInvalidCodeFormat        = errors.New("invalid code format")
	ErrInvalidCodeBlockPosition = errors.Join(ErrInvalidParagraph, errors.New("invalid code block position"))
)

type codeType uint

const (
	codeOneLine   codeType = 1
	codeMultiLine codeType = 2
)

type astCode struct {
	content  string
	before   string
	codeType codeType
}

func (a *astCode) Eval(_ *Option) (template.HTML, *ParseError) {
	content := template.HTML(html.EscapeString(a.content))
	switch a.codeType {
	case codeOneLine:
		return dom.NewLiteralContentElement("code", content).Render(), nil
	case codeMultiLine:
		code := dom.NewContentElement("code", []dom.Element{dom.NewLiteralElement(content)})
		return dom.NewContentElement("pre", []dom.Element{code}).Render(), nil
	default:
		return "", &ParseError{lxs: lexers{}, internal: ErrUnknownCodeType}
	}
}

func code(lxs *lexers) (*astCode, *ParseError) {
	tree := new(astCode)
	current := lxs.Current().Value
	if len(current) == 3 {
		tree.codeType = codeMultiLine
	} else if len(current) == 1 {
		tree.codeType = codeOneLine
	} else {
		return nil, &ParseError{lxs: *lxs, internal: ErrInvalidCodeFormat}
	}
	started := false
	for lxs.Next() && lxs.Current().Value != current {
		if lxs.Current().Type == lexerBreak {
			if tree.codeType == codeOneLine {
				return nil, &ParseError{lxs: *lxs, internal: ErrInvalidCodeFormat}
			}
			if !started {
				started = true
			}
		}
		if started || tree.codeType == codeOneLine {
			tree.content += lxs.Current().Value
		} else {
			tree.before += lxs.Current().Value
		}
	}
	return tree, nil
}