Public: anyone can read this; the crew can change it.

src/tui/screens/workspace.ts and src/web/highlight.ts split by concept, highlighter grammars loaded only for the file kind opened #16784

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/15369-src-tui-screens-workspace-ts-and-src-web → main 0 commits fork

  • Merged. mason/15369-src-tui-screens-workspace-ts-and-src-web was merged into main as f8c6a37.

Review

Sign in to review this change.
18 files changed +2596 −2478
src/web/highlight.ts +14 −2478
@@ -25,2484 +25,20 @@
2525 * web paints on top (a regex is a string; a tag is a keyword; a property is a
2626 * keyword). A consumer that knows only `cls` still renders correctly, which is
2727 * why the richer web palette costs the terminal nothing.
28 */
29
30 export type TokenClass =
31 | "keyword"
32 | "string"
33 | "comment"
34 | "number"
35 | "function"
36 | "type"
37 | "operator"
38 | "punctuation"
39 | "constant"
40 | "meta"
41 | "plain";
42
43 /**
44 * A refinement of `cls`. Optional by design: dropping it must never make a
45 * line wrong, only less specific.
46 */
47 export type TokenKind =
48 | "property"
49 | "tag"
50 | "attribute"
51 | "regex"
52 | "variable"
53 | "decorator"
54 | "heading"
55 | "emphasis"
56 | "link"
57 | "inserted"
58 | "deleted";
59
60 export interface Token {
61 readonly cls: TokenClass;
62 readonly text: string;
63 readonly kind?: TokenKind;
64 }
65
66 export type Language =
67 | "ts"
68 | "python"
69 | "go"
70 | "rust"
71 | "c"
72 | "java"
73 | "kotlin"
74 | "swift"
75 | "ruby"
76 | "php"
77 | "lua"
78 | "zig"
79 | "elixir"
80 | "nix"
81 | "json"
82 | "yaml"
83 | "toml"
84 | "ini"
85 | "markdown"
86 | "css"
87 | "html"
88 | "shell"
89 | "sql"
90 | "dockerfile"
91 | "makefile"
92 | "diff"
93 | "plain";
94
95 // ---- tokens ----
96
97 function tok(cls: TokenClass, text: string, kind?: TokenKind): Token {
98 return kind === undefined ? { cls, text } : { cls, text, kind };
99 }
100
101 /** A blank line still needs one (empty) token so line counts stay aligned. */
102 function emptySafe(tokens: Token[]): Token[] {
103 return tokens.length > 0 ? tokens : [tok("plain", "")];
104 }
105
106 /**
107 * The sink every scanner writes through. It merges runs of the same
108 * (class, kind) so a line of punctuation is one token, not forty.
109 */
110 class Out {
111 readonly tokens: Token[] = [];
112 push(cls: TokenClass, text: string, kind?: TokenKind): void {
113 if (text === "") return;
114 const last = this.tokens[this.tokens.length - 1];
115 if (last && last.cls === cls && last.kind === kind) {
116 this.tokens[this.tokens.length - 1] = tok(cls, last.text + text, kind);
117 return;
118 }
119 this.tokens.push(tok(cls, text, kind));
120 }
121 /** Append another scanner's output (an embedded language's line). */
122 take(tokens: readonly Token[]): void {
123 for (const t of tokens) this.push(t.cls, t.text, t.kind);
124 }
125 done(): Token[] {
126 return emptySafe(this.tokens);
127 }
128 }
129
130 // ---- character classes (charCode, not regex: these run per character) ----
131
132 const SPACE = 32,
133 TAB = 9,
134 CR = 13;
135 const isSpaceCh = (c: number): boolean => c === SPACE || c === TAB || c === CR;
136 const isDigitCh = (c: number): boolean => c >= 48 && c <= 57;
137 const isUpperCh = (c: number): boolean => c >= 65 && c <= 90;
138 const isAlphaCh = (c: number): boolean =>
139 isUpperCh(c) || (c >= 97 && c <= 122) || c > 127;
140 const isIdentCh = (c: number): boolean =>
141 isAlphaCh(c) || isDigitCh(c) || c === 95;
142
143 const set = (words: string): Set<string> =>
144 new Set(words.split(/\s+/).filter(Boolean));
145
146 // ---- state carried across lines ----
147
148 interface StrState {
149 /** The delimiter that closes it. */
150 close: string;
151 escape: boolean;
152 /** `${…}` (or `#{…}`) inside is code, not string. */
153 interpolate?: boolean;
154 interpolateAs?: "code" | "variable";
155 }
156
157 interface Heredoc {
158 tag: string;
159 /** `<<~` / `<<-`: the terminator may be indented. */
160 indent: boolean;
161 }
162
163 interface Embed {
164 lang: Language;
165 /** The fence or closing tag that ends it, matched per language. */
166 end: string;
167 inner: ScanState;
168 }
169
170 export interface ScanState {
171 /** Inside a block comment. */
172 readonly block: boolean;
173 /** Inside a multi-line string. */
174 readonly str: StrState | null;
175 /** Waiting for a heredoc terminator. */
176 readonly heredoc: Heredoc | null;
177 /** A fenced code block, or an HTML `<script>`/`<style>` body. */
178 readonly embed: Embed | null;
179 /** YAML block scalar: lines indented past this column are string. */
180 readonly scalar: number | null;
181 /** HTML: inside a tag's attribute list. */
182 readonly tag: boolean;
183 /** CSS: brace depth, which decides selector context from declaration. */
184 readonly depth: number;
185 }
186
187 /** The state a scan of the first line of a file starts from. */
188 export const INITIAL_SCAN: ScanState = {
189 block: false,
190 str: null,
191 heredoc: null,
192 embed: null,
193 scalar: null,
194 tag: false,
195 depth: 0,
196 };
197
198 interface Scanned {
199 tokens: Token[];
200 state: ScanState;
201 }
202
203 // ---- language specs ----
204
205 interface StrSpec {
206 open: string;
207 close: string;
208 escape: boolean;
209 /** Stays open across newlines (template literals, `"""`, backticks). */
210 multiline: boolean;
211 /** `${…}`/`#{…}` inside is code. */
212 interpolate?: boolean;
213 /** Shell-ish strings paint `$x` as a variable; template literals as code. */
214 interpolateAs?: "code" | "variable";
215 /** Only opens where a value is expected (regex literals). */
216 valueOnly?: boolean;
217 /** What to paint it as; strings by default. */
218 cls?: TokenClass;
219 kind?: TokenKind;
220 }
221
222 interface LangSpec {
223 lineComment: string[];
224 blockComment?: [string, string];
225 strings: StrSpec[];
226 keywords: Set<string>;
227 types: Set<string>;
228 constants: Set<string>;
229 /** An identifier followed by "(" is rendered as a function. */
230 callAsFunction: boolean;
231 /** Capitalized identifiers read as types. False for shells and SQL. */
232 capitalIsType?: boolean;
233 /** Keywords match regardless of case (SQL). */
234 ignoreCase?: boolean;
235 /** `/…/` is a regex where a value is expected. */
236 regex?: boolean;
237 /** `<div …>` is markup where a value is expected (JSX). */
238 jsx?: boolean;
239 /** Characters that begin a variable: `$`, `@`, `%`. */
240 sigils?: string;
241 /** `@name` is a decorator/annotation. */
242 atDecorator?: boolean;
243 /** `#[…]` is an attribute (Rust), `#!…` too. */
244 hashAttr?: boolean;
245 /** `foo.bar` paints `bar` as a property. */
246 dotProperty?: boolean;
247 /** `#include`, `#define`: a C preprocessor line. */
248 preproc?: boolean;
249 /** `'a` is a lifetime, not a character literal (Rust). */
250 lifetimes?: boolean;
251 /** `name!`/`name?` end an identifier (Ruby, Elixir, Rust macros). */
252 identTail?: string;
253 /** Extra characters allowed inside an identifier (`-` in CSS-ish langs). */
254 identInner?: string;
255 /** `:atom` / `:symbol` is a constant. */
256 atoms?: boolean;
257 /** `<<EOF` opens a heredoc. */
258 heredoc?: boolean;
259 /** The first word of a command reads as the thing being run. */
260 commandPosition?: boolean;
261 /** `-v` / `--long` read as flags. */
262 flags?: boolean;
263 /** The word after these is a definition name. */
264 defineAfter?: Set<string>;
265 /** The word after these is a type name. */
266 typeAfter?: Set<string>;
267 /** A word in this set followed by `!` is a macro. */
268 macroBang?: boolean;
269 }
270
271 const dq: StrSpec = { open: '"', close: '"', escape: true, multiline: false };
272 const sq: StrSpec = { open: "'", close: "'", escape: true, multiline: false };
273 const tick: StrSpec = {
274 open: "`",
275 close: "`",
276 escape: true,
277 multiline: true,
278 interpolate: true,
279 };
280 const tripleD: StrSpec = {
281 open: '"""',
282 close: '"""',
283 escape: true,
284 multiline: true,
285 };
286 const tripleS: StrSpec = {
287 open: "'''",
288 close: "'''",
289 escape: true,
290 multiline: true,
291 };
292 const regexLit: StrSpec = {
293 open: "/",
294 close: "/",
295 escape: true,
296 multiline: false,
297 valueOnly: true,
298 cls: "string",
299 kind: "regex",
300 };
301
302 const TS_KEYWORDS = `abstract accessor as asserts async await break case catch class const continue
303 debugger declare default delete do else enum export extends finally for from function get if
304 implements import in infer instanceof interface is keyof let module namespace new of out override
305 package private protected public readonly return satisfies set static super switch this throw try
306 type typeof unique var void while with yield`;
307
308 const TS_TYPES = `string number boolean any unknown never void object bigint symbol undefined null
309 Array Promise Record Map Set WeakMap WeakSet Partial Required Readonly Pick Omit Exclude Extract
310 Awaited ReturnType Parameters Date RegExp Error Iterable AsyncIterable Uint8Array ArrayBuffer
311 Function Symbol BigInt`;
312
313 const SPECS: Partial<Record<Language, LangSpec>> = {
314 ts: {
315 lineComment: ["//"],
316 blockComment: ["/*", "*/"],
317 strings: [dq, sq, tick, regexLit],
318 keywords: set(TS_KEYWORDS),
319 types: set(TS_TYPES),
320 constants: set(
321 `true false null undefined NaN Infinity this super arguments`,
322 ),
323 callAsFunction: true,
324 capitalIsType: true,
325 regex: true,
326 jsx: true,
327 atDecorator: true,
328 dotProperty: true,
329 sigils: "#",
330 defineAfter: set(`function class interface type enum namespace`),
331 typeAfter: set(`class interface type enum namespace`),
332 },
333 python: {
334 lineComment: ["#"],
335 strings: [tripleD, tripleS, dq, sq],
336 keywords:
337 set(`and as assert async await break case class continue def del elif else except finally for
338 from global if import in is lambda match nonlocal not or pass raise return try while with yield`),
339 types: set(
340 `int float str bytes bool list dict tuple set frozenset object type bytearray complex range
341 Any Optional Union Callable Iterable Sequence Mapping`,
342 ),
343 constants: set(
344 `True False None NotImplemented Ellipsis self cls __name__ __main__`,
345 ),
346 callAsFunction: true,
347 capitalIsType: true,
348 atDecorator: true,
349 dotProperty: true,
350 defineAfter: set(`def class`),
351 typeAfter: set(`class`),
352 },
353 go: {
354 lineComment: ["//"],
355 blockComment: ["/*", "*/"],
356 strings: [
357 dq,
358 { open: "`", close: "`", escape: false, multiline: true },
359 sq,
360 ],
361 keywords:
362 set(`break case chan const continue default defer else fallthrough for func go goto if
363 import interface map package range return select struct switch type var`),
364 types:
365 set(`bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune
366 string uint uint8 uint16 uint32 uint64 uintptr any comparable`),
367 constants: set(`true false nil iota`),
368 callAsFunction: true,
369 capitalIsType: true,
370 dotProperty: true,
371 defineAfter: set(`func`),
372 typeAfter: set(`type struct interface`),
373 },
374 rust: {
375 lineComment: ["//"],
376 blockComment: ["/*", "*/"],
377 strings: [dq, sq],
378 keywords:
379 set(`as async await break const continue crate dyn else enum extern fn for if impl in let
380 loop match mod move mut pub ref return self Self static struct super trait type unsafe use
381 where while union yield`),
382 types:
383 set(`bool char str String Vec Option Result Box Rc Arc RefCell Cell HashMap HashSet BTreeMap
384 i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64`),
385 constants: set(`true false None Some Ok Err`),
386 callAsFunction: true,
387 capitalIsType: true,
388 lifetimes: true,
389 hashAttr: true,
390 macroBang: true,
391 dotProperty: true,
392 defineAfter: set(`fn`),
393 typeAfter: set(`struct enum trait type impl union`),
394 },
395 c: {
396 lineComment: ["//"],
397 blockComment: ["/*", "*/"],
398 strings: [dq, sq],
399 keywords:
400 set(`alignas alignof asm auto bool break case catch char class co_await co_return co_yield
401 concept const consteval constexpr continue decltype default delete do double dynamic_cast
402 else enum explicit export extern false final float for friend goto if inline int long mutable
403 namespace new noexcept nullptr operator override private protected public register
404 reinterpret_cast requires restrict return short signed sizeof static static_assert
405 static_cast struct switch template this thread_local throw true try typedef typeid typename
406 union unsigned using virtual void volatile wchar_t while
407 id instancetype nonatomic atomic strong weak copy assign retain nullable nonnull`),
408 types:
409 set(`int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t size_t ssize_t ptrdiff_t
410 FILE va_list std string vector map unordered_map shared_ptr unique_ptr NSString NSArray
411 NSDictionary NSInteger NSUInteger BOOL CGFloat`),
412 constants: set(`true false NULL nullptr nil YES NO self super __func__`),
413 callAsFunction: true,
414 capitalIsType: true,
415 preproc: true,
416 atDecorator: true,
417 dotProperty: true,
418 },
419 java: {
420 lineComment: ["//"],
421 blockComment: ["/*", "*/"],
422 strings: [tripleD, dq, sq],
423 keywords:
424 set(`abstract assert break case catch class const continue default do else enum extends final
425 finally for goto if implements import instanceof interface native new package permits private
426 protected public record return sealed static strictfp super switch synchronized this throw
427 throws transient try var void volatile while yield`),
428 types:
429 set(`boolean byte char double float int long short String Object Integer Long Double Boolean
430 List Map Set Optional Stream`),
431 constants: set(`true false null this super`),
432 callAsFunction: true,
433 capitalIsType: true,
434 atDecorator: true,
435 dotProperty: true,
436 defineAfter: set(`class interface enum record`),
437 typeAfter: set(`class interface enum record`),
438 },
439 kotlin: {
440 lineComment: ["//"],
441 blockComment: ["/*", "*/"],
442 strings: [tripleD, dq, sq],
443 keywords:
444 set(`abstract actual annotation as break by catch class companion const constructor continue
445 crossinline data delegate do dynamic else enum expect external final finally for fun get if
446 import in infix init inline inner interface internal is lateinit noinline object open operator
447 out override package private protected public reified return sealed set super suspend tailrec
448 this throw try typealias val var vararg when where while`),
449 types:
450 set(`Any Boolean Byte Char Double Float Int Long Nothing Number Short String Unit List Map Set
451 MutableList MutableMap Array Sequence`),
452 constants: set(`true false null this super it`),
453 callAsFunction: true,
454 capitalIsType: true,
455 atDecorator: true,
456 dotProperty: true,
457 sigils: "$",
458 defineAfter: set(`fun class interface object`),
459 typeAfter: set(`class interface object`),
460 },
461 swift: {
462 lineComment: ["//"],
463 blockComment: ["/*", "*/"],
464 strings: [tripleD, dq],
465 keywords:
466 set(`actor as associatedtype async await break case catch class continue convenience default
467 defer deinit didSet do else enum extension fallthrough fileprivate final for func get guard if
468 import in indirect init inout internal is lazy let mutating nonisolated open operator override
469 private protocol public repeat required rethrows return self set some static struct subscript
470 super switch throw throws try typealias var weak where while willSet unowned`),
471 types:
472 set(`Any AnyObject Array Bool Character Dictionary Double Float Int Int8 Int16 Int32 Int64
473 Optional Set String UInt UInt8 UInt32 UInt64 Void Result Data URL`),
474 constants: set(`true false nil self Self super`),
475 callAsFunction: true,
476 capitalIsType: true,
477 atDecorator: true,
478 dotProperty: true,
479 defineAfter: set(`func class struct enum protocol extension actor`),
480 typeAfter: set(`class struct enum protocol extension actor`),
481 },
482 ruby: {
483 lineComment: ["#"],
484 strings: [
485 dq,
486 sq,
487 { open: "%w[", close: "]", escape: false, multiline: false },
488 ],
489 keywords:
490 set(`alias and begin break case class def defined? do else elsif end ensure for if in module
491 next nil not or redo rescue retry return self super then undef unless until when while yield
492 lambda proc require require_relative include extend attr_accessor attr_reader attr_writer
493 private protected public raise puts new`),
494 types: set(
495 `String Symbol Integer Float Array Hash Struct Class Module Proc Range Time`,
496 ),
497 constants: set(`true false nil self __FILE__ __dir__`),
498 callAsFunction: true,
499 capitalIsType: true,
500 sigils: "@$",
501 atoms: true,
502 heredoc: true,
503 regex: true,
504 identTail: "?!",
505 dotProperty: true,
506 defineAfter: set(`def`),
507 typeAfter: set(`class module`),
508 },
509 php: {
510 lineComment: ["//", "#"],
511 blockComment: ["/*", "*/"],
512 strings: [dq, sq],
513 keywords:
514 set(`abstract and array as break callable case catch class clone const continue declare
515 default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum
516 extends final finally fn for foreach function global goto if implements include include_once
517 instanceof insteadof interface isset list match namespace new or print private protected
518 public readonly require require_once return static switch throw trait try unset use var while
519 xor yield`),
520 types: set(
521 `int float string bool array object callable iterable void mixed never self static`,
522 ),
523 constants: set(`true false null TRUE FALSE NULL $this`),
524 callAsFunction: true,
525 capitalIsType: true,
526 sigils: "$",
527 atDecorator: true,
528 dotProperty: true,
529 defineAfter: set(`function class interface trait enum`),
530 typeAfter: set(`class interface trait enum`),
531 },
532 lua: {
533 lineComment: ["--"],
534 blockComment: ["--[[", "]]"],
535 strings: [
536 dq,
537 sq,
538 { open: "[[", close: "]]", escape: false, multiline: true },
539 ],
540 keywords:
541 set(`and break do else elseif end false for function goto if in local nil not or repeat
542 return then true until while`),
543 types: set(`string table math io os coroutine debug utf8`),
544 constants: set(`true false nil self _G _ENV`),
545 callAsFunction: true,
546 capitalIsType: false,
547 dotProperty: true,
548 defineAfter: set(`function`),
549 },
550 zig: {
551 lineComment: ["//"],
552 strings: [dq, sq],
553 keywords:
554 set(`align allowzero and anyframe anytype asm async await break callconv catch comptime const
555 continue defer else enum errdefer error export extern fn for if inline noalias nosuspend
556 opaque or orelse packed pub resume return linksection struct suspend switch test threadlocal
557 try union unreachable usingnamespace var volatile while`),
558 types:
559 set(`bool void noreturn type anyerror comptime_int comptime_float u8 u16 u32 u64 u128 usize
560 i8 i16 i32 i64 i128 isize f16 f32 f64 f128 c_int c_uint`),
561 constants: set(`true false null undefined`),
562 callAsFunction: true,
563 capitalIsType: true,
564 atDecorator: true,
565 dotProperty: true,
566 defineAfter: set(`fn`),
567 },
568 elixir: {
569 lineComment: ["#"],
570 strings: [tripleD, dq, sq],
571 keywords:
572 set(`after alias and case catch cond def defdelegate defexception defguard defimpl defmacro
573 defmodule defp defprotocol defstruct do else end fn for if import in not or quote raise
574 receive require rescue try unless unquote use when with`),
575 types: set(
576 `Enum Map List String Atom Integer Float Process Task Agent GenServer Supervisor`,
577 ),
578 constants: set(`true false nil __MODULE__ __ENV__`),
579 callAsFunction: true,
580 capitalIsType: true,
581 sigils: "@",
582 atoms: true,
583 identTail: "?!",
584 dotProperty: true,
585 defineAfter: set(`def defp defmacro defmodule defstruct defguard`),
586 typeAfter: set(`defmodule defprotocol defimpl`),
587 },
588 nix: {
589 lineComment: ["#"],
590 blockComment: ["/*", "*/"],
591 strings: [
592 {
593 open: "''",
594 close: "''",
595 escape: false,
596 multiline: true,
597 interpolate: true,
598 },
599 {
600 open: '"',
601 close: '"',
602 escape: true,
603 multiline: false,
604 interpolate: true,
605 },
606 ],
607 keywords: set(`assert else if in inherit let or rec then with import`),
608 types: set(`builtins pkgs lib stdenv fetchurl mkDerivation`),
609 constants: set(`true false null`),
610 callAsFunction: false,
611 capitalIsType: false,
612 identInner: "-",
613 dotProperty: true,
614 },
615 json: {
616 // JSON proper has no comments; JSONC does, and a `//` outside a string is
617 // never valid JSON anyway, so accepting one costs nothing and helps.
618 lineComment: ["//"],
619 blockComment: ["/*", "*/"],
620 strings: [dq],
621 keywords: set(``),
622 types: set(``),
623 constants: set(`true false null`),
624 callAsFunction: false,
625 capitalIsType: false,
626 },
627 sql: {
628 lineComment: ["--", "#"],
629 blockComment: ["/*", "*/"],
630 strings: [
631 sq,
632 { open: "`", close: "`", escape: false, multiline: false },
633 dq,
634 ],
635 keywords:
636 set(`select from where insert into values update set delete create table alter drop index
637 view trigger procedure function returns begin end join left right full inner outer cross on
638 using group by order having limit offset union all as distinct and or not null is primary key
639 foreign references default unique check constraint cascade returning with recursive case when
640 then else exists in between like ilike asc desc count sum avg min max coalesce cast if temp
641 temporary replace grant revoke commit rollback transaction`),
642 types:
643 set(`int integer bigint smallint text varchar char boolean bool date datetime timestamp time
644 real float double blob numeric decimal serial uuid json jsonb bytea interval`),
645 constants: set(
646 `true false null current_timestamp current_date current_user`,
647 ),
648 callAsFunction: true,
649 capitalIsType: false,
650 ignoreCase: true,
651 },
652 shell: {
653 lineComment: ["#"],
654 strings: [
655 {
656 open: '"',
657 close: '"',
658 escape: true,
659 multiline: false,
660 interpolate: true,
661 interpolateAs: "variable",
662 },
663 { open: "'", close: "'", escape: false, multiline: false },
664 ],
665 keywords:
666 set(`if then else elif fi for while do done case esac in function select until return break
667 continue export local readonly declare typeset set unset shift source alias eval exec trap
668 exit time coproc`),
669 types: set(``),
670 constants: set(`true false`),
671 callAsFunction: false,
672 capitalIsType: false,
673 sigils: "$",
674 heredoc: true,
675 identInner: "-.",
676 commandPosition: true,
677 flags: true,
678 },
679 dockerfile: {
680 lineComment: ["#"],
681 strings: [dq, sq],
682 keywords: set(`as`),
683 types: set(``),
684 constants: set(``),
685 callAsFunction: false,
686 capitalIsType: false,
687 sigils: "$",
688 ignoreCase: true,
689 flags: true,
690 },
691 };
692
693 /** Shell words after which the next word is a command again. */
694 const COMMAND_OPENERS = set(
695 `then else elif do done fi in time exec sudo command xargs nohup env watch`,
696 );
697
698 /** Dockerfile instructions, which are only keywords at the start of a line. */
699 const DOCKER_INSTRUCTIONS = set(
700 `FROM RUN CMD LABEL MAINTAINER EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD
701 STOPSIGNAL HEALTHCHECK SHELL`,
702 );
703
704 // ---- language detection ----
705
706 const EXT: Record<string, Language> = {
707 ts: "ts",
708 tsx: "ts",
709 mts: "ts",
710 cts: "ts",
711 js: "ts",
712 jsx: "ts",
713 mjs: "ts",
714 cjs: "ts",
715 py: "python",
716 pyi: "python",
717 pyw: "python",
718 go: "go",
719 rs: "rust",
720 c: "c",
721 h: "c",
722 cc: "c",
723 cpp: "c",
724 cxx: "c",
725 hpp: "c",
726 hh: "c",
727 hxx: "c",
728 m: "c",
729 mm: "c",
730 java: "java",
731 kt: "kotlin",
732 kts: "kotlin",
733 swift: "swift",
734 rb: "ruby",
735 rake: "ruby",
736 gemspec: "ruby",
737 php: "php",
738 lua: "lua",
739 zig: "zig",
740 ex: "elixir",
741 exs: "elixir",
742 nix: "nix",
743 json: "json",
744 jsonc: "json",
745 json5: "json",
746 yaml: "yaml",
747 yml: "yaml",
748 toml: "toml",
749 ini: "ini",
750 cfg: "ini",
751 conf: "ini",
752 properties: "ini",
753 editorconfig: "ini",
754 md: "markdown",
755 markdown: "markdown",
756 mdx: "markdown",
757 css: "css",
758 scss: "css",
759 sass: "css",
760 less: "css",
761 html: "html",
762 htm: "html",
763 xhtml: "html",
764 vue: "html",
765 svelte: "html",
766 xml: "html",
767 svg: "html",
768 sh: "shell",
769 bash: "shell",
770 zsh: "shell",
771 fish: "shell",
772 ksh: "shell",
773 env: "shell",
774 sql: "sql",
775 diff: "diff",
776 patch: "diff",
777 mk: "makefile",
778 make: "makefile",
779 };
780
781 const FILENAMES: Record<string, Language> = {
782 dockerfile: "dockerfile",
783 containerfile: "dockerfile",
784 makefile: "makefile",
785 gnumakefile: "makefile",
786 justfile: "makefile",
787 rakefile: "ruby",
788 gemfile: "ruby",
789 podfile: "ruby",
790 brewfile: "ruby",
791 vagrantfile: "ruby",
792 ".gitignore": "shell",
793 ".dockerignore": "shell",
794 ".gitattributes": "shell",
795 ".npmrc": "ini",
796 ".editorconfig": "ini",
797 ".env": "shell",
798 ".bashrc": "shell",
799 ".bash_profile": "shell",
800 ".zshrc": "shell",
801 ".profile": "shell",
802 ".zprofile": "shell",
803 "cargo.lock": "toml",
804 "go.mod": "go",
805 "go.sum": "plain",
806 "cmakelists.txt": "makefile",
807 };
808
809 const SHEBANG: [RegExp, Language][] = [
810 [/\b(?:python|python3|python2|uv run)\b/, "python"],
811 [/\b(?:node|bun|deno|ts-node)\b/, "ts"],
812 [/\bruby\b/, "ruby"],
813 [/\b(?:bash|zsh|sh|dash|ksh|fish)\b/, "shell"],
814 [/\bphp\b/, "php"],
815 [/\blua\b/, "lua"],
816 [/\belixir\b/, "elixir"],
817 [/\bmake\b/, "makefile"],
818 ];
819
820 const MODELINE_ALIASES: Record<string, Language> = {
821 javascript: "ts",
822 typescript: "ts",
823 js: "ts",
824 ts: "ts",
825 sh: "shell",
826 bash: "shell",
827 zsh: "shell",
828 "shell-script": "shell",
829 conf: "ini",
830 make: "makefile",
831 yml: "yaml",
832 "c++": "c",
833 cpp: "c",
834 objc: "c",
835 rb: "ruby",
836 py: "python",
837 };
838
839 /** Every language this file can highlight — the fence-info vocabulary too. */
840 export const LANGUAGES: readonly Language[] = [
841 "ts",
842 "python",
843 "go",
844 "rust",
845 "c",
846 "java",
847 "kotlin",
848 "swift",
849 "ruby",
850 "php",
851 "lua",
852 "zig",
853 "elixir",
854 "nix",
855 "json",
856 "yaml",
857 "toml",
858 "ini",
859 "markdown",
860 "css",
861 "html",
862 "shell",
863 "sql",
864 "dockerfile",
865 "makefile",
866 "diff",
867 "plain",
868 ];
869
870 /** A language name as a fence info string or a modeline writes it. */
871 export function languageFromName(name: string): Language {
872 const word =
873 name
874 .trim()
875 .toLowerCase()
876 .split(/[\s,;:]/)[0] ?? "";
877 if (word === "") return "plain";
878 const alias = MODELINE_ALIASES[word];
879 if (alias) return alias;
880 if (Object.hasOwn(EXT, word)) return EXT[word]!;
881 if (Object.hasOwn(FILENAMES, word)) return FILENAMES[word]!;
882 return LANGUAGES.includes(word as Language) ? (word as Language) : "plain";
883 }
884
885
886 /**
887 * The language of a file. The extension decides where it can; otherwise the
888 * bare filename (`Dockerfile`, `Makefile`, `.zshrc`), and only then the first
889 * line — a shebang or an editor modeline — which is the one thing a file with
890 * no extension can say about itself.
891 */
892 export function detectLanguage(path: string, firstLine?: string): Language {
893 const name = path.slice(path.lastIndexOf("/") + 1);
894 const lower = name.toLowerCase();
895 const byName = FILENAMES[lower];
896 if (byName) return byName;
897 // `Dockerfile.dev`, `Makefile.local`: the stem still names the language.
898 const stem = lower.split(".")[0] ?? "";
899 const dot = lower.lastIndexOf(".");
900 if (dot > 0) {
901 const byExt = EXT[lower.slice(dot + 1)];
902 if (byExt) return byExt;
903 }
904 if (dot > 0 && FILENAMES[stem] && stem !== "") {
905 const byStem = FILENAMES[stem];
906 if (byStem === "dockerfile" || byStem === "makefile") return byStem;
907 }
908 if (firstLine !== undefined) {
909 const fromLine = languageFromFirstLine(firstLine);
910 if (fromLine !== "plain") return fromLine;
911 }
912 return "plain";
913 }
914
915 /** A shebang (`#!/usr/bin/env python3`) or a modeline (`vim: ft=ruby`). */
916 export function languageFromFirstLine(line: string): Language {
917 const head = line.slice(0, 200);
918 if (head.startsWith("#!")) {
919 for (const [pattern, lang] of SHEBANG) if (pattern.test(head)) return lang;
920 }
921 const vim = /(?:ft|filetype|syntax)=([A-Za-z0-9_+-]+)/.exec(head);
922 if (vim) return languageFromName(vim[1]!);
923 const emacs = /-\*-\s*(?:mode:\s*)?([A-Za-z0-9_+-]+)/.exec(head);
924 if (emacs) return languageFromName(emacs[1]!);
925 if (/^<\?xml|^<!doctype html/i.test(head.trim())) return "html";
926 return "plain";
927 }
928
929 // ---- the entry points ----
930
931 type Scanner = (line: string, state: ScanState) => Scanned;
932
933 function scannerFor(lang: Language): Scanner | null {
934 switch (lang) {
935 case "markdown":
936 return scanMarkdown;
937 case "yaml":
938 return scanYaml;
939 case "toml":
940 return (line, state) => scanToml(line, state, true);
941 case "ini":
942 return (line, state) => scanToml(line, state, false);
943 case "html":
944 return scanHtml;
945 case "css":
946 return scanCss;
947 case "diff":
948 return scanDiff;
949 case "makefile":
950 return scanMakefile;
951 case "dockerfile":
952 return scanDockerfile;
953 default: {
954 const spec = SPECS[lang];
955 return spec ? (line, state) => scanGeneric(line, spec, state) : null;
956 }
957 }
958 }
959
960 /**
961 * Tokenize **one** line, given the state the previous line ended in.
96228 *
963 * `highlightLines` re-tokenizes a whole file, which is right for a page that
964 * renders one. An editor is the other case: a keystroke changes one line, and
965 * re-scanning ten thousand of them per character is the difference between an
966 * editor that feels instant and one that does not. So the primitive the whole
967 * file walk is already built on is offered directly, and a caller that keeps a
968 * `ScanState[]` beside its lines can re-scan from the edit downward until the
969 * state converges — usually one line, unbounded only inside an unterminated
970 * block comment.
29 * This file is the door; the work is in `highlight/`, one module a concept:
30 * `tokens` (the vocabulary and the sink), `state` (what a line hands the
31 * next), `detect` (which language a file is), `scanners` (the entry points), `specs` and
32 * `generic` (the table-driven scanner), and one module for each of Markdown,
33 * YAML, TOML/INI, HTML, CSS, diff, Makefile and Dockerfile.
97134 */
972 export function scanOneLine(
973 line: string,
974 lang: Language,
975 state: ScanState,
976 ): Scanned {
977 const scan = scannerFor(lang);
978 if (!scan) return { tokens: [tok("plain", line)], state };
979 return scan(line, state);
980 }
98135
982 export function highlightLines(code: string, lang: Language): Token[][] {
983 const lines = code.split("\n");
984 const scan = scannerFor(lang);
985 if (!scan) return lines.map((line) => [tok("plain", line)]);
986
987 const out: Token[][] = [];
988 let state: ScanState = INITIAL_SCAN;
989 for (const line of lines) {
990 const scanned = scan(line, state);
991 out.push(scanned.tokens);
992 state = scanned.state;
993 }
994 return out;
995 }
996
997 // ---- shared scanning helpers ----
998
999 /** Consume a string body from `start`, honouring escapes. */
1000 function consumeStringBody(
1001 line: string,
1002 start: number,
1003 spec: { close: string; escape: boolean },
1004 ): { end: number; closed: boolean } {
1005 let i = start;
1006 const n = line.length;
1007 while (i < n) {
1008 if (spec.escape && line.charCodeAt(i) === 92) {
1009 i += 2;
1010 continue;
1011 }
1012 if (line.startsWith(spec.close, i)) {
1013 return { end: i + spec.close.length, closed: true };
1014 }
1015 i++;
1016 }
1017 return { end: n, closed: false };
1018 }
1019
1020 /**
1021 * Emit a string body, breaking out `${…}`/`#{…}` interpolations so the code
1022 * inside a template literal is not painted as prose.
1023 */
1024 function pushString(
1025 out: Out,
1026 text: string,
1027 interpolate: boolean,
1028 cls: TokenClass = "string",
1029 kind?: TokenKind,
1030 as: "code" | "variable" = "code",
1031 ): void {
1032 if (!interpolate || text.length < 2) {
1033 out.push(cls, text, kind);
1034 return;
1035 }
1036 let i = 0;
1037 let run = 0;
1038 while (i < text.length) {
1039 const c = text.charCodeAt(i);
1040 if (c === 92) {
1041 i += 2;
1042 continue;
1043 }
1044 const braced =
1045 (c === 36 || c === 35) && text.charCodeAt(i + 1) === 123; /* { */
1046 const bare =
1047 as === "variable" &&
1048 c === 36 &&
1049 (isAlphaCh(text.charCodeAt(i + 1)) || text.charCodeAt(i + 1) === 95);
1050 if (!braced && !bare) {
1051 i++;
1052 continue;
1053 }
1054 out.push(cls, text.slice(run, i), kind);
1055 if (bare) {
1056 const end = readVariable(text, i);
1057 out.push("meta", text.slice(i, end), "variable");
1058 i = end;
1059 run = end;
1060 continue;
1061 }
1062 let depth = 1;
1063 let j = i + 2;
1064 while (j < text.length && depth > 0) {
1065 const d = text.charCodeAt(j);
1066 if (d === 123) depth++;
1067 else if (d === 125) depth--;
1068 j++;
1069 }
1070 if (as === "variable") {
1071 out.push("meta", text.slice(i, j), "variable");
1072 } else {
1073 out.push("punctuation", text.slice(i, i + 2));
1074 out.push("plain", text.slice(i + 2, depth === 0 ? j - 1 : j));
1075 if (depth === 0) out.push("punctuation", "}");
1076 }
1077 i = j;
1078 run = j;
1079 }
1080 out.push(cls, text.slice(run), kind);
1081 }
1082
1083 /** A number literal: hex/binary/octal, separators, exponents, suffixes. */
1084 function scanNumber(line: string, start: number): number {
1085 const n = line.length;
1086 let i = start;
1087 if (
1088 line.charCodeAt(i) === 48 /* 0 */ &&
1089 i + 1 < n &&
1090 /[xXbBoO]/.test(line[i + 1]!)
1091 ) {
1092 i += 2;
1093 while (i < n && /[0-9a-fA-F_]/.test(line[i]!)) i++;
1094 } else {
1095 while (
1096 i < n &&
1097 (isDigitCh(line.charCodeAt(i)) || line.charCodeAt(i) === 95)
1098 )
1099 i++;
1100 if (
1101 i < n &&
1102 line.charCodeAt(i) === 46 &&
1103 isDigitCh(line.charCodeAt(i + 1))
1104 ) {
1105 i++;
1106 while (
1107 i < n &&
1108 (isDigitCh(line.charCodeAt(i)) || line.charCodeAt(i) === 95)
1109 )
1110 i++;
1111 }
1112 if (i < n && (line[i] === "e" || line[i] === "E")) {
1113 let j = i + 1;
1114 if (j < n && (line[j] === "+" || line[j] === "-")) j++;
1115 if (j < n && isDigitCh(line.charCodeAt(j))) {
1116 i = j;
1117 while (i < n && isDigitCh(line.charCodeAt(i))) i++;
1118 }
1119 }
1120 }
1121 // Suffixes: 10n, 1.0f32, 3u8, 100L, 5px is CSS's business, not ours here.
1122 while (
1123 i < n &&
1124 (isAlphaCh(line.charCodeAt(i)) || isDigitCh(line.charCodeAt(i)))
1125 ) {
1126 const rest = line.slice(i);
1127 if (!/^(n|[uif](8|16|32|64|128|size)?|[lLfFdDuU]+)/.test(rest)) break;
1128 i += /^(n|[uif](8|16|32|64|128|size)?|[lLfFdDuU]+)/.exec(rest)![0].length;
1129 break;
1130 }
1131 return i;
1132 }
1133
1134 /** Where the run of spaces starting at `i` ends. */
1135 function spaceRun(line: string, i: number): number {
1136 let j = i;
1137 while (j < line.length && isSpaceCh(line.charCodeAt(j))) j++;
1138 return j;
1139 }
1140
1141 /** The column of the first non-space character, or -1 for a blank line. */
1142 function indentOf(line: string): number {
1143 const at = spaceRun(line, 0);
1144 return at === line.length ? -1 : at;
1145 }
1146
1147 // ---- the generic scanner ----
1148
1149 /**
1150 * The scanner most languages use: comments, strings, numbers, identifiers
1151 * classified against the spec's word sets, and everything else as operator or
1152 * punctuation. `expectValue` tracks whether the next `/` is a regex or a
1153 * division, and whether a `<` opens JSX — the one piece of grammar a
1154 * table-driven scanner cannot do without.
1155 */
1156 function scanGeneric(
1157 line: string,
1158 spec: LangSpec,
1159 initial: ScanState,
1160 ): Scanned {
1161 const out = new Out();
1162 let state = initial;
1163 let i = 0;
1164 const n = line.length;
1165 let expectValue = true;
1166 let pendingHeredoc: Heredoc | null = null;
1167 let lastWord = "";
1168 // Shell only: the first word of a command is the thing being run.
1169 let atCommand = true;
1170
1171 // A heredoc body swallows whole lines until its terminator.
1172 if (state.heredoc) {
1173 const hd = state.heredoc;
1174 const body = hd.indent ? line.trimStart() : line;
1175 if (body.trimEnd() === hd.tag) {
1176 out.push("meta", line);
1177 return { tokens: out.done(), state: { ...state, heredoc: null } };
1178 }
1179 pushString(out, line, true, "string", undefined, "variable");
1180 return { tokens: out.done(), state };
1181 }
1182
1183 // Continue an open block comment.
1184 if (state.block && spec.blockComment) {
1185 const end = line.indexOf(spec.blockComment[1]);
1186 if (end === -1) {
1187 out.push("comment", line);
1188 return { tokens: out.done(), state };
1189 }
1190 out.push("comment", line.slice(0, end + spec.blockComment[1].length));
1191 i = end + spec.blockComment[1].length;
1192 state = { ...state, block: false };
1193 }
1194
1195 // Continue an open multi-line string.
1196 if (state.str) {
1197 const open = state.str;
1198 const consumed = consumeStringBody(line, 0, open);
1199 pushString(
1200 out,
1201 line.slice(0, consumed.end),
1202 open.interpolate === true,
1203 "string",
1204 undefined,
1205 open.interpolateAs ?? "code",
1206 );
1207 if (!consumed.closed) return { tokens: out.done(), state };
1208 i = consumed.end;
1209 state = { ...state, str: null };
1210 }
1211
1212 while (i < n) {
1213 const c = line.charCodeAt(i);
1214
1215 if (isSpaceCh(c)) {
1216 const j = spaceRun(line, i);
1217 out.push("plain", line.slice(i, j));
1218 i = j;
1219 continue;
1220 }
1221
1222 // A C preprocessor line: `#include <stdio.h>`, `#define X 1`.
1223 if (
1224 spec.preproc &&
1225 c === 35 &&
1226 out.tokens.every((t) => t.cls === "plain")
1227 ) {
1228 const directive = /^#\s*[a-z_]+/.exec(line.slice(i));
1229 if (directive) {
1230 out.push("meta", directive[0]);
1231 i += directive[0].length;
1232 const angle = /^\s*<[^>\s]*>/.exec(line.slice(i));
1233 if (angle) {
1234 out.push("plain", angle[0].slice(0, angle[0].indexOf("<")));
1235 out.push("string", angle[0].slice(angle[0].indexOf("<")));
1236 i += angle[0].length;
1237 }
1238 continue;
1239 }
1240 }
1241
1242 // Line comment. In shells a `#` only starts one at a word boundary, so
1243 // `curl http://x#y` and `${x#y}` survive.
1244 const lc = spec.lineComment.find((p) => line.startsWith(p, i));
1245 if (
1246 lc !== undefined &&
1247 (lc !== "#" || i === 0 || isSpaceCh(line.charCodeAt(i - 1)))
1248 ) {
1249 out.push("comment", line.slice(i));
1250 i = n;
1251 continue;
1252 }
1253
1254 // Block comment.
1255 if (spec.blockComment && line.startsWith(spec.blockComment[0], i)) {
1256 const close = spec.blockComment[1];
1257 const end = line.indexOf(close, i + spec.blockComment[0].length);
1258 if (end === -1) {
1259 out.push("comment", line.slice(i));
1260 i = n;
1261 state = { ...state, block: true };
1262 } else {
1263 out.push("comment", line.slice(i, end + close.length));
1264 i = end + close.length;
1265 }
1266 continue;
1267 }
1268
1269 // Rust `#[derive(Debug)]`, and `#![no_std]`.
1270 if (spec.hashAttr && c === 35 && /^#!?\[/.test(line.slice(i))) {
1271 const end = line.indexOf("]", i);
1272 const stop = end === -1 ? n : end + 1;
1273 out.push("meta", line.slice(i, stop), "decorator");
1274 i = stop;
1275 expectValue = true;
1276 continue;
1277 }
1278
1279 // A decorator or annotation: `@Component`, `@staticmethod`, `@interface`.
1280 if (spec.atDecorator && c === 64 && isAlphaCh(line.charCodeAt(i + 1))) {
1281 let j = i + 1;
1282 while (
1283 j < n &&
1284 (isIdentCh(line.charCodeAt(j)) || line.charCodeAt(j) === 46)
1285 )
1286 j++;
1287 out.push("meta", line.slice(i, j), "decorator");
1288 i = j;
1289 expectValue = false;
1290 continue;
1291 }
1292
1293 // A variable sigil: `$PATH`, `${x}`, `@ivar`, `@@class`.
1294 if (spec.sigils && spec.sigils.includes(line[i]!)) {
1295 const j = readVariable(line, i);
1296 if (j > i + 1) {
1297 out.push("meta", line.slice(i, j), "variable");
1298 i = j;
1299 expectValue = false;
1300 continue;
1301 }
1302 }
1303
1304 // `:atom` / `:symbol`, but not `::` and not `a ? b : c`.
1305 if (
1306 spec.atoms &&
1307 c === 58 &&
1308 isAlphaCh(line.charCodeAt(i + 1)) &&
1309 line.charCodeAt(i - 1) !== 58
1310 ) {
1311 let j = i + 1;
1312 while (j < n && isIdentCh(line.charCodeAt(j))) j++;
1313 if (spec.identTail && j < n && spec.identTail.includes(line[j]!)) j++;
1314 out.push("constant", line.slice(i, j));
1315 i = j;
1316 expectValue = false;
1317 continue;
1318 }
1319
1320 // A Rust lifetime: `'a` with no closing quote is not a character.
1321 if (spec.lifetimes && c === 39 && isAlphaCh(line.charCodeAt(i + 1))) {
1322 let j = i + 1;
1323 while (j < n && isIdentCh(line.charCodeAt(j))) j++;
1324 if (line.charCodeAt(j) !== 39) {
1325 out.push("meta", line.slice(i, j), "variable");
1326 i = j;
1327 expectValue = false;
1328 continue;
1329 }
1330 }
1331
1332 // `/>` closes a JSX tag that an `{expression}` attribute interrupted.
1333 if (spec.jsx && c === 47 && line.charCodeAt(i + 1) === 62) {
1334 out.push("punctuation", "/>");
1335 i += 2;
1336 expectValue = true;
1337 continue;
1338 }
1339
1340 // JSX/TSX markup, where a value is expected.
1341 if (spec.jsx && c === 60 && expectValue) {
1342 const consumed = scanJsxTag(line, i, out);
1343 if (consumed > i) {
1344 i = consumed;
1345 expectValue = true;
1346 continue;
1347 }
1348 }
1349
1350 // A string, or a regex literal where a value is expected.
1351 const strSpec = spec.strings.find(
1352 (s) =>
1353 line.startsWith(s.open, i) && (s.valueOnly !== true || expectValue),
1354 );
1355 if (strSpec) {
1356 // An empty regex `//` is a comment everywhere it could be one.
1357 const bodyStart = i + strSpec.open.length;
1358 const consumed = consumeStringBody(line, bodyStart, strSpec);
1359 const cls = strSpec.cls ?? "string";
1360 if (consumed.closed) {
1361 let end = consumed.end;
1362 // Regex flags, string suffixes: `/x/gi`, `"a"u8`.
1363 while (end < n && isAlphaCh(line.charCodeAt(end))) end++;
1364 pushString(
1365 out,
1366 line.slice(i, end),
1367 strSpec.interpolate === true,
1368 cls,
1369 strSpec.kind,
1370 strSpec.interpolateAs ?? "code",
1371 );
1372 i = end;
1373 } else if (strSpec.multiline) {
1374 pushString(
1375 out,
1376 line.slice(i),
1377 strSpec.interpolate === true,
1378 cls,
1379 strSpec.kind,
1380 strSpec.interpolateAs ?? "code",
1381 );
1382 i = n;
1383 state = {
1384 ...state,
1385 str: {
1386 close: strSpec.close,
1387 escape: strSpec.escape,
1388 ...(strSpec.interpolate === true ? { interpolate: true } : {}),
1389 ...(strSpec.interpolateAs === undefined
1390 ? {}
1391 : { interpolateAs: strSpec.interpolateAs }),
1392 },
1393 };
1394 } else {
1395 // Unterminated single-line string: take the rest of the line.
1396 pushString(
1397 out,
1398 line.slice(i),
1399 strSpec.interpolate === true,
1400 cls,
1401 strSpec.kind,
1402 strSpec.interpolateAs ?? "code",
1403 );
1404 i = n;
1405 }
1406 expectValue = false;
1407 continue;
1408 }
1409
1410 // A heredoc opener: `<<EOF`, `<<-'EOF'`, `<<~HTML`.
1411 if (spec.heredoc && c === 60 && line.charCodeAt(i + 1) === 60) {
1412 const opener = /^<<([-~]?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/.exec(
1413 line.slice(i),
1414 );
1415 if (opener) {
1416 out.push("operator", line.slice(i, i + 2 + opener[1]!.length));
1417 out.push("meta", opener[0].slice(2 + opener[1]!.length));
1418 i += opener[0].length;
1419 pendingHeredoc = { tag: opener[3]!, indent: opener[1] !== "" };
1420 expectValue = false;
1421 continue;
1422 }
1423 }
1424
1425 // A command-line flag: `-v`, `--long-form`, `-euo`.
1426 if (
1427 spec.flags &&
1428 c === 45 &&
1429 (i === 0 || isSpaceCh(line.charCodeAt(i - 1))) &&
1430 !atCommand
1431 ) {
1432 const flag = /^--?[A-Za-z][A-Za-z0-9_-]*/.exec(line.slice(i));
1433 if (flag) {
1434 out.push("constant", flag[0], "attribute");
1435 i += flag[0].length;
1436 expectValue = false;
1437 continue;
1438 }
1439 }
1440
1441 // Number.
1442 if (
1443 isDigitCh(c) ||
1444 (c === 46 && isDigitCh(line.charCodeAt(i + 1)) && expectValue)
1445 ) {
1446 const j = scanNumber(line, i);
1447 out.push("number", line.slice(i, j));
1448 i = j;
1449 expectValue = false;
1450 continue;
1451 }
1452
1453 // Identifier / keyword / type / constant / function.
1454 if (isAlphaCh(c) || c === 95 || (c === 36 && !spec.sigils)) {
1455 let j = i + 1;
1456 while (
1457 j < n &&
1458 (isIdentCh(line.charCodeAt(j)) ||
1459 line.charCodeAt(j) === 36 ||
1460 (spec.identInner !== undefined && spec.identInner.includes(line[j]!)))
1461 )
1462 j++;
1463 if (spec.identTail && j < n && spec.identTail.includes(line[j]!)) j++;
1464 const word = line.slice(i, j);
1465 const probe = spec.ignoreCase === true ? word.toLowerCase() : word;
1466 const call = line[j] === "(";
1467
1468 let cls: TokenClass = "plain";
1469 let kind: TokenKind | undefined;
1470 if (spec.keywords.has(probe)) cls = "keyword";
1471 else if (spec.constants.has(probe)) cls = "constant";
1472 else if (spec.types.has(probe)) cls = "type";
1473 else if (spec.defineAfter?.has(lastWord)) {
1474 cls = spec.typeAfter?.has(lastWord) ? "type" : "function";
1475 } else if (spec.typeAfter?.has(lastWord)) cls = "type";
1476 else if (spec.macroBang && line[j] === "!" && line[j + 1] !== "=") {
1477 // `println!` is one thing, not a name and a negation.
1478 out.push("function", `${word}!`, "decorator");
1479 lastWord = probe;
1480 atCommand = false;
1481 i = j + 1;
1482 expectValue = true;
1483 continue;
1484 } else if (call && spec.callAsFunction) cls = "function";
1485 else if (
1486 spec.dotProperty &&
1487 i > 0 &&
1488 line.charCodeAt(i - 1) === 46 &&
1489 line.charCodeAt(i - 2) !== 46
1490 ) {
1491 cls = "plain";
1492 kind = "property";
1493 } else if (spec.capitalIsType !== false && isUpperCh(c)) cls = "type";
1494 else if (spec.commandPosition && atCommand)
1495 cls = line[j] === "=" ? "plain" : "function";
1496 if (spec.commandPosition && atCommand && line[j] === "=")
1497 kind = "variable";
1498
1499 out.push(cls, word, kind);
1500 lastWord = probe;
1501 i = j;
1502 expectValue =
1503 cls === "keyword" && !spec.constants.has(probe) && probe !== "this";
1504 atCommand =
1505 cls === "keyword" && COMMAND_OPENERS.has(probe) ? true : false;
1506 continue;
1507 }
1508
1509 // Operators and punctuation.
1510 if (c === 123) state = { ...state, depth: state.depth + 1 };
1511 if (c === 125) state = { ...state, depth: Math.max(0, state.depth - 1) };
1512 if (
1513 c === 40 ||
1514 c === 41 ||
1515 c === 91 ||
1516 c === 93 ||
1517 c === 123 ||
1518 c === 125 ||
1519 c === 59 ||
1520 c === 44 ||
1521 c === 46
1522 ) {
1523 out.push("punctuation", line[i]!);
1524 expectValue = c !== 41 && c !== 93 && c !== 46;
1525 } else {
1526 out.push("operator", line[i]!);
1527 expectValue = true;
1528 }
1529 if (c === 124 || c === 59 || c === 38 || c === 40 || c === 123)
1530 atCommand = true;
1531 else if (!isSpaceCh(c)) atCommand = false;
1532 lastWord = "";
1533 i++;
1534 }
1535
1536 const next: ScanState =
1537 pendingHeredoc === null ? state : { ...state, heredoc: pendingHeredoc };
1538 return { tokens: out.done(), state: next };
1539 }
1540
1541 /** `$name`, `${expr}`, `$(cmd)`, `@ivar`, `@@cvar`, `$1`. */
1542 function readVariable(line: string, at: number): number {
1543 const n = line.length;
1544 let i = at + 1;
1545 if (line.charCodeAt(at) === 64 && line.charCodeAt(i) === 64) i++; // @@cvar
1546 const c = line.charCodeAt(i);
1547 if (c === 123 /* { */ || c === 40 /* ( */) {
1548 const close = c === 123 ? 125 : 41;
1549 let depth = 1;
1550 i++;
1551 while (i < n && depth > 0) {
1552 const d = line.charCodeAt(i);
1553 if (d === c) depth++;
1554 else if (d === close) depth--;
1555 i++;
1556 }
1557 return i;
1558 }
1559 if (isDigitCh(c) || c === 42 || c === 64 || c === 63 || c === 35)
1560 return i + 1;
1561 while (i < n && isIdentCh(line.charCodeAt(i))) i++;
1562 return i;
1563 }
1564
1565 /**
1566 * A JSX element's opening or closing tag. Returns where it ends, or `at` if
1567 * this `<` was not markup after all. Inside the tag, names and attributes get
1568 * their own colours; a `{` hands control back to the code scanner.
1569 */
1570 function scanJsxTag(line: string, at: number, out: Out): number {
1571 const n = line.length;
1572 let i = at + 1;
1573 if (line[i] === "/") i++;
1574 const start = i;
1575 while (
1576 i < n &&
1577 (isIdentCh(line.charCodeAt(i)) || line[i] === "." || line[i] === "-")
1578 )
1579 i++;
1580 // `<>` (a fragment) is markup; `a < b` is not.
1581 if (i === start && line[at + 1] !== ">") return at;
1582 out.push("punctuation", line.slice(at, start));
1583 out.push("keyword", line.slice(start, i), "tag");
1584
1585 while (i < n) {
1586 const c = line.charCodeAt(i);
1587 if (isSpaceCh(c)) {
1588 const j = spaceRun(line, i);
1589 out.push("plain", line.slice(i, j));
1590 i = j;
1591 continue;
1592 }
1593 if (c === 62 /* > */) {
1594 out.push("punctuation", ">");
1595 return i + 1;
1596 }
1597 if (c === 47 && line.charCodeAt(i + 1) === 62) {
1598 out.push("punctuation", "/>");
1599 return i + 2;
1600 }
1601 if (c === 123 /* { */) return i; // an expression: back to the code scanner
1602 if (c === 61 /* = */) {
1603 out.push("operator", "=");
1604 i++;
1605 continue;
1606 }
1607 if (c === 34 || c === 39) {
1608 const quote = line[i]!;
1609 const consumed = consumeStringBody(line, i + 1, {
1610 close: quote,
1611 escape: true,
1612 });
1613 out.push("string", line.slice(i, consumed.end));
1614 i = consumed.end;
1615 continue;
1616 }
1617 if (isAlphaCh(c) || c === 95) {
1618 let j = i;
1619 while (
1620 j < n &&
1621 (isIdentCh(line.charCodeAt(j)) || line[j] === "-" || line[j] === ":")
1622 )
1623 j++;
1624 out.push("type", line.slice(i, j), "attribute");
1625 i = j;
1626 continue;
1627 }
1628 out.push("punctuation", line[i]!);
1629 i++;
1630 }
1631 return n;
1632 }
1633
1634 // ---- Markdown ----
1635
1636 const FENCE = /^(\s*)(```+|~~~+)(.*)$/;
1637
1638 /**
1639 * Markdown, block by block. A fenced block carries its info string's language
1640 * and scans its body with that language's scanner — the thing that makes a
1641 * README's code samples look like code and not like prose.
1642 */
1643 function scanMarkdown(line: string, state: ScanState): Scanned {
1644 const out = new Out();
1645
1646 if (state.embed) {
1647 const embed = state.embed;
1648 const closing = FENCE.exec(line);
1649 if (
1650 closing &&
1651 closing[2]!.startsWith(embed.end) &&
1652 closing[3]!.trim() === ""
1653 ) {
1654 out.push("plain", closing[1]!);
1655 out.push("meta", closing[2]! + closing[3]!);
1656 return { tokens: out.done(), state: { ...state, embed: null } };
1657 }
1658 const inner = scanOneLine(line, embed.lang, embed.inner);
1659 out.take(inner.tokens);
1660 return {
1661 tokens: out.done(),
1662 state: { ...state, embed: { ...embed, inner: inner.state } },
1663 };
1664 }
1665
1666 const fence = FENCE.exec(line);
1667 if (fence) {
1668 out.push("plain", fence[1]!);
1669 out.push("meta", fence[2]!);
1670 out.push("type", fence[3]!);
1671 const lang = languageFromName(fence[3]!);
1672 return {
1673 tokens: out.done(),
1674 state: {
1675 ...state,
1676 embed: { lang, end: fence[2]!.slice(0, 3), inner: INITIAL_SCAN },
1677 },
1678 };
1679 }
1680
1681 // An indented code block: four spaces (or a tab) with nothing around it.
1682 if (/^(\t| {4})\S/.test(line)) {
1683 out.push("string", line);
1684 return { tokens: out.done(), state };
1685 }
1686
1687 const heading = /^(\s{0,3}#{1,6})(\s.*)?$/.exec(line);
1688 if (heading) {
1689 out.push("keyword", line, "heading");
1690 return { tokens: out.done(), state };
1691 }
1692 if (/^\s{0,3}(=+|-{2,})\s*$/.test(line) && line.trim() !== "") {
1693 out.push("keyword", line, "heading");
1694 return { tokens: out.done(), state };
1695 }
1696 if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) {
1697 out.push("punctuation", line);
1698 return { tokens: out.done(), state };
1699 }
1700
1701 let i = 0;
1702 const quote = /^(\s*(?:>\s?)+)/.exec(line);
1703 if (quote) {
1704 out.push("comment", quote[1]!);
1705 i = quote[1]!.length;
1706 }
1707 const bullet = /^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(line.slice(i));
1708 if (bullet) {
1709 out.push("plain", bullet[1]!);
1710 out.push("punctuation", bullet[2]!);
1711 out.push("plain", bullet[3]!);
1712 i += bullet[0].length;
1713 const task = /^\[[ xX]\]/.exec(line.slice(i));
1714 if (task) {
1715 out.push("constant", task[0]);
1716 i += task[0].length;
1717 }
1718 }
1719 scanMarkdownInline(line.slice(i), out, quote !== null);
1720 return { tokens: out.done(), state };
1721 }
1722
1723 /** Inline markdown: code spans, emphasis, links, autolinks, table pipes. */
1724 function scanMarkdownInline(text: string, out: Out, quoted: boolean): void {
1725 const base: TokenClass = quoted ? "comment" : "plain";
1726 const n = text.length;
1727 let i = 0;
1728 let run = 0;
1729 const flush = (to: number) => {
1730 out.push(base, text.slice(run, to));
1731 run = to;
1732 };
1733 while (i < n) {
1734 const c = text.charCodeAt(i);
1735 if (c === 92) {
1736 i += 2;
1737 continue;
1738 }
1739 if (c === 96 /* ` */) {
1740 let ticks = 0;
1741 while (text.charCodeAt(i + ticks) === 96) ticks++;
1742 const close = text.indexOf("`".repeat(ticks), i + ticks);
1743 if (close !== -1) {
1744 flush(i);
1745 const end = close + ticks;
1746 out.push("string", text.slice(i, end));
1747 i = end;
1748 run = end;
1749 continue;
1750 }
1751 i += ticks;
1752 continue;
1753 }
1754 if (c === 42 /* * */ || c === 95 /* _ */) {
1755 const marker = text[i]!;
1756 const doubled = text[i + 1] === marker;
1757 const open = doubled ? marker + marker : marker;
1758 const close = text.indexOf(open, i + open.length);
1759 if (close !== -1 && close > i + open.length) {
1760 flush(i);
1761 const end = close + open.length;
1762 out.push("plain", text.slice(i, end), "emphasis");
1763 i = end;
1764 run = end;
1765 continue;
1766 }
1767 i += open.length;
1768 continue;
1769 }
1770 if (c === 91 /* [ */ || (c === 33 && text.charCodeAt(i + 1) === 91)) {
1771 const openAt = c === 33 ? i + 1 : i;
1772 const close = text.indexOf("]", openAt);
1773 if (close !== -1 && text[close + 1] === "(") {
1774 const end = text.indexOf(")", close + 2);
1775 if (end !== -1) {
1776 flush(i);
1777 out.push("punctuation", text.slice(i, openAt + 1));
1778 out.push("meta", text.slice(openAt + 1, close), "link");
1779 out.push("punctuation", "](");
1780 out.push("string", text.slice(close + 2, end), "link");
1781 out.push("punctuation", ")");
1782 i = end + 1;
1783 run = i;
1784 continue;
1785 }
1786 }
1787 i++;
1788 continue;
1789 }
1790 if (c === 60 /* < */) {
1791 const close = text.indexOf(">", i);
1792 if (
1793 close !== -1 &&
1794 /^<(https?:\/\/|mailto:)[^>\s]+>$/.test(text.slice(i, close + 1))
1795 ) {
1796 flush(i);
1797 out.push("meta", text.slice(i, close + 1), "link");
1798 i = close + 1;
1799 run = i;
1800 continue;
1801 }
1802 i++;
1803 continue;
1804 }
1805 if (c === 124 /* | */) {
1806 flush(i);
1807 out.push("punctuation", "|");
1808 i++;
1809 run = i;
1810 continue;
1811 }
1812 i++;
1813 }
1814 flush(n);
1815 }
1816
1817 // ---- YAML ----
1818
1819 const YAML_KEY =
1820 /^(\s*(?:-\s+)*)((?:"[^"]*"|'[^']*'|[^\s:#][^:#]*?))(\s*:)(\s|$)/;
1821
1822 function scanYaml(line: string, state: ScanState): Scanned {
1823 const out = new Out();
1824
1825 // A block scalar's body: everything indented past the introducing line.
1826 if (state.scalar !== null) {
1827 const indent = indentOf(line);
1828 if (indent === -1 || indent > state.scalar) {
1829 out.push("string", line);
1830 return { tokens: out.done(), state };
1831 }
1832 state = { ...state, scalar: null };
1833 }
1834
1835 if (/^\s*#/.test(line)) {
1836 out.push("comment", line);
1837 return { tokens: out.done(), state };
1838 }
1839 if (/^(---|\.\.\.)\s*$/.test(line)) {
1840 out.push("meta", line);
1841 return { tokens: out.done(), state };
1842 }
1843
1844 let i = 0;
1845 const key = YAML_KEY.exec(line);
1846 if (key) {
1847 out.push("plain", key[1]!);
1848 out.push("keyword", key[2]!, "property");
1849 out.push("punctuation", key[3]!);
1850 i = key[1]!.length + key[2]!.length + key[3]!.length;
1851 } else {
1852 const dash = /^(\s*)(-)(\s|$)/.exec(line);
1853 if (dash) {
1854 out.push("plain", dash[1]!);
1855 out.push("punctuation", "-");
1856 i = dash[1]!.length + 1;
1857 }
1858 }
1859
1860 // A block scalar indicator ends the line and opens the body.
1861 const scalar = /^(\s*)([|>][+-]?\d*)\s*(#.*)?$/.exec(line.slice(i));
1862 if (scalar) {
1863 out.push("plain", scalar[1]!);
1864 out.push("operator", scalar[2]!);
1865 if (scalar[3])
1866 out.push("comment", line.slice(line.length - scalar[3].length));
1867 else
1868 out.push("plain", line.slice(i + scalar[1]!.length + scalar[2]!.length));
1869 return {
1870 tokens: out.done(),
1871 state: { ...state, scalar: Math.max(0, indentOf(line)) },
1872 };
1873 }
1874
1875 scanYamlValue(line, i, out);
1876 return { tokens: out.done(), state };
1877 }
1878
1879 function scanYamlValue(line: string, from: number, out: Out): void {
1880 const n = line.length;
1881 let i = from;
1882 while (i < n) {
1883 const c = line.charCodeAt(i);
1884 if (isSpaceCh(c)) {
1885 const j = spaceRun(line, i);
1886 out.push("plain", line.slice(i, j));
1887 i = j;
1888 continue;
1889 }
1890 if (c === 35 /* # */ && (i === 0 || isSpaceCh(line.charCodeAt(i - 1)))) {
1891 out.push("comment", line.slice(i));
1892 return;
1893 }
1894 if (c === 34 || c === 39) {
1895 const consumed = consumeStringBody(line, i + 1, {
1896 close: line[i]!,
1897 escape: c === 34,
1898 });
1899 out.push("string", line.slice(i, consumed.end));
1900 i = consumed.end;
1901 continue;
1902 }
1903 if (c === 38 /* & */ || c === 42 /* * */) {
1904 let j = i + 1;
1905 while (j < n && isIdentCh(line.charCodeAt(j))) j++;
1906 if (j > i + 1) {
1907 out.push("meta", line.slice(i, j), "variable");
1908 i = j;
1909 continue;
1910 }
1911 }
1912 if (c === 33 /* ! */) {
1913 let j = i;
1914 while (j < n && !isSpaceCh(line.charCodeAt(j))) j++;
1915 out.push("type", line.slice(i, j));
1916 i = j;
1917 continue;
1918 }
1919 if (isDigitCh(c) || (c === 45 && isDigitCh(line.charCodeAt(i + 1)))) {
1920 let j = c === 45 ? i + 1 : i;
1921 j = scanNumber(line, j);
1922 // A date reads as a number too: 2026-09-01.
1923 while (j < n && /[-:.TZ0-9+]/.test(line[j]!)) j++;
1924 out.push("number", line.slice(i, j));
1925 i = j;
1926 continue;
1927 }
1928 if (isAlphaCh(c) || c === 95) {
1929 let j = i;
1930 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
1931 const word = line.slice(i, j);
1932 const lower = word.toLowerCase();
1933 const isConst =
1934 lower === "true" ||
1935 lower === "false" ||
1936 lower === "null" ||
1937 lower === "yes" ||
1938 lower === "no" ||
1939 lower === "on" ||
1940 lower === "off" ||
1941 lower === "~";
1942 out.push(isConst ? "constant" : "plain", word);
1943 i = j;
1944 continue;
1945 }
1946 if (c === 123 || c === 125 || c === 91 || c === 93 || c === 44)
1947 out.push("punctuation", line[i]!);
1948 else out.push("operator", line[i]!);
1949 i++;
1950 }
1951 }
1952
1953 // ---- TOML and INI ----
1954
1955 function scanToml(line: string, state: ScanState, toml: boolean): Scanned {
1956 const out = new Out();
1957
1958 if (state.str) {
1959 const consumed = consumeStringBody(line, 0, state.str);
1960 out.push("string", line.slice(0, consumed.end));
1961 if (!consumed.closed) return { tokens: out.done(), state };
1962 scanTomlValue(line, consumed.end, out, toml);
1963 return { tokens: out.done(), state: { ...state, str: null } };
1964 }
1965
1966 const comment = /^(\s*)([#;].*)$/.exec(line);
1967 if (comment) {
1968 out.push("plain", comment[1]!);
1969 out.push("comment", comment[2]!);
1970 return { tokens: out.done(), state };
1971 }
1972 const table = /^(\s*)(\[\[?[^\]]*\]\]?)(.*)$/.exec(line);
1973 if (table) {
1974 out.push("plain", table[1]!);
1975 out.push("type", table[2]!, "heading");
1976 out.push("plain", table[3]!);
1977 return { tokens: out.done(), state };
1978 }
1979 const assign = /^(\s*)((?:"[^"]*"|[^=\s]+))(\s*=\s*)/.exec(line);
1980 if (assign) {
1981 out.push("plain", assign[1]!);
1982 out.push("keyword", assign[2]!, "property");
1983 out.push("operator", assign[3]!);
1984 return scanTomlRest(line, assign[0].length, out, state, toml);
1985 }
1986 return scanTomlRest(line, 0, out, state, toml);
1987 }
1988
1989 function scanTomlRest(
1990 line: string,
1991 from: number,
1992 out: Out,
1993 state: ScanState,
1994 toml: boolean,
1995 ): Scanned {
1996 if (toml && line.startsWith('"""', from)) {
1997 const consumed = consumeStringBody(line, from + 3, {
1998 close: '"""',
1999 escape: true,
2000 });
2001 out.push("string", line.slice(from, consumed.end));
2002 if (!consumed.closed) {
2003 return {
2004 tokens: out.done(),
2005 state: { ...state, str: { close: '"""', escape: true } },
2006 };
2007 }
2008 scanTomlValue(line, consumed.end, out, toml);
2009 return { tokens: out.done(), state };
2010 }
2011 scanTomlValue(line, from, out, toml);
2012 return { tokens: out.done(), state };
2013 }
2014
2015 function scanTomlValue(
2016 line: string,
2017 from: number,
2018 out: Out,
2019 toml: boolean,
2020 ): void {
2021 const n = line.length;
2022 let i = from;
2023 while (i < n) {
2024 const c = line.charCodeAt(i);
2025 if (isSpaceCh(c)) {
2026 const j = spaceRun(line, i);
2027 out.push("plain", line.slice(i, j));
2028 i = j;
2029 continue;
2030 }
2031 if (c === 35 || (!toml && c === 59)) {
2032 out.push("comment", line.slice(i));
2033 return;
2034 }
2035 if (c === 34 || c === 39) {
2036 const consumed = consumeStringBody(line, i + 1, {
2037 close: line[i]!,
2038 escape: c === 34,
2039 });
2040 out.push("string", line.slice(i, consumed.end));
2041 i = consumed.end;
2042 continue;
2043 }
2044 if (isDigitCh(c) || (c === 45 && isDigitCh(line.charCodeAt(i + 1)))) {
2045 let j = scanNumber(line, c === 45 ? i + 1 : i);
2046 while (j < n && /[-:.TZ0-9+]/.test(line[j]!)) j++;
2047 out.push("number", line.slice(i, j));
2048 i = j;
2049 continue;
2050 }
2051 if (isAlphaCh(c) || c === 95) {
2052 let j = i;
2053 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
2054 const word = line.slice(i, j);
2055 out.push(
2056 word === "true" || word === "false" ? "constant" : "plain",
2057 word,
2058 );
2059 i = j;
2060 continue;
2061 }
2062 if (c === 91 || c === 93 || c === 123 || c === 125 || c === 44)
2063 out.push("punctuation", line[i]!);
2064 else out.push("operator", line[i]!);
2065 i++;
2066 }
2067 }
2068
2069 // ---- HTML ----
2070
2071 function scanHtml(line: string, state: ScanState): Scanned {
2072 const out = new Out();
2073 let i = 0;
2074 const n = line.length;
2075
2076 // Inside <script>/<style>: scan with that language until the closing tag.
2077 if (state.embed) {
2078 const embed = state.embed;
2079 const close = line.toLowerCase().indexOf(embed.end);
2080 if (close === -1) {
2081 const inner = scanOneLine(line, embed.lang, embed.inner);
2082 out.take(inner.tokens);
2083 return {
2084 tokens: out.done(),
2085 state: { ...state, embed: { ...embed, inner: inner.state } },
2086 };
2087 }
2088 if (close > 0) {
2089 const inner = scanOneLine(line.slice(0, close), embed.lang, embed.inner);
2090 out.take(inner.tokens);
2091 }
2092 i = close;
2093 state = { ...state, embed: null };
2094 }
2095
2096 if (state.block) {
2097 const end = line.indexOf("-->", i);
2098 if (end === -1) {
2099 out.push("comment", line.slice(i));
2100 return { tokens: out.done(), state };
2101 }
2102 out.push("comment", line.slice(i, end + 3));
2103 i = end + 3;
2104 state = { ...state, block: false };
2105 }
2106
2107 while (i < n) {
2108 if (state.tag) {
2109 i = scanHtmlAttributes(line, i, out);
2110 if (i < n || line.endsWith(">")) state = { ...state, tag: false };
2111 continue;
2112 }
2113 const lt = line.indexOf("<", i);
2114 if (lt === -1) {
2115 pushHtmlText(out, line.slice(i));
2116 i = n;
2117 continue;
2118 }
2119 pushHtmlText(out, line.slice(i, lt));
2120 i = lt;
2121
2122 if (line.startsWith("<!--", i)) {
2123 const end = line.indexOf("-->", i + 4);
2124 if (end === -1) {
2125 out.push("comment", line.slice(i));
2126 return { tokens: out.done(), state: { ...state, block: true } };
2127 }
2128 out.push("comment", line.slice(i, end + 3));
2129 i = end + 3;
2130 continue;
2131 }
2132 if (line.startsWith("<!", i) || line.startsWith("<?", i)) {
2133 const end = line.indexOf(">", i);
2134 const stop = end === -1 ? n : end + 1;
2135 out.push("meta", line.slice(i, stop));
2136 i = stop;
2137 continue;
2138 }
2139 const name = /^<\/?([A-Za-z][A-Za-z0-9:-]*)/.exec(line.slice(i));
2140 if (!name) {
2141 out.push("punctuation", "<");
2142 i++;
2143 continue;
2144 }
2145 const lead = name[0].startsWith("</") ? 2 : 1;
2146 out.push("punctuation", line.slice(i, i + lead));
2147 out.push("keyword", name[1]!, "tag");
2148 i += name[0].length;
2149 const after = scanHtmlAttributes(line, i, out);
2150 const tag = name[1]!.toLowerCase();
2151 const closed = line.slice(i, after).includes(">");
2152 i = after;
2153 if (!closed) {
2154 state = { ...state, tag: true };
2155 continue;
2156 }
2157 if (lead === 1 && (tag === "script" || tag === "style")) {
2158 state = {
2159 ...state,
2160 embed: {
2161 lang: tag === "script" ? "ts" : "css",
2162 end: `</${tag}`,
2163 inner: INITIAL_SCAN,
2164 },
2165 };
2166 const rest = line.toLowerCase().indexOf(`</${tag}`, i);
2167 if (rest === -1) {
2168 if (i < n) {
2169 const inner = scanOneLine(
2170 line.slice(i),
2171 tag === "script" ? "ts" : "css",
2172 INITIAL_SCAN,
2173 );
2174 out.take(inner.tokens);
2175 }
2176 return { tokens: out.done(), state };
2177 }
2178 const inner = scanOneLine(
2179 line.slice(i, rest),
2180 tag === "script" ? "ts" : "css",
2181 INITIAL_SCAN,
2182 );
2183 out.take(inner.tokens);
2184 i = rest;
2185 state = { ...state, embed: null };
2186 }
2187 }
2188 return { tokens: out.done(), state };
2189 }
2190
2191 /** Text between tags, with entities picked out. */
2192 function pushHtmlText(out: Out, text: string): void {
2193 let run = 0;
2194 const entity = /&(#\d+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});/g;
2195 let match: RegExpExecArray | null;
2196 while ((match = entity.exec(text)) !== null) {
2197 out.push("plain", text.slice(run, match.index));
2198 out.push("constant", match[0]);
2199 run = match.index + match[0].length;
2200 }
2201 out.push("plain", text.slice(run));
2202 }
2203
2204 /** Attributes up to and including the `>` that closes the tag. */
2205 function scanHtmlAttributes(line: string, from: number, out: Out): number {
2206 const n = line.length;
2207 let i = from;
2208 while (i < n) {
2209 const c = line.charCodeAt(i);
2210 if (isSpaceCh(c)) {
2211 const j = spaceRun(line, i);
2212 out.push("plain", line.slice(i, j));
2213 i = j;
2214 continue;
2215 }
2216 if (c === 62 /* > */) {
2217 out.push("punctuation", ">");
2218 return i + 1;
2219 }
2220 if (c === 47 && line.charCodeAt(i + 1) === 62) {
2221 out.push("punctuation", "/>");
2222 return i + 2;
2223 }
2224 if (c === 61) {
2225 out.push("operator", "=");
2226 i++;
2227 continue;
2228 }
2229 if (c === 34 || c === 39) {
2230 const consumed = consumeStringBody(line, i + 1, {
2231 close: line[i]!,
2232 escape: false,
2233 });
2234 out.push("string", line.slice(i, consumed.end));
2235 i = consumed.end;
2236 continue;
2237 }
2238 let j = i;
2239 while (
2240 j < n &&
2241 !isSpaceCh(line.charCodeAt(j)) &&
2242 line[j] !== "=" &&
2243 line[j] !== ">"
2244 )
2245 j++;
2246 if (j === i) j++;
2247 out.push("type", line.slice(i, j), "attribute");
2248 i = j;
2249 }
2250 return n;
2251 }
2252
2253 // ---- CSS (and SCSS/LESS) ----
2254
2255 function scanCss(line: string, initial: ScanState): Scanned {
2256 const out = new Out();
2257 let state = initial;
2258 let i = 0;
2259 let paren = 0;
2260 const n = line.length;
2261
2262 if (state.block) {
2263 const end = line.indexOf("*/");
2264 if (end === -1) {
2265 out.push("comment", line);
2266 return { tokens: out.done(), state };
2267 }
2268 out.push("comment", line.slice(0, end + 2));
2269 i = end + 2;
2270 state = { ...state, block: false };
2271 }
2272
2273 while (i < n) {
2274 const c = line.charCodeAt(i);
2275 if (isSpaceCh(c)) {
2276 const j = spaceRun(line, i);
2277 out.push("plain", line.slice(i, j));
2278 i = j;
2279 continue;
2280 }
2281 if (line.startsWith("//", i)) {
2282 out.push("comment", line.slice(i));
2283 break;
2284 }
2285 if (line.startsWith("/*", i)) {
2286 const end = line.indexOf("*/", i + 2);
2287 if (end === -1) {
2288 out.push("comment", line.slice(i));
2289 state = { ...state, block: true };
2290 break;
2291 }
2292 out.push("comment", line.slice(i, end + 2));
2293 i = end + 2;
2294 continue;
2295 }
2296 if (c === 34 || c === 39) {
2297 const consumed = consumeStringBody(line, i + 1, {
2298 close: line[i]!,
2299 escape: true,
2300 });
2301 out.push("string", line.slice(i, consumed.end));
2302 i = consumed.end;
2303 continue;
2304 }
2305 if (c === 64 /* @ */) {
2306 let j = i + 1;
2307 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
2308 out.push("keyword", line.slice(i, j));
2309 i = j;
2310 continue;
2311 }
2312 if (c === 36 /* $ */ || line.startsWith("--", i)) {
2313 let j = i + (c === 36 ? 1 : 2);
2314 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
2315 out.push("meta", line.slice(i, j), "variable");
2316 i = j;
2317 continue;
2318 }
2319 if (c === 33 /* ! */) {
2320 const bang = /^![a-z-]+/.exec(line.slice(i));
2321 if (bang) {
2322 out.push("meta", bang[0]);
2323 i += bang[0].length;
2324 continue;
2325 }
2326 }
2327 if (c === 35 /* # */ && /^#[0-9a-fA-F]{3,8}\b/.test(line.slice(i))) {
2328 const hex = /^#[0-9a-fA-F]{3,8}/.exec(line.slice(i))!;
2329 out.push("number", hex[0]);
2330 i += hex[0].length;
2331 continue;
2332 }
2333 if (isDigitCh(c) || (c === 46 && isDigitCh(line.charCodeAt(i + 1)))) {
2334 let j = scanNumber(line, i);
2335 const unit = /^(%|[a-zA-Z]+)/.exec(line.slice(j));
2336 if (unit) j += unit[0].length;
2337 out.push("number", line.slice(i, j));
2338 i = j;
2339 continue;
2340 }
2341 if (c === 123) {
2342 out.push("punctuation", "{");
2343 state = { ...state, depth: state.depth + 1 };
2344 i++;
2345 continue;
2346 }
2347 if (c === 125) {
2348 out.push("punctuation", "}");
2349 state = { ...state, depth: Math.max(0, state.depth - 1) };
2350 i++;
2351 continue;
2352 }
2353 if (c === 46 || c === 35 /* .class #id */) {
2354 const sel = /^[.#][A-Za-z_-][A-Za-z0-9_-]*/.exec(line.slice(i));
2355 if (sel && state.depth === 0) {
2356 out.push("function", sel[0]);
2357 i += sel[0].length;
2358 continue;
2359 }
2360 }
2361 if (c === 58 /* : */) {
2362 const pseudo = /^::?[A-Za-z-]+/.exec(line.slice(i));
2363 if (pseudo && state.depth === 0) {
2364 out.push("type", pseudo[0]);
2365 i += pseudo[0].length;
2366 continue;
2367 }
2368 }
2369 if (isAlphaCh(c) || c === 95 || c === 45) {
2370 let j = i;
2371 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
2372 const word = line.slice(i, j);
2373 const after = spaceRun(line, j);
2374 if (line[j] === "(") out.push("function", word);
2375 else if ((state.depth > 0 || paren > 0) && line[after] === ":")
2376 out.push("keyword", word, "property");
2377 else if (state.depth > 0) out.push("constant", word);
2378 else out.push("type", word, "tag");
2379 i = j;
2380 continue;
2381 }
2382 if (c === 40) paren++;
2383 if (c === 41) paren = Math.max(0, paren - 1);
2384 if (c === 44 || c === 59 || c === 40 || c === 41)
2385 out.push("punctuation", line[i]!);
2386 else out.push("operator", line[i]!);
2387 i++;
2388 }
2389 return { tokens: out.done(), state };
2390 }
2391
2392 // ---- diff ----
2393
2394 function scanDiff(line: string, state: ScanState): Scanned {
2395 const out = new Out();
2396 if (
2397 /^(diff |index |new file|deleted file|similarity|rename |old mode|new mode)/.test(
2398 line,
2399 )
2400 ) {
2401 out.push("meta", line);
2402 } else if (line.startsWith("@@")) {
2403 out.push("function", line);
2404 } else if (line.startsWith("+++") || line.startsWith("---")) {
2405 out.push("meta", line, "heading");
2406 } else if (line.startsWith("+")) {
2407 out.push("meta", line, "inserted");
2408 } else if (line.startsWith("-")) {
2409 out.push("keyword", line, "deleted");
2410 } else if (line.startsWith("\\")) {
2411 out.push("comment", line);
2412 } else {
2413 out.push("plain", line);
2414 }
2415 return { tokens: out.done(), state };
2416 }
2417
2418 // ---- Makefile ----
2419
2420 function scanMakefile(line: string, state: ScanState): Scanned {
2421 const out = new Out();
2422 if (/^\s*#/.test(line)) {
2423 out.push("comment", line);
2424 return { tokens: out.done(), state };
2425 }
2426 // A recipe line is shell, and reads far better scanned as shell.
2427 if (line.startsWith("\t")) {
2428 out.push("punctuation", "\t");
2429 const inner = scanOneLine(line.slice(1), "shell", INITIAL_SCAN);
2430 out.take(inner.tokens);
2431 return { tokens: out.done(), state };
2432 }
2433 const target = /^([A-Za-z0-9_./$()%-]+)(\s*:{1,2}=?)(?!=)/.exec(line);
2434 if (target && !line.slice(0, target[1]!.length).includes("=")) {
2435 if (target[2]!.includes("=")) {
2436 out.push("keyword", target[1]!, "property");
2437 } else {
2438 out.push("function", target[1]!);
2439 }
2440 out.push("operator", target[2]!);
2441 scanMakeRest(line, target[0].length, out);
2442 return { tokens: out.done(), state };
2443 }
2444 const assign = /^([A-Za-z0-9_.-]+)(\s*[:+?]?=)/.exec(line);
2445 if (assign) {
2446 out.push("keyword", assign[1]!, "property");
2447 out.push("operator", assign[2]!);
2448 scanMakeRest(line, assign[0].length, out);
2449 return { tokens: out.done(), state };
2450 }
2451 const directive =
2452 /^(\s*)(include|ifeq|ifneq|ifdef|ifndef|else|endif|define|endef|export|unexport|vpath|\.PHONY)\b/.exec(
2453 line,
2454 );
2455 if (directive) {
2456 out.push("plain", directive[1]!);
2457 out.push("keyword", directive[2]!);
2458 scanMakeRest(line, directive[0].length, out);
2459 return { tokens: out.done(), state };
2460 }
2461 scanMakeRest(line, 0, out);
2462 return { tokens: out.done(), state };
2463 }
2464
2465 function scanMakeRest(line: string, from: number, out: Out): void {
2466 const n = line.length;
2467 let i = from;
2468 let run = from;
2469 while (i < n) {
2470 const c = line.charCodeAt(i);
2471 if (c === 35 /* # */) {
2472 out.push("plain", line.slice(run, i));
2473 out.push("comment", line.slice(i));
2474 return;
2475 }
2476 if (c === 36 /* $ */) {
2477 const end = readVariable(line, i);
2478 out.push("plain", line.slice(run, i));
2479 out.push("meta", line.slice(i, end), "variable");
2480 i = end;
2481 run = end;
2482 continue;
2483 }
2484 i++;
2485 }
2486 out.push("plain", line.slice(run));
2487 }
2488
2489 // ---- Dockerfile ----
2490
2491 function scanDockerfile(line: string, state: ScanState): Scanned {
2492 const out = new Out();
2493 if (/^\s*#/.test(line)) {
2494 out.push(/^\s*#\s*(syntax|escape)=/.test(line) ? "meta" : "comment", line);
2495 return { tokens: out.done(), state };
2496 }
2497 const instruction = /^(\s*)([A-Za-z]+)(\s|$)/.exec(line);
2498 let from = 0;
2499 if (instruction && DOCKER_INSTRUCTIONS.has(instruction[2]!.toUpperCase())) {
2500 out.push("plain", instruction[1]!);
2501 out.push("keyword", instruction[2]!);
2502 from = instruction[1]!.length + instruction[2]!.length;
2503 }
2504 const spec = SPECS.dockerfile!;
2505 const rest = scanGeneric(line.slice(from), spec, INITIAL_SCAN);
2506 out.take(rest.tokens);
2507 return { tokens: out.done(), state };
2508 }
36 export type { TokenClass, TokenKind, Token, Language } from "./highlight/tokens.ts";
37 export { INITIAL_SCAN, type ScanState } from "./highlight/state.ts";
38 export {
39 LANGUAGES,
40 languageFromName,
41 detectLanguage,
42 languageFromFirstLine,
43 } from "./highlight/detect.ts";
44 export { scanOneLine, highlightLines } from "./highlight/scanners.ts";
src/web/highlight/chars.ts added +20
@@ -0,0 +1,20 @@
1 /** Character classes and word sets the scanners share. */
2
3
4 // ---- character classes (charCode, not regex: these run per character) ----
5
6 export const SPACE = 32,
7 TAB = 9,
8 CR = 13;
9 export const isSpaceCh = (c: number): boolean => c === SPACE || c === TAB || c === CR;
10 export const isDigitCh = (c: number): boolean => c >= 48 && c <= 57;
11 export const isUpperCh = (c: number): boolean => c >= 65 && c <= 90;
12 export const isAlphaCh = (c: number): boolean =>
13 isUpperCh(c) || (c >= 97 && c <= 122) || c > 127;
14 export const isIdentCh = (c: number): boolean =>
15 isAlphaCh(c) || isDigitCh(c) || c === 95;
16
17 export const set = (words: string): Set<string> =>
18 new Set(words.split(/\s+/).filter(Boolean));
19
20 // ---- state carried across lines ----
src/web/highlight/css.ts added +144
@@ -0,0 +1,144 @@
1 /** CSS scanner. */
2 import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh } from "./chars.ts";
3 import { consumeStringBody, scanNumber, spaceRun } from "./lexing.ts";
4 import { type ScanState, type Scanned } from "./state.ts";
5 import { Out } from "./tokens.ts";
6
7 export function scanCss(line: string, initial: ScanState): Scanned {
8 const out = new Out();
9 let state = initial;
10 let i = 0;
11 let paren = 0;
12 const n = line.length;
13
14 if (state.block) {
15 const end = line.indexOf("*/");
16 if (end === -1) {
17 out.push("comment", line);
18 return { tokens: out.done(), state };
19 }
20 out.push("comment", line.slice(0, end + 2));
21 i = end + 2;
22 state = { ...state, block: false };
23 }
24
25 while (i < n) {
26 const c = line.charCodeAt(i);
27 if (isSpaceCh(c)) {
28 const j = spaceRun(line, i);
29 out.push("plain", line.slice(i, j));
30 i = j;
31 continue;
32 }
33 if (line.startsWith("//", i)) {
34 out.push("comment", line.slice(i));
35 break;
36 }
37 if (line.startsWith("/*", i)) {
38 const end = line.indexOf("*/", i + 2);
39 if (end === -1) {
40 out.push("comment", line.slice(i));
41 state = { ...state, block: true };
42 break;
43 }
44 out.push("comment", line.slice(i, end + 2));
45 i = end + 2;
46 continue;
47 }
48 if (c === 34 || c === 39) {
49 const consumed = consumeStringBody(line, i + 1, {
50 close: line[i]!,
51 escape: true,
52 });
53 out.push("string", line.slice(i, consumed.end));
54 i = consumed.end;
55 continue;
56 }
57 if (c === 64 /* @ */) {
58 let j = i + 1;
59 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
60 out.push("keyword", line.slice(i, j));
61 i = j;
62 continue;
63 }
64 if (c === 36 /* $ */ || line.startsWith("--", i)) {
65 let j = i + (c === 36 ? 1 : 2);
66 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
67 out.push("meta", line.slice(i, j), "variable");
68 i = j;
69 continue;
70 }
71 if (c === 33 /* ! */) {
72 const bang = /^![a-z-]+/.exec(line.slice(i));
73 if (bang) {
74 out.push("meta", bang[0]);
75 i += bang[0].length;
76 continue;
77 }
78 }
79 if (c === 35 /* # */ && /^#[0-9a-fA-F]{3,8}\b/.test(line.slice(i))) {
80 const hex = /^#[0-9a-fA-F]{3,8}/.exec(line.slice(i))!;
81 out.push("number", hex[0]);
82 i += hex[0].length;
83 continue;
84 }
85 if (isDigitCh(c) || (c === 46 && isDigitCh(line.charCodeAt(i + 1)))) {
86 let j = scanNumber(line, i);
87 const unit = /^(%|[a-zA-Z]+)/.exec(line.slice(j));
88 if (unit) j += unit[0].length;
89 out.push("number", line.slice(i, j));
90 i = j;
91 continue;
92 }
93 if (c === 123) {
94 out.push("punctuation", "{");
95 state = { ...state, depth: state.depth + 1 };
96 i++;
97 continue;
98 }
99 if (c === 125) {
100 out.push("punctuation", "}");
101 state = { ...state, depth: Math.max(0, state.depth - 1) };
102 i++;
103 continue;
104 }
105 if (c === 46 || c === 35 /* .class #id */) {
106 const sel = /^[.#][A-Za-z_-][A-Za-z0-9_-]*/.exec(line.slice(i));
107 if (sel && state.depth === 0) {
108 out.push("function", sel[0]);
109 i += sel[0].length;
110 continue;
111 }
112 }
113 if (c === 58 /* : */) {
114 const pseudo = /^::?[A-Za-z-]+/.exec(line.slice(i));
115 if (pseudo && state.depth === 0) {
116 out.push("type", pseudo[0]);
117 i += pseudo[0].length;
118 continue;
119 }
120 }
121 if (isAlphaCh(c) || c === 95 || c === 45) {
122 let j = i;
123 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
124 const word = line.slice(i, j);
125 const after = spaceRun(line, j);
126 if (line[j] === "(") out.push("function", word);
127 else if ((state.depth > 0 || paren > 0) && line[after] === ":")
128 out.push("keyword", word, "property");
129 else if (state.depth > 0) out.push("constant", word);
130 else out.push("type", word, "tag");
131 i = j;
132 continue;
133 }
134 if (c === 40) paren++;
135 if (c === 41) paren = Math.max(0, paren - 1);
136 if (c === 44 || c === 59 || c === 40 || c === 41)
137 out.push("punctuation", line[i]!);
138 else out.push("operator", line[i]!);
139 i++;
140 }
141 return { tokens: out.done(), state };
142 }
143
144 // ---- diff ----
src/web/highlight/detect.ts added +225
@@ -0,0 +1,225 @@
1 /** Which language a path, name, shebang or modeline means. */
2 import { type Language } from "./tokens.ts";
3
4 export const EXT: Record<string, Language> = {
5 ts: "ts",
6 tsx: "ts",
7 mts: "ts",
8 cts: "ts",
9 js: "ts",
10 jsx: "ts",
11 mjs: "ts",
12 cjs: "ts",
13 py: "python",
14 pyi: "python",
15 pyw: "python",
16 go: "go",
17 rs: "rust",
18 c: "c",
19 h: "c",
20 cc: "c",
21 cpp: "c",
22 cxx: "c",
23 hpp: "c",
24 hh: "c",
25 hxx: "c",
26 m: "c",
27 mm: "c",
28 java: "java",
29 kt: "kotlin",
30 kts: "kotlin",
31 swift: "swift",
32 rb: "ruby",
33 rake: "ruby",
34 gemspec: "ruby",
35 php: "php",
36 lua: "lua",
37 zig: "zig",
38 ex: "elixir",
39 exs: "elixir",
40 nix: "nix",
41 json: "json",
42 jsonc: "json",
43 json5: "json",
44 yaml: "yaml",
45 yml: "yaml",
46 toml: "toml",
47 ini: "ini",
48 cfg: "ini",
49 conf: "ini",
50 properties: "ini",
51 editorconfig: "ini",
52 md: "markdown",
53 markdown: "markdown",
54 mdx: "markdown",
55 css: "css",
56 scss: "css",
57 sass: "css",
58 less: "css",
59 html: "html",
60 htm: "html",
61 xhtml: "html",
62 vue: "html",
63 svelte: "html",
64 xml: "html",
65 svg: "html",
66 sh: "shell",
67 bash: "shell",
68 zsh: "shell",
69 fish: "shell",
70 ksh: "shell",
71 env: "shell",
72 sql: "sql",
73 diff: "diff",
74 patch: "diff",
75 mk: "makefile",
76 make: "makefile",
77 };
78
79 export const FILENAMES: Record<string, Language> = {
80 dockerfile: "dockerfile",
81 containerfile: "dockerfile",
82 makefile: "makefile",
83 gnumakefile: "makefile",
84 justfile: "makefile",
85 rakefile: "ruby",
86 gemfile: "ruby",
87 podfile: "ruby",
88 brewfile: "ruby",
89 vagrantfile: "ruby",
90 ".gitignore": "shell",
91 ".dockerignore": "shell",
92 ".gitattributes": "shell",
93 ".npmrc": "ini",
94 ".editorconfig": "ini",
95 ".env": "shell",
96 ".bashrc": "shell",
97 ".bash_profile": "shell",
98 ".zshrc": "shell",
99 ".profile": "shell",
100 ".zprofile": "shell",
101 "cargo.lock": "toml",
102 "go.mod": "go",
103 "go.sum": "plain",
104 "cmakelists.txt": "makefile",
105 };
106
107 export const SHEBANG: [RegExp, Language][] = [
108 [/\b(?:python|python3|python2|uv run)\b/, "python"],
109 [/\b(?:node|bun|deno|ts-node)\b/, "ts"],
110 [/\bruby\b/, "ruby"],
111 [/\b(?:bash|zsh|sh|dash|ksh|fish)\b/, "shell"],
112 [/\bphp\b/, "php"],
113 [/\blua\b/, "lua"],
114 [/\belixir\b/, "elixir"],
115 [/\bmake\b/, "makefile"],
116 ];
117
118 export const MODELINE_ALIASES: Record<string, Language> = {
119 javascript: "ts",
120 typescript: "ts",
121 js: "ts",
122 ts: "ts",
123 sh: "shell",
124 bash: "shell",
125 zsh: "shell",
126 "shell-script": "shell",
127 conf: "ini",
128 make: "makefile",
129 yml: "yaml",
130 "c++": "c",
131 cpp: "c",
132 objc: "c",
133 rb: "ruby",
134 py: "python",
135 };
136
137 /** Every language this file can highlight — the fence-info vocabulary too. */
138 export const LANGUAGES: readonly Language[] = [
139 "ts",
140 "python",
141 "go",
142 "rust",
143 "c",
144 "java",
145 "kotlin",
146 "swift",
147 "ruby",
148 "php",
149 "lua",
150 "zig",
151 "elixir",
152 "nix",
153 "json",
154 "yaml",
155 "toml",
156 "ini",
157 "markdown",
158 "css",
159 "html",
160 "shell",
161 "sql",
162 "dockerfile",
163 "makefile",
164 "diff",
165 "plain",
166 ];
167
168 /** A language name as a fence info string or a modeline writes it. */
169 export function languageFromName(name: string): Language {
170 const word =
171 name
172 .trim()
173 .toLowerCase()
174 .split(/[\s,;:]/)[0] ?? "";
175 if (word === "") return "plain";
176 const alias = MODELINE_ALIASES[word];
177 if (alias) return alias;
178 if (Object.hasOwn(EXT, word)) return EXT[word]!;
179 if (Object.hasOwn(FILENAMES, word)) return FILENAMES[word]!;
180 return LANGUAGES.includes(word as Language) ? (word as Language) : "plain";
181 }
182
183
184 /**
185 * The language of a file. The extension decides where it can; otherwise the
186 * bare filename (`Dockerfile`, `Makefile`, `.zshrc`), and only then the first
187 * line — a shebang or an editor modeline — which is the one thing a file with
188 * no extension can say about itself.
189 */
190 export function detectLanguage(path: string, firstLine?: string): Language {
191 const name = path.slice(path.lastIndexOf("/") + 1);
192 const lower = name.toLowerCase();
193 const byName = FILENAMES[lower];
194 if (byName) return byName;
195 // `Dockerfile.dev`, `Makefile.local`: the stem still names the language.
196 const stem = lower.split(".")[0] ?? "";
197 const dot = lower.lastIndexOf(".");
198 if (dot > 0) {
199 const byExt = EXT[lower.slice(dot + 1)];
200 if (byExt) return byExt;
201 }
202 if (dot > 0 && FILENAMES[stem] && stem !== "") {
203 const byStem = FILENAMES[stem];
204 if (byStem === "dockerfile" || byStem === "makefile") return byStem;
205 }
206 if (firstLine !== undefined) {
207 const fromLine = languageFromFirstLine(firstLine);
208 if (fromLine !== "plain") return fromLine;
209 }
210 return "plain";
211 }
212
213 /** A shebang (`#!/usr/bin/env python3`) or a modeline (`vim: ft=ruby`). */
214 export function languageFromFirstLine(line: string): Language {
215 const head = line.slice(0, 200);
216 if (head.startsWith("#!")) {
217 for (const [pattern, lang] of SHEBANG) if (pattern.test(head)) return lang;
218 }
219 const vim = /(?:ft|filetype|syntax)=([A-Za-z0-9_+-]+)/.exec(head);
220 if (vim) return languageFromName(vim[1]!);
221 const emacs = /-\*-\s*(?:mode:\s*)?([A-Za-z0-9_+-]+)/.exec(head);
222 if (emacs) return languageFromName(emacs[1]!);
223 if (/^<\?xml|^<!doctype html/i.test(head.trim())) return "html";
224 return "plain";
225 }
src/web/highlight/diff.ts added +29
@@ -0,0 +1,29 @@
1 /** Unified diff scanner. */
2 import { type ScanState, type Scanned } from "./state.ts";
3 import { Out } from "./tokens.ts";
4
5 export function scanDiff(line: string, state: ScanState): Scanned {
6 const out = new Out();
7 if (
8 /^(diff |index |new file|deleted file|similarity|rename |old mode|new mode)/.test(
9 line,
10 )
11 ) {
12 out.push("meta", line);
13 } else if (line.startsWith("@@")) {
14 out.push("function", line);
15 } else if (line.startsWith("+++") || line.startsWith("---")) {
16 out.push("meta", line, "heading");
17 } else if (line.startsWith("+")) {
18 out.push("meta", line, "inserted");
19 } else if (line.startsWith("-")) {
20 out.push("keyword", line, "deleted");
21 } else if (line.startsWith("\\")) {
22 out.push("comment", line);
23 } else {
24 out.push("plain", line);
25 }
26 return { tokens: out.done(), state };
27 }
28
29 // ---- Makefile ----
src/web/highlight/dockerfile.ts added +31
@@ -0,0 +1,31 @@
1 /** Dockerfile scanner. */
2 import { set } from "./chars.ts";
3 import { scanGeneric } from "./generic.ts";
4 import { SPECS } from "./specs.ts";
5 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
6 import { Out } from "./tokens.ts";
7
8 export const DOCKER_INSTRUCTIONS = set(
9 `FROM RUN CMD LABEL MAINTAINER EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD
10 STOPSIGNAL HEALTHCHECK SHELL`,
11 );
12
13
14 export function scanDockerfile(line: string, state: ScanState): Scanned {
15 const out = new Out();
16 if (/^\s*#/.test(line)) {
17 out.push(/^\s*#\s*(syntax|escape)=/.test(line) ? "meta" : "comment", line);
18 return { tokens: out.done(), state };
19 }
20 const instruction = /^(\s*)([A-Za-z]+)(\s|$)/.exec(line);
21 let from = 0;
22 if (instruction && DOCKER_INSTRUCTIONS.has(instruction[2]!.toUpperCase())) {
23 out.push("plain", instruction[1]!);
24 out.push("keyword", instruction[2]!);
25 from = instruction[1]!.length + instruction[2]!.length;
26 }
27 const spec = SPECS.dockerfile!;
28 const rest = scanGeneric(line.slice(from), spec, INITIAL_SCAN);
29 out.take(rest.tokens);
30 return { tokens: out.done(), state };
31 }
src/web/highlight/generic.ts added +498
@@ -0,0 +1,498 @@
1 /** The table-driven scanner most languages use. */
2 import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh, isUpperCh, set } from "./chars.ts";
3 import { consumeStringBody, pushString, scanNumber, spaceRun } from "./lexing.ts";
4 import { type LangSpec } from "./specs.ts";
5 import { type Heredoc, type ScanState, type Scanned } from "./state.ts";
6 import { Out, type TokenClass, type TokenKind } from "./tokens.ts";
7
8 /** Shell words after which the next word is a command again. */
9 export const COMMAND_OPENERS = set(
10 `then else elif do done fi in time exec sudo command xargs nohup env watch`,
11 );
12
13 /**
14 * The scanner most languages use: comments, strings, numbers, identifiers
15 * classified against the spec's word sets, and everything else as operator or
16 * punctuation. `expectValue` tracks whether the next `/` is a regex or a
17 * division, and whether a `<` opens JSX — the one piece of grammar a
18 * table-driven scanner cannot do without.
19 */
20 export function scanGeneric(
21 line: string,
22 spec: LangSpec,
23 initial: ScanState,
24 ): Scanned {
25 const out = new Out();
26 let state = initial;
27 let i = 0;
28 const n = line.length;
29 let expectValue = true;
30 let pendingHeredoc: Heredoc | null = null;
31 let lastWord = "";
32 // Shell only: the first word of a command is the thing being run.
33 let atCommand = true;
34
35 // A heredoc body swallows whole lines until its terminator.
36 if (state.heredoc) {
37 const hd = state.heredoc;
38 const body = hd.indent ? line.trimStart() : line;
39 if (body.trimEnd() === hd.tag) {
40 out.push("meta", line);
41 return { tokens: out.done(), state: { ...state, heredoc: null } };
42 }
43 pushString(out, line, true, "string", undefined, "variable");
44 return { tokens: out.done(), state };
45 }
46
47 // Continue an open block comment.
48 if (state.block && spec.blockComment) {
49 const end = line.indexOf(spec.blockComment[1]);
50 if (end === -1) {
51 out.push("comment", line);
52 return { tokens: out.done(), state };
53 }
54 out.push("comment", line.slice(0, end + spec.blockComment[1].length));
55 i = end + spec.blockComment[1].length;
56 state = { ...state, block: false };
57 }
58
59 // Continue an open multi-line string.
60 if (state.str) {
61 const open = state.str;
62 const consumed = consumeStringBody(line, 0, open);
63 pushString(
64 out,
65 line.slice(0, consumed.end),
66 open.interpolate === true,
67 "string",
68 undefined,
69 open.interpolateAs ?? "code",
70 );
71 if (!consumed.closed) return { tokens: out.done(), state };
72 i = consumed.end;
73 state = { ...state, str: null };
74 }
75
76 while (i < n) {
77 const c = line.charCodeAt(i);
78
79 if (isSpaceCh(c)) {
80 const j = spaceRun(line, i);
81 out.push("plain", line.slice(i, j));
82 i = j;
83 continue;
84 }
85
86 // A C preprocessor line: `#include <stdio.h>`, `#define X 1`.
87 if (
88 spec.preproc &&
89 c === 35 &&
90 out.tokens.every((t) => t.cls === "plain")
91 ) {
92 const directive = /^#\s*[a-z_]+/.exec(line.slice(i));
93 if (directive) {
94 out.push("meta", directive[0]);
95 i += directive[0].length;
96 const angle = /^\s*<[^>\s]*>/.exec(line.slice(i));
97 if (angle) {
98 out.push("plain", angle[0].slice(0, angle[0].indexOf("<")));
99 out.push("string", angle[0].slice(angle[0].indexOf("<")));
100 i += angle[0].length;
101 }
102 continue;
103 }
104 }
105
106 // Line comment. In shells a `#` only starts one at a word boundary, so
107 // `curl http://x#y` and `${x#y}` survive.
108 const lc = spec.lineComment.find((p) => line.startsWith(p, i));
109 if (
110 lc !== undefined &&
111 (lc !== "#" || i === 0 || isSpaceCh(line.charCodeAt(i - 1)))
112 ) {
113 out.push("comment", line.slice(i));
114 i = n;
115 continue;
116 }
117
118 // Block comment.
119 if (spec.blockComment && line.startsWith(spec.blockComment[0], i)) {
120 const close = spec.blockComment[1];
121 const end = line.indexOf(close, i + spec.blockComment[0].length);
122 if (end === -1) {
123 out.push("comment", line.slice(i));
124 i = n;
125 state = { ...state, block: true };
126 } else {
127 out.push("comment", line.slice(i, end + close.length));
128 i = end + close.length;
129 }
130 continue;
131 }
132
133 // Rust `#[derive(Debug)]`, and `#![no_std]`.
134 if (spec.hashAttr && c === 35 && /^#!?\[/.test(line.slice(i))) {
135 const end = line.indexOf("]", i);
136 const stop = end === -1 ? n : end + 1;
137 out.push("meta", line.slice(i, stop), "decorator");
138 i = stop;
139 expectValue = true;
140 continue;
141 }
142
143 // A decorator or annotation: `@Component`, `@staticmethod`, `@interface`.
144 if (spec.atDecorator && c === 64 && isAlphaCh(line.charCodeAt(i + 1))) {
145 let j = i + 1;
146 while (
147 j < n &&
148 (isIdentCh(line.charCodeAt(j)) || line.charCodeAt(j) === 46)
149 )
150 j++;
151 out.push("meta", line.slice(i, j), "decorator");
152 i = j;
153 expectValue = false;
154 continue;
155 }
156
157 // A variable sigil: `$PATH`, `${x}`, `@ivar`, `@@class`.
158 if (spec.sigils && spec.sigils.includes(line[i]!)) {
159 const j = readVariable(line, i);
160 if (j > i + 1) {
161 out.push("meta", line.slice(i, j), "variable");
162 i = j;
163 expectValue = false;
164 continue;
165 }
166 }
167
168 // `:atom` / `:symbol`, but not `::` and not `a ? b : c`.
169 if (
170 spec.atoms &&
171 c === 58 &&
172 isAlphaCh(line.charCodeAt(i + 1)) &&
173 line.charCodeAt(i - 1) !== 58
174 ) {
175 let j = i + 1;
176 while (j < n && isIdentCh(line.charCodeAt(j))) j++;
177 if (spec.identTail && j < n && spec.identTail.includes(line[j]!)) j++;
178 out.push("constant", line.slice(i, j));
179 i = j;
180 expectValue = false;
181 continue;
182 }
183
184 // A Rust lifetime: `'a` with no closing quote is not a character.
185 if (spec.lifetimes && c === 39 && isAlphaCh(line.charCodeAt(i + 1))) {
186 let j = i + 1;
187 while (j < n && isIdentCh(line.charCodeAt(j))) j++;
188 if (line.charCodeAt(j) !== 39) {
189 out.push("meta", line.slice(i, j), "variable");
190 i = j;
191 expectValue = false;
192 continue;
193 }
194 }
195
196 // `/>` closes a JSX tag that an `{expression}` attribute interrupted.
197 if (spec.jsx && c === 47 && line.charCodeAt(i + 1) === 62) {
198 out.push("punctuation", "/>");
199 i += 2;
200 expectValue = true;
201 continue;
202 }
203
204 // JSX/TSX markup, where a value is expected.
205 if (spec.jsx && c === 60 && expectValue) {
206 const consumed = scanJsxTag(line, i, out);
207 if (consumed > i) {
208 i = consumed;
209 expectValue = true;
210 continue;
211 }
212 }
213
214 // A string, or a regex literal where a value is expected.
215 const strSpec = spec.strings.find(
216 (s) =>
217 line.startsWith(s.open, i) && (s.valueOnly !== true || expectValue),
218 );
219 if (strSpec) {
220 // An empty regex `//` is a comment everywhere it could be one.
221 const bodyStart = i + strSpec.open.length;
222 const consumed = consumeStringBody(line, bodyStart, strSpec);
223 const cls = strSpec.cls ?? "string";
224 if (consumed.closed) {
225 let end = consumed.end;
226 // Regex flags, string suffixes: `/x/gi`, `"a"u8`.
227 while (end < n && isAlphaCh(line.charCodeAt(end))) end++;
228 pushString(
229 out,
230 line.slice(i, end),
231 strSpec.interpolate === true,
232 cls,
233 strSpec.kind,
234 strSpec.interpolateAs ?? "code",
235 );
236 i = end;
237 } else if (strSpec.multiline) {
238 pushString(
239 out,
240 line.slice(i),
241 strSpec.interpolate === true,
242 cls,
243 strSpec.kind,
244 strSpec.interpolateAs ?? "code",
245 );
246 i = n;
247 state = {
248 ...state,
249 str: {
250 close: strSpec.close,
251 escape: strSpec.escape,
252 ...(strSpec.interpolate === true ? { interpolate: true } : {}),
253 ...(strSpec.interpolateAs === undefined
254 ? {}
255 : { interpolateAs: strSpec.interpolateAs }),
256 },
257 };
258 } else {
259 // Unterminated single-line string: take the rest of the line.
260 pushString(
261 out,
262 line.slice(i),
263 strSpec.interpolate === true,
264 cls,
265 strSpec.kind,
266 strSpec.interpolateAs ?? "code",
267 );
268 i = n;
269 }
270 expectValue = false;
271 continue;
272 }
273
274 // A heredoc opener: `<<EOF`, `<<-'EOF'`, `<<~HTML`.
275 if (spec.heredoc && c === 60 && line.charCodeAt(i + 1) === 60) {
276 const opener = /^<<([-~]?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/.exec(
277 line.slice(i),
278 );
279 if (opener) {
280 out.push("operator", line.slice(i, i + 2 + opener[1]!.length));
281 out.push("meta", opener[0].slice(2 + opener[1]!.length));
282 i += opener[0].length;
283 pendingHeredoc = { tag: opener[3]!, indent: opener[1] !== "" };
284 expectValue = false;
285 continue;
286 }
287 }
288
289 // A command-line flag: `-v`, `--long-form`, `-euo`.
290 if (
291 spec.flags &&
292 c === 45 &&
293 (i === 0 || isSpaceCh(line.charCodeAt(i - 1))) &&
294 !atCommand
295 ) {
296 const flag = /^--?[A-Za-z][A-Za-z0-9_-]*/.exec(line.slice(i));
297 if (flag) {
298 out.push("constant", flag[0], "attribute");
299 i += flag[0].length;
300 expectValue = false;
301 continue;
302 }
303 }
304
305 // Number.
306 if (
307 isDigitCh(c) ||
308 (c === 46 && isDigitCh(line.charCodeAt(i + 1)) && expectValue)
309 ) {
310 const j = scanNumber(line, i);
311 out.push("number", line.slice(i, j));
312 i = j;
313 expectValue = false;
314 continue;
315 }
316
317 // Identifier / keyword / type / constant / function.
318 if (isAlphaCh(c) || c === 95 || (c === 36 && !spec.sigils)) {
319 let j = i + 1;
320 while (
321 j < n &&
322 (isIdentCh(line.charCodeAt(j)) ||
323 line.charCodeAt(j) === 36 ||
324 (spec.identInner !== undefined && spec.identInner.includes(line[j]!)))
325 )
326 j++;
327 if (spec.identTail && j < n && spec.identTail.includes(line[j]!)) j++;
328 const word = line.slice(i, j);
329 const probe = spec.ignoreCase === true ? word.toLowerCase() : word;
330 const call = line[j] === "(";
331
332 let cls: TokenClass = "plain";
333 let kind: TokenKind | undefined;
334 if (spec.keywords.has(probe)) cls = "keyword";
335 else if (spec.constants.has(probe)) cls = "constant";
336 else if (spec.types.has(probe)) cls = "type";
337 else if (spec.defineAfter?.has(lastWord)) {
338 cls = spec.typeAfter?.has(lastWord) ? "type" : "function";
339 } else if (spec.typeAfter?.has(lastWord)) cls = "type";
340 else if (spec.macroBang && line[j] === "!" && line[j + 1] !== "=") {
341 // `println!` is one thing, not a name and a negation.
342 out.push("function", `${word}!`, "decorator");
343 lastWord = probe;
344 atCommand = false;
345 i = j + 1;
346 expectValue = true;
347 continue;
348 } else if (call && spec.callAsFunction) cls = "function";
349 else if (
350 spec.dotProperty &&
351 i > 0 &&
352 line.charCodeAt(i - 1) === 46 &&
353 line.charCodeAt(i - 2) !== 46
354 ) {
355 cls = "plain";
356 kind = "property";
357 } else if (spec.capitalIsType !== false && isUpperCh(c)) cls = "type";
358 else if (spec.commandPosition && atCommand)
359 cls = line[j] === "=" ? "plain" : "function";
360 if (spec.commandPosition && atCommand && line[j] === "=")
361 kind = "variable";
362
363 out.push(cls, word, kind);
364 lastWord = probe;
365 i = j;
366 expectValue =
367 cls === "keyword" && !spec.constants.has(probe) && probe !== "this";
368 atCommand =
369 cls === "keyword" && COMMAND_OPENERS.has(probe) ? true : false;
370 continue;
371 }
372
373 // Operators and punctuation.
374 if (c === 123) state = { ...state, depth: state.depth + 1 };
375 if (c === 125) state = { ...state, depth: Math.max(0, state.depth - 1) };
376 if (
377 c === 40 ||
378 c === 41 ||
379 c === 91 ||
380 c === 93 ||
381 c === 123 ||
382 c === 125 ||
383 c === 59 ||
384 c === 44 ||
385 c === 46
386 ) {
387 out.push("punctuation", line[i]!);
388 expectValue = c !== 41 && c !== 93 && c !== 46;
389 } else {
390 out.push("operator", line[i]!);
391 expectValue = true;
392 }
393 if (c === 124 || c === 59 || c === 38 || c === 40 || c === 123)
394 atCommand = true;
395 else if (!isSpaceCh(c)) atCommand = false;
396 lastWord = "";
397 i++;
398 }
399
400 const next: ScanState =
401 pendingHeredoc === null ? state : { ...state, heredoc: pendingHeredoc };
402 return { tokens: out.done(), state: next };
403 }
404
405 /** `$name`, `${expr}`, `$(cmd)`, `@ivar`, `@@cvar`, `$1`. */
406 export function readVariable(line: string, at: number): number {
407 const n = line.length;
408 let i = at + 1;
409 if (line.charCodeAt(at) === 64 && line.charCodeAt(i) === 64) i++; // @@cvar
410 const c = line.charCodeAt(i);
411 if (c === 123 /* { */ || c === 40 /* ( */) {
412 const close = c === 123 ? 125 : 41;
413 let depth = 1;
414 i++;
415 while (i < n && depth > 0) {
416 const d = line.charCodeAt(i);
417 if (d === c) depth++;
418 else if (d === close) depth--;
419 i++;
420 }
421 return i;
422 }
423 if (isDigitCh(c) || c === 42 || c === 64 || c === 63 || c === 35)
424 return i + 1;
425 while (i < n && isIdentCh(line.charCodeAt(i))) i++;
426 return i;
427 }
428
429 /**
430 * A JSX element's opening or closing tag. Returns where it ends, or `at` if
431 * this `<` was not markup after all. Inside the tag, names and attributes get
432 * their own colours; a `{` hands control back to the code scanner.
433 */
434 export function scanJsxTag(line: string, at: number, out: Out): number {
435 const n = line.length;
436 let i = at + 1;
437 if (line[i] === "/") i++;
438 const start = i;
439 while (
440 i < n &&
441 (isIdentCh(line.charCodeAt(i)) || line[i] === "." || line[i] === "-")
442 )
443 i++;
444 // `<>` (a fragment) is markup; `a < b` is not.
445 if (i === start && line[at + 1] !== ">") return at;
446 out.push("punctuation", line.slice(at, start));
447 out.push("keyword", line.slice(start, i), "tag");
448
449 while (i < n) {
450 const c = line.charCodeAt(i);
451 if (isSpaceCh(c)) {
452 const j = spaceRun(line, i);
453 out.push("plain", line.slice(i, j));
454 i = j;
455 continue;
456 }
457 if (c === 62 /* > */) {
458 out.push("punctuation", ">");
459 return i + 1;
460 }
461 if (c === 47 && line.charCodeAt(i + 1) === 62) {
462 out.push("punctuation", "/>");
463 return i + 2;
464 }
465 if (c === 123 /* { */) return i; // an expression: back to the code scanner
466 if (c === 61 /* = */) {
467 out.push("operator", "=");
468 i++;
469 continue;
470 }
471 if (c === 34 || c === 39) {
472 const quote = line[i]!;
473 const consumed = consumeStringBody(line, i + 1, {
474 close: quote,
475 escape: true,
476 });
477 out.push("string", line.slice(i, consumed.end));
478 i = consumed.end;
479 continue;
480 }
481 if (isAlphaCh(c) || c === 95) {
482 let j = i;
483 while (
484 j < n &&
485 (isIdentCh(line.charCodeAt(j)) || line[j] === "-" || line[j] === ":")
486 )
487 j++;
488 out.push("type", line.slice(i, j), "attribute");
489 i = j;
490 continue;
491 }
492 out.push("punctuation", line[i]!);
493 i++;
494 }
495 return n;
496 }
497
498 // ---- Markdown ----
src/web/highlight/html.ts added +190
@@ -0,0 +1,190 @@
1 /** HTML scanner. */
2 import { scanOneLine } from "./scanners.ts";
3 import { isSpaceCh } from "./chars.ts";
4 import { consumeStringBody, spaceRun } from "./lexing.ts";
5 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
6 import { Out } from "./tokens.ts";
7
8 export function scanHtml(line: string, state: ScanState): Scanned {
9 const out = new Out();
10 let i = 0;
11 const n = line.length;
12
13 // Inside <script>/<style>: scan with that language until the closing tag.
14 if (state.embed) {
15 const embed = state.embed;
16 const close = line.toLowerCase().indexOf(embed.end);
17 if (close === -1) {
18 const inner = scanOneLine(line, embed.lang, embed.inner);
19 out.take(inner.tokens);
20 return {
21 tokens: out.done(),
22 state: { ...state, embed: { ...embed, inner: inner.state } },
23 };
24 }
25 if (close > 0) {
26 const inner = scanOneLine(line.slice(0, close), embed.lang, embed.inner);
27 out.take(inner.tokens);
28 }
29 i = close;
30 state = { ...state, embed: null };
31 }
32
33 if (state.block) {
34 const end = line.indexOf("-->", i);
35 if (end === -1) {
36 out.push("comment", line.slice(i));
37 return { tokens: out.done(), state };
38 }
39 out.push("comment", line.slice(i, end + 3));
40 i = end + 3;
41 state = { ...state, block: false };
42 }
43
44 while (i < n) {
45 if (state.tag) {
46 i = scanHtmlAttributes(line, i, out);
47 if (i < n || line.endsWith(">")) state = { ...state, tag: false };
48 continue;
49 }
50 const lt = line.indexOf("<", i);
51 if (lt === -1) {
52 pushHtmlText(out, line.slice(i));
53 i = n;
54 continue;
55 }
56 pushHtmlText(out, line.slice(i, lt));
57 i = lt;
58
59 if (line.startsWith("<!--", i)) {
60 const end = line.indexOf("-->", i + 4);
61 if (end === -1) {
62 out.push("comment", line.slice(i));
63 return { tokens: out.done(), state: { ...state, block: true } };
64 }
65 out.push("comment", line.slice(i, end + 3));
66 i = end + 3;
67 continue;
68 }
69 if (line.startsWith("<!", i) || line.startsWith("<?", i)) {
70 const end = line.indexOf(">", i);
71 const stop = end === -1 ? n : end + 1;
72 out.push("meta", line.slice(i, stop));
73 i = stop;
74 continue;
75 }
76 const name = /^<\/?([A-Za-z][A-Za-z0-9:-]*)/.exec(line.slice(i));
77 if (!name) {
78 out.push("punctuation", "<");
79 i++;
80 continue;
81 }
82 const lead = name[0].startsWith("</") ? 2 : 1;
83 out.push("punctuation", line.slice(i, i + lead));
84 out.push("keyword", name[1]!, "tag");
85 i += name[0].length;
86 const after = scanHtmlAttributes(line, i, out);
87 const tag = name[1]!.toLowerCase();
88 const closed = line.slice(i, after).includes(">");
89 i = after;
90 if (!closed) {
91 state = { ...state, tag: true };
92 continue;
93 }
94 if (lead === 1 && (tag === "script" || tag === "style")) {
95 state = {
96 ...state,
97 embed: {
98 lang: tag === "script" ? "ts" : "css",
99 end: `</${tag}`,
100 inner: INITIAL_SCAN,
101 },
102 };
103 const rest = line.toLowerCase().indexOf(`</${tag}`, i);
104 if (rest === -1) {
105 if (i < n) {
106 const inner = scanOneLine(
107 line.slice(i),
108 tag === "script" ? "ts" : "css",
109 INITIAL_SCAN,
110 );
111 out.take(inner.tokens);
112 }
113 return { tokens: out.done(), state };
114 }
115 const inner = scanOneLine(
116 line.slice(i, rest),
117 tag === "script" ? "ts" : "css",
118 INITIAL_SCAN,
119 );
120 out.take(inner.tokens);
121 i = rest;
122 state = { ...state, embed: null };
123 }
124 }
125 return { tokens: out.done(), state };
126 }
127
128 /** Text between tags, with entities picked out. */
129 export function pushHtmlText(out: Out, text: string): void {
130 let run = 0;
131 const entity = /&(#\d+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});/g;
132 let match: RegExpExecArray | null;
133 while ((match = entity.exec(text)) !== null) {
134 out.push("plain", text.slice(run, match.index));
135 out.push("constant", match[0]);
136 run = match.index + match[0].length;
137 }
138 out.push("plain", text.slice(run));
139 }
140
141 /** Attributes up to and including the `>` that closes the tag. */
142 export function scanHtmlAttributes(line: string, from: number, out: Out): number {
143 const n = line.length;
144 let i = from;
145 while (i < n) {
146 const c = line.charCodeAt(i);
147 if (isSpaceCh(c)) {
148 const j = spaceRun(line, i);
149 out.push("plain", line.slice(i, j));
150 i = j;
151 continue;
152 }
153 if (c === 62 /* > */) {
154 out.push("punctuation", ">");
155 return i + 1;
156 }
157 if (c === 47 && line.charCodeAt(i + 1) === 62) {
158 out.push("punctuation", "/>");
159 return i + 2;
160 }
161 if (c === 61) {
162 out.push("operator", "=");
163 i++;
164 continue;
165 }
166 if (c === 34 || c === 39) {
167 const consumed = consumeStringBody(line, i + 1, {
168 close: line[i]!,
169 escape: false,
170 });
171 out.push("string", line.slice(i, consumed.end));
172 i = consumed.end;
173 continue;
174 }
175 let j = i;
176 while (
177 j < n &&
178 !isSpaceCh(line.charCodeAt(j)) &&
179 line[j] !== "=" &&
180 line[j] !== ">"
181 )
182 j++;
183 if (j === i) j++;
184 out.push("type", line.slice(i, j), "attribute");
185 i = j;
186 }
187 return n;
188 }
189
190 // ---- CSS (and SCSS/LESS) ----
src/web/highlight/lexing.ts added +154
@@ -0,0 +1,154 @@
1 /** Scanning helpers shared by every scanner: strings, numbers, indentation. */
2 import { isAlphaCh, isDigitCh, isSpaceCh } from "./chars.ts";
3 import { readVariable } from "./generic.ts";
4 import { Out, type TokenClass, type TokenKind } from "./tokens.ts";
5
6 /** Consume a string body from `start`, honouring escapes. */
7 export function consumeStringBody(
8 line: string,
9 start: number,
10 spec: { close: string; escape: boolean },
11 ): { end: number; closed: boolean } {
12 let i = start;
13 const n = line.length;
14 while (i < n) {
15 if (spec.escape && line.charCodeAt(i) === 92) {
16 i += 2;
17 continue;
18 }
19 if (line.startsWith(spec.close, i)) {
20 return { end: i + spec.close.length, closed: true };
21 }
22 i++;
23 }
24 return { end: n, closed: false };
25 }
26
27 /**
28 * Emit a string body, breaking out `${…}`/`#{…}` interpolations so the code
29 * inside a template literal is not painted as prose.
30 */
31 export function pushString(
32 out: Out,
33 text: string,
34 interpolate: boolean,
35 cls: TokenClass = "string",
36 kind?: TokenKind,
37 as: "code" | "variable" = "code",
38 ): void {
39 if (!interpolate || text.length < 2) {
40 out.push(cls, text, kind);
41 return;
42 }
43 let i = 0;
44 let run = 0;
45 while (i < text.length) {
46 const c = text.charCodeAt(i);
47 if (c === 92) {
48 i += 2;
49 continue;
50 }
51 const braced =
52 (c === 36 || c === 35) && text.charCodeAt(i + 1) === 123; /* { */
53 const bare =
54 as === "variable" &&
55 c === 36 &&
56 (isAlphaCh(text.charCodeAt(i + 1)) || text.charCodeAt(i + 1) === 95);
57 if (!braced && !bare) {
58 i++;
59 continue;
60 }
61 out.push(cls, text.slice(run, i), kind);
62 if (bare) {
63 const end = readVariable(text, i);
64 out.push("meta", text.slice(i, end), "variable");
65 i = end;
66 run = end;
67 continue;
68 }
69 let depth = 1;
70 let j = i + 2;
71 while (j < text.length && depth > 0) {
72 const d = text.charCodeAt(j);
73 if (d === 123) depth++;
74 else if (d === 125) depth--;
75 j++;
76 }
77 if (as === "variable") {
78 out.push("meta", text.slice(i, j), "variable");
79 } else {
80 out.push("punctuation", text.slice(i, i + 2));
81 out.push("plain", text.slice(i + 2, depth === 0 ? j - 1 : j));
82 if (depth === 0) out.push("punctuation", "}");
83 }
84 i = j;
85 run = j;
86 }
87 out.push(cls, text.slice(run), kind);
88 }
89
90 /** A number literal: hex/binary/octal, separators, exponents, suffixes. */
91 export function scanNumber(line: string, start: number): number {
92 const n = line.length;
93 let i = start;
94 if (
95 line.charCodeAt(i) === 48 /* 0 */ &&
96 i + 1 < n &&
97 /[xXbBoO]/.test(line[i + 1]!)
98 ) {
99 i += 2;
100 while (i < n && /[0-9a-fA-F_]/.test(line[i]!)) i++;
101 } else {
102 while (
103 i < n &&
104 (isDigitCh(line.charCodeAt(i)) || line.charCodeAt(i) === 95)
105 )
106 i++;
107 if (
108 i < n &&
109 line.charCodeAt(i) === 46 &&
110 isDigitCh(line.charCodeAt(i + 1))
111 ) {
112 i++;
113 while (
114 i < n &&
115 (isDigitCh(line.charCodeAt(i)) || line.charCodeAt(i) === 95)
116 )
117 i++;
118 }
119 if (i < n && (line[i] === "e" || line[i] === "E")) {
120 let j = i + 1;
121 if (j < n && (line[j] === "+" || line[j] === "-")) j++;
122 if (j < n && isDigitCh(line.charCodeAt(j))) {
123 i = j;
124 while (i < n && isDigitCh(line.charCodeAt(i))) i++;
125 }
126 }
127 }
128 // Suffixes: 10n, 1.0f32, 3u8, 100L, 5px is CSS's business, not ours here.
129 while (
130 i < n &&
131 (isAlphaCh(line.charCodeAt(i)) || isDigitCh(line.charCodeAt(i)))
132 ) {
133 const rest = line.slice(i);
134 if (!/^(n|[uif](8|16|32|64|128|size)?|[lLfFdDuU]+)/.test(rest)) break;
135 i += /^(n|[uif](8|16|32|64|128|size)?|[lLfFdDuU]+)/.exec(rest)![0].length;
136 break;
137 }
138 return i;
139 }
140
141 /** Where the run of spaces starting at `i` ends. */
142 export function spaceRun(line: string, i: number): number {
143 let j = i;
144 while (j < line.length && isSpaceCh(line.charCodeAt(j))) j++;
145 return j;
146 }
147
148 /** The column of the first non-space character, or -1 for a blank line. */
149 export function indentOf(line: string): number {
150 const at = spaceRun(line, 0);
151 return at === line.length ? -1 : at;
152 }
153
154 // ---- the generic scanner ----
src/web/highlight/makefile.ts added +76
@@ -0,0 +1,76 @@
1 /** Makefile scanner. */
2 import { scanOneLine } from "./scanners.ts";
3 import { readVariable } from "./generic.ts";
4 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
5 import { Out } from "./tokens.ts";
6
7 export function scanMakefile(line: string, state: ScanState): Scanned {
8 const out = new Out();
9 if (/^\s*#/.test(line)) {
10 out.push("comment", line);
11 return { tokens: out.done(), state };
12 }
13 // A recipe line is shell, and reads far better scanned as shell.
14 if (line.startsWith("\t")) {
15 out.push("punctuation", "\t");
16 const inner = scanOneLine(line.slice(1), "shell", INITIAL_SCAN);
17 out.take(inner.tokens);
18 return { tokens: out.done(), state };
19 }
20 const target = /^([A-Za-z0-9_./$()%-]+)(\s*:{1,2}=?)(?!=)/.exec(line);
21 if (target && !line.slice(0, target[1]!.length).includes("=")) {
22 if (target[2]!.includes("=")) {
23 out.push("keyword", target[1]!, "property");
24 } else {
25 out.push("function", target[1]!);
26 }
27 out.push("operator", target[2]!);
28 scanMakeRest(line, target[0].length, out);
29 return { tokens: out.done(), state };
30 }
31 const assign = /^([A-Za-z0-9_.-]+)(\s*[:+?]?=)/.exec(line);
32 if (assign) {
33 out.push("keyword", assign[1]!, "property");
34 out.push("operator", assign[2]!);
35 scanMakeRest(line, assign[0].length, out);
36 return { tokens: out.done(), state };
37 }
38 const directive =
39 /^(\s*)(include|ifeq|ifneq|ifdef|ifndef|else|endif|define|endef|export|unexport|vpath|\.PHONY)\b/.exec(
40 line,
41 );
42 if (directive) {
43 out.push("plain", directive[1]!);
44 out.push("keyword", directive[2]!);
45 scanMakeRest(line, directive[0].length, out);
46 return { tokens: out.done(), state };
47 }
48 scanMakeRest(line, 0, out);
49 return { tokens: out.done(), state };
50 }
51
52 export function scanMakeRest(line: string, from: number, out: Out): void {
53 const n = line.length;
54 let i = from;
55 let run = from;
56 while (i < n) {
57 const c = line.charCodeAt(i);
58 if (c === 35 /* # */) {
59 out.push("plain", line.slice(run, i));
60 out.push("comment", line.slice(i));
61 return;
62 }
63 if (c === 36 /* $ */) {
64 const end = readVariable(line, i);
65 out.push("plain", line.slice(run, i));
66 out.push("meta", line.slice(i, end), "variable");
67 i = end;
68 run = end;
69 continue;
70 }
71 i++;
72 }
73 out.push("plain", line.slice(run));
74 }
75
76 // ---- Dockerfile ----
src/web/highlight/markdown.ts added +188
@@ -0,0 +1,188 @@
1 /** Markdown scanner. */
2 import { scanOneLine } from "./scanners.ts";
3 import { languageFromName } from "./detect.ts";
4 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
5 import { Out, type TokenClass } from "./tokens.ts";
6
7 export const FENCE = /^(\s*)(```+|~~~+)(.*)$/;
8
9 /**
10 * Markdown, block by block. A fenced block carries its info string's language
11 * and scans its body with that language's scanner — the thing that makes a
12 * README's code samples look like code and not like prose.
13 */
14 export function scanMarkdown(line: string, state: ScanState): Scanned {
15 const out = new Out();
16
17 if (state.embed) {
18 const embed = state.embed;
19 const closing = FENCE.exec(line);
20 if (
21 closing &&
22 closing[2]!.startsWith(embed.end) &&
23 closing[3]!.trim() === ""
24 ) {
25 out.push("plain", closing[1]!);
26 out.push("meta", closing[2]! + closing[3]!);
27 return { tokens: out.done(), state: { ...state, embed: null } };
28 }
29 const inner = scanOneLine(line, embed.lang, embed.inner);
30 out.take(inner.tokens);
31 return {
32 tokens: out.done(),
33 state: { ...state, embed: { ...embed, inner: inner.state } },
34 };
35 }
36
37 const fence = FENCE.exec(line);
38 if (fence) {
39 out.push("plain", fence[1]!);
40 out.push("meta", fence[2]!);
41 out.push("type", fence[3]!);
42 const lang = languageFromName(fence[3]!);
43 return {
44 tokens: out.done(),
45 state: {
46 ...state,
47 embed: { lang, end: fence[2]!.slice(0, 3), inner: INITIAL_SCAN },
48 },
49 };
50 }
51
52 // An indented code block: four spaces (or a tab) with nothing around it.
53 if (/^(\t| {4})\S/.test(line)) {
54 out.push("string", line);
55 return { tokens: out.done(), state };
56 }
57
58 const heading = /^(\s{0,3}#{1,6})(\s.*)?$/.exec(line);
59 if (heading) {
60 out.push("keyword", line, "heading");
61 return { tokens: out.done(), state };
62 }
63 if (/^\s{0,3}(=+|-{2,})\s*$/.test(line) && line.trim() !== "") {
64 out.push("keyword", line, "heading");
65 return { tokens: out.done(), state };
66 }
67 if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) {
68 out.push("punctuation", line);
69 return { tokens: out.done(), state };
70 }
71
72 let i = 0;
73 const quote = /^(\s*(?:>\s?)+)/.exec(line);
74 if (quote) {
75 out.push("comment", quote[1]!);
76 i = quote[1]!.length;
77 }
78 const bullet = /^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(line.slice(i));
79 if (bullet) {
80 out.push("plain", bullet[1]!);
81 out.push("punctuation", bullet[2]!);
82 out.push("plain", bullet[3]!);
83 i += bullet[0].length;
84 const task = /^\[[ xX]\]/.exec(line.slice(i));
85 if (task) {
86 out.push("constant", task[0]);
87 i += task[0].length;
88 }
89 }
90 scanMarkdownInline(line.slice(i), out, quote !== null);
91 return { tokens: out.done(), state };
92 }
93
94 /** Inline markdown: code spans, emphasis, links, autolinks, table pipes. */
95 export function scanMarkdownInline(text: string, out: Out, quoted: boolean): void {
96 const base: TokenClass = quoted ? "comment" : "plain";
97 const n = text.length;
98 let i = 0;
99 let run = 0;
100 const flush = (to: number) => {
101 out.push(base, text.slice(run, to));
102 run = to;
103 };
104 while (i < n) {
105 const c = text.charCodeAt(i);
106 if (c === 92) {
107 i += 2;
108 continue;
109 }
110 if (c === 96 /* ` */) {
111 let ticks = 0;
112 while (text.charCodeAt(i + ticks) === 96) ticks++;
113 const close = text.indexOf("`".repeat(ticks), i + ticks);
114 if (close !== -1) {
115 flush(i);
116 const end = close + ticks;
117 out.push("string", text.slice(i, end));
118 i = end;
119 run = end;
120 continue;
121 }
122 i += ticks;
123 continue;
124 }
125 if (c === 42 /* * */ || c === 95 /* _ */) {
126 const marker = text[i]!;
127 const doubled = text[i + 1] === marker;
128 const open = doubled ? marker + marker : marker;
129 const close = text.indexOf(open, i + open.length);
130 if (close !== -1 && close > i + open.length) {
131 flush(i);
132 const end = close + open.length;
133 out.push("plain", text.slice(i, end), "emphasis");
134 i = end;
135 run = end;
136 continue;
137 }
138 i += open.length;
139 continue;
140 }
141 if (c === 91 /* [ */ || (c === 33 && text.charCodeAt(i + 1) === 91)) {
142 const openAt = c === 33 ? i + 1 : i;
143 const close = text.indexOf("]", openAt);
144 if (close !== -1 && text[close + 1] === "(") {
145 const end = text.indexOf(")", close + 2);
146 if (end !== -1) {
147 flush(i);
148 out.push("punctuation", text.slice(i, openAt + 1));
149 out.push("meta", text.slice(openAt + 1, close), "link");
150 out.push("punctuation", "](");
151 out.push("string", text.slice(close + 2, end), "link");
152 out.push("punctuation", ")");
153 i = end + 1;
154 run = i;
155 continue;
156 }
157 }
158 i++;
159 continue;
160 }
161 if (c === 60 /* < */) {
162 const close = text.indexOf(">", i);
163 if (
164 close !== -1 &&
165 /^<(https?:\/\/|mailto:)[^>\s]+>$/.test(text.slice(i, close + 1))
166 ) {
167 flush(i);
168 out.push("meta", text.slice(i, close + 1), "link");
169 i = close + 1;
170 run = i;
171 continue;
172 }
173 i++;
174 continue;
175 }
176 if (c === 124 /* | */) {
177 flush(i);
178 out.push("punctuation", "|");
179 i++;
180 run = i;
181 continue;
182 }
183 i++;
184 }
185 flush(n);
186 }
187
188 // ---- YAML ----
src/web/highlight/scanners.ts added +86
@@ -0,0 +1,86 @@
1 /**
2 * The entry points that run a scanner: one line, or a whole file. Each
3 * language maps to its grammar's scanner, and a scan is synchronous.
4 */
5 import { scanCss } from "./css.ts";
6 import { scanDiff } from "./diff.ts";
7 import { scanDockerfile } from "./dockerfile.ts";
8 import { scanGeneric } from "./generic.ts";
9 import { scanHtml } from "./html.ts";
10 import { scanMakefile } from "./makefile.ts";
11 import { scanMarkdown } from "./markdown.ts";
12 import { SPECS } from "./specs.ts";
13 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
14 import { scanToml } from "./toml.ts";
15 import { tok, type Language, type Token } from "./tokens.ts";
16 import { scanYaml } from "./yaml.ts";
17
18 type Scanner = (line: string, state: ScanState) => Scanned;
19
20 function scannerFor(lang: Language): Scanner | null {
21 switch (lang) {
22 case "markdown":
23 return scanMarkdown;
24 case "yaml":
25 return scanYaml;
26 case "toml":
27 case "ini": {
28 const toml = lang === "toml";
29 return (line, state) => scanToml(line, state, toml);
30 }
31 case "html":
32 return scanHtml;
33 case "css":
34 return scanCss;
35 case "diff":
36 return scanDiff;
37 case "makefile":
38 return scanMakefile;
39 case "dockerfile":
40 return scanDockerfile;
41 case "plain":
42 return null;
43 default: {
44 const spec = SPECS[lang];
45 if (!spec) return null;
46 return (line, state) => scanGeneric(line, spec, state);
47 }
48 }
49 }
50
51 /**
52 * Tokenize **one** line, given the state the previous line ended in.
53 *
54 * `highlightLines` re-tokenizes a whole file, which is right for a page that
55 * renders one. An editor is the other case: a keystroke changes one line, and
56 * re-scanning ten thousand of them per character is the difference between an
57 * editor that feels instant and one that does not. So the primitive the whole
58 * file walk is already built on is offered directly, and a caller that keeps a
59 * `ScanState[]` beside its lines can re-scan from the edit downward until the
60 * state converges — usually one line, unbounded only inside an unterminated
61 * block comment.
62 */
63 export function scanOneLine(
64 line: string,
65 lang: Language,
66 state: ScanState,
67 ): Scanned {
68 const scan = scannerFor(lang);
69 if (!scan) return { tokens: [tok("plain", line)], state };
70 return scan(line, state);
71 }
72
73 export function highlightLines(code: string, lang: Language): Token[][] {
74 const lines = code.split("\n");
75 const scan = scannerFor(lang);
76 if (!scan) return lines.map((line) => [tok("plain", line)]);
77
78 const out: Token[][] = [];
79 let state: ScanState = INITIAL_SCAN;
80 for (const line of lines) {
81 const scanned = scan(line, state);
82 out.push(scanned.tokens);
83 state = scanned.state;
84 }
85 return out;
86 }
src/web/highlight/specs.ts added +491
@@ -0,0 +1,491 @@
1 /** Per-language rule tables read by the generic scanner. */
2 import { set } from "./chars.ts";
3 import { type Language, type TokenClass, type TokenKind } from "./tokens.ts";
4
5 export interface StrSpec {
6 open: string;
7 close: string;
8 escape: boolean;
9 /** Stays open across newlines (template literals, `"""`, backticks). */
10 multiline: boolean;
11 /** `${…}`/`#{…}` inside is code. */
12 interpolate?: boolean;
13 /** Shell-ish strings paint `$x` as a variable; template literals as code. */
14 interpolateAs?: "code" | "variable";
15 /** Only opens where a value is expected (regex literals). */
16 valueOnly?: boolean;
17 /** What to paint it as; strings by default. */
18 cls?: TokenClass;
19 kind?: TokenKind;
20 }
21
22 export interface LangSpec {
23 lineComment: string[];
24 blockComment?: [string, string];
25 strings: StrSpec[];
26 keywords: Set<string>;
27 types: Set<string>;
28 constants: Set<string>;
29 /** An identifier followed by "(" is rendered as a function. */
30 callAsFunction: boolean;
31 /** Capitalized identifiers read as types. False for shells and SQL. */
32 capitalIsType?: boolean;
33 /** Keywords match regardless of case (SQL). */
34 ignoreCase?: boolean;
35 /** `/…/` is a regex where a value is expected. */
36 regex?: boolean;
37 /** `<div …>` is markup where a value is expected (JSX). */
38 jsx?: boolean;
39 /** Characters that begin a variable: `$`, `@`, `%`. */
40 sigils?: string;
41 /** `@name` is a decorator/annotation. */
42 atDecorator?: boolean;
43 /** `#[…]` is an attribute (Rust), `#!…` too. */
44 hashAttr?: boolean;
45 /** `foo.bar` paints `bar` as a property. */
46 dotProperty?: boolean;
47 /** `#include`, `#define`: a C preprocessor line. */
48 preproc?: boolean;
49 /** `'a` is a lifetime, not a character literal (Rust). */
50 lifetimes?: boolean;
51 /** `name!`/`name?` end an identifier (Ruby, Elixir, Rust macros). */
52 identTail?: string;
53 /** Extra characters allowed inside an identifier (`-` in CSS-ish langs). */
54 identInner?: string;
55 /** `:atom` / `:symbol` is a constant. */
56 atoms?: boolean;
57 /** `<<EOF` opens a heredoc. */
58 heredoc?: boolean;
59 /** The first word of a command reads as the thing being run. */
60 commandPosition?: boolean;
61 /** `-v` / `--long` read as flags. */
62 flags?: boolean;
63 /** The word after these is a definition name. */
64 defineAfter?: Set<string>;
65 /** The word after these is a type name. */
66 typeAfter?: Set<string>;
67 /** A word in this set followed by `!` is a macro. */
68 macroBang?: boolean;
69 }
70
71 export const dq: StrSpec = { open: '"', close: '"', escape: true, multiline: false };
72 export const sq: StrSpec = { open: "'", close: "'", escape: true, multiline: false };
73 export const tick: StrSpec = {
74 open: "`",
75 close: "`",
76 escape: true,
77 multiline: true,
78 interpolate: true,
79 };
80 export const tripleD: StrSpec = {
81 open: '"""',
82 close: '"""',
83 escape: true,
84 multiline: true,
85 };
86 export const tripleS: StrSpec = {
87 open: "'''",
88 close: "'''",
89 escape: true,
90 multiline: true,
91 };
92 export const regexLit: StrSpec = {
93 open: "/",
94 close: "/",
95 escape: true,
96 multiline: false,
97 valueOnly: true,
98 cls: "string",
99 kind: "regex",
100 };
101
102 export const TS_KEYWORDS = `abstract accessor as asserts async await break case catch class const continue
103 debugger declare default delete do else enum export extends finally for from function get if
104 implements import in infer instanceof interface is keyof let module namespace new of out override
105 package private protected public readonly return satisfies set static super switch this throw try
106 type typeof unique var void while with yield`;
107
108 export const TS_TYPES = `string number boolean any unknown never void object bigint symbol undefined null
109 Array Promise Record Map Set WeakMap WeakSet Partial Required Readonly Pick Omit Exclude Extract
110 Awaited ReturnType Parameters Date RegExp Error Iterable AsyncIterable Uint8Array ArrayBuffer
111 Function Symbol BigInt`;
112
113 export const SPECS: Partial<Record<Language, LangSpec>> = {
114 ts: {
115 lineComment: ["//"],
116 blockComment: ["/*", "*/"],
117 strings: [dq, sq, tick, regexLit],
118 keywords: set(TS_KEYWORDS),
119 types: set(TS_TYPES),
120 constants: set(
121 `true false null undefined NaN Infinity this super arguments`,
122 ),
123 callAsFunction: true,
124 capitalIsType: true,
125 regex: true,
126 jsx: true,
127 atDecorator: true,
128 dotProperty: true,
129 sigils: "#",
130 defineAfter: set(`function class interface type enum namespace`),
131 typeAfter: set(`class interface type enum namespace`),
132 },
133 python: {
134 lineComment: ["#"],
135 strings: [tripleD, tripleS, dq, sq],
136 keywords:
137 set(`and as assert async await break case class continue def del elif else except finally for
138 from global if import in is lambda match nonlocal not or pass raise return try while with yield`),
139 types: set(
140 `int float str bytes bool list dict tuple set frozenset object type bytearray complex range
141 Any Optional Union Callable Iterable Sequence Mapping`,
142 ),
143 constants: set(
144 `True False None NotImplemented Ellipsis self cls __name__ __main__`,
145 ),
146 callAsFunction: true,
147 capitalIsType: true,
148 atDecorator: true,
149 dotProperty: true,
150 defineAfter: set(`def class`),
151 typeAfter: set(`class`),
152 },
153 go: {
154 lineComment: ["//"],
155 blockComment: ["/*", "*/"],
156 strings: [
157 dq,
158 { open: "`", close: "`", escape: false, multiline: true },
159 sq,
160 ],
161 keywords:
162 set(`break case chan const continue default defer else fallthrough for func go goto if
163 import interface map package range return select struct switch type var`),
164 types:
165 set(`bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune
166 string uint uint8 uint16 uint32 uint64 uintptr any comparable`),
167 constants: set(`true false nil iota`),
168 callAsFunction: true,
169 capitalIsType: true,
170 dotProperty: true,
171 defineAfter: set(`func`),
172 typeAfter: set(`type struct interface`),
173 },
174 rust: {
175 lineComment: ["//"],
176 blockComment: ["/*", "*/"],
177 strings: [dq, sq],
178 keywords:
179 set(`as async await break const continue crate dyn else enum extern fn for if impl in let
180 loop match mod move mut pub ref return self Self static struct super trait type unsafe use
181 where while union yield`),
182 types:
183 set(`bool char str String Vec Option Result Box Rc Arc RefCell Cell HashMap HashSet BTreeMap
184 i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64`),
185 constants: set(`true false None Some Ok Err`),
186 callAsFunction: true,
187 capitalIsType: true,
188 lifetimes: true,
189 hashAttr: true,
190 macroBang: true,
191 dotProperty: true,
192 defineAfter: set(`fn`),
193 typeAfter: set(`struct enum trait type impl union`),
194 },
195 c: {
196 lineComment: ["//"],
197 blockComment: ["/*", "*/"],
198 strings: [dq, sq],
199 keywords:
200 set(`alignas alignof asm auto bool break case catch char class co_await co_return co_yield
201 concept const consteval constexpr continue decltype default delete do double dynamic_cast
202 else enum explicit export extern false final float for friend goto if inline int long mutable
203 namespace new noexcept nullptr operator override private protected public register
204 reinterpret_cast requires restrict return short signed sizeof static static_assert
205 static_cast struct switch template this thread_local throw true try typedef typeid typename
206 union unsigned using virtual void volatile wchar_t while
207 id instancetype nonatomic atomic strong weak copy assign retain nullable nonnull`),
208 types:
209 set(`int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t size_t ssize_t ptrdiff_t
210 FILE va_list std string vector map unordered_map shared_ptr unique_ptr NSString NSArray
211 NSDictionary NSInteger NSUInteger BOOL CGFloat`),
212 constants: set(`true false NULL nullptr nil YES NO self super __func__`),
213 callAsFunction: true,
214 capitalIsType: true,
215 preproc: true,
216 atDecorator: true,
217 dotProperty: true,
218 },
219 java: {
220 lineComment: ["//"],
221 blockComment: ["/*", "*/"],
222 strings: [tripleD, dq, sq],
223 keywords:
224 set(`abstract assert break case catch class const continue default do else enum extends final
225 finally for goto if implements import instanceof interface native new package permits private
226 protected public record return sealed static strictfp super switch synchronized this throw
227 throws transient try var void volatile while yield`),
228 types:
229 set(`boolean byte char double float int long short String Object Integer Long Double Boolean
230 List Map Set Optional Stream`),
231 constants: set(`true false null this super`),
232 callAsFunction: true,
233 capitalIsType: true,
234 atDecorator: true,
235 dotProperty: true,
236 defineAfter: set(`class interface enum record`),
237 typeAfter: set(`class interface enum record`),
238 },
239 kotlin: {
240 lineComment: ["//"],
241 blockComment: ["/*", "*/"],
242 strings: [tripleD, dq, sq],
243 keywords:
244 set(`abstract actual annotation as break by catch class companion const constructor continue
245 crossinline data delegate do dynamic else enum expect external final finally for fun get if
246 import in infix init inline inner interface internal is lateinit noinline object open operator
247 out override package private protected public reified return sealed set super suspend tailrec
248 this throw try typealias val var vararg when where while`),
249 types:
250 set(`Any Boolean Byte Char Double Float Int Long Nothing Number Short String Unit List Map Set
251 MutableList MutableMap Array Sequence`),
252 constants: set(`true false null this super it`),
253 callAsFunction: true,
254 capitalIsType: true,
255 atDecorator: true,
256 dotProperty: true,
257 sigils: "$",
258 defineAfter: set(`fun class interface object`),
259 typeAfter: set(`class interface object`),
260 },
261 swift: {
262 lineComment: ["//"],
263 blockComment: ["/*", "*/"],
264 strings: [tripleD, dq],
265 keywords:
266 set(`actor as associatedtype async await break case catch class continue convenience default
267 defer deinit didSet do else enum extension fallthrough fileprivate final for func get guard if
268 import in indirect init inout internal is lazy let mutating nonisolated open operator override
269 private protocol public repeat required rethrows return self set some static struct subscript
270 super switch throw throws try typealias var weak where while willSet unowned`),
271 types:
272 set(`Any AnyObject Array Bool Character Dictionary Double Float Int Int8 Int16 Int32 Int64
273 Optional Set String UInt UInt8 UInt32 UInt64 Void Result Data URL`),
274 constants: set(`true false nil self Self super`),
275 callAsFunction: true,
276 capitalIsType: true,
277 atDecorator: true,
278 dotProperty: true,
279 defineAfter: set(`func class struct enum protocol extension actor`),
280 typeAfter: set(`class struct enum protocol extension actor`),
281 },
282 ruby: {
283 lineComment: ["#"],
284 strings: [
285 dq,
286 sq,
287 { open: "%w[", close: "]", escape: false, multiline: false },
288 ],
289 keywords:
290 set(`alias and begin break case class def defined? do else elsif end ensure for if in module
291 next nil not or redo rescue retry return self super then undef unless until when while yield
292 lambda proc require require_relative include extend attr_accessor attr_reader attr_writer
293 private protected public raise puts new`),
294 types: set(
295 `String Symbol Integer Float Array Hash Struct Class Module Proc Range Time`,
296 ),
297 constants: set(`true false nil self __FILE__ __dir__`),
298 callAsFunction: true,
299 capitalIsType: true,
300 sigils: "@$",
301 atoms: true,
302 heredoc: true,
303 regex: true,
304 identTail: "?!",
305 dotProperty: true,
306 defineAfter: set(`def`),
307 typeAfter: set(`class module`),
308 },
309 php: {
310 lineComment: ["//", "#"],
311 blockComment: ["/*", "*/"],
312 strings: [dq, sq],
313 keywords:
314 set(`abstract and array as break callable case catch class clone const continue declare
315 default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum
316 extends final finally fn for foreach function global goto if implements include include_once
317 instanceof insteadof interface isset list match namespace new or print private protected
318 public readonly require require_once return static switch throw trait try unset use var while
319 xor yield`),
320 types: set(
321 `int float string bool array object callable iterable void mixed never self static`,
322 ),
323 constants: set(`true false null TRUE FALSE NULL $this`),
324 callAsFunction: true,
325 capitalIsType: true,
326 sigils: "$",
327 atDecorator: true,
328 dotProperty: true,
329 defineAfter: set(`function class interface trait enum`),
330 typeAfter: set(`class interface trait enum`),
331 },
332 lua: {
333 lineComment: ["--"],
334 blockComment: ["--[[", "]]"],
335 strings: [
336 dq,
337 sq,
338 { open: "[[", close: "]]", escape: false, multiline: true },
339 ],
340 keywords:
341 set(`and break do else elseif end false for function goto if in local nil not or repeat
342 return then true until while`),
343 types: set(`string table math io os coroutine debug utf8`),
344 constants: set(`true false nil self _G _ENV`),
345 callAsFunction: true,
346 capitalIsType: false,
347 dotProperty: true,
348 defineAfter: set(`function`),
349 },
350 zig: {
351 lineComment: ["//"],
352 strings: [dq, sq],
353 keywords:
354 set(`align allowzero and anyframe anytype asm async await break callconv catch comptime const
355 continue defer else enum errdefer error export extern fn for if inline noalias nosuspend
356 opaque or orelse packed pub resume return linksection struct suspend switch test threadlocal
357 try union unreachable usingnamespace var volatile while`),
358 types:
359 set(`bool void noreturn type anyerror comptime_int comptime_float u8 u16 u32 u64 u128 usize
360 i8 i16 i32 i64 i128 isize f16 f32 f64 f128 c_int c_uint`),
361 constants: set(`true false null undefined`),
362 callAsFunction: true,
363 capitalIsType: true,
364 atDecorator: true,
365 dotProperty: true,
366 defineAfter: set(`fn`),
367 },
368 elixir: {
369 lineComment: ["#"],
370 strings: [tripleD, dq, sq],
371 keywords:
372 set(`after alias and case catch cond def defdelegate defexception defguard defimpl defmacro
373 defmodule defp defprotocol defstruct do else end fn for if import in not or quote raise
374 receive require rescue try unless unquote use when with`),
375 types: set(
376 `Enum Map List String Atom Integer Float Process Task Agent GenServer Supervisor`,
377 ),
378 constants: set(`true false nil __MODULE__ __ENV__`),
379 callAsFunction: true,
380 capitalIsType: true,
381 sigils: "@",
382 atoms: true,
383 identTail: "?!",
384 dotProperty: true,
385 defineAfter: set(`def defp defmacro defmodule defstruct defguard`),
386 typeAfter: set(`defmodule defprotocol defimpl`),
387 },
388 nix: {
389 lineComment: ["#"],
390 blockComment: ["/*", "*/"],
391 strings: [
392 {
393 open: "''",
394 close: "''",
395 escape: false,
396 multiline: true,
397 interpolate: true,
398 },
399 {
400 open: '"',
401 close: '"',
402 escape: true,
403 multiline: false,
404 interpolate: true,
405 },
406 ],
407 keywords: set(`assert else if in inherit let or rec then with import`),
408 types: set(`builtins pkgs lib stdenv fetchurl mkDerivation`),
409 constants: set(`true false null`),
410 callAsFunction: false,
411 capitalIsType: false,
412 identInner: "-",
413 dotProperty: true,
414 },
415 json: {
416 // JSON proper has no comments; JSONC does, and a `//` outside a string is
417 // never valid JSON anyway, so accepting one costs nothing and helps.
418 lineComment: ["//"],
419 blockComment: ["/*", "*/"],
420 strings: [dq],
421 keywords: set(``),
422 types: set(``),
423 constants: set(`true false null`),
424 callAsFunction: false,
425 capitalIsType: false,
426 },
427 sql: {
428 lineComment: ["--", "#"],
429 blockComment: ["/*", "*/"],
430 strings: [
431 sq,
432 { open: "`", close: "`", escape: false, multiline: false },
433 dq,
434 ],
435 keywords:
436 set(`select from where insert into values update set delete create table alter drop index
437 view trigger procedure function returns begin end join left right full inner outer cross on
438 using group by order having limit offset union all as distinct and or not null is primary key
439 foreign references default unique check constraint cascade returning with recursive case when
440 then else exists in between like ilike asc desc count sum avg min max coalesce cast if temp
441 temporary replace grant revoke commit rollback transaction`),
442 types:
443 set(`int integer bigint smallint text varchar char boolean bool date datetime timestamp time
444 real float double blob numeric decimal serial uuid json jsonb bytea interval`),
445 constants: set(
446 `true false null current_timestamp current_date current_user`,
447 ),
448 callAsFunction: true,
449 capitalIsType: false,
450 ignoreCase: true,
451 },
452 shell: {
453 lineComment: ["#"],
454 strings: [
455 {
456 open: '"',
457 close: '"',
458 escape: true,
459 multiline: false,
460 interpolate: true,
461 interpolateAs: "variable",
462 },
463 { open: "'", close: "'", escape: false, multiline: false },
464 ],
465 keywords:
466 set(`if then else elif fi for while do done case esac in function select until return break
467 continue export local readonly declare typeset set unset shift source alias eval exec trap
468 exit time coproc`),
469 types: set(``),
470 constants: set(`true false`),
471 callAsFunction: false,
472 capitalIsType: false,
473 sigils: "$",
474 heredoc: true,
475 identInner: "-.",
476 commandPosition: true,
477 flags: true,
478 },
479 dockerfile: {
480 lineComment: ["#"],
481 strings: [dq, sq],
482 keywords: set(`as`),
483 types: set(``),
484 constants: set(``),
485 callAsFunction: false,
486 capitalIsType: false,
487 sigils: "$",
488 ignoreCase: true,
489 flags: true,
490 },
491 };
src/web/highlight/state.ts added +57
@@ -0,0 +1,57 @@
1 /** The state one line's scan hands the next. */
2 import { type Language, type Token } from "./tokens.ts";
3
4 export interface StrState {
5 /** The delimiter that closes it. */
6 close: string;
7 escape: boolean;
8 /** `${…}` (or `#{…}`) inside is code, not string. */
9 interpolate?: boolean;
10 interpolateAs?: "code" | "variable";
11 }
12
13 export interface Heredoc {
14 tag: string;
15 /** `<<~` / `<<-`: the terminator may be indented. */
16 indent: boolean;
17 }
18
19 export interface Embed {
20 lang: Language;
21 /** The fence or closing tag that ends it, matched per language. */
22 end: string;
23 inner: ScanState;
24 }
25
26 export interface ScanState {
27 /** Inside a block comment. */
28 readonly block: boolean;
29 /** Inside a multi-line string. */
30 readonly str: StrState | null;
31 /** Waiting for a heredoc terminator. */
32 readonly heredoc: Heredoc | null;
33 /** A fenced code block, or an HTML `<script>`/`<style>` body. */
34 readonly embed: Embed | null;
35 /** YAML block scalar: lines indented past this column are string. */
36 readonly scalar: number | null;
37 /** HTML: inside a tag's attribute list. */
38 readonly tag: boolean;
39 /** CSS: brace depth, which decides selector context from declaration. */
40 readonly depth: number;
41 }
42
43 /** The state a scan of the first line of a file starts from. */
44 export const INITIAL_SCAN: ScanState = {
45 block: false,
46 str: null,
47 heredoc: null,
48 embed: null,
49 scalar: null,
50 tag: false,
51 depth: 0,
52 };
53
54 export interface Scanned {
55 tokens: Token[];
56 state: ScanState;
57 }
src/web/highlight/tokens.ts added +102
@@ -0,0 +1,102 @@
1 /** Token vocabulary: the classes and kinds a scanner emits, and the sink it writes through. */
2
3
4 export type TokenClass =
5 | "keyword"
6 | "string"
7 | "comment"
8 | "number"
9 | "function"
10 | "type"
11 | "operator"
12 | "punctuation"
13 | "constant"
14 | "meta"
15 | "plain";
16
17 /**
18 * A refinement of `cls`. Optional by design: dropping it must never make a
19 * line wrong, only less specific.
20 */
21 export type TokenKind =
22 | "property"
23 | "tag"
24 | "attribute"
25 | "regex"
26 | "variable"
27 | "decorator"
28 | "heading"
29 | "emphasis"
30 | "link"
31 | "inserted"
32 | "deleted";
33
34 export interface Token {
35 readonly cls: TokenClass;
36 readonly text: string;
37 readonly kind?: TokenKind;
38 }
39
40 export type Language =
41 | "ts"
42 | "python"
43 | "go"
44 | "rust"
45 | "c"
46 | "java"
47 | "kotlin"
48 | "swift"
49 | "ruby"
50 | "php"
51 | "lua"
52 | "zig"
53 | "elixir"
54 | "nix"
55 | "json"
56 | "yaml"
57 | "toml"
58 | "ini"
59 | "markdown"
60 | "css"
61 | "html"
62 | "shell"
63 | "sql"
64 | "dockerfile"
65 | "makefile"
66 | "diff"
67 | "plain";
68
69 // ---- tokens ----
70
71 export function tok(cls: TokenClass, text: string, kind?: TokenKind): Token {
72 return kind === undefined ? { cls, text } : { cls, text, kind };
73 }
74
75 /** A blank line still needs one (empty) token so line counts stay aligned. */
76 export function emptySafe(tokens: Token[]): Token[] {
77 return tokens.length > 0 ? tokens : [tok("plain", "")];
78 }
79
80 /**
81 * The sink every scanner writes through. It merges runs of the same
82 * (class, kind) so a line of punctuation is one token, not forty.
83 */
84 export class Out {
85 readonly tokens: Token[] = [];
86 push(cls: TokenClass, text: string, kind?: TokenKind): void {
87 if (text === "") return;
88 const last = this.tokens[this.tokens.length - 1];
89 if (last && last.cls === cls && last.kind === kind) {
90 this.tokens[this.tokens.length - 1] = tok(cls, last.text + text, kind);
91 return;
92 }
93 this.tokens.push(tok(cls, text, kind));
94 }
95 /** Append another scanner's output (an embedded language's line). */
96 take(tokens: readonly Token[]): void {
97 for (const t of tokens) this.push(t.cls, t.text, t.kind);
98 }
99 done(): Token[] {
100 return emptySafe(this.tokens);
101 }
102 }
src/web/highlight/toml.ts added +121
@@ -0,0 +1,121 @@
1 /** TOML and INI scanner. */
2 import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh } from "./chars.ts";
3 import { consumeStringBody, scanNumber, spaceRun } from "./lexing.ts";
4 import { type ScanState, type Scanned } from "./state.ts";
5 import { Out } from "./tokens.ts";
6
7 export function scanToml(line: string, state: ScanState, toml: boolean): Scanned {
8 const out = new Out();
9
10 if (state.str) {
11 const consumed = consumeStringBody(line, 0, state.str);
12 out.push("string", line.slice(0, consumed.end));
13 if (!consumed.closed) return { tokens: out.done(), state };
14 scanTomlValue(line, consumed.end, out, toml);
15 return { tokens: out.done(), state: { ...state, str: null } };
16 }
17
18 const comment = /^(\s*)([#;].*)$/.exec(line);
19 if (comment) {
20 out.push("plain", comment[1]!);
21 out.push("comment", comment[2]!);
22 return { tokens: out.done(), state };
23 }
24 const table = /^(\s*)(\[\[?[^\]]*\]\]?)(.*)$/.exec(line);
25 if (table) {
26 out.push("plain", table[1]!);
27 out.push("type", table[2]!, "heading");
28 out.push("plain", table[3]!);
29 return { tokens: out.done(), state };
30 }
31 const assign = /^(\s*)((?:"[^"]*"|[^=\s]+))(\s*=\s*)/.exec(line);
32 if (assign) {
33 out.push("plain", assign[1]!);
34 out.push("keyword", assign[2]!, "property");
35 out.push("operator", assign[3]!);
36 return scanTomlRest(line, assign[0].length, out, state, toml);
37 }
38 return scanTomlRest(line, 0, out, state, toml);
39 }
40
41 export function scanTomlRest(
42 line: string,
43 from: number,
44 out: Out,
45 state: ScanState,
46 toml: boolean,
47 ): Scanned {
48 if (toml && line.startsWith('"""', from)) {
49 const consumed = consumeStringBody(line, from + 3, {
50 close: '"""',
51 escape: true,
52 });
53 out.push("string", line.slice(from, consumed.end));
54 if (!consumed.closed) {
55 return {
56 tokens: out.done(),
57 state: { ...state, str: { close: '"""', escape: true } },
58 };
59 }
60 scanTomlValue(line, consumed.end, out, toml);
61 return { tokens: out.done(), state };
62 }
63 scanTomlValue(line, from, out, toml);
64 return { tokens: out.done(), state };
65 }
66
67 export function scanTomlValue(
68 line: string,
69 from: number,
70 out: Out,
71 toml: boolean,
72 ): void {
73 const n = line.length;
74 let i = from;
75 while (i < n) {
76 const c = line.charCodeAt(i);
77 if (isSpaceCh(c)) {
78 const j = spaceRun(line, i);
79 out.push("plain", line.slice(i, j));
80 i = j;
81 continue;
82 }
83 if (c === 35 || (!toml && c === 59)) {
84 out.push("comment", line.slice(i));
85 return;
86 }
87 if (c === 34 || c === 39) {
88 const consumed = consumeStringBody(line, i + 1, {
89 close: line[i]!,
90 escape: c === 34,
91 });
92 out.push("string", line.slice(i, consumed.end));
93 i = consumed.end;
94 continue;
95 }
96 if (isDigitCh(c) || (c === 45 && isDigitCh(line.charCodeAt(i + 1)))) {
97 let j = scanNumber(line, c === 45 ? i + 1 : i);
98 while (j < n && /[-:.TZ0-9+]/.test(line[j]!)) j++;
99 out.push("number", line.slice(i, j));
100 i = j;
101 continue;
102 }
103 if (isAlphaCh(c) || c === 95) {
104 let j = i;
105 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
106 const word = line.slice(i, j);
107 out.push(
108 word === "true" || word === "false" ? "constant" : "plain",
109 word,
110 );
111 i = j;
112 continue;
113 }
114 if (c === 91 || c === 93 || c === 123 || c === 125 || c === 44)
115 out.push("punctuation", line[i]!);
116 else out.push("operator", line[i]!);
117 i++;
118 }
119 }
120
121 // ---- HTML ----
src/web/highlight/yaml.ts added +141
@@ -0,0 +1,141 @@
1 /** YAML scanner. */
2 import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh } from "./chars.ts";
3 import { consumeStringBody, indentOf, scanNumber, spaceRun } from "./lexing.ts";
4 import { type ScanState, type Scanned } from "./state.ts";
5 import { Out } from "./tokens.ts";
6
7 export const YAML_KEY =
8 /^(\s*(?:-\s+)*)((?:"[^"]*"|'[^']*'|[^\s:#][^:#]*?))(\s*:)(\s|$)/;
9
10 export function scanYaml(line: string, state: ScanState): Scanned {
11 const out = new Out();
12
13 // A block scalar's body: everything indented past the introducing line.
14 if (state.scalar !== null) {
15 const indent = indentOf(line);
16 if (indent === -1 || indent > state.scalar) {
17 out.push("string", line);
18 return { tokens: out.done(), state };
19 }
20 state = { ...state, scalar: null };
21 }
22
23 if (/^\s*#/.test(line)) {
24 out.push("comment", line);
25 return { tokens: out.done(), state };
26 }
27 if (/^(---|\.\.\.)\s*$/.test(line)) {
28 out.push("meta", line);
29 return { tokens: out.done(), state };
30 }
31
32 let i = 0;
33 const key = YAML_KEY.exec(line);
34 if (key) {
35 out.push("plain", key[1]!);
36 out.push("keyword", key[2]!, "property");
37 out.push("punctuation", key[3]!);
38 i = key[1]!.length + key[2]!.length + key[3]!.length;
39 } else {
40 const dash = /^(\s*)(-)(\s|$)/.exec(line);
41 if (dash) {
42 out.push("plain", dash[1]!);
43 out.push("punctuation", "-");
44 i = dash[1]!.length + 1;
45 }
46 }
47
48 // A block scalar indicator ends the line and opens the body.
49 const scalar = /^(\s*)([|>][+-]?\d*)\s*(#.*)?$/.exec(line.slice(i));
50 if (scalar) {
51 out.push("plain", scalar[1]!);
52 out.push("operator", scalar[2]!);
53 if (scalar[3])
54 out.push("comment", line.slice(line.length - scalar[3].length));
55 else
56 out.push("plain", line.slice(i + scalar[1]!.length + scalar[2]!.length));
57 return {
58 tokens: out.done(),
59 state: { ...state, scalar: Math.max(0, indentOf(line)) },
60 };
61 }
62
63 scanYamlValue(line, i, out);
64 return { tokens: out.done(), state };
65 }
66
67 export function scanYamlValue(line: string, from: number, out: Out): void {
68 const n = line.length;
69 let i = from;
70 while (i < n) {
71 const c = line.charCodeAt(i);
72 if (isSpaceCh(c)) {
73 const j = spaceRun(line, i);
74 out.push("plain", line.slice(i, j));
75 i = j;
76 continue;
77 }
78 if (c === 35 /* # */ && (i === 0 || isSpaceCh(line.charCodeAt(i - 1)))) {
79 out.push("comment", line.slice(i));
80 return;
81 }
82 if (c === 34 || c === 39) {
83 const consumed = consumeStringBody(line, i + 1, {
84 close: line[i]!,
85 escape: c === 34,
86 });
87 out.push("string", line.slice(i, consumed.end));
88 i = consumed.end;
89 continue;
90 }
91 if (c === 38 /* & */ || c === 42 /* * */) {
92 let j = i + 1;
93 while (j < n && isIdentCh(line.charCodeAt(j))) j++;
94 if (j > i + 1) {
95 out.push("meta", line.slice(i, j), "variable");
96 i = j;
97 continue;
98 }
99 }
100 if (c === 33 /* ! */) {
101 let j = i;
102 while (j < n && !isSpaceCh(line.charCodeAt(j))) j++;
103 out.push("type", line.slice(i, j));
104 i = j;
105 continue;
106 }
107 if (isDigitCh(c) || (c === 45 && isDigitCh(line.charCodeAt(i + 1)))) {
108 let j = c === 45 ? i + 1 : i;
109 j = scanNumber(line, j);
110 // A date reads as a number too: 2026-09-01.
111 while (j < n && /[-:.TZ0-9+]/.test(line[j]!)) j++;
112 out.push("number", line.slice(i, j));
113 i = j;
114 continue;
115 }
116 if (isAlphaCh(c) || c === 95) {
117 let j = i;
118 while (j < n && (isIdentCh(line.charCodeAt(j)) || line[j] === "-")) j++;
119 const word = line.slice(i, j);
120 const lower = word.toLowerCase();
121 const isConst =
122 lower === "true" ||
123 lower === "false" ||
124 lower === "null" ||
125 lower === "yes" ||
126 lower === "no" ||
127 lower === "on" ||
128 lower === "off" ||
129 lower === "~";
130 out.push(isConst ? "constant" : "plain", word);
131 i = j;
132 continue;
133 }
134 if (c === 123 || c === 125 || c === 91 || c === 93 || c === 44)
135 out.push("punctuation", line[i]!);
136 else out.push("operator", line[i]!);
137 i++;
138 }
139 }
140
141 // ---- TOML and INI ----
test/highlight-entry.test.ts added +29
@@ -0,0 +1,29 @@
1 import { expect, test } from "bun:test";
2 import * as highlight from "../src/web/highlight.ts";
3
4 test("the highlight door keeps its public names", () => {
5 for (const name of [
6 "INITIAL_SCAN",
7 "LANGUAGES",
8 "languageFromName",
9 "detectLanguage",
10 "languageFromFirstLine",
11 "scanOneLine",
12 "highlightLines",
13 ]) {
14 expect(name in highlight).toBe(true);
15 }
16 });
17
18 test("every language scans losslessly through its scanner", () => {
19 const sample = "a = 1 # x\n\"s\" <b> {k: v}\n";
20 for (const lang of highlight.LANGUAGES) {
21 const lines = highlight.highlightLines(sample, lang);
22 expect(lines.length).toBe(sample.split("\n").length);
23 lines.forEach((tokens, i) => {
24 expect(tokens.map((t) => t.text).join("")).toBe(sample.split("\n")[i]!);
25 });
26 const one = highlight.scanOneLine("x = 1", lang, highlight.INITIAL_SCAN);
27 expect(one.tokens.map((t) => t.text).join("")).toBe("x = 1");
28 }
29 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs