File size: 6,329 Bytes
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { cTokens, maskCNonCode } from './cSyntaxHighlight.js';

export const EDITOR_FONTS = {
  consolas: { label: 'Consolas', family: 'Consolas, "Liberation Mono", monospace' },
  cascadia: { label: 'Cascadia Code', family: '"Cascadia Code", "Cascadia Mono", Consolas, monospace' },
  courier: { label: 'Courier New', family: '"Courier New", Courier, monospace' },
  system: { label: 'Monospace', family: 'ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace' },
};

export function wordRange(source, position) {
  let start = position, end = position;
  while (start > 0 && /\w/.test(source[start - 1])) start--;
  while (end < source.length && /\w/.test(source[end])) end++;
  return /^[A-Za-z_]\w*$/.test(source.slice(start, end)) ? { start, end } : null;
}

export function newlineEdit(source, start, end = start, unit = '    ') {
  const prefix = source.slice(0, start), clean = maskCNonCode(prefix);
  const currentLine = prefix.slice(prefix.lastIndexOf('\n') + 1);
  const leading = currentLine.match(/^[\t ]*/)[0];
  const stack = [];
  let lineStart = 0;
  for (let index = 0; index < clean.length; index++) {
    if (clean[index] === '\n') lineStart = index + 1;
    if (clean[index] === '{') {
      const lineIndent = prefix.slice(lineStart, index).match(/^[\t ]*/)[0];
      const parentIndent = stack.length ? stack.at(-1) + unit : '';
      stack.push(lineIndent.length >= parentIndent.length ? lineIndent : parentIndent);
    } else if (clean[index] === '}') stack.pop();
  }
  const blockIndent = stack.length ? stack.at(-1) + unit : '';
  const closesBlock = /^\s*}/.test(clean.slice(clean.lastIndexOf('\n') + 1));
  let indent = closesBlock ? blockIndent : leading.length >= blockIndent.length ? leading : blockIndent;
  const cleanLine = clean.slice(clean.lastIndexOf('\n') + 1);
  if (/(?:[);]|\belse|\bdo)\s*$/.test(cleanLine)) {
    const next = reindentC(prefix + '\n__indent_probe;', unit).split('\n').at(-1);
    indent = next.match(/^[\t ]*/)[0];
  }
  if (!cleanLine.trim() && currentLine.trim()) indent = leading;
  const after = source.slice(end);
  if (cleanLine.trimEnd().endsWith('{') && /^[\t ]*}/.test(after)) {
    const closingIndent = stack.at(-1) || '';
    const spaces = after.match(/^[\t ]*/)[0].length;
    return { start, end: end + spaces, text: `\n${indent}\n${closingIndent}`, caret: start + 1 + indent.length };
  }
  return { start, end, text: `\n${indent}`, caret: start + 1 + indent.length };
}

export function reindentC(source, unit = '    ') {
  const raw = source.split('\n'), protectedLines = new Set();
  for (const token of cTokens(source)) {
    if (!['string', 'comment'].includes(token.kind) || !token.text.includes('\n')) continue;
    const start = source.slice(0, token.start).split('\n').length - 1;
    for (let line = 1; line < token.text.split('\n').length; line++) protectedLines.add(start + line);
  }
  let macro = false;
  const clean = maskCNonCode(source).split('\n').map((line, index) => {
    if (macro || /^\s*#/.test(raw[index])) {
      protectedLines.add(index); macro = /\\\s*$/.test(raw[index]);
      return line.replace(/[^\n]/g, ' ');
    }
    return line;
  }).join('\n');
  let tokenLine = 0, lastOffset = 0;
  const tokens = [...clean.matchAll(/[A-Za-z_]\w*|[^\s]/g)].map(m => {
    tokenLine += clean.slice(lastOffset, m.index).split('\n').length - 1; lastOffset = m.index;
    return { text: m[0], line: tokenLine };
  });
  const indents = new Map(); let i = 0;
  const peek = () => tokens[i]?.text;
  const take = depth => { const token = tokens[i++]; if (token && !indents.has(token.line)) indents.set(token.line, Math.max(0, depth)); };
  function group(depth) {
    const close = peek() === '(' ? ')' : ']'; take(depth);
    while (i < tokens.length && peek() !== close) {
      if (peek() === '(' || peek() === '[') group(depth + 1); else take(depth + 1);
    }
    if (peek() === close) take(depth);
  }
  function block(depth) {
    take(depth); let branch = false;
    while (i < tokens.length && peek() !== '}') {
      if (peek() === 'case' || peek() === 'default') {
        while (i < tokens.length && peek() !== ':') take(depth + 1);
        if (peek() === ':') take(depth + 1);
        branch = true;
      } else statement(depth + (branch ? 2 : 1));
    }
    if (peek() === '}') take(depth);
  }
  function body(depth) { if (peek() === '{') block(depth); else statement(depth + 1); }
  function statement(depth) {
    const kind = peek();
    if (kind === '{') { block(depth); return; }
    if (['if', 'for', 'while', 'switch'].includes(kind)) {
      take(depth); if (peek() === '(') group(depth);
      body(depth);
      if (kind === 'if' && peek() === 'else') { take(depth); if (peek() === 'if') statement(depth); else body(depth); }
      return;
    }
    if (kind === 'do') {
      take(depth); body(depth);
      if (peek() === 'while') { take(depth); if (peek() === '(') group(depth); if (peek() === ';') take(depth); }
      return;
    }
    while (i < tokens.length) {
      if (peek() === '(' || peek() === '[') group(depth);
      else if (peek() === '{') { block(depth); if (![';', ','].includes(peek())) return; }
      else if (peek() === ';') { take(depth); return; }
      else if (peek() === '}') return;
      else take(depth);
    }
  }
  while (i < tokens.length) { const before = i; statement(0); if (i === before) take(0); }
  return raw.map((line, index) => protectedLines.has(index) || !indents.has(index) ? line : unit.repeat(indents.get(index)) + line.trimStart()).join('\n');
}

export function tabEdit(source, start, end = start, backwards = false, unit = '    ') {
  if (start === end && !backwards) return { start, end, text: unit, caret: start + unit.length };
  const first = source.lastIndexOf('\n', start - 1) + 1;
  const last = source.indexOf('\n', end > start && source[end - 1] === '\n' ? end - 1 : end);
  const limit = last < 0 ? source.length : last;
  const original = source.slice(first, limit);
  const lines = original.split('\n');
  const text = lines.map(line => backwards ? line.replace(/^(?:\t| {1,4})/, '') : unit + line).join('\n');
  if (start === end) return { start: first, end: limit, text, caret: Math.max(first, start - (original.length - text.length)) };
  return { start: first, end: limit, text, selectionStart: first, caret: first + text.length };
}