jevstrudel.git / packages / codemirror / block_utilities.mjs

Block-based evaluation utilities

3export function getBlockRegions(code) {
4  const chars = code.split('');
5  let i = 0,
6    blanks = [],
7    blockStart = 0,
8    regions = [];
9  while (i < chars.length) {
10    const isBlank = chars[i] === '\n';
11    if (isBlank) {
12      blanks.push(i);
13    } else if (chars[i].trim() !== '') {
14      if (blanks.length > 1) {
15        regions.push([blockStart, blanks[0]]);
16        blockStart = i;
17      }
18      blanks = [];
19    }
20    i++;
21  }
22  regions.push([blockStart, blanks.length ? blanks[0] : i]);
23  return regions;
24}
26export function getBlockAt(code, cursor) {
27  const regions = getBlockRegions(code);
28  for (const [start, end] of regions) {
29    if (cursor >= start && cursor <= end) {
30      return [start, end];
31    }
32  }
33  return null;
34}
35
36export const evalBlock = (strudelMirror) => {
37  const { state } = strudelMirror.editor;
38  const code = state.doc.toString();
39  const cursor = state.selection.main.head;
40  const range = getBlockAt(code, cursor);
41  if (range) {
42    const [a, b] = range;
43    const block = code.slice(a, b);
44    if (block) {
45      // Flash the block being evaluated
46      strudelMirror.flash(200, { from: a, to: b });
47      strudelMirror.repl.evaluateBlock(block, true, { range });
48    }
49  }
50  return true;
51};