All files / src/plugins CodeMirrorAutoIndentAddon.js

81.81% Statements 27/33
64.7% Branches 11/17
100% Functions 3/3
89.28% Lines 25/28

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                1x 1x               2x 2x 2x     2x     2x       2x 2x     1x 1x 1x 1x 1x   1x             1x   1x     1x 1x 1x 1x 1x   1x             1x   1x    
// @ts-nocheck
// Copyright (C) 2017 by Joël Porquet <joel.porquet@gmail.com>
// Distributed under an MIT license: https://github.com/joel-porquet/CodeMirror-markdown-list-autoindent/blob/master/LICENSE
 
"use strict";
 
import CodeMirror from "codemirror";
 
var cmPos = CodeMirror.Pos;
var listTokenRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/;
 
/**
 * @param {CodeMirror.Position} pos
 * @param {CodeMirror} cm
 */
function matchListToken(pos, cm) {
  /* Get some info about the current state */
  var eolState = cm.getStateAfter(pos.line);
  var inList = eolState.list !== false;
  var inQuote = eolState.quote !== 0;
 
  /* Get the line from the start to where the cursor currently is */
  var lineStart = cm.getRange(cmPos(pos.line, 0), pos);
 
  /* Matches the beginning of the list line with the list token RE */
  var match = listTokenRE.exec(lineStart);
 
  /* Not being in a list, or being in a list but not right after the list
   * token, are both not considered a match */
  Iif ((!inList && !inQuote) || !match) { return false; }
  else { return true; }
}
 
CodeMirror.commands.autoIndentMarkdownList = function(/** @type CodeMirror */ cm) {
  Iif (cm.getOption("disableInput")) { return CodeMirror.Pass; }
  var ranges = cm.listSelections();
  for (var i = 0; i < ranges.length; i++) {
    var pos = ranges[i].head;
 
    Iif (!ranges[i].empty() || !matchListToken(pos, cm)) {
      /* If no match, call regular Tab handler */
      cm.execCommand("defaultTab");
      return undefined;
    }
 
    /* Select the whole list line and indent it by one unit */
    cm.indentLine(pos.line, "add");
  }
  return undefined;
};
 
CodeMirror.commands.autoUnindentMarkdownList = function(/** @type CodeMirror */ cm) {
  Iif (cm.getOption("disableInput")) { return CodeMirror.Pass; }
  var ranges = cm.listSelections();
  for (var i = 0; i < ranges.length; i++) {
    var pos = ranges[i].head;
 
    Iif (!ranges[i].empty() || !matchListToken(pos, cm)) {
      /* If no match, call regular Shift-Tab handler */
      cm.execCommand("indentAuto");
      // return;
    }
 
    /* Select the whole list line and unindent it by one unit */
    cm.indentLine(pos.line, "subtract");
  }
  return undefined;
};