aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/editor/indentationMarkerViewPlugin.ts
blob: d5ad536ba6902ad35d5d04a608f77a4cfc180e1b (plain) (blame)
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/**
 * @file CodeMirror plugin to highlight indentation
 *
 * This file is based on the
 * [@replit/codemirror-indentation-markers](https://github.com/replit/codemirror-indentation-markers)
 * package, which is available under the
 * [MIT License](https://github.com/replit/codemirror-indentation-markers/blob/543cc508ca5cef5d8350af23973eb1425e31525c/LICENSE).
 *
 * The highlighting heuristics were adjusted to make them more suitable
 * for logic programming.
 *
 * @see https://github.com/replit/codemirror-indentation-markers/blob/543cc508ca5cef5d8350af23973eb1425e31525c/src/index.ts
 */

import { getIndentUnit } from '@codemirror/language';
import { Text, RangeSet, EditorState } from '@codemirror/state';
import {
  ViewPlugin,
  Decoration,
  EditorView,
  WidgetType,
  PluginValue,
} from '@codemirror/view';

export const INDENTATION_MARKER_CLASS = 'cm-indentation-marker';

export const INDENTATION_MARKER_ACTIVE_CLASS = 'active';

const indentationMark = Decoration.mark({
  class: INDENTATION_MARKER_CLASS,
  tagName: 'span',
});

const activeIndentationMark = Decoration.mark({
  class: `${INDENTATION_MARKER_CLASS} ${INDENTATION_MARKER_ACTIVE_CLASS}`,
  tagName: 'span',
});

/**
 * Widget used to simulate N indentation markers on empty lines.
 */
class IndentationWidget extends WidgetType {
  constructor(
    readonly numIndent: number,
    readonly indentSize: number,
    readonly activeIndent?: number,
  ) {
    super();
  }

  override eq(other: IndentationWidget) {
    return (
      this.numIndent === other.numIndent &&
      this.indentSize === other.indentSize &&
      this.activeIndent === other.activeIndent
    );
  }

  override toDOM(view: EditorView) {
    const indentSize = getIndentUnit(view.state);

    const wrapper = document.createElement('span');
    wrapper.style.top = '0';
    wrapper.style.left = '4px';
    wrapper.style.position = 'absolute';
    wrapper.style.pointerEvents = 'none';

    for (let indent = 0; indent < this.numIndent; indent += 1) {
      const element = document.createElement('span');
      element.className = INDENTATION_MARKER_CLASS;
      element.classList.toggle(
        INDENTATION_MARKER_ACTIVE_CLASS,
        indent === this.activeIndent,
      );
      element.innerHTML = ' '.repeat(indentSize);
      wrapper.appendChild(element);
    }

    return wrapper;
  }
}

/**
 * Returns the number of indentation markers a non-empty line should have
 * based on the text in the line and the size of the indent.
 */
function getNumIndentMarkersForNonEmptyLine(
  text: string,
  indentSize: number,
  onIndentMarker?: (pos: number) => void,
) {
  let numIndents = 0;
  let numConsecutiveSpaces = 0;
  let prevChar: string | undefined;

  for (let char = 0; char < text.length; char += 1) {
    // Bail if we encounter a non-whitespace character
    if (text[char] !== ' ' && text[char] !== '\t') {
      // We still increment the indentation level if we would
      // have added a marker here had this been a space or tab.
      if (numConsecutiveSpaces % indentSize === 0 && char !== 0) {
        numIndents += 1;
      }

      return numIndents;
    }

    // Every tab and N space has an indentation marker
    const shouldAddIndent =
      prevChar === '\t' || numConsecutiveSpaces % indentSize === 0;

    if (shouldAddIndent) {
      numIndents += 1;

      if (onIndentMarker) {
        onIndentMarker(char);
      }
    }

    if (text[char] === ' ') {
      numConsecutiveSpaces += 1;
    } else {
      numConsecutiveSpaces = 0;
    }

    prevChar = text[char];
  }

  return numIndents;
}

/**
 * Returns the number of indent markers an empty line should have
 * based on the number of indent markers of the previous
 * and next non-empty lines.
 */
function getNumIndentMarkersForEmptyLine(prev: number, next: number) {
  const min = Math.min(prev, next);
  const max = Math.max(prev, next);

  // If only one side is non-zero, we omit markers,
  // because in logic programming, a block often ends with an empty line.
  if (min === 0 && max > 0) {
    return 0;
  }

  // Else, default to the minimum of the two
  return min;
}

/**
 * Returns the next non-empty line and its indent level.
 */
