@native-sdk/cli 0.6.3 → 0.7.1

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 (64) hide show
  1. package/build.zig +65 -91
  2. package/package.json +9 -9
  3. package/packages/core/package-lock.json +2 -2
  4. package/packages/core/package.json +1 -1
  5. package/packages/core/sdk/text.ts +25 -14
  6. package/packages/core/src/checker.ts +39 -0
  7. package/packages/core/src/emitter.ts +125 -1
  8. package/skill-data/native-ui/SKILL.md +23 -6
  9. package/src/platform/macos/appkit_host.m +25 -1
  10. package/src/platform/macos/cef_host.mm +24 -2
  11. package/src/platform/macos/root.zig +13 -0
  12. package/src/primitives/canvas/code.zig +1008 -0
  13. package/src/primitives/canvas/code_tests.zig +1912 -0
  14. package/src/primitives/canvas/events.zig +111 -1
  15. package/src/primitives/canvas/layout_audit.zig +3 -1
  16. package/src/primitives/canvas/markdown.zig +13 -11
  17. package/src/primitives/canvas/markdown_tests.zig +168 -6
  18. package/src/primitives/canvas/root.zig +8 -2
  19. package/src/primitives/canvas/tests.zig +1 -0
  20. package/src/primitives/canvas/text.zig +6 -0
  21. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  22. package/src/primitives/canvas/text_span_tests.zig +254 -0
  23. package/src/primitives/canvas/text_spans.zig +556 -32
  24. package/src/primitives/canvas/themes/geist.zig +29 -0
  25. package/src/primitives/canvas/tokens.zig +72 -2
  26. package/src/primitives/canvas/ui.zig +400 -22
  27. package/src/primitives/canvas/ui_markup.zig +78 -7
  28. package/src/primitives/canvas/ui_markup_compiled.zig +89 -0
  29. package/src/primitives/canvas/ui_markup_compiled_tests.zig +45 -0
  30. package/src/primitives/canvas/ui_markup_contract.zig +41 -0
  31. package/src/primitives/canvas/ui_markup_view.zig +89 -0
  32. package/src/primitives/canvas/ui_markup_view_tests.zig +154 -3
  33. package/src/primitives/canvas/ui_schema.zig +30 -6
  34. package/src/primitives/canvas/ui_schema_tests.zig +13 -10
  35. package/src/primitives/canvas/ui_tests.zig +26 -0
  36. package/src/primitives/canvas/widget_invalidation.zig +4 -0
  37. package/src/primitives/canvas/widget_layout.zig +57 -8
  38. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  39. package/src/primitives/canvas/widget_metrics.zig +35 -1
  40. package/src/primitives/canvas/widget_render.zig +1077 -11
  41. package/src/primitives/canvas/widget_render_controls.zig +4 -4
  42. package/src/primitives/canvas/widget_runtime.zig +2 -0
  43. package/src/primitives/canvas/widget_text_input.zig +165 -8
  44. package/src/primitives/canvas/widget_text_select.zig +2 -2
  45. package/src/primitives/canvas/widget_tree.zig +6 -5
  46. package/src/primitives/canvas/widgets.zig +38 -0
  47. package/src/root.zig +1 -0
  48. package/src/runtime/canvas_budget_edge_tests.zig +3 -2
  49. package/src/runtime/canvas_limits.zig +13 -6
  50. package/src/runtime/canvas_widget_clipboard_tests.zig +137 -4
  51. package/src/runtime/canvas_widget_context_menu.zig +17 -2
  52. package/src/runtime/canvas_widget_event_tests.zig +18 -14
  53. package/src/runtime/canvas_widget_events.zig +58 -21
  54. package/src/runtime/canvas_widget_runtime.zig +112 -6
  55. package/src/runtime/canvas_widget_scroll_driver_tests.zig +59 -0
  56. package/src/runtime/canvas_widget_split_tree_tests.zig +100 -0
  57. package/src/runtime/canvas_widget_state.zig +27 -0
  58. package/src/runtime/canvas_widget_text_tests.zig +383 -0
  59. package/src/runtime/core.zig +15 -5
  60. package/src/runtime/gpu_surface_events.zig +12 -12
  61. package/src/runtime/view.zig +61 -19
  62. package/src/runtime/view_widget_scroll.zig +48 -18
  63. package/src/runtime/view_widget_text.zig +248 -17
  64. package/src/runtime/window_view_runtime.zig +9 -0
