File size: 3,535 Bytes
b09157d
 
 
 
 
f5375f2
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5375f2
 
b09157d
f5375f2
 
 
 
 
 
 
 
 
 
 
 
 
b09157d
 
 
 
 
 
 
 
 
 
 
f5375f2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const C_TOKENS = /\/\*[\s\S]*?(?:\*\/|(?![\s\S]))|\/\/[^\n]*|(?:u8|[LuU])?"(?:\\[\s\S]|[^"\\\n])*(?:"|$)|(?:[LuU])?'(?:\\.|[^'\\\n])*(?:'|$)|^[\t ]*#[\t ]*[A-Za-z_]\w*|\b0[xX][\da-fA-F]+(?:\.[\da-fA-F]*)?(?:[pP][+-]?\d+)?[uUlLfF]*\b|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[uUlLfF]*\b|\b[A-Za-z_]\w*\b|>>=|<<=|->|\+\+|--|&&|\|\||[+\-*/%=!<>&|^~?:]+|[{}()[\]]/gm;
const TYPES = new Set('char double float int long short signed unsigned void _Bool _Complex _Imaginary bool size_t ptrdiff_t FILE int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t'.split(' '));
const CONTROL = new Set('break case continue default do else for goto if return switch while'.split(' '));
const KEYWORDS = new Set('auto const enum extern inline register restrict sizeof static struct typedef union volatile _Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local'.split(' '));
const escape = value => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');

export function cTokens(source) {
  return [...source.matchAll(C_TOKENS)].map(match => {
    const text = match[0];
    let kind;
    if (text.startsWith('//') || text.startsWith('/*')) kind = 'comment';
    else if (/^(?:u8|[LuU])?["']/.test(text)) kind = 'string';
    else if (/^[\t ]*#/.test(text)) kind = 'preprocessor';
    else if (/^[\d.]/.test(text)) kind = 'number';
    else if (TYPES.has(text)) kind = 'type';
    else if (CONTROL.has(text)) kind = 'control';
    else if (KEYWORDS.has(text)) kind = 'keyword';
    else if (/^[{}()[\]]$/.test(text)) kind = 'bracket';
    else if (/^[A-Za-z_]\w*$/.test(text)) kind = /^\s*\(/.test(source.slice(match.index + text.length)) ? 'function' : /^[A-Z_][A-Z_\d]*$/.test(text) ? 'constant' : 'variable';
    else kind = 'operator';
    return { text, start: match.index, end: match.index + text.length, kind };
  });
}

export function maskCNonCode(source) {
  let result = '', last = 0;
  for (const token of cTokens(source)) {
    result += source.slice(last, token.start);
    result += ['comment', 'string'].includes(token.kind) ? token.text.replace(/[^\n]/g, ' ') : token.text;
    last = token.end;
  }
  return (result + source.slice(last)).replace(/^[\t ]*#[^\n]*/gm, line => line.replace(/[^\n]/g, ' '));
}

function withOccurrences(value, selected) {
  if (!/^[A-Za-z_]\w*$/.test(selected)) return escape(value);
  const boundary = /^[A-Za-z_]\w*$/.test(selected) ? "\\b" : "";
  const expression = new RegExp(`${boundary}${selected.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}${boundary}`, "g");
  let result = "", last = 0;
  for (const match of value.matchAll(expression)) {
    result += escape(value.slice(last, match.index));
    result += `<mark class="code-occurrence">${escape(match[0])}</mark>`;
    last = match.index + match[0].length;
  }
  return result + escape(value.slice(last));
}

// HTML is escaped before insertion; the only markup emitted here is ours.
export function highlightC(source, selected = "") {
  let html = "", last = 0, depth = 0;
  for (const token of cTokens(source)) {
    html += withOccurrences(source.slice(last, token.start), selected);
    let kind = token.kind;
    if (kind === 'bracket') {
      if (/[})\]]/.test(token.text)) depth = Math.max(0, depth - 1);
      kind += ` bracket-${depth % 3}`;
      if (/[{(\[]/.test(token.text)) depth++;
    }
    html += `<span class="token-${kind}">${withOccurrences(token.text, selected)}</span>`;
    last = token.end;
  }
  return html + withOccurrences(source.slice(last), selected) + "\n";
}