~adnano/astronaut

astronaut/parse.go -rw-r--r-- 2.2 KiB
947cfac7Adnan Maolood Update default bindings 17 days 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
package main

import (
	"strings"
)

type LineType uint8

const (
	LineText LineType = iota
	LineLink
	LinePreformattingStart
	LinePreformattedText
	LinePreformattingEnd
	LineHeading1
	LineHeading2
	LineHeading3
	LineListItem
	LineQuote
)

// Line represents a line in a text document.
type Line struct {
	Type     LineType
	Text     string
	URL      string // only set for links
	Tabindex int    // only set for links
}

// Parser is a Gemini text parser.
type Parser struct {
	pre      bool
	tabindex int
}

// NewParser returns a new Gemini text parser.
func NewParser() *Parser {
	return &Parser{
		tabindex: 1,
	}
}

// ParseLine parses a single Gemini text line.
func (p *Parser) ParseLine(text string) Line {
	const spacetab = " \t"
	var line Line
	if strings.HasPrefix(text, "```") {
		p.pre = !p.pre
		text = text[3:]
		if p.pre {
			line.Type = LinePreformattingStart
		} else {
			line.Type = LinePreformattingEnd
		}
		line.Text = text
	} else if p.pre {
		line.Type = LinePreformattedText
		line.Text = text
	} else if strings.HasPrefix(text, "=>") {
		text = text[2:]
		text = strings.TrimLeft(text, spacetab)
		split := strings.IndexAny(text, spacetab)
		line.Type = LineLink
		if split == -1 {
			// text is a URL
			line.URL = text
		} else {
			url := text[:split]
			name := text[split:]
			name = strings.TrimLeft(name, spacetab)
			line.Text = name
			line.URL = url
		}
		// Set tabindex
		line.Tabindex = p.tabindex
		p.tabindex++
	} else if strings.HasPrefix(text, "*") {
		text = text[1:]
		text = strings.TrimLeft(text, spacetab)
		line.Type = LineListItem
		line.Text = text
	} else if strings.HasPrefix(text, "###") {
		text = text[3:]
		text = strings.TrimLeft(text, spacetab)
		line.Type = LineHeading3
		line.Text = text
	} else if strings.HasPrefix(text, "##") {
		text = text[2:]
		text = strings.TrimLeft(text, spacetab)
		line.Type = LineHeading2
		line.Text = text
	} else if strings.HasPrefix(text, "#") {
		text = text[1:]
		text = strings.TrimLeft(text, spacetab)
		line.Type = LineHeading1
		line.Text = text
	} else if strings.HasPrefix(text, ">") {
		text = text[1:]
		text = strings.TrimLeft(text, spacetab)
		line.Type = LineQuote
		line.Text = text
	} else {
		line.Type = LineText
		line.Text = text
	}
	return line
}