@native-sdk/cli 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +9 -9
  2. package/packages/core/package-lock.json +2 -2
  3. package/packages/core/package.json +1 -1
  4. package/skill-data/native-ui/SKILL.md +17 -2
  5. package/src/primitives/canvas/code.zig +590 -0
  6. package/src/primitives/canvas/code_tests.zig +1062 -0
  7. package/src/primitives/canvas/layout_audit.zig +3 -1
  8. package/src/primitives/canvas/markdown.zig +13 -11
  9. package/src/primitives/canvas/markdown_tests.zig +167 -4
  10. package/src/primitives/canvas/root.zig +4 -2
  11. package/src/primitives/canvas/tests.zig +1 -0
  12. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  13. package/src/primitives/canvas/text_span_tests.zig +254 -0
  14. package/src/primitives/canvas/text_spans.zig +556 -32
  15. package/src/primitives/canvas/themes/geist.zig +29 -0
  16. package/src/primitives/canvas/tokens.zig +72 -2
  17. package/src/primitives/canvas/ui.zig +304 -5
  18. package/src/primitives/canvas/ui_markup.zig +59 -2
  19. package/src/primitives/canvas/ui_markup_compiled.zig +76 -0
  20. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  21. package/src/primitives/canvas/ui_markup_contract.zig +34 -0
  22. package/src/primitives/canvas/ui_markup_view.zig +73 -0
  23. package/src/primitives/canvas/ui_markup_view_tests.zig +85 -0
  24. package/src/primitives/canvas/ui_schema.zig +17 -6
  25. package/src/primitives/canvas/ui_schema_tests.zig +7 -6
  26. package/src/primitives/canvas/widget_invalidation.zig +3 -0
  27. package/src/primitives/canvas/widget_layout.zig +57 -8
  28. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  29. package/src/primitives/canvas/widget_metrics.zig +30 -1
  30. package/src/primitives/canvas/widget_render.zig +454 -9
  31. package/src/primitives/canvas/widget_text_select.zig +2 -2
  32. package/src/primitives/canvas/widgets.zig +13 -0
  33. package/src/root.zig +1 -0
  34. package/src/runtime/canvas_widget_clipboard_tests.zig +130 -0
  35. package/src/runtime/canvas_widget_context_menu.zig +12 -2
  36. package/src/runtime/canvas_widget_events.zig +7 -1
  37. package/src/runtime/canvas_widget_runtime.zig +7 -2
  38. package/src/runtime/canvas_widget_text_tests.zig +57 -0
  39. package/src/runtime/view.zig +7 -3
  40. package/src/runtime/view_widget_text.zig +194 -4
