โ– humdrum codex / glint v1.0.2
license AGPL-3.0
6.6 KB raw
  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
package editor

import (
	"regexp"
	"strings"

	"glint/internal/theme"

	"github.com/charmbracelet/lipgloss"
)

var (
	headingRe = regexp.MustCompile(`^\s*#{1,6}\s`)
	listRe    = regexp.MustCompile(`^\s*([-*+]|\d+\.)\s`)
)

// blockState carries cross-line context (fenced code, leading frontmatter).
type blockState struct {
	inFence         bool
	inFrontmatter   bool
	frontmatterDone bool
}

// ScanLines styles every line, threading block state across lines. The returned
// slice is parallel to the input: out[i] are the spans for lines[i], whose
// concatenated text equals lines[i] exactly.
func ScanLines(lines []string, th theme.Theme) [][]Span {
	st := &blockState{}
	out := make([][]Span, len(lines))
	for i, ln := range lines {
		out[i] = scanLine(i, ln, st, th)
	}
	return out
}

func scanLine(row int, line string, st *blockState, th theme.Theme) []Span {
	code := lipgloss.NewStyle().Foreground(th.Code)
	muted := lipgloss.NewStyle().Foreground(th.Blockquote)
	trimmed := strings.TrimSpace(line)

	// Fenced code block: body lines are entirely code-colored.
	if st.inFence {
		if strings.HasPrefix(trimmed, "```") {
			st.inFence = false
		}
		return wholeLine(line, code)
	}
	if strings.HasPrefix(trimmed, "```") {
		st.inFence = true
		return wholeLine(line, code)
	}

	// Leading YAML frontmatter: only valid starting at row 0.
	if st.inFrontmatter {
		if trimmed == "---" {
			st.inFrontmatter = false
			st.frontmatterDone = true
			return wholeLine(line, muted)
		}
		return scanFrontmatter(line, th)
	}
	if row == 0 && trimmed == "---" {
		st.inFrontmatter = true
		return wholeLine(line, muted)
	}

	// Heading: color the whole line, hashes included.
	if headingRe.MatchString(line) {
		return wholeLine(line, lipgloss.NewStyle().Foreground(th.Heading).Bold(true))
	}

	// Blockquote.
	if strings.HasPrefix(trimmed, ">") {
		return wholeLine(line, muted)
	}

	// List marker, then inline-scan the remainder.
	if loc := listRe.FindStringIndex(line); loc != nil {
		marker := line[:loc[1]]
		rest := line[loc[1]:]
		spans := []Span{{Text: marker, Style: lipgloss.NewStyle().Foreground(th.ListMarker)}}
		return append(spans, scanInline(rest, th)...)
	}

	return scanInline(line, th)
}

// wholeLine returns a single span for the whole line, or no spans if empty.
func wholeLine(line string, style lipgloss.Style) []Span {
	if line == "" {
		return nil
	}
	return []Span{{Text: line, Style: style}}
}

// scanFrontmatter highlights one YAML frontmatter line, keeping every character
// visible: the spans concatenate back to the raw line exactly.
//   - "# comment"         -> whole line muted
//   - "  - item"          -> leading ws + dash (ListMarker) + item (Text)
//   - "key: value"        -> "key:" (Accent) + " value" (Text)
//   - anything else       -> whole line Text
func scanFrontmatter(line string, th theme.Theme) []Span {
	muted := lipgloss.NewStyle().Foreground(th.Blockquote)
	accent := lipgloss.NewStyle().Foreground(th.Accent)
	plain := lipgloss.NewStyle().Foreground(th.Text)
	marker := lipgloss.NewStyle().Foreground(th.ListMarker)

	trimmed := strings.TrimSpace(line)

	// Comment line.
	if strings.HasPrefix(trimmed, "#") {
		return wholeLine(line, muted)
	}

	// List item: optional leading whitespace, then "- ...".
	if loc := listRe.FindStringIndex(line); loc != nil && strings.HasPrefix(trimmed, "-") {
		mk := line[:loc[1]]   // leading ws + "- "
		rest := line[loc[1]:] // item text
		spans := []Span{{Text: mk, Style: marker}}
		if rest != "" {
			spans = append(spans, Span{Text: rest, Style: plain})
		}
		return spans
	}

	// key: value โ€” split at the first colon. Keep the colon with the key.
	if idx := strings.IndexByte(line, ':'); idx >= 0 {
		key := line[:idx+1]  // includes the colon
		rest := line[idx+1:] // remainder (may start with a space)
		spans := []Span{{Text: key, Style: accent}}
		if rest != "" {
			spans = append(spans, Span{Text: rest, Style: plain})
		}
		return spans
	}

	// Bare line (e.g. a continuation): plain text.
	return wholeLine(line, plain)
}

