codelight.js 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! codelight.js 1.2.0 | MIT License | https://github.com/codelightjs/codelight.js */
1
+ /*! codelight.js 1.3.0 | MIT License | https://github.com/codelightjs/codelight.js */
2
2
  "use strict";
3
3
  var codelight = (() => {
4
4
  var __defProp = Object.defineProperty;
@@ -24,6 +24,7 @@ var codelight = (() => {
24
24
  // src/codelight.ts
25
25
  var codelight_exports = {};
26
26
  __export(codelight_exports, {
27
+ addCopyButton: () => addCopyButton,
27
28
  createMarkup: () => createMarkup,
28
29
  createStream: () => createStream,
29
30
  default: () => codelight_default,
@@ -43,6 +44,43 @@ var codelight = (() => {
43
44
  tokenize: () => tokenize
44
45
  });
45
46
 
47
+ // src/lib/copy.ts
48
+ async function copyText(text, doc = document) {
49
+ try {
50
+ await doc.defaultView.navigator.clipboard.writeText(text);
51
+ } catch {
52
+ const area = doc.createElement("textarea");
53
+ area.value = text;
54
+ area.setAttribute("readonly", "");
55
+ area.style.cssText = "position:fixed;top:-1000px;opacity:0";
56
+ doc.body.append(area);
57
+ area.select();
58
+ doc.execCommand("copy");
59
+ area.remove();
60
+ }
61
+ }
62
+ function addCopyButton(code, options = {}) {
63
+ const pre = code.parentElement;
64
+ if (!pre || [...pre.children].some((c) => c.classList.contains("cl-copy"))) return null;
65
+ const doc = code.ownerDocument;
66
+ const label = options.label ?? "Copy";
67
+ const button = doc.createElement("button");
68
+ button.type = "button";
69
+ button.className = "cl-copy";
70
+ button.textContent = label;
71
+ button.setAttribute("aria-label", "Copy code");
72
+ let timer;
73
+ button.addEventListener("click", async () => {
74
+ await copyText(code.textContent ?? "", doc);
75
+ button.textContent = options.copiedLabel ?? "Copied";
76
+ clearTimeout(timer);
77
+ timer = setTimeout(() => button.textContent = label, 1500);
78
+ });
79
+ pre.classList.add("cl-has-copy");
80
+ pre.append(button);
81
+ return button;
82
+ }
83
+
46
84
  // src/lib/engine.ts
47
85
  var LineBuilder = class {
48
86
  constructor() {
@@ -62,17 +100,9 @@ var codelight = (() => {
62
100
  var SPACE = /\s+/y;
63
101
  var OPERATOR = /[+\-*/%=<>!&|^~?:]+/y;
64
102
  var CALL = /\s*\(/y;
103
+ var HEREDOC = /<<(-?)\s*(['"]?)([A-Za-z_]\w*)\2/y;
65
104
  var PUNCTUATION = "()[]{},;.";
66
- function findClose(line, from, close, escape) {
67
- for (let j = from; j < line.length; j++) {
68
- if (escape && line[j] === "\\") {
69
- j++;
70
- continue;
71
- }
72
- if (line.startsWith(close, j)) return j + close.length;
73
- }
74
- return -1;
75
- }
105
+ var PAIRS = { "}": "{", ")": "(", "]": "[" };
76
106
  function defineLanguage(def) {
77
107
  const ci = def.caseInsensitive ?? false;
78
108
  const keywords = words(def.keywords, ci);
@@ -81,9 +111,11 @@ var codelight = (() => {
81
111
  const variables = words(def.variables, ci);
82
112
  const builtins = words(def.builtins, ci);
83
113
  const rules = (def.rules ?? []).map((r) => ({ match: sticky(r.match), type: r.type }));
84
- const strings = [...def.strings ?? []].sort((a, b) => b.open.length - a.open.length);
114
+ const strings = [...def.strings ?? []].sort((a, b) => b.open.length - a.open.length).map((s) => ({ open: s.open, close: s.close ?? s.open, escape: s.escape ?? true, multiline: s.multiline ?? false, type: s.type ?? "string", interpolate: s.interpolate }));
85
115
  const ident = sticky(def.identifier ?? IDENT);
86
116
  const calls = def.calls ?? true;
117
+ const numbers = def.numbers ?? true;
118
+ const operators = def.operators ?? true;
87
119
  function classify(word, line, end) {
88
120
  const k = ci ? word.toLowerCase() : word;
89
121
  if (keywords.has(k)) return "keyword";
@@ -101,38 +133,90 @@ var codelight = (() => {
101
133
  return {
102
134
  tokenizeLine(line, state) {
103
135
  const out = new LineBuilder();
104
- let open = state;
136
+ const stack = state ? [...state] : [];
137
+ const top = () => stack[stack.length - 1];
138
+ let heredoc;
105
139
  let i = 0;
106
- if (open) {
107
- const end = findClose(line, 0, open.close, open.escape);
108
- if (end < 0) {
109
- out.add(open.type, line);
110
- return { tokens: out.tokens, state: open };
111
- }
112
- out.add(open.type, line.slice(0, end));
113
- i = end;
114
- open = null;
140
+ let m;
141
+ const doc = top();
142
+ if (doc?.t === "heredoc") {
143
+ if ((doc.dash ? line.replace(/^\t+/, "") : line) === doc.end) {
144
+ out.add("meta", line);
145
+ stack.pop();
146
+ } else out.add("string", line);
147
+ return { tokens: out.tokens, state: stack.length ? stack : null };
115
148
  }
116
149
  scan: while (i < line.length) {
150
+ const f = top();
151
+ if (f?.t === "comment") {
152
+ const end = line.indexOf(f.close, i);
153
+ if (end < 0) {
154
+ out.add("comment", line.slice(i));
155
+ break;
156
+ }
157
+ out.add("comment", line.slice(i, end + f.close.length));
158
+ i = end + f.close.length;
159
+ stack.pop();
160
+ continue;
161
+ }
162
+ if (f?.t === "string") {
163
+ const s = f.s;
164
+ for (let j = i; j < line.length; j++) {
165
+ if (s.interpolate && line.startsWith(s.interpolate[0], j)) {
166
+ if (s.interpolate[0] === "{" && line[j + 1] === "{") {
167
+ j++;
168
+ continue;
169
+ }
170
+ out.add(s.type, line.slice(i, j));
171
+ out.add("punctuation", s.interpolate[0]);
172
+ i = j + s.interpolate[0].length;
173
+ const close = s.interpolate[1];
174
+ stack.push({ t: "code", close, open: PAIRS[close] ?? "", depth: 0 });
175
+ continue scan;
176
+ }
177
+ if (s.escape && line[j] === "\\") {
178
+ j++;
179
+ continue;
180
+ }
181
+ if (line.startsWith(s.close, j)) {
182
+ out.add(s.type, line.slice(i, j + s.close.length));
183
+ i = j + s.close.length;
184
+ stack.pop();
185
+ continue scan;
186
+ }
187
+ }
188
+ out.add(s.type, line.slice(i));
189
+ break;
190
+ }
191
+ if (f?.t === "code") {
192
+ if (f.depth === 0 && line.startsWith(f.close, i)) {
193
+ out.add("punctuation", f.close);
194
+ i += f.close.length;
195
+ stack.pop();
196
+ continue;
197
+ }
198
+ const ch2 = line[i];
199
+ if (ch2 === f.open || f.depth > 0 && ch2 === f.close) {
200
+ stack[stack.length - 1] = { ...f, depth: f.depth + (ch2 === f.open ? 1 : -1) };
201
+ out.add("punctuation", ch2);
202
+ i++;
203
+ continue;
204
+ }
205
+ }
117
206
  for (const r of rules) {
118
207
  r.match.lastIndex = i;
119
- const m2 = r.match.exec(line);
120
- if (m2 && m2[0]) {
121
- out.add(r.type, m2[0]);
122
- i += m2[0].length;
208
+ const hit = r.match.exec(line);
209
+ if (hit && hit[0]) {
210
+ out.add(r.type, hit[0]);
211
+ i += hit[0].length;
123
212
  continue scan;
124
213
  }
125
214
  }
126
215
  for (const [o, c] of def.blockComment ?? []) {
127
216
  if (!line.startsWith(o, i)) continue;
128
- const end = line.indexOf(c, i + o.length);
129
- if (end < 0) {
130
- out.add("comment", line.slice(i));
131
- open = { close: c, type: "comment", escape: false };
132
- break scan;
133
- }
134
- out.add("comment", line.slice(i, end + c.length));
135
- i = end + c.length;
217
+ out.add("comment", o);
218
+ i += o.length;
219
+ stack.push({ t: "comment", close: c });
136
220
  continue scan;
137
221
  }
138
222
  for (const p of def.lineComment ?? []) {
@@ -143,22 +227,20 @@ var codelight = (() => {
143
227
  }
144
228
  for (const s of strings) {
145
229
  if (!line.startsWith(s.open, i)) continue;
146
- const type = s.type ?? "string";
147
- const close = s.close ?? s.open;
148
- const escape = s.escape ?? true;
149
- const end = findClose(line, i + s.open.length, close, escape);
150
- if (end < 0) {
151
- out.add(type, line.slice(i));
152
- if (s.multiline) open = { close, type, escape };
153
- break scan;
154
- }
155
- out.add(type, line.slice(i, end));
156
- i = end;
230
+ out.add(s.type, s.open);
231
+ i += s.open.length;
232
+ stack.push({ t: "string", s });
157
233
  continue scan;
158
234
  }
159
- let m;
235
+ if (def.heredoc && (m = (HEREDOC.lastIndex = i, HEREDOC.exec(line)))) {
236
+ out.add("operator", `<<${m[1]}`);
237
+ out.add("meta", m[0].slice(2 + m[1].length));
238
+ heredoc = { t: "heredoc", end: m[3], dash: !!m[1] };
239
+ i += m[0].length;
240
+ continue;
241
+ }
160
242
  NUMBER.lastIndex = i;
161
- if (m = NUMBER.exec(line)) {
243
+ if (numbers && (m = NUMBER.exec(line))) {
162
244
  out.add("number", m[0]);
163
245
  i += m[0].length;
164
246
  continue;
@@ -177,7 +259,7 @@ var codelight = (() => {
177
259
  }
178
260
  OPERATOR.lastIndex = i;
179
261
  if (m = OPERATOR.exec(line)) {
180
- out.add("operator", m[0]);
262
+ out.add(operators ? "operator" : void 0, m[0]);
181
263
  i += m[0].length;
182
264
  continue;
183
265
  }
@@ -185,7 +267,10 @@ var codelight = (() => {
185
267
  out.add(PUNCTUATION.includes(ch) ? "punctuation" : void 0, ch);
186
268
  i++;
187
269
  }
188
- return { tokens: out.tokens, state: open };
270
+ const cut = stack.findIndex((fr) => fr.t === "string" && !fr.s.multiline);
271
+ if (cut >= 0) stack.length = cut;
272
+ if (heredoc) stack.push(heredoc);
273
+ return { tokens: out.tokens, state: stack.length ? stack : null };
189
274
  }
190
275
  };
191
276
  }
@@ -193,6 +278,29 @@ var codelight = (() => {
193
278
  tokenizeLine: (line) => ({ tokens: line ? [{ text: line }] : [], state: null })
194
279
  };
195
280
 
281
+ // src/lib/lines.ts
282
+ function parseLines(spec) {
283
+ const out = /* @__PURE__ */ new Set();
284
+ if (spec == null) return out;
285
+ if (typeof spec === "number") return out.add(spec);
286
+ if (Array.isArray(spec)) return new Set(spec);
287
+ for (const part of spec.split(/[\s,]+/)) {
288
+ const m = /^(\d+)(?:-(\d+))?$/.exec(part);
289
+ if (!m) continue;
290
+ const from = Number(m[1]);
291
+ const to = Number(m[2] ?? m[1]);
292
+ for (let n = Math.min(from, to); n <= Math.max(from, to) && n - from < 1e5; n++) out.add(n);
293
+ }
294
+ return out;
295
+ }
296
+ var wantsLines = (o) => !!o && (!!o.lineNumbers || o.highlightLines != null);
297
+ function lineClass(n, numbers, marked) {
298
+ return "cl-line" + (numbers ? " cl-ln" : "") + (marked.has(n) ? " cl-mark" : "");
299
+ }
300
+ function wrapLine(html, n, numbers, marked) {
301
+ return `<span class="${lineClass(n, numbers, marked)}" data-line="${n}">${html}</span>`;
302
+ }
303
+
196
304
  // src/languages/bash.ts
197
305
  var bash_default = defineLanguage({
198
306
  strings: [{ open: '"', multiline: true }, { open: "'", escape: false, multiline: true }],
@@ -205,7 +313,8 @@ var codelight = (() => {
205
313
  { match: /(?<=\s)--?[A-Za-z][\w-]*/, type: "attr" }
206
314
  ],
207
315
  identifier: /[A-Za-z_][\w-]*/,
208
- calls: false
316
+ calls: false,
317
+ heredoc: true
209
318
  });
210
319
 
211
320
  // src/languages/_common.ts
@@ -240,12 +349,20 @@ var codelight = (() => {
240
349
  });
241
350
 
242
351
  // src/languages/csharp.ts
352
+ var INTERPOLATE = ["{", "}"];
243
353
  var csharp_default = defineLanguage({
244
354
  ...C_COMMENTS,
245
- strings: [{ open: '@"', close: '"', escape: false, multiline: true }, { open: '$"', close: '"' }, ...QUOTES],
355
+ strings: [
356
+ { open: '$@"', close: '"', escape: false, multiline: true, interpolate: INTERPOLATE },
357
+ { open: '@$"', close: '"', escape: false, multiline: true, interpolate: INTERPOLATE },
358
+ { open: '@"', close: '"', escape: false, multiline: true },
359
+ { open: '$"', close: '"', interpolate: INTERPOLATE },
360
+ ...QUOTES
361
+ ],
246
362
  keywords: "abstract as base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual volatile while async await var record get set init yield where when",
247
363
  types: "bool byte char decimal double float int long object sbyte short string uint ulong ushort void dynamic",
248
364
  constants: "true false null",
365
+ rules: [{ match: /(?<=^\s*)\[[A-Z]\w*(?:\([^)]*\))?\]/, type: "meta" }],
249
366
  classNames: true
250
367
  });
251
368
 
@@ -274,6 +391,21 @@ var codelight = (() => {
274
391
  };
275
392
  var diff_default = diff;
276
393
 
394
+ // src/languages/dockerfile.ts
395
+ var INSTRUCTIONS = "FROM|RUN|CMD|LABEL|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL|MAINTAINER";
396
+ var dockerfile_default = defineLanguage({
397
+ strings: [{ open: '"' }, { open: "'", escape: false }],
398
+ rules: [
399
+ { match: /(?<=^\s*)#.*/, type: "comment" },
400
+ { match: new RegExp(`(?<=^\\s*)(?:${INSTRUCTIONS})\\b`, "i"), type: "keyword" },
401
+ { match: /(?<=^\s*FROM\s.*\s)AS(?=\s)/i, type: "keyword" },
402
+ { match: /\$(?:\{[^}]*\}|[A-Za-z_]\w*)/, type: "variable" },
403
+ { match: /(?<=\s)--[A-Za-z][\w-]*/, type: "attr" }
404
+ ],
405
+ identifier: /[A-Za-z_][\w.-]*/,
406
+ calls: false
407
+ });
408
+
277
409
  // src/languages/go.ts
278
410
  var go_default = defineLanguage({
279
411
  ...C_COMMENTS,
@@ -284,6 +416,38 @@ var codelight = (() => {
284
416
  builtins: "append cap close copy delete len make new panic print println recover"
285
417
  });
286
418
 
419
+ // src/languages/graphql.ts
420
+ var graphql_default = defineLanguage({
421
+ lineComment: ["#"],
422
+ strings: [{ open: '"""', multiline: true }, { open: '"' }],
423
+ keywords: "query mutation subscription fragment on type interface union enum input scalar schema extend directive implements repeatable",
424
+ constants: "true false null",
425
+ types: "Int Float String Boolean ID",
426
+ rules: [
427
+ { match: /\$[A-Za-z_]\w*/, type: "variable" },
428
+ { match: /@[A-Za-z_]\w*/, type: "meta" },
429
+ { match: /\.\.\./, type: "operator" },
430
+ { match: /[A-Za-z_]\w*(?=\s*:)/, type: "property" }
431
+ ],
432
+ classNames: true
433
+ });
434
+
435
+ // src/languages/hcl.ts
436
+ var hcl_default = defineLanguage({
437
+ lineComment: ["#", "//"],
438
+ blockComment: [["/*", "*/"]],
439
+ strings: [{ open: '"', interpolate: ["${", "}"] }],
440
+ constants: "true false null",
441
+ types: "string number bool list map set object tuple any",
442
+ rules: [
443
+ { match: /(?<=^\s*)(?:resource|data|variable|output|module|provider|locals|terraform|moved|import|check)\b/, type: "keyword" },
444
+ { match: /\b(?:for|in|if|for_each|count|depends_on|lifecycle|dynamic|content)\b(?!\s*=)/, type: "keyword" },
445
+ { match: /(?<=^\s*)[A-Za-z_][\w-]*(?=\s*=(?!=))/, type: "property" }
446
+ ],
447
+ identifier: /[A-Za-z_][\w-]*/,
448
+ heredoc: true
449
+ });
450
+
287
451
  // src/languages/java.ts
288
452
  var java_default = defineLanguage({
289
453
  ...C_COMMENTS,
@@ -298,14 +462,19 @@ var codelight = (() => {
298
462
  // src/languages/javascript.ts
299
463
  var JS_KEYWORDS = "break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield async await of static get set from as";
300
464
  var JS_CONSTANTS = "true false null undefined NaN Infinity";
465
+ var TEMPLATE = { open: "`", multiline: true, interpolate: ["${", "}"] };
301
466
  var JSX_TAG = { match: /(?<=(?:^|[(=?:,&|{}[>;]|\breturn)\s*)<\/?[A-Za-z][\w.:-]*(?=[\s/>]|$)/, type: "tag" };
467
+ var REGEX = {
468
+ match: /(?<=(?:^|[(,=:[!&|?{;]|\breturn|\btypeof|\bcase)\s*)\/(?![*/\s>])(?:\\.|\[(?:\\.|[^\]\\])*\]|[^\\/[])+\/[dgimsuvy]*/,
469
+ type: "regex"
470
+ };
302
471
  var DECORATOR = { match: /@[A-Za-z_$][\w$.]*/, type: "meta" };
303
472
  var javascript_default = defineLanguage({
304
473
  ...C_COMMENTS,
305
- strings: [...QUOTES, { open: "`", multiline: true }],
474
+ strings: [...QUOTES, TEMPLATE],
306
475
  keywords: JS_KEYWORDS,
307
476
  constants: JS_CONSTANTS,
308
- rules: [JSX_TAG, DECORATOR],
477
+ rules: [JSX_TAG, REGEX, DECORATOR],
309
478
  classNames: true
310
479
  });
311
480
 
@@ -318,6 +487,44 @@ var codelight = (() => {
318
487
  calls: false
319
488
  });
320
489
 
490
+ // src/languages/kotlin.ts
491
+ var INTERPOLATE2 = ["${", "}"];
492
+ var kotlin_default = defineLanguage({
493
+ ...C_COMMENTS,
494
+ strings: [
495
+ { open: '"""', multiline: true, escape: false, interpolate: INTERPOLATE2 },
496
+ { open: '"', interpolate: INTERPOLATE2 },
497
+ { open: "'" }
498
+ ],
499
+ keywords: "package import class interface object fun val var if else when for while do return break continue throw try catch finally is in as typealias this super data sealed enum open abstract override private protected public internal companion lateinit suspend inline reified by init get set where out vararg const operator infix annotation",
500
+ constants: "true false null",
501
+ types: "Int Long Short Byte Double Float Boolean Char String Unit Any Nothing List Map Set",
502
+ // Annotations (`@Serializable`) and labels (`return@forEach`).
503
+ rules: [{ match: /@[A-Za-z_]\w*(?::\w+)?/, type: "meta" }],
504
+ classNames: true
505
+ });
506
+
507
+ // src/languages/markdown.ts
508
+ var markdown_default = defineLanguage({
509
+ blockComment: [["<!--", "-->"]],
510
+ rules: [
511
+ { match: /^#{1,6}\s.*/, type: "keyword" },
512
+ { match: /^ {0,3}(?:`{3,}|~{3,}).*/, type: "meta" },
513
+ { match: /^\s*>.*/, type: "comment" },
514
+ { match: /^\s*(?:[-*+]|\d+[.)])(?=\s)/, type: "punctuation" },
515
+ { match: /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/, type: "punctuation" },
516
+ { match: /`[^`]+`/, type: "string" },
517
+ { match: /!?\[[^\]]*\]\([^)\s]*(?:\s+"[^"]*")?\)/, type: "function" },
518
+ { match: /\*\*[^*]+\*\*|__[^_]+__/, type: "type" },
519
+ { match: /(?<![\w*])\*[^*\s][^*]*\*(?!\*)|(?<!\w)_[^_\s][^_]*_(?!\w)/, type: "attr" },
520
+ { match: /<\/?[A-Za-z][^>]*>/, type: "tag" }
521
+ ],
522
+ identifier: /[A-Za-z_][\w'-]*/,
523
+ calls: false,
524
+ numbers: false,
525
+ operators: false
526
+ });
527
+
321
528
  // src/languages/php.ts
322
529
  var php_default = defineLanguage({
323
530
  lineComment: ["//", "#"],
@@ -333,17 +540,51 @@ var codelight = (() => {
333
540
  classNames: true
334
541
  });
335
542
 
543
+ // src/languages/powershell.ts
544
+ var powershell_default = defineLanguage({
545
+ lineComment: ["#"],
546
+ blockComment: [["<#", "#>"]],
547
+ strings: [
548
+ // Double-quoted strings run the code inside `$(…)`.
549
+ { open: '@"', close: '"@', escape: false, multiline: true, interpolate: ["$(", ")"] },
550
+ { open: "@'", close: "'@", escape: false, multiline: true },
551
+ { open: '"', escape: false, multiline: true, interpolate: ["$(", ")"] },
552
+ { open: "'", escape: false, multiline: true }
553
+ ],
554
+ keywords: "if else elseif switch foreach for while do until break continue return function filter param begin process end try catch finally throw trap in exit class enum using",
555
+ caseInsensitive: true,
556
+ rules: [
557
+ { match: /\$(?:true|false|null)\b/i, type: "constant" },
558
+ { match: /\$(?:\{[^}]+\}|[\w:]+)/, type: "variable" },
559
+ { match: /-(?:eq|ne|gt|ge|lt|le|like|notlike|match|notmatch|contains|notcontains|in|notin|and|or|not|xor|replace|split|join|is|isnot|as)\b/i, type: "operator" },
560
+ { match: /\[[A-Za-z][\w.]*(?:\[\])?\]/, type: "type" },
561
+ { match: /\b[A-Z][a-z]+-[A-Z]\w+/, type: "function" },
562
+ { match: /(?<=\s)-[A-Za-z]\w*/, type: "attr" }
563
+ ],
564
+ identifier: /[A-Za-z_][\w-]*/
565
+ });
566
+
336
567
  // src/languages/python.ts
568
+ var F_STRINGS = ["f", "F", "rf", "rF", "Rf", "RF", "fr", "fR", "Fr", "FR"].flatMap(
569
+ (prefix) => ['"""', "'''", '"', "'"].map((quote) => ({
570
+ open: prefix + quote,
571
+ close: quote,
572
+ escape: !/r/i.test(prefix),
573
+ multiline: quote.length === 3,
574
+ interpolate: ["{", "}"]
575
+ }))
576
+ );
337
577
  var python_default = defineLanguage({
338
578
  lineComment: ["#"],
339
- strings: [{ open: '"""', multiline: true }, { open: "'''", multiline: true }, ...QUOTES],
579
+ strings: [...F_STRINGS, { open: '"""', multiline: true }, { open: "'''", multiline: true }, ...QUOTES],
340
580
  keywords: "and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield match case",
341
581
  constants: "True False None",
342
582
  variables: "self cls",
343
583
  types: "int float str bool list dict set tuple bytes object Exception",
344
584
  rules: [
345
585
  { match: /(?<=^\s*)@[\w.]+/, type: "meta" },
346
- { match: /[rRbBuUfF]{1,2}(?=["'])/, type: "string" }
586
+ // r"…", b"…", u"…" prefixes (f-strings are handled above).
587
+ { match: /[rRbBuU]{1,2}(?=["'])/, type: "string" }
347
588
  ],
348
589
  classNames: true
349
590
  });
@@ -393,16 +634,53 @@ var codelight = (() => {
393
634
  caseInsensitive: true
394
635
  });
395
636
 
637
+ // src/languages/swift.ts
638
+ var INTERPOLATE3 = ["\\(", ")"];
639
+ var swift_default = defineLanguage({
640
+ ...C_COMMENTS,
641
+ strings: [
642
+ { open: '"""', multiline: true, interpolate: INTERPOLATE3 },
643
+ { open: '"', interpolate: INTERPOLATE3 }
644
+ ],
645
+ keywords: "import let var func class struct enum protocol extension if else guard switch case default for in while repeat return break continue fallthrough throw throws rethrows try catch do defer as is init deinit self Self super static private fileprivate internal public open final override mutating nonmutating weak unowned lazy inout where async await some any typealias associatedtype subscript convenience required",
646
+ constants: "true false nil",
647
+ types: "Int Double Float String Bool Character Array Dictionary Set Void Optional Result Error",
648
+ rules: [
649
+ { match: /@[A-Za-z_]\w*/, type: "meta" },
650
+ { match: /#(?:available|if|else|elseif|endif|selector|keyPath|warning|error)\b/, type: "meta" }
651
+ ],
652
+ classNames: true
653
+ });
654
+
655
+ // src/languages/toml.ts
656
+ var toml_default = defineLanguage({
657
+ lineComment: ["#"],
658
+ strings: [
659
+ { open: '"""', multiline: true },
660
+ { open: "'''", multiline: true, escape: false },
661
+ { open: '"' },
662
+ { open: "'", escape: false }
663
+ ],
664
+ constants: "true false inf nan",
665
+ rules: [
666
+ { match: /(?<=^\s*)\[\[?[^\]]*\]\]?/, type: "tag" },
667
+ { match: /(?<=^\s*)[\w.\-"' ]+?(?=\s*=)/, type: "property" },
668
+ { match: /\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?)?/, type: "number" }
669
+ ],
670
+ identifier: /[A-Za-z_][\w-]*/,
671
+ calls: false
672
+ });
673
+
396
674
  // src/languages/typescript.ts
397
675
  var TS_KEYWORDS = " interface type enum implements namespace declare abstract readonly private protected public keyof infer is satisfies asserts module override unique";
398
676
  var ts = (jsx) => ({
399
677
  ...C_COMMENTS,
400
- strings: [...QUOTES, { open: "`", multiline: true }],
678
+ strings: [...QUOTES, TEMPLATE],
401
679
  keywords: JS_KEYWORDS + TS_KEYWORDS,
402
680
  types: "string number boolean any unknown never void object symbol bigint",
403
681
  constants: JS_CONSTANTS,
404
682
  // Plain TypeScript has no JSX, so `Map<string, number>` is never mistaken for a tag.
405
- rules: jsx ? [JSX_TAG, DECORATOR] : [DECORATOR],
683
+ rules: jsx ? [JSX_TAG, REGEX, DECORATOR] : [REGEX, DECORATOR],
406
684
  classNames: true
407
685
  });
408
686
  var typescript_default = defineLanguage(ts(false));
@@ -579,6 +857,14 @@ var codelight = (() => {
579
857
  yaml: yaml_default,
580
858
  xml: xml_default,
581
859
  diff: diff_default,
860
+ kotlin: kotlin_default,
861
+ swift: swift_default,
862
+ dockerfile: dockerfile_default,
863
+ toml: toml_default,
864
+ markdown: markdown_default,
865
+ graphql: graphql_default,
866
+ powershell: powershell_default,
867
+ hcl: hcl_default,
582
868
  plaintext: plain
583
869
  };
584
870
 
@@ -628,6 +914,20 @@ var codelight = (() => {
628
914
  vue: "xml",
629
915
  svelte: "xml",
630
916
  patch: "diff",
917
+ kt: "kotlin",
918
+ kts: "kotlin",
919
+ docker: "dockerfile",
920
+ containerfile: "dockerfile",
921
+ md: "markdown",
922
+ mdx: "markdown",
923
+ gql: "graphql",
924
+ ps1: "powershell",
925
+ pwsh: "powershell",
926
+ ps: "powershell",
927
+ terraform: "hcl",
928
+ tf: "hcl",
929
+ tfvars: "hcl",
930
+ opentofu: "hcl",
631
931
  text: "plaintext",
632
932
  txt: "plaintext",
633
933
  plain: "plaintext",
@@ -666,8 +966,11 @@ var codelight = (() => {
666
966
  return r.tokens;
667
967
  });
668
968
  }
669
- function highlight(code, lang) {
670
- return tokenize(code, lang).map(renderLine).join("\n");
969
+ function highlight(code, lang, options) {
970
+ const lines = tokenize(code, lang).map(renderLine);
971
+ if (!wantsLines(options)) return lines.join("\n");
972
+ const marked = parseLines(options.highlightLines);
973
+ return lines.map((html, i) => wrapLine(html, i + 1, !!options.lineNumbers, marked)).join("\n");
671
974
  }
672
975
  function createStream(lang) {
673
976
  const language = resolve(lang);
@@ -696,18 +999,25 @@ var codelight = (() => {
696
999
 
697
1000
  // src/lib/auto.ts
698
1001
  var MARKDOWN_CLASS = /(?:^|\s)language-(\S+)/;
1002
+ var attr = (code, name) => code.getAttribute(name) ?? code.parentElement?.getAttribute(name) ?? null;
699
1003
  function languageOf(code) {
700
- return code.getAttribute("data-lang") ?? code.parentElement?.getAttribute("data-lang") ?? MARKDOWN_CLASS.exec(code.className)?.[1] ?? "";
1004
+ return attr(code, "data-lang") ?? MARKDOWN_CLASS.exec(code.className)?.[1] ?? "";
701
1005
  }
702
- function highlightElement(code, lang = languageOf(code)) {
703
- code.innerHTML = highlight(code.textContent ?? "", lang);
1006
+ function highlightElement(code, lang = languageOf(code), options = {}) {
1007
+ const lineNumbers = options.lineNumbers ?? attr(code, "data-line-numbers") != null;
1008
+ const highlightLines = options.highlightLines ?? attr(code, "data-highlight-lines") ?? void 0;
1009
+ code.innerHTML = highlight(code.textContent ?? "", lang, { lineNumbers, highlightLines });
704
1010
  code.classList.add("cl");
705
1011
  code.setAttribute("data-cl", lang);
1012
+ if (options.copyButton) addCopyButton(code);
706
1013
  }
707
- function highlightAll(root) {
1014
+ function highlightAll(rootOrOptions, maybeOptions = {}) {
1015
+ const isRoot = !!rootOrOptions && typeof rootOrOptions.querySelectorAll === "function";
1016
+ const root = isRoot ? rootOrOptions : void 0;
1017
+ const options = isRoot ? maybeOptions : { ...rootOrOptions, ...maybeOptions };
708
1018
  if (!root && typeof document === "undefined") return;
709
1019
  const run = () => {
710
- for (const code of (root ?? document).querySelectorAll("pre > code:not([data-cl])")) highlightElement(code);
1020
+ for (const code of (root ?? document).querySelectorAll("pre > code:not([data-cl])")) highlightElement(code, void 0, options);
711
1021
  };
712
1022
  if (!root && document.readyState === "loading") document.addEventListener("DOMContentLoaded", run, { once: true });
713
1023
  else run();
@@ -716,17 +1026,21 @@ var codelight = (() => {
716
1026
  // src/lib/dom.ts
717
1027
  function mount(target, options = {}) {
718
1028
  const doc = target.ownerDocument;
1029
+ const numbers = !!options.lineNumbers;
1030
+ const marked = parseLines(options.highlightLines);
719
1031
  let lang = options.lang;
720
1032
  let stream;
721
1033
  let tail;
722
- const lineElement = () => {
723
- const el = doc.createElement("span");
724
- el.className = "cl-line";
725
- return el;
1034
+ let done = 0;
1035
+ const number = (el, n) => {
1036
+ el.className = lineClass(n, numbers, marked);
1037
+ if (numbers || marked.size) el.setAttribute("data-line", String(n));
726
1038
  };
727
1039
  const start = () => {
728
1040
  stream = createStream(lang);
729
- tail = lineElement();
1041
+ done = 0;
1042
+ tail = doc.createElement("span");
1043
+ number(tail, 1);
730
1044
  target.replaceChildren(tail);
731
1045
  };
732
1046
  target.classList.add("cl");
@@ -742,13 +1056,15 @@ var codelight = (() => {
742
1056
  if (!chunk) return;
743
1057
  const { lines, tail: last } = stream.push(chunk);
744
1058
  if (lines.length) {
745
- const done = doc.createDocumentFragment();
1059
+ const finished = doc.createDocumentFragment();
746
1060
  for (const line of lines) {
747
- const el = lineElement();
1061
+ const el = doc.createElement("span");
1062
+ number(el, ++done);
748
1063
  el.innerHTML = renderLine(line);
749
- done.append(el, "\n");
1064
+ finished.append(el, "\n");
750
1065
  }
751
- target.insertBefore(done, tail);
1066
+ target.insertBefore(finished, tail);
1067
+ number(tail, done + 1);
752
1068
  }
753
1069
  tail.innerHTML = renderLine(last);
754
1070
  },
@@ -818,7 +1134,182 @@ var codelight = (() => {
818
1134
  }
819
1135
 
820
1136
  // src/styles/default.css
821
- var default_default = '/*!\n codelight.js theme: default\n Light or dark to match the system. To force one, put a cl-light or cl-dark class\n (or light / dark, or data-theme="light" / "dark") on the code or any parent.\n*/\n.cl {\n --cl-fg: #1e2430;\n --cl-bg: #f7f7f9;\n --cl-keyword: #b4235a;\n --cl-string: #1d6b45;\n --cl-comment: #6b7280;\n --cl-number: #a35200;\n --cl-function: #3a52c4;\n --cl-type: #8a3ab9;\n --cl-constant: #a35200;\n --cl-variable: #9a3f0c;\n --cl-property: #1f6f9a;\n --cl-operator: #b4235a;\n --cl-punctuation: #4b5563;\n --cl-tag: #2459a8;\n --cl-attr: #8a3ab9;\n --cl-meta: #6b4fbb;\n --cl-inserted: #166534;\n --cl-inserted-bg: #dcfce7;\n --cl-deleted: #9f1239;\n --cl-deleted-bg: #ffe4e6;\n color: var(--cl-fg);\n background: var(--cl-bg);\n}\n@media (prefers-color-scheme: dark) {\n .cl {\n --cl-fg: #e4e7ee;\n --cl-bg: #11141a;\n --cl-keyword: #ff7aa8;\n --cl-string: #8fdba8;\n --cl-comment: #8a93a3;\n --cl-number: #ffb86b;\n --cl-function: #8fb4ff;\n --cl-type: #d0a3ff;\n --cl-constant: #ffb86b;\n --cl-variable: #ffa070;\n --cl-property: #7fd0f0;\n --cl-operator: #ff7aa8;\n --cl-punctuation: #aab1bd;\n --cl-tag: #8fb4ff;\n --cl-attr: #d0a3ff;\n --cl-meta: #b49cff;\n --cl-inserted: #a7f3c0;\n --cl-inserted-bg: #0f3a24;\n --cl-deleted: #fecdd3;\n --cl-deleted-bg: #4c1020;\n }\n}\n.cl-dark .cl, .cl.cl-dark, .dark .cl, [data-theme="dark"] .cl {\n --cl-fg: #e4e7ee;\n --cl-bg: #11141a;\n --cl-keyword: #ff7aa8;\n --cl-string: #8fdba8;\n --cl-comment: #8a93a3;\n --cl-number: #ffb86b;\n --cl-function: #8fb4ff;\n --cl-type: #d0a3ff;\n --cl-constant: #ffb86b;\n --cl-variable: #ffa070;\n --cl-property: #7fd0f0;\n --cl-operator: #ff7aa8;\n --cl-punctuation: #aab1bd;\n --cl-tag: #8fb4ff;\n --cl-attr: #d0a3ff;\n --cl-meta: #b49cff;\n --cl-inserted: #a7f3c0;\n --cl-inserted-bg: #0f3a24;\n --cl-deleted: #fecdd3;\n --cl-deleted-bg: #4c1020;\n}\n.cl-light .cl, .cl.cl-light, .light .cl, [data-theme="light"] .cl {\n --cl-fg: #1e2430;\n --cl-bg: #f7f7f9;\n --cl-keyword: #b4235a;\n --cl-string: #1d6b45;\n --cl-comment: #6b7280;\n --cl-number: #a35200;\n --cl-function: #3a52c4;\n --cl-type: #8a3ab9;\n --cl-constant: #a35200;\n --cl-variable: #9a3f0c;\n --cl-property: #1f6f9a;\n --cl-operator: #b4235a;\n --cl-punctuation: #4b5563;\n --cl-tag: #2459a8;\n --cl-attr: #8a3ab9;\n --cl-meta: #6b4fbb;\n --cl-inserted: #166534;\n --cl-inserted-bg: #dcfce7;\n --cl-deleted: #9f1239;\n --cl-deleted-bg: #ffe4e6;\n}\npre > code.cl {\n display: block;\n padding: 1rem 1.25rem;\n overflow: auto;\n}\n.cl-keyword { color: var(--cl-keyword); }\n.cl-string { color: var(--cl-string); }\n.cl-comment { color: var(--cl-comment); }\n.cl-number { color: var(--cl-number); }\n.cl-function { color: var(--cl-function); }\n.cl-type { color: var(--cl-type); }\n.cl-constant { color: var(--cl-constant); }\n.cl-variable { color: var(--cl-variable); }\n.cl-property { color: var(--cl-property); }\n.cl-operator { color: var(--cl-operator); }\n.cl-punctuation { color: var(--cl-punctuation); }\n.cl-tag { color: var(--cl-tag); }\n.cl-attr { color: var(--cl-attr); }\n.cl-meta { color: var(--cl-meta); }\n.cl-comment { font-style: italic; }\n.cl-inserted { color: var(--cl-inserted); background: var(--cl-inserted-bg); }\n.cl-deleted { color: var(--cl-deleted); background: var(--cl-deleted-bg); }\n';
1137
+ var default_default = `/*!
1138
+ codelight.js theme: default
1139
+ Light or dark to match the system. To force one, put a cl-light or cl-dark class
1140
+ (or light / dark, or data-theme="light" / "dark") on the code or any parent.
1141
+ */
1142
+ .cl, .cl-copy {
1143
+ --cl-fg: #1e2430;
1144
+ --cl-bg: #f7f7f9;
1145
+ --cl-keyword: #b4235a;
1146
+ --cl-string: #1d6b45;
1147
+ --cl-regex: #0b6477;
1148
+ --cl-comment: #656c79;
1149
+ --cl-number: #a35200;
1150
+ --cl-function: #3a52c4;
1151
+ --cl-type: #8a3ab9;
1152
+ --cl-constant: #a35200;
1153
+ --cl-variable: #9a3f0c;
1154
+ --cl-property: #1f6f9a;
1155
+ --cl-operator: #b4235a;
1156
+ --cl-punctuation: #4b5563;
1157
+ --cl-tag: #2459a8;
1158
+ --cl-attr: #8a3ab9;
1159
+ --cl-meta: #6b4fbb;
1160
+ --cl-inserted: #166534;
1161
+ --cl-inserted-bg: #dcfce7;
1162
+ --cl-deleted: #9f1239;
1163
+ --cl-deleted-bg: #ffe4e6;
1164
+ --cl-line-number: #656c79;
1165
+ --cl-mark-bg: #fdf6e1;
1166
+ --cl-border: #d5d9e0;
1167
+ }
1168
+ .cl {
1169
+ color: var(--cl-fg);
1170
+ background: var(--cl-bg);
1171
+ }
1172
+ @media (prefers-color-scheme: dark) {
1173
+ .cl, .cl-copy {
1174
+ --cl-fg: #e4e7ee;
1175
+ --cl-bg: #11141a;
1176
+ --cl-keyword: #ff7aa8;
1177
+ --cl-string: #8fdba8;
1178
+ --cl-regex: #67e3f2;
1179
+ --cl-comment: #8a93a3;
1180
+ --cl-number: #ffb86b;
1181
+ --cl-function: #8fb4ff;
1182
+ --cl-type: #d0a3ff;
1183
+ --cl-constant: #ffb86b;
1184
+ --cl-variable: #ffa070;
1185
+ --cl-property: #7fd0f0;
1186
+ --cl-operator: #ff7aa8;
1187
+ --cl-punctuation: #aab1bd;
1188
+ --cl-tag: #8fb4ff;
1189
+ --cl-attr: #d0a3ff;
1190
+ --cl-meta: #b49cff;
1191
+ --cl-inserted: #a7f3c0;
1192
+ --cl-inserted-bg: #0f3a24;
1193
+ --cl-deleted: #fecdd3;
1194
+ --cl-deleted-bg: #4c1020;
1195
+ --cl-line-number: #8a93a3;
1196
+ --cl-mark-bg: #262116;
1197
+ --cl-border: #2e3440;
1198
+ }
1199
+ }
1200
+ .cl-dark .cl, .cl.cl-dark, .dark .cl, [data-theme="dark"] .cl, .cl-dark .cl-copy, .dark .cl-copy, [data-theme="dark"] .cl-copy {
1201
+ --cl-fg: #e4e7ee;
1202
+ --cl-bg: #11141a;
1203
+ --cl-keyword: #ff7aa8;
1204
+ --cl-string: #8fdba8;
1205
+ --cl-regex: #67e3f2;
1206
+ --cl-comment: #8a93a3;
1207
+ --cl-number: #ffb86b;
1208
+ --cl-function: #8fb4ff;
1209
+ --cl-type: #d0a3ff;
1210
+ --cl-constant: #ffb86b;
1211
+ --cl-variable: #ffa070;
1212
+ --cl-property: #7fd0f0;
1213
+ --cl-operator: #ff7aa8;
1214
+ --cl-punctuation: #aab1bd;
1215
+ --cl-tag: #8fb4ff;
1216
+ --cl-attr: #d0a3ff;
1217
+ --cl-meta: #b49cff;
1218
+ --cl-inserted: #a7f3c0;
1219
+ --cl-inserted-bg: #0f3a24;
1220
+ --cl-deleted: #fecdd3;
1221
+ --cl-deleted-bg: #4c1020;
1222
+ --cl-line-number: #8a93a3;
1223
+ --cl-mark-bg: #262116;
1224
+ --cl-border: #2e3440;
1225
+ }
1226
+ .cl-light .cl, .cl.cl-light, .light .cl, [data-theme="light"] .cl, .cl-light .cl-copy, .light .cl-copy, [data-theme="light"] .cl-copy {
1227
+ --cl-fg: #1e2430;
1228
+ --cl-bg: #f7f7f9;
1229
+ --cl-keyword: #b4235a;
1230
+ --cl-string: #1d6b45;
1231
+ --cl-regex: #0b6477;
1232
+ --cl-comment: #656c79;
1233
+ --cl-number: #a35200;
1234
+ --cl-function: #3a52c4;
1235
+ --cl-type: #8a3ab9;
1236
+ --cl-constant: #a35200;
1237
+ --cl-variable: #9a3f0c;
1238
+ --cl-property: #1f6f9a;
1239
+ --cl-operator: #b4235a;
1240
+ --cl-punctuation: #4b5563;
1241
+ --cl-tag: #2459a8;
1242
+ --cl-attr: #8a3ab9;
1243
+ --cl-meta: #6b4fbb;
1244
+ --cl-inserted: #166534;
1245
+ --cl-inserted-bg: #dcfce7;
1246
+ --cl-deleted: #9f1239;
1247
+ --cl-deleted-bg: #ffe4e6;
1248
+ --cl-line-number: #656c79;
1249
+ --cl-mark-bg: #fdf6e1;
1250
+ --cl-border: #d5d9e0;
1251
+ }
1252
+ pre > code.cl {
1253
+ display: block;
1254
+ padding: 1rem 1.25rem;
1255
+ overflow: auto;
1256
+ }
1257
+ .cl-keyword { color: var(--cl-keyword); }
1258
+ .cl-string { color: var(--cl-string); }
1259
+ .cl-regex { color: var(--cl-regex); }
1260
+ .cl-comment { color: var(--cl-comment); }
1261
+ .cl-number { color: var(--cl-number); }
1262
+ .cl-function { color: var(--cl-function); }
1263
+ .cl-type { color: var(--cl-type); }
1264
+ .cl-constant { color: var(--cl-constant); }
1265
+ .cl-variable { color: var(--cl-variable); }
1266
+ .cl-property { color: var(--cl-property); }
1267
+ .cl-operator { color: var(--cl-operator); }
1268
+ .cl-punctuation { color: var(--cl-punctuation); }
1269
+ .cl-tag { color: var(--cl-tag); }
1270
+ .cl-attr { color: var(--cl-attr); }
1271
+ .cl-meta { color: var(--cl-meta); }
1272
+ .cl-comment { font-style: italic; }
1273
+ .cl-inserted { color: var(--cl-inserted); background: var(--cl-inserted-bg); }
1274
+ .cl-deleted { color: var(--cl-deleted); background: var(--cl-deleted-bg); }
1275
+
1276
+ /* Line numbers: from data-line, so they're never copied with the code. */
1277
+ .cl-ln::before {
1278
+ content: attr(data-line);
1279
+ display: inline-block;
1280
+ min-width: var(--cl-gutter, 2.5ch);
1281
+ margin-right: 1.25em;
1282
+ text-align: right;
1283
+ color: var(--cl-line-number);
1284
+ font-style: normal;
1285
+ user-select: none;
1286
+ -webkit-user-select: none;
1287
+ }
1288
+ /* Highlighted lines fill the width of the block. */
1289
+ .cl-mark {
1290
+ display: inline-block;
1291
+ min-width: 100%;
1292
+ min-height: 1lh;
1293
+ background: var(--cl-mark-bg);
1294
+ }
1295
+
1296
+ /* Copy button */
1297
+ .cl-has-copy { position: relative; }
1298
+ .cl-copy {
1299
+ position: absolute;
1300
+ top: 0.5rem;
1301
+ right: 0.5rem;
1302
+ padding: 0.2rem 0.65rem;
1303
+ font: 500 12px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
1304
+ color: var(--cl-fg);
1305
+ background: var(--cl-bg);
1306
+ border: 1px solid var(--cl-border);
1307
+ border-radius: 6px;
1308
+ cursor: pointer;
1309
+ opacity: 0.8;
1310
+ }
1311
+ .cl-copy:hover, .cl-copy:focus-visible { opacity: 1; }
1312
+ `;
822
1313
 
823
1314
  // src/lib/theme.ts
824
1315
  var themeCss = default_default;
@@ -832,6 +1323,7 @@ var codelight = (() => {
832
1323
 
833
1324
  // src/codelight.ts
834
1325
  var codelight = {
1326
+ addCopyButton,
835
1327
  createMarkup,
836
1328
  createStream,
837
1329
  defineLanguage,