@@ -0,0 +1,1008 @@
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
+ yaml,
22
+ shell,
23
+ python,
24
+ rust,
25
+ c_like,
26
+ go,
27
+ html,
28
+ css,
29
+ sql,
30
+ jsx,
31
+ tsx,
32
+ markdown,
33
+ };
34
+
35
+ /// Lexer state carried between bounded source chunks by `Ui.code`.
36
+ /// Keeping it explicit lets the component reset its span budget without
37
+ /// forgetting a multiline tag, string, or block comment.
38
+ pub const HighlightState = struct {
39
+ html_in_tag: bool = false,
40
+ html_expect_tag_name: bool = false,
41
+ html_expression_depth: usize = 0,
42
+ /// Expression depth at which the current tag opened. JSX tags can sit
43
+ /// inside `{...}`; their closing `>` must return to that expression,
44
+ /// not erase it.
45
+ html_tag_expression_base: usize = 0,
46
+ /// JSX permits an element inside an attribute expression before the
47
+ /// enclosing opening tag has closed. Preserve those enclosing tag
48
+ /// contexts so the inner `>` resumes attribute highlighting instead
49
+ /// of ending it.
50
+ html_tag_context_bases: [max_html_tag_contexts]usize = [_]usize{0} ** max_html_tag_contexts,
51
+ html_tag_context_expect_names: [max_html_tag_contexts]bool = [_]bool{false} ** max_html_tag_contexts,
52
+ html_tag_context_opened_elements: [max_html_tag_contexts]bool = [_]bool{false} ** max_html_tag_contexts,
53
+ html_tag_context_len: usize = 0,
54
+ /// Expression depth at which each currently open element began.
55
+ /// A closing tag is structural at that same depth even when ordinary
56
+ /// JSX text immediately before it ends in an identifier.
57
+ html_element_expression_bases: [max_html_tag_contexts]usize = [_]usize{0} ** max_html_tag_contexts,
58
+ html_element_len: usize = 0,
59
+ html_tag_opened_element: bool = false,
60
+ /// Last non-whitespace source byte from the preceding presentation
61
+ /// chunk. JSX comparison/tag disambiguation needs its left context even
62
+ /// when a bounded paragraph happens to split immediately before `<`.
63
+ html_previous_significant: u8 = 0,
64
+ html_comment: bool = false,
65
+ block_comment: bool = false,
66
+ line_comment: bool = false,
67
+ preprocessor_line: bool = false,
68
+ string_quote: ?u8 = null,
69
+ markdown_line_start: bool = true,
70
+ markdown_fence_byte: u8 = 0,
71
+ markdown_fence_len: u8 = 0,
72
+ markdown_inline_code_len: u8 = 0,
73
+ };
74
+
75
+ fn pushHtmlTagContext(state: *HighlightState) void {
76
+ if (!state.html_in_tag or state.html_tag_context_len >= max_html_tag_contexts) return;
77
+ const index = state.html_tag_context_len;
78
+ state.html_tag_context_bases[index] = state.html_tag_expression_base;
79
+ state.html_tag_context_expect_names[index] = state.html_expect_tag_name;
80
+ state.html_tag_context_opened_elements[index] = state.html_tag_opened_element;
81
+ state.html_tag_context_len += 1;
82
+ }
83
+
84
+ fn restoreHtmlTagContext(state: *HighlightState) bool {
85
+ if (state.html_tag_context_len == 0) return false;
86
+ state.html_tag_context_len -= 1;
87
+ const index = state.html_tag_context_len;
88
+ state.html_in_tag = true;
89
+ state.html_tag_expression_base = state.html_tag_context_bases[index];
90
+ state.html_expect_tag_name = state.html_tag_context_expect_names[index];
91
+ state.html_tag_opened_element = state.html_tag_context_opened_elements[index];
92
+ return true;
93
+ }
94
+
95
+ /// Resolve a public language name. Unknown names remain plain instead of
96
+ /// guessing a grammar and coloring ordinary identifiers as keywords.
97
+ pub fn languageFromName(name_raw: []const u8) Language {
98
+ const name = std.mem.trim(u8, name_raw, " \t\r\n");
99
+ if (std.ascii.eqlIgnoreCase(name, "zig")) return .zig;
100
+ if (std.ascii.eqlIgnoreCase(name, "jsx")) return .jsx;
101
+ if (std.ascii.eqlIgnoreCase(name, "tsx")) return .tsx;
102
+ if (std.ascii.eqlIgnoreCase(name, "js") or
103
+ std.ascii.eqlIgnoreCase(name, "mjs") or
104
+ std.ascii.eqlIgnoreCase(name, "javascript")) return .javascript;
105
+ if (std.ascii.eqlIgnoreCase(name, "ts") or std.ascii.eqlIgnoreCase(name, "typescript")) return .typescript;
106
+ if (std.ascii.eqlIgnoreCase(name, "json") or std.ascii.eqlIgnoreCase(name, "jsonc")) return .json;
107
+ if (std.ascii.eqlIgnoreCase(name, "yaml") or std.ascii.eqlIgnoreCase(name, "yml")) return .yaml;
108
+ 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;
109
+ if (std.ascii.eqlIgnoreCase(name, "py") or std.ascii.eqlIgnoreCase(name, "python")) return .python;
110
+ if (std.ascii.eqlIgnoreCase(name, "rs") or std.ascii.eqlIgnoreCase(name, "rust")) return .rust;
111
+ if (std.ascii.eqlIgnoreCase(name, "c") or std.ascii.eqlIgnoreCase(name, "h") or
112
+ std.ascii.eqlIgnoreCase(name, "cc") or std.ascii.eqlIgnoreCase(name, "cpp") or std.ascii.eqlIgnoreCase(name, "c++") or
113
+ std.ascii.eqlIgnoreCase(name, "cs") or std.ascii.eqlIgnoreCase(name, "csharp") or
114
+ std.ascii.eqlIgnoreCase(name, "java") or std.ascii.eqlIgnoreCase(name, "kotlin") or
115
+ std.ascii.eqlIgnoreCase(name, "swift"))
116
+ {
117
+ return .c_like;
118
+ }
119
+ if (std.ascii.eqlIgnoreCase(name, "go") or std.ascii.eqlIgnoreCase(name, "golang")) return .go;
120
+ if (std.ascii.eqlIgnoreCase(name, "html") or std.ascii.eqlIgnoreCase(name, "xml") or std.ascii.eqlIgnoreCase(name, "svg")) return .html;
121
+ if (std.ascii.eqlIgnoreCase(name, "css") or std.ascii.eqlIgnoreCase(name, "scss") or std.ascii.eqlIgnoreCase(name, "less")) return .css;
122
+ if (std.ascii.eqlIgnoreCase(name, "sql")) return .sql;
123
+ if (std.ascii.eqlIgnoreCase(name, "md") or std.ascii.eqlIgnoreCase(name, "markdown")) return .markdown;
124
+ return .plain;
125
+ }
126
+
127
+ pub fn isLanguageName(name_raw: []const u8) bool {
128
+ const name = std.mem.trim(u8, name_raw, " \t\r\n");
129
+ return languageFromName(name) != .plain or
130
+ std.ascii.eqlIgnoreCase(name, "plain") or
131
+ std.ascii.eqlIgnoreCase(name, "text");
132
+ }
133
+
134
+ /// Resolve the first word of a Markdown fence's info string.
135
+ pub fn languageFromFence(opening: []const u8) Language {
136
+ const trimmed = std.mem.trim(u8, opening, " \t");
137
+ if (trimmed.len <= 3) return .plain;
138
+ var info = std.mem.trim(u8, trimmed[3..], " \t");
139
+ if (std.mem.startsWith(u8, info, "{.")) info = info[2..];
140
+ var end: usize = 0;
141
+ while (end < info.len) : (end += 1) {
142
+ const byte = info[end];
143
+ if (!(std.ascii.isAlphanumeric(byte) or byte == '_' or byte == '-' or byte == '+' or byte == '#')) break;
144
+ }
145
+ return languageFromName(info[0..end]);
146
+ }
147
+
148
+ fn wordInList(word: []const u8, list: []const u8, ignore_case: bool) bool {
149
+ var words = std.mem.tokenizeScalar(u8, list, ' ');
150
+ while (words.next()) |candidate| {
151
+ if (if (ignore_case) std.ascii.eqlIgnoreCase(word, candidate) else std.mem.eql(u8, word, candidate)) return true;
152
+ }
153
+ return false;
154
+ }
155
+
156
+ /// Zig fences dominate SDK documentation, so the hot grammar uses a
157
+ /// length-indexed map instead of rescanning a word list per identifier.
158
+ const zig_words = std.StaticStringMap(text_spans.TextSpanColor).initComptime(.{
159
+ .{ "addrspace", .syntax_keyword }, .{ "align", .syntax_keyword }, .{ "allowzero", .syntax_keyword },
160
+ .{ "and", .syntax_keyword }, .{ "anyerror", .syntax_literal }, .{ "anyframe", .syntax_keyword },
161
+ .{ "anytype", .syntax_keyword }, .{ "asm", .syntax_keyword }, .{ "async", .syntax_keyword },
162
+ .{ "await", .syntax_keyword }, .{ "bool", .syntax_literal }, .{ "break", .syntax_keyword },
163
+ .{ "callconv", .syntax_keyword }, .{ "catch", .syntax_keyword }, .{ "comptime", .syntax_keyword },
164
+ .{ "comptime_float", .syntax_literal }, .{ "comptime_int", .syntax_literal }, .{ "const", .syntax_keyword },
165
+ .{ "continue", .syntax_keyword }, .{ "defer", .syntax_keyword }, .{ "else", .syntax_keyword },
166
+ .{ "enum", .syntax_keyword }, .{ "errdefer", .syntax_keyword }, .{ "error", .syntax_keyword },
167
+ .{ "export", .syntax_keyword }, .{ "extern", .syntax_keyword }, .{ "f16", .syntax_literal },
168
+ .{ "f32", .syntax_literal }, .{ "f64", .syntax_literal }, .{ "f80", .syntax_literal },
169
+ .{ "f128", .syntax_literal }, .{ "false", .syntax_literal }, .{ "fn", .syntax_keyword },
170
+ .{ "for", .syntax_keyword }, .{ "i8", .syntax_literal }, .{ "i16", .syntax_literal },
171
+ .{ "i32", .syntax_literal }, .{ "i64", .syntax_literal }, .{ "i128", .syntax_literal },
172
+ .{ "if", .syntax_keyword }, .{ "inline", .syntax_keyword }, .{ "isize", .syntax_literal },
173
+ .{ "linksection", .syntax_keyword }, .{ "noalias", .syntax_keyword }, .{ "noinline", .syntax_keyword },
174
+ .{ "noreturn", .syntax_literal }, .{ "nosuspend", .syntax_keyword }, .{ "null", .syntax_literal },
175
+ .{ "opaque", .syntax_keyword }, .{ "or", .syntax_keyword }, .{ "orelse", .syntax_keyword },
176
+ .{ "packed", .syntax_keyword }, .{ "pub", .syntax_keyword }, .{ "resume", .syntax_keyword },
177
+ .{ "return", .syntax_keyword }, .{ "struct", .syntax_keyword }, .{ "suspend", .syntax_keyword },
178
+ .{ "switch", .syntax_keyword }, .{ "test", .syntax_keyword }, .{ "threadlocal", .syntax_keyword },
179
+ .{ "true", .syntax_literal }, .{ "try", .syntax_keyword }, .{ "type", .syntax_literal },
180
+ .{ "u8", .syntax_literal }, .{ "u16", .syntax_literal }, .{ "u32", .syntax_literal },
181
+ .{ "u64", .syntax_literal }, .{ "u128", .syntax_literal }, .{ "undefined", .syntax_literal },
182
+ .{ "union", .syntax_keyword }, .{ "unreachable", .syntax_keyword }, .{ "usize", .syntax_literal },
183
+ .{ "usingnamespace", .syntax_keyword }, .{ "var", .syntax_keyword }, .{ "void", .syntax_literal },
184
+ .{ "volatile", .syntax_keyword }, .{ "while", .syntax_keyword },
185
+ });
186
+
187
+ fn wordColor(language: Language, word: []const u8) ?text_spans.TextSpanColor {
188
+ if (word.len > 0 and word[0] == '@') return .syntax_function;
189
+ if (language == .zig) return zig_words.get(word);
190
+ if (language == .python and wordInList(word, "True False None", false)) return .syntax_literal;
191
+ if (language == .yaml and wordInList(word, "true false null yes no on off", true)) return .syntax_literal;
192
+ if (wordInList(word, "true false null nil none undefined this self super", language == .sql)) return .syntax_literal;
193
+
194
+ const keywords = switch (language) {
195
+ .plain => return null,
196
+ .zig => unreachable,
197
+ .javascript, .jsx => "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",
198
+ .typescript, .tsx => "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",
199
+ .json => "",
200
+ .yaml => "",
201
+ .shell => "case coproc do done elif else esac fi for function if in select then time until while",
202
+ .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",
203
+ .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",
204
+ .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",
205
+ .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",
206
+ .html => "",
207
+ .css => "and important inherit initial none not only or revert unset",
208
+ .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",
209
+ .markdown => "",
210
+ };
211
+ if (wordInList(word, keywords, language == .sql)) return .syntax_keyword;
212
+
213
+ const types = switch (language) {
214
+ .rust => "bool char str String Vec Option Result Box i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64",
215
+ .c_like => "bool boolean byte char decimal double float int long object sbyte short string uint ulong ushort void",
216
+ .go => "any bool byte comparable complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptr",
217
+ .javascript, .typescript, .jsx, .tsx => "Array BigInt Boolean Date Error Map Number Object Promise RegExp Set String Symbol",
218
+ .python => "bool bytes dict float int list object set str tuple",
219
+ else => "",
220
+ };
221
+ if (wordInList(word, types, false)) return .syntax_literal;
222
+ return null;
223
+ }
224
+
225
+ fn identifierStructuralColor(language: Language, source: []const u8, end: usize) ?text_spans.TextSpanColor {
226
+ var cursor = end;
227
+ while (cursor < source.len and (source[cursor] == ' ' or source[cursor] == '\t')) cursor += 1;
228
+ if (cursor >= source.len or source[cursor] == '\n') return null;
229
+ if (source[cursor] == '(' and language != .plain and language != .json) return .syntax_function;
230
+ // JavaScript/TypeScript object keys and typed bindings use the same
231
+ // identifier ink as variables. CSS declarations retain the dedicated
232
+ // property role.
233
+ if (source[cursor] == ':' and language == .css) return .syntax_property;
234
+ if (source[cursor] == '{' and language == .css) return .syntax_literal;
235
+ return null;
236
+ }
237
+
238
+ fn identifierStart(byte: u8) bool {
239
+ return std.ascii.isAlphabetic(byte) or byte == '_' or byte == '@' or byte == '$';
240
+ }
241
+
242
+ fn identifierContinue(byte: u8) bool {
243
+ return std.ascii.isAlphanumeric(byte) or byte == '_' or byte == '@' or byte == '$';
244
+ }
245
+
246
+ fn yamlMappingKeyEnd(source: []const u8, start: usize) ?usize {
247
+ if (start >= source.len) return null;
248
+ // Let the sequence/explicit-key indicator stand on its own; the key
249
+ // beginning after its whitespace is considered from the next token.
250
+ if ((source[start] == '-' or source[start] == '?') and
251
+ start + 1 < source.len and
252
+ (source[start + 1] == ' ' or source[start + 1] == '\t'))
253
+ {
254
+ return null;
255
+ }
256
+
257
+ var before = start;
258
+ while (before > 0 and (source[before - 1] == ' ' or source[before - 1] == '\t')) before -= 1;
259
+ if (before > 0) {
260
+ switch (source[before - 1]) {
261
+ '\n', '\r', '{', '[', ',', '-', '?' => {},
262
+ else => return null,
263
+ }
264
+ }
265
+
266
+ var quote: ?u8 = null;
267
+ var cursor = start;
268
+ while (cursor < source.len) {
269
+ const byte = source[cursor];
270
+ if (quote) |active_quote| {
271
+ if (active_quote == '"' and byte == '\\' and cursor + 1 < source.len) {
272
+ cursor += 2;
273
+ continue;
274
+ }
275
+ if (byte == active_quote) {
276
+ // YAML single-quoted strings escape a quote by doubling it.
277
+ if (active_quote == '\'' and cursor + 1 < source.len and source[cursor + 1] == '\'') {
278
+ cursor += 2;
279
+ continue;
280
+ }
281
+ quote = null;
282
+ }
283
+ cursor += 1;
284
+ continue;
285
+ }
286
+
287
+ if (byte == '"' or byte == '\'') {
288
+ quote = byte;
289
+ cursor += 1;
290
+ continue;
291
+ }
292
+ if (byte == ':') {
293
+ const separates_value = cursor + 1 == source.len or switch (source[cursor + 1]) {
294
+ ' ', '\t', '\r', '\n', ',', '}', ']' => true,
295
+ else => false,
296
+ };
297
+ if (!separates_value) {
298
+ cursor += 1;
299
+ continue;
300
+ }
301
+ var end = cursor;
302
+ while (end > start and (source[end - 1] == ' ' or source[end - 1] == '\t')) end -= 1;
303
+ return if (end > start) end else null;
304
+ }
305
+ if (byte == '\n' or byte == '\r' or byte == ',' or byte == '}' or byte == ']') return null;
306
+ cursor += 1;
307
+ }
308
+ return null;
309
+ }
310
+
311
+ fn yamlSymbolEnd(source: []const u8, start: usize) usize {
312
+ var cursor = start + 1;
313
+ while (cursor < source.len) : (cursor += 1) {
314
+ switch (source[cursor]) {
315
+ ' ', '\t', '\r', '\n', ',', '[', ']', '{', '}' => break,
316
+ else => {},
317
+ }
318
+ }
319
+ return cursor;
320
+ }
321
+
322
+ fn yamlDocumentMarkerLength(rest: []const u8) usize {
323
+ if (rest.len < 3) return 0;
324
+ if (!std.mem.startsWith(u8, rest, "---") and !std.mem.startsWith(u8, rest, "...")) return 0;
325
+ if (rest.len == 3) return 3;
326
+ return switch (rest[3]) {
327
+ ' ', '\t', '\r', '\n', '#' => 3,
328
+ else => 0,
329
+ };
330
+ }
331
+
332
+ fn htmlTagOpenerByte(byte: u8) bool {
333
+ return identifierStart(byte) or byte == '/' or byte == '!' or byte == '?' or byte == '>';
334
+ }
335
+
336
+ fn htmlPreviousAllowsTag(byte: u8) bool {
337
+ return switch (byte) {
338
+ 0, '{', '(', '[', ',', ':', '?', '=', '>', '!', '&', '|', ';' => true,
339
+ else => false,
340
+ };
341
+ }
342
+
343
+ fn isHtmlFamily(language: Language) bool {
344
+ return language == .html or language == .jsx or language == .tsx;
345
+ }
346
+
347
+ fn embeddedScriptLanguage(language: Language) Language {
348
+ return switch (language) {
349
+ .jsx => .javascript,
350
+ .html, .tsx => .typescript,
351
+ else => language,
352
+ };
353
+ }
354
+
355
+ /// A `<` in HTML-family source is structural only when it can begin a tag.
356
+ /// Inside a JSX expression, the preceding token must also leave room for an
357
+ /// expression operand; `count < limit` is relational, while
358
+ /// `ok && <Badge />` starts nested JSX.
359
+ fn htmlLessThanStartsTag(source: []const u8, index: usize, language: Language, state: HighlightState) bool {
360
+ if (index + 1 >= source.len or !htmlTagOpenerByte(source[index + 1])) return false;
361
+ if (language == .html and state.html_expression_depth == 0) return true;
362
+ if (!state.html_in_tag and state.html_element_len > 0 and
363
+ state.html_expression_depth == state.html_element_expression_bases[state.html_element_len - 1])
364
+ {
365
+ return true;
366
+ }
367
+
368
+ var cursor = index;
369
+ while (cursor > 0) {
370
+ cursor -= 1;
371
+ const byte = source[cursor];
372
+ if (byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n') continue;
373
+ if (identifierContinue(byte)) {
374
+ const end = cursor + 1;
375
+ while (cursor > 0 and identifierContinue(source[cursor - 1])) cursor -= 1;
376
+ return wordInList(source[cursor..end], "return throw yield", false);
377
+ }
378
+ return htmlPreviousAllowsTag(byte);
379
+ }
380
+ return htmlPreviousAllowsTag(state.html_previous_significant);
381
+ }
382
+
383
+ fn updateHtmlPreviousSignificant(state: *HighlightState, source: []const u8) void {
384
+ var cursor = source.len;
385
+ while (cursor > 0) {
386
+ cursor -= 1;
387
+ const byte = source[cursor];
388
+ if (byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n') continue;
389
+ state.html_previous_significant = byte;
390
+ return;
391
+ }
392
+ }
393
+
394
+ fn stringQuote(language: Language, byte: u8) bool {
395
+ return switch (language) {
396
+ .plain, .html, .markdown => false,
397
+ .json => byte == '"',
398
+ // A Rust apostrophe begins a character only when a closing quote
399
+ // follows one scalar or escape; otherwise it introduces a lifetime
400
+ // (`'a`, `'static`) and must not open multiline string state.
401
+ .rust => byte == '"',
402
+ .shell, .javascript, .typescript, .jsx, .tsx, .go => byte == '"' or byte == '\'' or byte == '`',
403
+ else => byte == '"' or byte == '\'',
404
+ };
405
+ }
406
+
407
+ fn rustCharLiteralLength(rest: []const u8) ?usize {
408
+ if (rest.len < 3 or rest[0] != '\'') return null;
409
+ var cursor: usize = 1;
410
+ if (rest[cursor] == '\\') {
411
+ cursor += 1;
412
+ if (cursor >= rest.len) return null;
413
+ switch (rest[cursor]) {
414
+ 'x' => {
415
+ cursor += 1;
416
+ if (cursor + 2 > rest.len or
417
+ !std.ascii.isHex(rest[cursor]) or
418
+ !std.ascii.isHex(rest[cursor + 1]))
419
+ {
420
+ return null;
421
+ }
422
+ cursor += 2;
423
+ },
424
+ 'u' => {
425
+ cursor += 1;
426
+ if (cursor >= rest.len or rest[cursor] != '{') return null;
427
+ cursor += 1;
428
+ var digits: usize = 0;
429
+ while (cursor < rest.len and rest[cursor] != '}') : (cursor += 1) {
430
+ if (rest[cursor] == '_') continue;
431
+ if (!std.ascii.isHex(rest[cursor])) return null;
432
+ digits += 1;
433
+ }
434
+ if (digits == 0 or cursor >= rest.len) return null;
435
+ cursor += 1;
436
+ },
437
+ else => cursor += 1,
438
+ }
439
+ } else {
440
+ const scalar_len = std.unicode.utf8ByteSequenceLength(rest[cursor]) catch return null;
441
+ if (cursor + scalar_len > rest.len) return null;
442
+ _ = std.unicode.utf8Decode(rest[cursor .. cursor + scalar_len]) catch return null;
443
+ cursor += scalar_len;
444
+ }
445
+ if (cursor >= rest.len or rest[cursor] != '\'') return null;
446
+ return cursor + 1;
447
+ }
448
+
449
+ fn backslashEscapesQuote(language: Language, state: HighlightState, quote: u8) bool {
450
+ return switch (language) {
451
+ // Plain HTML attributes do not use JavaScript escapes for either
452
+ // quote style, but strings inside JSX expressions do.
453
+ .html => state.html_expression_depth > 0,
454
+ // JSX attribute text follows HTML quote rules; JavaScript strings
455
+ // at top level or inside an attribute expression use escapes.
456
+ .jsx, .tsx => !state.html_in_tag or state.html_expression_depth > state.html_tag_expression_base,
457
+ // Shell single quotes are literal. SQL quotes are escaped by
458
+ // doubling them, never with a backslash.
459
+ .shell => quote != '\'',
460
+ .yaml => quote == '"',
461
+ .sql => false,
462
+ else => true,
463
+ };
464
+ }
465
+
466
+ fn lineCommentPrefix(language: Language, source: []const u8, index: usize) usize {
467
+ const rest = source[index..];
468
+ if (rest.len == 0) return 0;
469
+ return switch (language) {
470
+ .zig, .javascript, .typescript, .jsx, .tsx, .rust, .c_like, .go => if (std.mem.startsWith(u8, rest, "//")) 2 else 0,
471
+ .shell, .python => if (rest[0] == '#') 1 else 0,
472
+ .yaml => if (rest[0] == '#' and
473
+ (index == 0 or source[index - 1] == ' ' or source[index - 1] == '\t' or
474
+ source[index - 1] == '\r' or source[index - 1] == '\n')) 1 else 0,
475
+ .sql => if (std.mem.startsWith(u8, rest, "--")) 2 else 0,
476
+ else => 0,
477
+ };
478
+ }
479
+
480
+ fn hasBlockComments(language: Language) bool {
481
+ return switch (language) {
482
+ .zig, .javascript, .typescript, .jsx, .tsx, .rust, .c_like, .go, .css, .sql => true,
483
+ else => false,
484
+ };
485
+ }
486
+
487
+ /// Add one token, coalescing adjacent tokens with the same color. The
488
+ /// final slot is a plain-syntax remainder, so capacity never drops source.
489
+ fn appendSpan(
490
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
491
+ len: *usize,
492
+ source: []const u8,
493
+ start: usize,
494
+ end: usize,
495
+ color: ?text_spans.TextSpanColor,
496
+ ) bool {
497
+ if (end <= start) return true;
498
+ if (len.* > 0) {
499
+ const previous = &storage[len.* - 1];
500
+ if (previous.color == color and previous.text.ptr + previous.text.len == source[start..].ptr) {
501
+ previous.text = previous.text.ptr[0 .. previous.text.len + end - start];
502
+ return true;
503
+ }
504
+ }
505
+ if (len.* + 1 >= storage.len) {
506
+ storage[len.*] = .{ .text = source[start..], .monospace = true, .color = .syntax_plain };
507
+ len.* += 1;
508
+ return false;
509
+ }
510
+ storage[len.*] = .{ .text = source[start..end], .monospace = true, .color = color };
511
+ len.* += 1;
512
+ return true;
513
+ }
514
+
515
+ fn appendMarkdownSpan(
516
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
517
+ len: *usize,
518
+ source: []const u8,
519
+ start: usize,
520
+ end: usize,
521
+ color: text_spans.TextSpanColor,
522
+ styling_full: *bool,
523
+ ) void {
524
+ if (styling_full.*) return;
525
+ if (!appendSpan(storage, len, source, start, end, color)) styling_full.* = true;
526
+ }
527
+
528
+ fn markdownDelimiterRun(source: []const u8, start: usize, byte: u8) usize {
529
+ var end = start;
530
+ while (end < source.len and source[end] == byte) end += 1;
531
+ return end - start;
532
+ }
533
+
534
+ fn markdownFenceLine(
535
+ source: []const u8,
536
+ start: usize,
537
+ state: HighlightState,
538
+ ) ?struct { marker_start: usize, marker_end: usize, line_end: usize, closes: bool } {
539
+ var marker_start = start;
540
+ var indent: usize = 0;
541
+ while (marker_start < source.len and indent < 3 and source[marker_start] == ' ') : (indent += 1) marker_start += 1;
542
+ if (marker_start >= source.len) return null;
543
+ const byte = source[marker_start];
544
+ if (byte != '`' and byte != '~') return null;
545
+ const run = markdownDelimiterRun(source, marker_start, byte);
546
+ if (run < 3) return null;
547
+
548
+ const line_break = std.mem.indexOfScalarPos(u8, source, marker_start + run, '\n');
549
+ const line_end = if (line_break) |newline| newline + 1 else source.len;
550
+ if (state.markdown_fence_byte == 0) {
551
+ return .{ .marker_start = marker_start, .marker_end = marker_start + run, .line_end = line_end, .closes = false };
552
+ }
553
+ if (byte != state.markdown_fence_byte or run < state.markdown_fence_len) return null;
554
+ const suffix_end = if (line_break) |newline| newline else source.len;
555
+ if (std.mem.trim(u8, source[marker_start + run .. suffix_end], " \t\r").len != 0) return null;
556
+ return .{ .marker_start = marker_start, .marker_end = marker_start + run, .line_end = line_end, .closes = true };
557
+ }
558
+
559
+ fn markdownListMarkerEnd(source: []const u8, start: usize) ?usize {
560
+ if (start >= source.len) return null;
561
+ if ((source[start] == '-' or source[start] == '+' or source[start] == '*') and
562
+ start + 1 < source.len and (source[start + 1] == ' ' or source[start + 1] == '\t'))
563
+ {
564
+ return start + 1;
565
+ }
566
+ if (!std.ascii.isDigit(source[start])) return null;
567
+ var end = start + 1;
568
+ while (end < source.len and std.ascii.isDigit(source[end])) end += 1;
569
+ if (end >= source.len or (source[end] != '.' and source[end] != ')')) return null;
570
+ if (end + 1 >= source.len or (source[end + 1] != ' ' and source[end + 1] != '\t')) return null;
571
+ return end + 1;
572
+ }
573
+
574
+ fn markdownInlineCodeEnd(source: []const u8, start: usize, delimiter_len: usize) ?usize {
575
+ var cursor = start;
576
+ while (cursor < source.len) {
577
+ if (source[cursor] == '`') {
578
+ const run = markdownDelimiterRun(source, cursor, '`');
579
+ if (run == delimiter_len) return cursor + run;
580
+ cursor += run;
581
+ continue;
582
+ }
583
+ cursor += 1;
584
+ }
585
+ return null;
586
+ }
587
+
588
+ fn highlightMarkdownWithState(
589
+ source: []const u8,
590
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
591
+ state: *HighlightState,
592
+ ) []const TextSpan {
593
+ var len: usize = 0;
594
+ var styling_full = false;
595
+ var index: usize = 0;
596
+ while (index < source.len) {
597
+ if (state.markdown_line_start) {
598
+ if (markdownFenceLine(source, index, state.*)) |fence| {
599
+ appendMarkdownSpan(storage, &len, source, index, fence.marker_start, .syntax_plain, &styling_full);
600
+ appendMarkdownSpan(storage, &len, source, fence.marker_start, fence.marker_end, .syntax_keyword, &styling_full);
601
+ appendMarkdownSpan(storage, &len, source, fence.marker_end, fence.line_end, if (fence.closes) .syntax_plain else .syntax_constant, &styling_full);
602
+ if (fence.closes) {
603
+ state.markdown_fence_byte = 0;
604
+ state.markdown_fence_len = 0;
605
+ } else {
606
+ state.markdown_fence_byte = source[fence.marker_start];
607
+ state.markdown_fence_len = @intCast(@min(fence.marker_end - fence.marker_start, std.math.maxInt(u8)));
608
+ }
609
+ state.markdown_line_start = fence.line_end > fence.marker_end and source[fence.line_end - 1] == '\n';
610
+ index = fence.line_end;
611
+ continue;
612
+ }
613
+ if (state.markdown_fence_byte != 0) {
614
+ const newline = std.mem.indexOfScalarPos(u8, source, index, '\n');
615
+ const end = if (newline) |line_break| line_break + 1 else source.len;
616
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_literal, &styling_full);
617
+ state.markdown_line_start = newline != null;
618
+ index = end;
619
+ continue;
620
+ }
621
+
622
+ var content = index;
623
+ var indent: usize = 0;
624
+ while (content < source.len and indent < 3 and source[content] == ' ') : (indent += 1) content += 1;
625
+ appendMarkdownSpan(storage, &len, source, index, content, .syntax_plain, &styling_full);
626
+ if (content < source.len and source[content] == '#') {
627
+ const run = markdownDelimiterRun(source, content, '#');
628
+ if (run <= 6 and content + run < source.len and (source[content + run] == ' ' or source[content + run] == '\t')) {
629
+ appendMarkdownSpan(storage, &len, source, content, content + run, .syntax_keyword, &styling_full);
630
+ index = content + run;
631
+ state.markdown_line_start = false;
632
+ continue;
633
+ }
634
+ }
635
+ if (content < source.len and source[content] == '>') {
636
+ appendMarkdownSpan(storage, &len, source, content, content + 1, .syntax_keyword, &styling_full);
637
+ index = content + 1;
638
+ state.markdown_line_start = false;
639
+ continue;
640
+ }
641
+ if (markdownListMarkerEnd(source, content)) |marker_end| {
642
+ appendMarkdownSpan(storage, &len, source, content, marker_end, .syntax_keyword, &styling_full);
643
+ index = marker_end;
644
+ state.markdown_line_start = false;
645
+ continue;
646
+ }
647
+ index = content;
648
+ state.markdown_line_start = false;
649
+ if (index >= source.len) break;
650
+ }
651
+
652
+ if (source[index] == '\n') {
653
+ appendMarkdownSpan(storage, &len, source, index, index + 1, .syntax_plain, &styling_full);
654
+ index += 1;
655
+ state.markdown_line_start = true;
656
+ continue;
657
+ }
658
+ if (state.html_comment) {
659
+ const closing = std.mem.indexOfPos(u8, source, index, "-->");
660
+ const end = if (closing) |close| close + 3 else source.len;
661
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_comment, &styling_full);
662
+ state.html_comment = closing == null;
663
+ index = end;
664
+ continue;
665
+ }
666
+ if (std.mem.startsWith(u8, source[index..], "<!--")) {
667
+ const closing = std.mem.indexOfPos(u8, source, index + 4, "-->");
668
+ const end = if (closing) |close| close + 3 else source.len;
669
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_comment, &styling_full);
670
+ state.html_comment = closing == null;
671
+ index = end;
672
+ continue;
673
+ }
674
+ if (state.markdown_inline_code_len != 0) {
675
+ const delimiter_len = state.markdown_inline_code_len;
676
+ if (markdownInlineCodeEnd(source, index, delimiter_len)) |end| {
677
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_literal, &styling_full);
678
+ state.markdown_inline_code_len = 0;
679
+ index = end;
680
+ } else {
681
+ appendMarkdownSpan(storage, &len, source, index, source.len, .syntax_literal, &styling_full);
682
+ index = source.len;
683
+ }
684
+ continue;
685
+ }
686
+ if (source[index] == '`') {
687
+ const delimiter_len = markdownDelimiterRun(source, index, '`');
688
+ const content_start = index + delimiter_len;
689
+ if (markdownInlineCodeEnd(source, content_start, delimiter_len)) |end| {
690
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_literal, &styling_full);
691
+ state.markdown_inline_code_len = 0;
692
+ index = end;
693
+ } else {
694
+ appendMarkdownSpan(storage, &len, source, index, source.len, .syntax_literal, &styling_full);
695
+ state.markdown_inline_code_len = @intCast(@min(delimiter_len, std.math.maxInt(u8)));
696
+ index = source.len;
697
+ }
698
+ continue;
699
+ }
700
+ if (source[index] == '\\' and index + 1 < source.len) {
701
+ appendMarkdownSpan(storage, &len, source, index, index + 2, .syntax_constant, &styling_full);
702
+ index += 2;
703
+ continue;
704
+ }
705
+ if (std.mem.startsWith(u8, source[index..], "![")) {
706
+ appendMarkdownSpan(storage, &len, source, index, index + 2, .syntax_keyword, &styling_full);
707
+ index += 2;
708
+ continue;
709
+ }
710
+ if (source[index] == '[' or source[index] == ']') {
711
+ appendMarkdownSpan(storage, &len, source, index, index + 1, .syntax_property, &styling_full);
712
+ index += 1;
713
+ continue;
714
+ }
715
+ if (source[index] == '(' and index > 0 and source[index - 1] == ']') {
716
+ const close = std.mem.indexOfScalarPos(u8, source, index + 1, ')');
717
+ const end = if (close) |value| value + 1 else source.len;
718
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_literal, &styling_full);
719
+ index = end;
720
+ continue;
721
+ }
722
+ if (source[index] == '<' and
723
+ (std.mem.startsWith(u8, source[index..], "<http://") or std.mem.startsWith(u8, source[index..], "<https://")))
724
+ {
725
+ const close = std.mem.indexOfScalarPos(u8, source, index + 1, '>');
726
+ const end = if (close) |value| value + 1 else source.len;
727
+ appendMarkdownSpan(storage, &len, source, index, end, .syntax_literal, &styling_full);
728
+ index = end;
729
+ continue;
730
+ }
731
+ if (source[index] == '*' or source[index] == '_' or source[index] == '~') {
732
+ const run = @min(markdownDelimiterRun(source, index, source[index]), 2);
733
+ appendMarkdownSpan(storage, &len, source, index, index + run, .syntax_keyword, &styling_full);
734
+ index += run;
735
+ continue;
736
+ }
737
+
738
+ const start = index;
739
+ while (index < source.len and
740
+ source[index] != '\n' and source[index] != '`' and source[index] != '\\' and
741
+ source[index] != '[' and source[index] != ']' and source[index] != '(' and
742
+ source[index] != '<' and source[index] != '*' and source[index] != '_' and source[index] != '~')
743
+ {
744
+ index += 1;
745
+ }
746
+ if (index == start) index += 1;
747
+ appendMarkdownSpan(storage, &len, source, start, index, .syntax_plain, &styling_full);
748
+ }
749
+ return storage[0..len];
750
+ }
751
+
752
+ /// Tokenize `source` into theme-colored monospace spans.
753
+ pub fn highlight(
754
+ source: []const u8,
755
+ language: Language,
756
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
757
+ ) []const TextSpan {
758
+ var state: HighlightState = .{};
759
+ return highlightWithState(source, language, storage, &state);
760
+ }
761
+
762
+ /// Stateful form used when one code surface emits multiple bounded
763
+ /// paragraphs. Each chunk gets the full span capacity while lexer context
764
+ /// survives into the next chunk.
765
+ pub fn highlightWithState(
766
+ source: []const u8,
767
+ language: Language,
768
+ storage: *[text_spans.max_text_spans_per_paragraph]TextSpan,
769
+ state: *HighlightState,
770
+ ) []const TextSpan {
771
+ if (source.len == 0) return &.{};
772
+ if (language == .plain) {
773
+ storage[0] = .{ .text = source, .monospace = true, .color = .syntax_plain };
774
+ return storage[0..1];
775
+ }
776
+ if (language == .markdown) return highlightMarkdownWithState(source, storage, state);
777
+
778
+ var len: usize = 0;
779
+ var styling_full = false;
780
+ var index: usize = 0;
781
+ while (index < source.len) {
782
+ const start = index;
783
+ const rest = source[index..];
784
+ var color: ?text_spans.TextSpanColor = .syntax_plain;
785
+
786
+ // Artificial presentation chunks can end in the middle of a
787
+ // logical source line. A real newline ends the two line-scoped
788
+ // states before ordinary token dispatch handles that byte.
789
+ if (rest[0] == '\n') {
790
+ state.line_comment = false;
791
+ state.preprocessor_line = false;
792
+ }
793
+
794
+ if (state.line_comment) {
795
+ while (index < source.len and source[index] != '\n') index += 1;
796
+ state.line_comment = index == source.len;
797
+ color = .syntax_comment;
798
+ } else if (state.preprocessor_line) {
799
+ while (index < source.len and source[index] != '\n') index += 1;
800
+ state.preprocessor_line = index == source.len;
801
+ color = .syntax_constant;
802
+ } else if (state.html_comment) {
803
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "-->")) index += 1;
804
+ if (index < source.len) {
805
+ index = @min(source.len, index + 3);
806
+ state.html_comment = false;
807
+ }
808
+ color = .syntax_comment;
809
+ } else if (state.block_comment) {
810
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "*/")) index += 1;
811
+ if (index < source.len) {
812
+ index = @min(source.len, index + 2);
813
+ state.block_comment = false;
814
+ }
815
+ color = .syntax_comment;
816
+ } else if (state.string_quote) |quote| {
817
+ var closed = false;
818
+ while (index < source.len) {
819
+ if (source[index] == '\\' and
820
+ backslashEscapesQuote(language, state.*, quote) and
821
+ index + 1 < source.len)
822
+ {
823
+ index += 2;
824
+ continue;
825
+ }
826
+ const byte = source[index];
827
+ index += 1;
828
+ if (byte == quote) {
829
+ closed = true;
830
+ break;
831
+ }
832
+ }
833
+ if (closed) state.string_quote = null;
834
+ color = .syntax_literal;
835
+ } else if (language == .html and std.mem.startsWith(u8, rest, "<!--")) {
836
+ index += 4;
837
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "-->")) index += 1;
838
+ if (index < source.len) {
839
+ index = @min(source.len, index + 3);
840
+ } else {
841
+ state.html_comment = true;
842
+ }
843
+ color = .syntax_comment;
844
+ } else if (hasBlockComments(language) and std.mem.startsWith(u8, rest, "/*")) {
845
+ index += 2;
846
+ while (index < source.len and !std.mem.startsWith(u8, source[index..], "*/")) index += 1;
847
+ if (index < source.len) {
848
+ index = @min(source.len, index + 2);
849
+ } else {
850
+ state.block_comment = true;
851
+ }
852
+ color = .syntax_comment;
853
+ } else if (lineCommentPrefix(language, source, index) != 0) {
854
+ while (index < source.len and source[index] != '\n') index += 1;
855
+ state.line_comment = index == source.len;
856
+ color = .syntax_comment;
857
+ } else if (language == .c_like and rest[0] == '#') {
858
+ while (index < source.len and source[index] != '\n') index += 1;
859
+ state.preprocessor_line = index == source.len;
860
+ color = .syntax_constant;
861
+ } else if (isHtmlFamily(language) and
862
+ rest[0] == '<' and
863
+ htmlLessThanStartsTag(source, index, language, state.*))
864
+ {
865
+ index += 1;
866
+ const opener = if (index < source.len) source[index] else 0;
867
+ const closing = opener == '/';
868
+ if (closing) index += 1;
869
+ pushHtmlTagContext(state);
870
+ state.html_in_tag = true;
871
+ state.html_expect_tag_name = true;
872
+ state.html_tag_expression_base = state.html_expression_depth;
873
+ state.html_tag_opened_element = false;
874
+ if (closing) {
875
+ if (state.html_element_len > 0) state.html_element_len -= 1;
876
+ } else if ((identifierStart(opener) or opener == '>') and
877
+ state.html_element_len < state.html_element_expression_bases.len)
878
+ {
879
+ state.html_element_expression_bases[state.html_element_len] = state.html_expression_depth;
880
+ state.html_element_len += 1;
881
+ state.html_tag_opened_element = true;
882
+ }
883
+ color = .syntax_plain;
884
+ } else if (isHtmlFamily(language) and
885
+ state.html_in_tag and
886
+ state.html_expression_depth == state.html_tag_expression_base and
887
+ rest[0] == '>')
888
+ {
889
+ if (state.html_tag_opened_element and index > 0 and source[index - 1] == '/' and state.html_element_len > 0) {
890
+ state.html_element_len -= 1;
891
+ }
892
+ index += 1;
893
+ if (!restoreHtmlTagContext(state)) {
894
+ state.html_in_tag = false;
895
+ state.html_expect_tag_name = false;
896
+ state.html_tag_opened_element = false;
897
+ }
898
+ color = .syntax_plain;
899
+ } else if (isHtmlFamily(language) and rest[0] == '{') {
900
+ index += 1;
901
+ state.html_expression_depth += 1;
902
+ color = .syntax_plain;
903
+ } else if (isHtmlFamily(language) and state.html_expression_depth > 0 and rest[0] == '}') {
904
+ index += 1;
905
+ state.html_expression_depth -= 1;
906
+ color = .syntax_plain;
907
+ } else if (if (language == .rust) rustCharLiteralLength(rest) else null) |literal_len| {
908
+ index += literal_len;
909
+ color = .syntax_literal;
910
+ } else if (if (language == .yaml) yamlMappingKeyEnd(source, index) else null) |key_end| {
911
+ index = key_end;
912
+ color = .syntax_property;
913
+ } else if (language == .yaml and yamlDocumentMarkerLength(rest) != 0) {
914
+ index += yamlDocumentMarkerLength(rest);
915
+ color = .syntax_keyword;
916
+ } else if (language == .yaml and
917
+ (rest[0] == '&' or rest[0] == '*' or rest[0] == '!' or rest[0] == '%'))
918
+ {
919
+ index = yamlSymbolEnd(source, index);
920
+ color = .syntax_constant;
921
+ } else if (language == .yaml and rest[0] == '~') {
922
+ index += 1;
923
+ color = .syntax_literal;
924
+ } else if (language == .yaml and (rest[0] == '|' or rest[0] == '>')) {
925
+ index += 1;
926
+ color = .syntax_keyword;
927
+ } else if (stringQuote(language, rest[0]) or
928
+ (isHtmlFamily(language) and
929
+ (state.html_in_tag or state.html_expression_depth > 0) and
930
+ (rest[0] == '"' or rest[0] == '\'' or rest[0] == '`')))
931
+ {
932
+ const quote = rest[0];
933
+ index += 1;
934
+ var closed = false;
935
+ while (index < source.len) {
936
+ if (source[index] == '\\' and
937
+ backslashEscapesQuote(language, state.*, quote) and
938
+ index + 1 < source.len)
939
+ {
940
+ index += 2;
941
+ continue;
942
+ }
943
+ const byte = source[index];
944
+ index += 1;
945
+ if (byte == quote) {
946
+ closed = true;
947
+ break;
948
+ }
949
+ }
950
+ if (!closed) state.string_quote = quote;
951
+ color = .syntax_literal;
952
+ } else if (std.ascii.isDigit(rest[0])) {
953
+ index += 1;
954
+ while (index < source.len) {
955
+ const byte = source[index];
956
+ if (!(std.ascii.isAlphanumeric(byte) or byte == '_' or byte == '.')) break;
957
+ index += 1;
958
+ }
959
+ color = .syntax_literal;
960
+ } else if (identifierStart(rest[0])) {
961
+ index += 1;
962
+ while (index < source.len and
963
+ (identifierContinue(source[index]) or
964
+ ((language == .css or
965
+ (isHtmlFamily(language) and state.html_in_tag)) and
966
+ source[index] == '-')))
967
+ {
968
+ index += 1;
969
+ }
970
+ if (isHtmlFamily(language) and state.html_in_tag) {
971
+ if (state.html_expect_tag_name) {
972
+ color = .syntax_literal;
973
+ state.html_expect_tag_name = false;
974
+ } else if (state.html_expression_depth == state.html_tag_expression_base) {
975
+ color = .syntax_function;
976
+ } else {
977
+ const script_language = embeddedScriptLanguage(language);
978
+ color = wordColor(script_language, source[start..index]) orelse
979
+ identifierStructuralColor(script_language, source, index) orelse
980
+ .syntax_plain;
981
+ }
982
+ } else if (isHtmlFamily(language) and
983
+ (state.html_expression_depth > 0 or language == .jsx or language == .tsx))
984
+ {
985
+ const script_language = embeddedScriptLanguage(language);
986
+ color = wordColor(script_language, source[start..index]) orelse
987
+ identifierStructuralColor(script_language, source, index) orelse
988
+ .syntax_plain;
989
+ } else {
990
+ color = wordColor(language, source[start..index]) orelse
991
+ identifierStructuralColor(language, source, index) orelse
992
+ .syntax_plain;
993
+ }
994
+ } else {
995
+ index += 1;
996
+ }
997
+
998
+ if (isHtmlFamily(language)) updateHtmlPreviousSignificant(state, source[start..index]);
999
+
1000
+ // The last span already covers the entire plain-syntax remainder once
1001
+ // capacity fills, but keep scanning it so state handed to the next
1002
+ // paragraph still reflects comments, strings, and JSX expressions.
1003
+ if (!styling_full and !appendSpan(storage, &len, source, start, index, color)) {
1004
+ styling_full = true;
1005
+ }
1006
+ }
1007
+ return storage[0..len];
1008
+ }