// scanInline emits styled spans for inline constructs, keeping all markup
// characters visible. Plain text gets the theme's Text foreground.
func scanInline(text string, th theme.Theme) []Span {
	plain := lipgloss.NewStyle().Foreground(th.Text)
	r := []rune(text)
	var spans []Span
	start, i := 0, 0
	flush := func(end int) {
		if end > start {
			spans = append(spans, Span{Text: string(r[start:end]), Style: plain})
		}
	}
	for i < len(r) {
		if tok, style, n, ok := matchToken(r, i, th); ok {
			flush(i)
			spans = append(spans, Span{Text: tok, Style: style})
			i += n
			start = i
			continue
		}
		i++
	}
	flush(len(r))
	return spans
}

// matchToken tries to match an inline construct starting at r[i]. It returns the
// token (including its markup), the style, the rune length, and whether matched.
func matchToken(r []rune, i int, th theme.Theme) (string, lipgloss.Style, int, bool) {
	// Inline code: `...`
	if r[i] == '`' {
		if j := indexRune(r, '`', i+1); j > i {
			return string(r[i : j+1]), lipgloss.NewStyle().Foreground(th.Code), j + 1 - i, true
		}
	}
	// Wikilink: [[...]]
	if r[i] == '[' && i+1 < len(r) && r[i+1] == '[' {
		if j := indexSeq(r, "]]", i+2); j >= 0 {
			end := j + 2
			return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Wikilink), end - i, true
		}
	}
	// Link: [text](url)
	if r[i] == '[' {
		if c := indexRune(r, ']', i+1); c > i && c+1 < len(r) && r[c+1] == '(' {
			if p := indexRune(r, ')', c+2); p > c {
				end := p + 1
				return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Link), end - i, true
			}
		}
	}
	// Bold: ** or __
	for _, d := range []string{"**", "__"} {
		if hasPrefixRunes(r, i, d) {
			if j := indexSeq(r, d, i+2); j >= 0 {
				end := j + 2
				return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Text).Bold(true), end - i, true
			}
		}
	}
	// Italic: * or _
	if r[i] == '*' || r[i] == '_' {
		if j := indexRune(r, r[i], i+1); j > i {
			end := j + 1
			return string(r[i:end]), lipgloss.NewStyle().Foreground(th.Text).Italic(true), end - i, true
		}
	}
	return "", lipgloss.Style{}, 0, false
}

func indexRune(r []rune, c rune, from int) int {
	for i := from; i < len(r); i++ {
		if r[i] == c {
			return i
		}
	}
	return -1
}

func indexSeq(r []rune, seq string, from int) int {
	s := []rune(seq)
	for i := from; i+len(s) <= len(r); i++ {
		match := true
		for k := range s {
			if r[i+k] != s[k] {
				match = false
				break
			}
		}
		if match {
			return i
		}
	}
	return -1
}

func hasPrefixRunes(r []rune, i int, prefix string) bool {
	p := []rune(prefix)
	if i+len(p) > len(r) {
		return false
	}
	for k := range p {
		if r[i+k] != p[k] {
			return false
		}
	}
	return true
}