// 匹配括号插件 - 精简实现
(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.off("cursorActivity", doMatchBrackets);
    }
    if (val) {
      cm.on("cursorActivity", doMatchBrackets);
    }
  });

  function doMatchBrackets(cm) {
    cm.operation(function() {
      const ranges = cm.listSelections();
      for (let i = 0; i < ranges.length; i++) {
        const match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head);
        if (match && match.match) {
          cm.addOverlay(match.match, { inclusive: true });
        }
      }
    });
  }

  function findMatchingBracket(cm, where) {
    const line = cm.getLine(where.line);
    const pos = where.ch - 1;
    const match = pos >= 0 && line.charAt(pos) in { "(": ")", "{": "}", "[": "]" };
    if (!match) return null;
    
    return {
      from: CodeMirror.Pos(where.line, pos),
      to: CodeMirror.Pos(where.line, pos + 1),
      match: { token: "matching-bracket" }
    };
  }
});