# All files / src/lib/markdown-it/highlight HighlightRuleComponent.ts

97.97% Statements 97/99
90.56% Branches 48/53
100% Functions 11/11
98.93% Lines 93/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    21418x

    18x
    18x
    18x
    18x

    18x

    38x
    38x
    38x

    36x
    36x
    29x
    29x

    30x
    30x

    2x
    2x

    2x

    1x
    1x
    1x

    28x
    28x
    28x
    28x

    6x

    6x
    6x
    6x

    6x

    6x

    9x
    6x
    3x

    6x
    3x
    3x

    3x

    22x

    22x
    15x

    7x

    32x

    28x

    12x
    12x

    12x
    2x

    10x
    10x

    12x
    2x

    10x
    10x

    12x

    8x
    8x
    8x
    8x
    8x
    8x
    24x
    24x
    24x
    24x
    24x

    8x

    8x
    2x
    6x
    2x

    4x
    4x

    8x
    4x
    4x

    4x
    4x

    8x

    4x
    4x
    4x

    4x
    2x

    2x
    2x
    2x
    3x
    3x
    3x
    3x
    3x

    2x

     import { splitCodeAndIndentation } from './helper';

    const LINESLICE_CHAR_REGEX = /(\+?)(\d+)\[(\d*):(\d*)]/;
    const LINESLICE_WORD_REGEX = /(\d+)\[(\d*)::(\d*)]/;
    const LINEPART_REGEX = /(\d+)\[(["'])((?:\\.|[^\\])*?)\2]/;
    const UNBOUNDED = -1;

    export class HighlightRuleComponent {
      lineNumber: number;
      isSlice: boolean;
      bounds: Array<[number, number]>;
      constructor(
        lineNumber: number,
        isSlice: boolean = false,
        bounds: Array<[number, number]> = [],
      ) {
        this.lineNumber = lineNumber;
        this.isSlice = isSlice;
        this.bounds = bounds;
      }

      static isValidLineNumber(lineNumStr: string, min: number, max: number, offset: number) {
        let lineNum = Number(lineNumStr);
        if (Number.isNaN(lineNum) || !Number.isInteger(lineNum)) return null;
        lineNum += offset;
        return lineNum >= min && lineNum <= max ? lineNum : null;
      }

      static parseRuleComponent(compString: string, lineNumberOffset: number, lines: string[]) {
        // Match line-part syntax
        const linepartMatch = compString.match(LINEPART_REGEX);
        if (linepartMatch) {
          // There are four capturing groups: [full match, line number, quote type, line part]
          const [, lineNumberString, , linePartWithQuotes] = linepartMatch;
          const lineNumber = HighlightRuleComponent
            .isValidLineNumber(lineNumberString, 1, lines.length, lineNumberOffset);
          if (!lineNumber) return null;

          const linePart = linePartWithQuotes.replace(/\\'/g, '\'').replace(/\\"/g, '"'); // unescape quotes
          const bounds = HighlightRuleComponent.computeLinePartBounds(linePart, lines[lineNumber - 1]);
          return new HighlightRuleComponent(lineNumber, true, bounds);
        }

        // Match line-slice (character and word variant) syntax
        const linesliceCharMatch = compString.match(LINESLICE_CHAR_REGEX);
        const linesliceWordMatch = compString.match(LINESLICE_WORD_REGEX);
        const sliceMatch = linesliceCharMatch || linesliceWordMatch;
        if (sliceMatch) {
          // There are four/five capturing groups: [full match, is absolute indexing (for char match),
          //                                        line number, start bound, end bound]
          const groups = sliceMatch.slice(1); // discard full match

          let isAbsoluteIndexing = false;
          if (sliceMatch === linesliceCharMatch) {
            isAbsoluteIndexing = groups.shift() === '+';
          }

          const lineNumber = HighlightRuleComponent
            .isValidLineNumber(groups.shift() ?? '', 1, lines.length, lineNumberOffset);
          Iif (!lineNumber) return null;

          const isUnbounded = groups.every(x => x === '');
          if (isUnbounded) {
            return new HighlightRuleComponent(lineNumber, true, []);
          }

          let bound = groups.map(x => (x !== '' ? parseInt(x, 10) : UNBOUNDED)) as [number, number];
          const isCharSlice = sliceMatch === linesliceCharMatch;
          bound = isCharSlice
            ? HighlightRuleComponent.computeCharBounds(bound, lines[lineNumber - 1], isAbsoluteIndexing)
            : HighlightRuleComponent.computeWordBounds(bound, lines[lineNumber - 1]);

          return new HighlightRuleComponent(lineNumber, true, [bound]);
        }

        // Match line-number syntax
        const lineNumber = HighlightRuleComponent
          .isValidLineNumber(compString, 1, lines.length, lineNumberOffset);
        if (lineNumber) {
          return new HighlightRuleComponent(lineNumber);
        }

        // the string is an improperly written rule
        return null;
      }

      /**
       * Compares the component's line number to a given line number.
       *
       * @param lineNumber The line number to compare
       * @returns {number} A negative number, zero, or a positive number when the given line number
       *  is after, at, or before the component's line number
       */
      compareLine(lineNumber: number): number {
        return this.lineNumber - lineNumber;
      }

      isUnboundedSlice() {
        return this.isSlice && this.bounds.length === 0;
      }

      /**
       * Computes the actual character bound given a user-defined character bound and a line,
       * comparing the bounds and the line's range.
       *
       * If the bound does not specify either the start or the end bound, the computed bound will default
       * to the start or end of line. The bound can be either absolute or relative to the indentation level.
       *
       * @param bound The user-defined bound
       * @param line The given line
       * @param isAbsoluteIndexing Whether the bound is absolute or relative to the indentation level
       * @returns {[number, number]} The actual bound computed
       */
      static computeCharBounds(bound: [number, number], line: string,
                               isAbsoluteIndexing: boolean): [number, number] {
        const [indents] = splitCodeAndIndentation(line);
        let [start, end] = bound;

        if (start === UNBOUNDED) {
          start = isAbsoluteIndexing ? 0 : indents.length;
        } else {
          start = isAbsoluteIndexing ? start : Math.max(start + indents.length, indents.length);
          start = Math.min(start, line.length);
        }

        if (end === UNBOUNDED) {
          end = line.length;
        } else {
          end = isAbsoluteIndexing ? end : Math.max(end + indents.length, indents.length);
          end = Math.min(end, line.length);
        }

        return [start, end];
      }

      /**
       * Computes the actual character bounds given a user-defined word bound and a line,
       * comparing the bounds and the line's range.
       *
       * If the bound does not specify either the start or the end bound, the computed bound will default
       * to the start or end of line, excluding leading whitespaces.
       *
       * @param bound The user-defined bound
       * @param line The given line
       * @returns {[number, number]} The actual bound computed
       */
      static computeWordBounds(bound: [number, number], line: string): [number, number] {
        const [indents, content] = splitCodeAndIndentation(line);
        const words = content.split(/\s+/);
        const wordPositions: number[][] = [];
        let contentRemaining = content;
        let curr = indents.length;
        words.forEach((word: string) => {
          const start = contentRemaining.indexOf(word);
          const end = start + word.length;
          wordPositions.push([curr + start, curr + end]);
          contentRemaining = contentRemaining.substring(end);
          curr += end;
        });

        let [start, end] = bound;

        if (start === UNBOUNDED || start < 0) {
          start = indents.length;
        } else if (start > words.length) {
          start = line.length;
        } else {
          const [wordStart] = wordPositions[start];
          start = wordStart;
        }

        if (end === UNBOUNDED || end > words.length) {
          end = line.length;
        } else Iif (end < 0) {
          end = indents.length;
        } else {
          const [, wordEnd] = wordPositions[end - 1];
          end = wordEnd;
        }

        return [start, end];
      }

      /**
       * Computes the actual bounds given a user-defined line part and a line.
       *
       * @param linePart The user-defined line part
       * @param line The given line
       * @returns {Array<[number, number]>} The bounds computed, each indicates the range of each
       * occurrences of the line part in the line
       */
      static computeLinePartBounds(linePart: string, line: string): Array<[number, number]> {
        const [indents, content] = splitCodeAndIndentation(line);
        let contentRemaining = content;
        let start = contentRemaining.indexOf(linePart);

        if (linePart === '' || start === -1) {
          return [[0, 0]];
        }

        const bounds: Array<[number, number]> = [];
        let curr = indents.length;
        while (start !== -1) {
          const end = start + linePart.length;
          bounds.push([curr + start, curr + end]);
          curr += end;
          contentRemaining = contentRemaining.substring(end);
          start = contentRemaining.indexOf(linePart);
        }

        return bounds;
      }
    }