@@ -0,0 +1,590 @@
1
+ //! Syntax-aware source-code presentation shared by `Ui.code` and
2
+ //! Markdown fenced blocks.
3
+ //!
4
+ //! The lexer is deliberately small and deterministic: it recognizes the
5
+ //! punctuation classes that make common snippets readable, emits only
6
+ //! theme-token colors, and always preserves an unstyled remainder when a
7
+ //! token-dense source reaches the paragraph span limit.
8
+
9
+ const std = @import("std");
10
+ const text_spans = @import("text_spans.zig");
11
+
12
+ pub const TextSpan = text_spans.TextSpan;
13
+ const max_html_tag_contexts: usize = 32;
14
+
15
+ pub const Language = enum {
16
+ plain,
17
+ zig,
18
+ javascript,
19
+ typescript,
20
+ json,
21
+ shell,
22
+ python,
23
+ rust,
24
+ c_like,
25
+ go,
26
+ html,
27
+ css,
28
+ sql,
29
+ };
30
+
31
+ /// Lexer state carried between bounded source chunks by `Ui.code`.
32
+ /// Keeping it explicit lets the component reset its span budget without
33
+ /// forgetting a multiline tag, string, or block comment.
34
+ pub const HighlightState = struct {
35
+ html_in_tag: bool = false,
36
+ html_expect_tag_name: bool = false,
37
+ html_expression_depth: usize = 0,
38
+ /// Expression depth at which the current tag opened. JSX tags can sit
39
+ /// inside `{...}`; their closing `>` must return to that expression,
40
+ /// not erase it.
41
+ html_tag_expression_base: usize = 0,
42
+ /// JSX permits an element inside an attribute expression before the
43
+ /// enclosing opening tag has closed. Preserve those enclosing tag
44
+ /// contexts so the inner `>` resumes attribute highlighting instead
45
+ /// of ending it.
46
+ html_tag_context_bases: [max_html_tag_contexts]usize = [_]usize{0} ** max_html_tag_contexts,
47
+ html_tag_context_expect_names: [max_html_tag_contexts]bool = [_]bool{false} ** max_html_tag_contexts,
48
+ html_tag_context_len: usize = 0,
49
+ /// Last non-whitespace source byte from the preceding presentation
50
+ /// chunk. JSX comparison/tag disambiguation needs its left context even
51
+ /// when a bounded paragraph happens to split immediately before `<`.
52
+ html_previous_significant: u8 = 0,
53
+ html_comment: bool = false,
54
+ block_comment: bool = false,
55
+ line_comment: bool = false,
56
+ preprocessor_line: bool = false,
57
+ string_quote: ?u8 = null,
58
+ };
59
+
60
+ fn pushHtmlTagContext(state: *HighlightState) void {
61
+ if (!state.html_in_tag or state.html_tag_context_len >= max_html_tag_contexts) return;
62
+ const index = state.html_tag_context_len;
63
+ state.html_tag_context_bases[index] = state.html_tag_expression_base;
64
+ state.html_tag_context_expect_names[index] = state.html_expect_tag_name;
65
+ state.html_tag_context_len += 1;
66
+ }
67
+
68
+ fn restoreHtmlTagContext(state: *HighlightState) bool {
69
+ if (state.html_tag_context_len == 0) return false;
70
+ state.html_tag_context_len -= 1;
71
+ const index = state.html_tag_context_len;
72
+ state.html_in_tag = true;
73
+ state.html_tag_expression_base = state.html_tag_context_bases[index];
74
+ state.html_expect_tag_name = state.html_tag_context_expect_names[index];
75
+ return true;
76
+ }
77
+
78
+ /// Resolve a public language name. Unknown names remain plain instead of
79
+ /// guessing a grammar and coloring ordinary identifiers as keywords.
80
+ pub fn languageFromName(name_raw: []const u8) Language {
81
+ const name = std.mem.trim(u8, name_raw, " \t\r\n");
82
+ if (std.ascii.eqlIgnoreCase(name, "zig")) return .zig;
83
+ if (std.ascii.eqlIgnoreCase(name, "jsx") or std.ascii.eqlIgnoreCase(name, "tsx")) return .html;
84
+ if (std.ascii.eqlIgnoreCase(name, "js") or std.ascii.eqlIgnoreCase(name, "javascript")) return .javascript;
85
+ if (std.ascii.eqlIgnoreCase(name, "ts") or std.ascii.eqlIgnoreCase(name, "typescript")) return .typescript;
86
+ if (std.ascii.eqlIgnoreCase(name, "json") or std.ascii.eqlIgnoreCase(name, "jsonc")) return .json;
87
+ if (std.ascii.eqlIgnoreCase(name, "sh") or std.ascii.eqlIgnoreCase(name, "bash") or std.ascii.eqlIgnoreCase(name, "zsh") or std.ascii.eqlIgnoreCase(name, "shell")) return .shell;
88
+ if (std.ascii.eqlIgnoreCase(name, "py") or std.ascii.eqlIgnoreCase(name, "python")) return .python;
89
+ if (std.ascii.eqlIgnoreCase(name, "rs") or std.ascii.eqlIgnoreCase(name, "rust")) return .rust;
90
+ if (std.ascii.eqlIgnoreCase(name, "c") or std.ascii.eqlIgnoreCase(name, "h") or
91
+ std.ascii.eqlIgnoreCase(name, "cc") or std.ascii.eqlIgnoreCase(name, "cpp") or std.ascii.eqlIgnoreCase(name, "c++") or
92
+ std.ascii.eqlIgnoreCase(name, "cs") or std.ascii.eqlIgnoreCase(name, "csharp") or
93
+ std.ascii.eqlIgnoreCase(name, "java") or std.ascii.eqlIgnoreCase(name, "kotlin") or
94
+ std.ascii.eqlIgnoreCase(name, "swift"))
95
+ {
96
+ return .c_like;
97
+ }
98
+ if (std.ascii.eqlIgnoreCase(name, "go") or std.ascii.eqlIgnoreCase(name, "golang")) return .go;
99
+ if (std.ascii.eqlIgnoreCase(name, "html") or std.ascii.eqlIgnoreCase(name, "xml") or std.ascii.eqlIgnoreCase(name, "svg")) return .html;
100
+ if (std.ascii.eqlIgnoreCase(name, "css") or std.ascii.eqlIgnoreCase(name, "scss") or std.ascii.eqlIgnoreCase(name, "less")) return .css;
101
+ if (std.ascii.eqlIgnoreCase(name, "sql")) return .sql;
102
+ return .plain;
103
+ }
104
+
105
+ pub fn isLanguageName(name_raw: []const u8) bool {
106
+ const name = std.mem.trim(u8, name_raw, " \t\r\n");
107
+ return languageFromName(name) != .plain or
108
+ std.ascii.eqlIgnoreCase(name, "plain") or
109
+ std.ascii.eqlIgnoreCase(name, "text");
110
+ }
111
+
112
+ /// Resolve the first word of a Markdown fence's info string.
113
+ pub fn languageFromFence(opening: []const u8) Language {
114
+ const trimmed = std.mem.trim(u8, opening, " \t");
115
+ if (trimmed.len <= 3) return .plain;
116
+ var info = std.mem.trim(u8, trimmed[3..], " \t");
117
+ if (std.mem.startsWith(u8, info, "{.")) info = info[2..];
118
+ var end: usize = 0;
119
+ while (end < info.len) : (end += 1) {
120
+ const byte = info[end];
121
+ if (!(std.ascii.isAlphanumeric(byte) or byte == '_' or byte == '-' or byte == '+' or byte == '#')) break;
122
+ }
123
+ return languageFromName(info[0..end]);
124
+ }
125
+
126
+ fn wordInList(word: []const u8, list: []const u8, ignore_case: bool) bool {
127
+ var words = std.mem.tokenizeScalar(u8, list, ' ');
128
+ while (words.next()) |candidate| {
129
+ if (if (ignore_case) std.ascii.eqlIgnoreCase(word, candidate) else std.mem.eql(u8, word, candidate)) return true;
130
+ }
131
+ return false;
132
+ }
133
+
134
+ /// Zig fences dominate SDK documentation, so the hot grammar uses a
135
+ /// length-indexed map instead of rescanning a word list per identifier.
136
+ const zig_words = std.StaticStringMap(text_spans.TextSpanColor).initComptime(.{
137
+ .{ "addrspace", .syntax_keyword }, .{ "align", .syntax_keyword }, .{ "allowzero", .syntax_keyword },
138
+ .{ "and", .syntax_keyword }, .{ "anyerror", .syntax_literal }, .{ "anyframe", .syntax_keyword },
139
+ .{ "anytype", .syntax_keyword }, .{ "asm", .syntax_keyword }, .{ "async", .syntax_keyword },
140
+ .{ "await", .syntax_keyword }, .{ "bool", .syntax_literal }, .{ "break", .syntax_keyword },
141
+ .{ "callconv", .syntax_keyword }, .{ "catch", .syntax_keyword }, .{ "comptime", .syntax_keyword },
142
+ .{ "comptime_float", .syntax_literal }, .{ "comptime_int", .syntax_literal }, .{ "const", .syntax_keyword },
143
+ .{ "continue", .syntax_keyword }, .{ "defer", .syntax_keyword }, .{ "else", .syntax_keyword },
144
+ .{ "enum", .syntax_keyword }, .{ "errdefer", .syntax_keyword }, .{ "error", .syntax_keyword },
145
+ .{ "export", .syntax_keyword }, .{ "extern", .syntax_keyword }, .{ "f16", .syntax_literal },
146
+ .{ "f32", .syntax_literal }, .{ "f64", .syntax_literal }, .{ "f80", .syntax_literal },
147
+ .{ "f128", .syntax_literal }, .{ "false", .syntax_literal }, .{ "fn", .syntax_keyword },
148
+ .{ "for", .syntax_keyword }, .{ "i8", .syntax_literal }, .{ "i16", .syntax_literal },
149
+ .{ "i32", .syntax_literal }, .{ "i64", .syntax_literal }, .{ "i128", .syntax_literal },
150
+ .{ "if", .syntax_keyword }, .{ "inline", .syntax_keyword }, .{ "isize", .syntax_literal },
151
+ .{ "linksection", .syntax_keyword }, .{ "noalias", .syntax_keyword }, .{ "noinline", .syntax_keyword },
152
+ .{ "noreturn", .syntax_literal }, .{ "nosuspend", .syntax_keyword }, .{ "null", .syntax_literal },
153
+ .{ "opaque", .syntax_keyword }, .{ "or", .syntax_keyword }, .{ "orelse", .syntax_keyword },
154
+ .{ "packed", .syntax_keyword }, .{ "pub", .syntax_keyword }, .{ "resume", .syntax_keyword },
155
+ .{ "return", .syntax_keyword }, .{ "struct", .syntax_keyword }, .{ "suspend", .syntax_keyword },
156
+ .{ "switch", .syntax_keyword }, .{ "test", .syntax_keyword }, .{ "threadlocal", .syntax_keyword },
157
+ .{ "true", .syntax_literal }, .{ "try", .syntax_keyword }, .{ "type", .syntax_literal },
158
+ .{ "u8", .syntax_literal }, .{ "u16", .syntax_literal }, .{ "u32", .syntax_literal },
159
+ .{ "u64", .syntax_literal }, .{ "u128", .syntax_literal }, .{ "undefined", .syntax_literal },
160
+ .{ "union", .syntax_keyword }, .{ "unreachable", .syntax_keyword }, .{ "usize", .syntax_literal },
161
+ .{ "usingnamespace", .syntax_keyword }, .{ "var", .syntax_keyword }, .{ "void", .syntax_literal },
162
+ .{ "volatile", .syntax_keyword }, .{ "while", .syntax_keyword },
163
+ });
164
+
165
+ fn wordColor(language: Language, word: []const u8) ?text_spans.TextSpanColor {
166
+ if (word.len > 0 and word[0] == '@') return .syntax_function;
167
+ if (language == .zig) return zig_words.get(word);
168
+ if (language == .python and wordInList(word, "True False None", false)) return .syntax_literal;
169
+ if (wordInList(word, "true false null nil none undefined this self super", language == .sql)) return .syntax_literal;
170
+
171
+ const keywords = switch (language) {
172
+ .plain => return null,
173
+ .zig => unreachable,
174
+ .javascript => "async await break case catch class const continue debugger default delete do else export extends finally for from function get if import in instanceof let new of return set static switch throw try typeof var void while with yield",
175
+ .typescript => "abstract any as asserts async await bigint boolean break case catch class const constructor continue declare default delete do else enum export extends finally for from function get if implements import in infer interface instanceof is keyof let module namespace never new number object of override private protected public readonly require return satisfies set static string super switch symbol this throw try type typeof undefined unique unknown var void while with yield",
176
+ .json => "",
177
+ .shell => "case coproc do done elif else esac fi for function if in select then time until while",
178
+ .python => "and as assert async await break case class continue def del elif else except finally for from global if import in is lambda match nonlocal not or pass raise return try while with yield",
179
+ .rust => "as async await break const continue crate dyn else enum extern fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait type union unsafe use where while",
180
+ .c_like => "abstract alignas alignof asm auto break case catch class const constexpr continue default delete do else enum explicit export extends extern final finally for foreach friend goto if implements import in inline interface internal namespace native new noexcept operator override package private protected public register reinterpret_cast return sealed signed sizeof static strictfp struct switch synchronized template this throw throws trait transient try typedef typeid typename union unsigned using virtual volatile while",
181
+ .go => "break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var",
182
+ .html => "",
183
+ .css => "and important inherit initial none not only or revert unset",
184
+ .sql => "add all alter and any as asc begin between by case check column commit constraint create cross database default delete desc distinct drop else end exists foreign from full grant group having in index inner insert intersect into is join key left like limit not null on or order outer primary references right rollback row select set table then union unique update values view when where with",
185
+ };
186
+ if (wordInList(word, keywords, language == .sql)) return .syntax_keyword;
187
+
188
+ const types = switch (language) {
189
+ .rust => "bool char str String Vec Option Result Box i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64",
190
+ .c_like => "bool boolean byte char decimal double float int long object sbyte short string uint ulong ushort void",
191
+ .go => "any bool byte comparable complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptr",
192
+ .javascript, .typescript => "Array BigInt Boolean Date Error Map Number Object Promise RegExp Set String Symbol",
193
+ .python => "bool bytes dict float int list object set str tuple",
194
+ else => "",
195
+ };
196
+ if (wordInList(word, types, false)) return .syntax_literal;
197
+ return null;
198
+ }
199
+
200
+ fn identifierStructuralColor(language: Language, source: []const u8, end: usize) ?text_spans.TextSpanColor {
201
+ var cursor = end;
202
+ while (cursor < source.len and (source[cursor] == ' ' or source[cursor] == '\t')) cursor += 1;
203
+ if (cursor >= source.len or source[cursor] == '\n') return null;
204
+ if (source[cursor] == '(' and language != .plain and language != .json) return .syntax_function;
205
+ if (source[cursor] == ':' and switch (language) {
206
+ .javascript, .typescript, .css => true,
207
+ else => false,
208
+ }) return .syntax_property;
209
+ if (source[cursor] == '{' and language == .css) return .syntax_literal;
210
+ return null;
211
+ }
212
+
213
+ fn identifierStart(byte: u8) bool {
214
+ return std.ascii.isAlphabetic(byte) or byte == '_' or byte == '@' or byte == '$';
215
+ }
216
+
217
+ fn identifierContinue(byte: u8) bool {
218
+ return std.ascii.isAlphanumeric(byte) or byte == '_' or byte == '@' or byte == '$';
219
+ }
220
+
221
+ fn htmlTagOpenerByte(byte: u8) bool {
222
+ return identifierStart(byte) or byte == '/' or byte == '!' or byte == '?' or byte == '>';
223
+ }
224
+
225
+ fn htmlPreviousAllowsTag(byte: u8) bool {
226
+ return switch (byte) {
227
+ 0, '{', '(', '[', ',', ':', '?', '=', '>', '!', '&', '|', ';' => true,
228
+ else => false,
229
+ };
230
+ }
231
+
232
+ /// A `<` in HTML-family source is structural only when it can begin a tag.
233
+ /// Inside a JSX expression, the preceding token must also leave room for an
234
+ /// expression operand; `count < limit` is relational, while
235
+ /// `ok && <Badge />` starts nested JSX.
236
+ fn htmlLessThanStartsTag(source: []const u8, index: usize, state: HighlightState) bool {
237
+ if (index + 1 >= source.len or !htmlTagOpenerByte(source[index + 1])) return false;
238
+ if (state.html_expression_depth == 0) return true;
239
+
240
+ var cursor = index;
241
+ while (cursor > 0) {
242
+ cursor -= 1;
243
+ const byte = source[cursor];
244
+ if (byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n') continue;
245
+ return htmlPreviousAllowsTag(byte);
246
+ }
247
+ return htmlPreviousAllowsTag(state.html_previous_significant);
248
+ }
249
+
250
+ fn updateHtmlPreviousSignificant(state: *HighlightState, source: []const u8) void {
251
+ var cursor = source.len;
252
+ while (cursor > 0) {
253
+ cursor -= 1;
254
+ const byte = source[cursor];
255
+ if (byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n') continue;
256
+ state.html_previous_significant = byte;
257
+ return;
258
+ }
259
+ }
260
+
261
+ fn stringQuote(language: Language, byte: u8) bool {
262
+ return switch (language) {
263
+ .plain, .html => false,
264
+ .json => byte == '"',
265
+ // A Rust apostrophe begins a character only when a closing quote
266
+ // follows one scalar or escape; otherwise it introduces a lifetime
267
+ // (`'a`, `'static`) and must not open multiline string state.
268
+ .rust => byte == '"',
269
+ .shell, .javascript, .typescript, .go => byte == '"' or byte == '\'' or byte == '`',
270
+ else => byte == '"' or byte == '\'',
271
+ };
272
+ }
273
+
274
+ fn rustCharLiteralLength(rest: []const u8) ?usize {
275
+ if (rest.len < 3 or rest[0] != '\'') return null;
276
+ var cursor: usize = 1;
277
+ if (rest[cursor] == '\\') {
278
+ cursor += 1;
279
+ if (cursor >= rest.len) return null;
280
+ switch (rest[cursor]) {
281
+ 'x' => {
282
+ cursor += 1;
283
+ if (cursor + 2 > rest.len or
284
+ !std.ascii.isHex(rest[cursor]) or
285
+ !std.ascii.isHex(rest[cursor + 1]))
286
+ {
287
+ return null;
288
+ }
289
+ cursor += 2;
290
+ },
291
+ 'u' => {
292
+ cursor += 1;
293
+ if (cursor >= rest.len or rest[cursor] != '{') return null;
294
+ cursor += 1;
295
+ var digits: usize = 0;
296
+ while (cursor < rest.len and rest[cursor] != '}') : (cursor += 1) {
297
+ if (rest[cursor] == '_') continue;
298
+ if (!std.ascii.isHex(rest[cursor])) return null;
299
+ digits += 1;
300
+ }
301
+ if (digits == 0 or cursor >= rest.len) return null;
302
+ cursor += 1;
303
+ },
304
+ else => cursor += 1,
305
+ }
306
+ } else {
307
+ const scalar_len = std.unicode.utf8ByteSequenceLength(rest[cursor]) catch return null;
308
+ if (cursor + scalar_len > rest.len) return null;
309
+ _ = std.unicode.utf8Decode(rest[cursor .. cursor + scalar_len]) catch return null;
310
+ cursor += scalar_len;
311
+ }
312
+ if (cursor >= rest.len or rest[cursor] != '\'') return null;
313
+ return cursor + 1;
314
+ }
315
+
316
+ fn backslashEscapesQuote(language: Language, state: HighlightState, quote: u8) bool {
317
+ return switch (language) {
318
+ // Plain HTML attributes do not use JavaScript escapes for either
319
+ // quote style, but strings inside JSX expressions do.
320
+ .html => state.html_expression_depth > 0,
321
+ // Shell single quotes are literal. SQL quotes are escaped by
322
+ // doubling them, never with a backslash.
323
+ .shell => quote != '\'',
324
+ .sql => false,
325
+ else => true,
326
+ };
327
+ }
328
+
329
+ fn lineCommentPrefix(language: Language, rest: []const u8) usize {
330
+ if (rest.len == 0) return 0;
331
+ return switch (language) {
332
+ .zig, .javascript, .typescript, .rust, .c_like, .go => if (std.mem.startsWith(u8, rest, "//")) 2 else 0,
333
+ .shell, .python => if (rest[0] == '#') 1 else 0,
334
+ .sql => if (std.mem.startsWith(u8, rest, "--")) 2 else 0,
335
+ else => 0,
336
+ };
337
+ }
338
+
339
+ fn hasBlockComments(language: Language) bool {
340
+ return switch (language) {
341
+ .zig, .javascript, .typescript, .rust, .c_like, .go, .css, .sql => true,
342
+ else => false,
343
+ };
344
+ }
345
+
346
+ /// Add one token, coalescing adjacent tokens with the same color. The
347
+ /// final slot is a plain-syntax remainder, so capacity never drops source.
348
+ fn appendSpan(
349
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
350
+ len: *usize,
351
+ source: []const u8,
352
+ start: usize,
353
+ end: usize,
354
+ color: ?text_spans.TextSpanColor,
355
+ ) bool {
356
+ if (end <= start) return true;
357
+ if (len.* > 0) {
358
+ const previous = &storage[len.* - 1];
359
+ if (previous.color == color and previous.text.ptr + previous.text.len == source[start..].ptr) {
360
+ previous.text = previous.text.ptr[0 .. previous.text.len + end - start];
361
+ return true;
362
+ }
363
+ }
364
+ if (len.* + 1 >= storage.len) {
365
+ storage[len.*] = .{ .text = source[start..], .monospace = true, .color = .syntax_plain };
366
+ len.* += 1;
367
+ return false;
368
+ }
369
+ storage[len.*] = .{ .text = source[start..end], .monospace = true, .color = color };
370
+ len.* += 1;
371
+ return true;
372
+ }
373
+
374
+ /// Tokenize `source` into theme-colored monospace spans.
375
+ pub fn highlight(
376
+ source: []const u8,
377
+ language: Language,
378
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
379
+ ) []const TextSpan {
380
+ var state: HighlightState = .{};
381
+ return highlightWithState(source, language, storage, &state);
382
+ }
383
+
384
+ /// Stateful form used when one code surface emits multiple bounded
385
+ /// paragraphs. Each chunk gets the full span capacity while lexer context
386
+ /// survives into the next chunk.
387
+ pub fn highlightWithState(
388
+ source: []const u8,
389
+ language: Language,
390
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
391
+ state: *HighlightState,
392
+ ) []const TextSpan {
393
+ if (source.len == 0) return &.{};
394
+ if (language == .plain) {
395
+ storage[0] = .{ .text = source, .monospace = true, .color = .syntax_plain };
396
+ return storage[0..1];
397
+ }
398
+
399
+ var len: usize = 0;
400
+ var styling_full = false;
401
+ var index: usize = 0;
402
+ while (index < source.len) {
403
+ const start = index;
404
+ const rest = source[index..];
405
+ var color: ?text_spans.TextSpanColor = .syntax_plain;
406
+
407
+ // Artificial presentation chunks can end in the middle of a
408
+ // logical source line. A real newline ends the two line-scoped
409
+ // states before ordinary token dispatch handles that byte.
410
+ if (rest[0] == '\n') {
411
+ state.line_comment = false;
412
+ state.preprocessor_line = false;
413
+ }
414
+
415
+ if (state.line_comment) {
416
+ while (index < source.len and source[index] != '\n') index += 1;
417
+ state.line_comment = index == source.len;
418
+ color = .syntax_comment;
419
+ } else if (state.preprocessor_line) {
420
+ while (index < source.len and source[index] != '\n') index += 1;
421
+ state.preprocessor_line = index == source.len;
422
+ color = .syntax_constant;
423
+ } else if (state.html_comment) {
424
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "-->")) index += 1;
425
+ if (index < source.len) {
426
+ index = @min(source.len, index + 3);
427
+ state.html_comment = false;
428
+ }
429
+ color = .syntax_comment;
430
+ } else if (state.block_comment) {
431
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "*/")) index += 1;
432
+ if (index < source.len) {
433
+ index = @min(source.len, index + 2);
434
+ state.block_comment = false;
435
+ }
436
+ color = .syntax_comment;
437
+ } else if (state.string_quote) |quote| {
438
+ var closed = false;
439
+ while (index < source.len) {
440
+ if (source[index] == '\\' and
441
+ backslashEscapesQuote(language, state.*, quote) and
442
+ index + 1 < source.len)
443
+ {
444
+ index += 2;
445
+ continue;
446
+ }
447
+ const byte = source[index];
448
+ index += 1;
449
+ if (byte == quote) {
450
+ closed = true;
451
+ break;
452
+ }
453
+ }
454
+ if (closed) state.string_quote = null;
455
+ color = .syntax_literal;
456
+ } else if (language == .html and std.mem.startsWith(u8, rest, "<!--")) {
457
+ index += 4;
458
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "-->")) index += 1;
459
+ if (index < source.len) {
460
+ index = @min(source.len, index + 3);
461
+ } else {
462
+ state.html_comment = true;
463
+ }
464
+ color = .syntax_comment;
465
+ } else if (hasBlockComments(language) and std.mem.startsWith(u8, rest, "/*")) {
466
+ index += 2;
467
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "*/")) index += 1;
468
+ if (index < source.len) {
469
+ index = @min(source.len, index + 2);
470
+ } else {
471
+ state.block_comment = true;
472
+ }
473
+ color = .syntax_comment;
474
+ } else if (lineCommentPrefix(language, rest) != 0) {
475
+ while (index < source.len and source[index] != '\n') index += 1;
476
+ state.line_comment = index == source.len;
477
+ color = .syntax_comment;
478
+ } else if (language == .c_like and rest[0] == '#') {
479
+ while (index < source.len and source[index] != '\n') index += 1;
480
+ state.preprocessor_line = index == source.len;
481
+ color = .syntax_constant;
482
+ } else if (language == .html and
483
+ rest[0] == '<' and
484
+ htmlLessThanStartsTag(source, index, state.*))
485
+ {
486
+ index += 1;
487
+ if (index < source.len and source[index] == '/') index += 1;
488
+ pushHtmlTagContext(state);
489
+ state.html_in_tag = true;
490
+ state.html_expect_tag_name = true;
491
+ state.html_tag_expression_base = state.html_expression_depth;
492
+ color = .syntax_plain;
493
+ } else if (language == .html and
494
+ state.html_in_tag and
495
+ state.html_expression_depth == state.html_tag_expression_base and
496
+ rest[0] == '>')
497
+ {
498
+ index += 1;
499
+ if (!restoreHtmlTagContext(state)) {
500
+ state.html_in_tag = false;
501
+ state.html_expect_tag_name = false;
502
+ }
503
+ color = .syntax_plain;
504
+ } else if (language == .html and rest[0] == '{') {
505
+ index += 1;
506
+ state.html_expression_depth += 1;
507
+ color = .syntax_plain;
508
+ } else if (language == .html and state.html_expression_depth > 0 and rest[0] == '}') {
509
+ index += 1;
510
+ state.html_expression_depth -= 1;
511
+ color = .syntax_plain;
512
+ } else if (if (language == .rust) rustCharLiteralLength(rest) else null) |literal_len| {
513
+ index += literal_len;
514
+ color = .syntax_literal;
515
+ } else if (stringQuote(language, rest[0]) or
516
+ (language == .html and
517
+ (state.html_in_tag or state.html_expression_depth > 0) and
518
+ (rest[0] == '"' or rest[0] == '\'' or rest[0] == '`')))
519
+ {
520
+ const quote = rest[0];
521
+ index += 1;
522
+ var closed = false;
523
+ while (index < source.len) {
524
+ if (source[index] == '\\' and
525
+ backslashEscapesQuote(language, state.*, quote) and
526
+ index + 1 < source.len)
527
+ {
528
+ index += 2;
529
+ continue;
530
+ }
531
+ const byte = source[index];
532
+ index += 1;
533
+ if (byte == quote) {
534
+ closed = true;
535
+ break;
536
+ }
537
+ }
538
+ if (!closed) state.string_quote = quote;
539
+ color = .syntax_literal;
540
+ } else if (std.ascii.isDigit(rest[0])) {
541
+ index += 1;
542
+ while (index < source.len) {
543
+ const byte = source[index];
544
+ if (!(std.ascii.isAlphanumeric(byte) or byte == '_' or byte == '.')) break;
545
+ index += 1;
546
+ }
547
+ color = .syntax_literal;
548
+ } else if (identifierStart(rest[0])) {
549
+ index += 1;
550
+ while (index < source.len and
551
+ (identifierContinue(source[index]) or
552
+ ((language == .html or language == .css) and source[index] == '-')))
553
+ {
554
+ index += 1;
555
+ }
556
+ if (language == .html and state.html_in_tag) {
557
+ if (state.html_expect_tag_name) {
558
+ color = .syntax_literal;
559
+ state.html_expect_tag_name = false;
560
+ } else if (state.html_expression_depth == 0) {
561
+ color = .syntax_function;
562
+ } else {
563
+ color = wordColor(.typescript, source[start..index]) orelse
564
+ identifierStructuralColor(.typescript, source, index) orelse
565
+ .syntax_plain;
566
+ }
567
+ } else if (language == .html and state.html_expression_depth > 0) {
568
+ color = wordColor(.typescript, source[start..index]) orelse
569
+ identifierStructuralColor(.typescript, source, index) orelse
570
+ .syntax_plain;
571
+ } else {
572
+ color = wordColor(language, source[start..index]) orelse
573
+ identifierStructuralColor(language, source, index) orelse
574
+ .syntax_plain;
575
+ }
576
+ } else {
577
+ index += 1;
578
+ }
579
+
580
+ if (language == .html) updateHtmlPreviousSignificant(state, source[start..index]);
581
+
582
+ // The last span already covers the entire plain-syntax remainder once
583
+ // capacity fills, but keep scanning it so state handed to the next
584
+ // paragraph still reflects comments, strings, and JSX expressions.
585
+ if (!styling_full and !appendSpan(storage, &len, source, start, index, color)) {
586
+ styling_full = true;
587
+ }
588
+ }
589
+ return storage[0..len];
590
+ }