function findNextNonEmptyLineAndIndentLevel(
  doc: Text,
  startLine: number,
  indentSize: number,
): [number, number] {
  const numLines = doc.lines;
  let lineNo = startLine;

  while (lineNo <= numLines) {
    const { text } = doc.line(lineNo);

    if (text.trim().length === 0) {
      lineNo += 1;
    } else {
      const indent = getNumIndentMarkersForNonEmptyLine(text, indentSize);
      return [lineNo, indent];
    }
  }

  // Reached the end of the doc
  return [numLines + 1, 0];
}

interface IndentationMarkerDesc {
  lineNumber: number;
  from: number;
  to: number;
  create(activeIndentIndex?: number): Decoration;
}

/**
 * Returns a range of lines with an active indent marker.
 */
function getLinesWithActiveIndentMarker(
  state: EditorState,
  indentMap: Map<number, number>,
): { start: number; end: number; activeIndent: number } {
  const currentLine = state.doc.lineAt(state.selection.main.head);
  const currentIndent = indentMap.get(currentLine.number);
  const currentLineNo = currentLine.number;

  if (!currentIndent) {
    return { start: -1, end: -1, activeIndent: NaN };
  }

  let start: number;
  let end: number;

  for (start = currentLineNo; start >= 0; start -= 1) {
    const indent = indentMap.get(start - 1);
    if (!indent || indent < currentIndent) {
      break;
    }
  }

  for (end = currentLineNo; ; end += 1) {
    const indent = indentMap.get(end + 1);
    if (!indent || indent < currentIndent) {
      break;
    }
  }

  return { start, end, activeIndent: currentIndent };
}
/**
 * Adds indentation markers to all lines within view.
 */
function addIndentationMarkers(view: EditorView) {
  const indentSize = getIndentUnit(view.state);
  const indentSizeMap = new Map</* lineNumber */ number, number>();
  const decorations: Array<IndentationMarkerDesc> = [];

  view.visibleRanges.forEach(({ from, to }) => {
    let pos = from;

    let prevIndentMarkers = 0;
    let nextIndentMarkers = 0;
    let nextNonEmptyLine = 0;

    while (pos <= to) {
      const line = view.state.doc.lineAt(pos);
      const { text } = line;

      // If a line is empty, we match the indentation according
      // to a heuristic based on the indentations of the
      // previous and next non-empty lines.
      if (text.trim().length === 0) {
        // To retrieve the next non-empty indentation level,
        // we perform a lookahead and cache the result.
        if (nextNonEmptyLine < line.number) {
          const [nextLine, nextIndent] = findNextNonEmptyLineAndIndentLevel(
            view.state.doc,
            line.number + 1,
            indentSize,
          );

          nextNonEmptyLine = nextLine;
          nextIndentMarkers = nextIndent;
        }

        const numIndentMarkers = getNumIndentMarkersForEmptyLine(
          prevIndentMarkers,
          nextIndentMarkers,
        );

        // Add the indent widget and move on to next line
        indentSizeMap.set(line.number, numIndentMarkers);
        decorations.push({
          from: pos,
          to: pos,
          lineNumber: line.number,
          create: (activeIndentIndex) =>
            Decoration.widget({
              widget: new IndentationWidget(
                numIndentMarkers,
                indentSize,
                activeIndentIndex,
              ),
            }),
        });
      } else {
        const indices: Array<number> = [];

        prevIndentMarkers = getNumIndentMarkersForNonEmptyLine(
          text,
          indentSize,
          (char) => indices.push(char),
        );

        indentSizeMap.set(line.number, indices.length);
        decorations.push(
          ...indices.map(
            (char, i): IndentationMarkerDesc => ({
              from: line.from + char,
              to: line.from + char + 1,
              lineNumber: line.number,
              create: (activeIndentIndex) =>
                activeIndentIndex === i
                  ? activeIndentationMark
                  : indentationMark,
            }),
          ),
        );
      }

      // Move on to the next line
      pos = line.to + 1;
    }
  });

  const activeBlockRange = getLinesWithActiveIndentMarker(
    view.state,
    indentSizeMap,
  );

  return RangeSet.of<Decoration>(
    Array.from(decorations).map(({ lineNumber, from, to, create }) => {
      const activeIndent =
        lineNumber >= activeBlockRange.start &&
        lineNumber <= activeBlockRange.end
          ? activeBlockRange.activeIndent - 1
          : undefined;

      return { from, to, value: create(activeIndent) };
    }),
    true,
  );
}

export default function indentationMarkerViewPlugin() {
  return ViewPlugin.define<PluginValue & { decorations: RangeSet<Decoration> }>(
    (view) => ({
      decorations: addIndentationMarkers(view),
      update(update) {
        if (
          update.docChanged ||
          update.viewportChanged ||
          update.selectionSet
        ) {
          this.decorations = addIndentationMarkers(update.view);
        }
      },
    }),
    {
      decorations: (v) => v.decorations,
    },
  );
}