/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/prettify-pinyin/index.js
var require_prettify_pinyin = __commonJS({
  "node_modules/prettify-pinyin/index.js"(exports, module2) {
    var replacements = {
      "a": ["\u0101", "\xE1", "\u01CE", "\xE0"],
      "e": ["\u0113", "\xE9", "\u011B", "\xE8"],
      "u": ["\u016B", "\xFA", "\u01D4", "\xF9"],
      "i": ["\u012B", "\xED", "\u01D0", "\xEC"],
      "o": ["\u014D", "\xF3", "\u01D2", "\xF2"],
      "\xFC": ["\u01D6", "\u01D8", "\u01DA", "\u01DC"]
    };
    var medials = ["i", "u", "\xFC"];
    var prettify = function(str) {
      str = str.replace("v", "\xFC");
      var syllables = str.split(" ");
      for (var i = 0; i < syllables.length; i++) {
        var syllable = syllables[i];
        var tone = parseInt(syllable[syllable.length - 1]);
        if (tone <= 0 || tone > 5) {
          console.error("invalid tone number:", tone, "in", syllable);
        } else if (tone === 5) {
          syllables[i] = syllable.slice(0, syllable.length - 1);
        } else {
          for (var j = 0; j < syllable.length; j++) {
            var currentLetter = syllable[j];
            var nextLetter = syllable[j + 1];
            if (replacements[currentLetter]) {
              var replaced;
              var letterToReplace;
              if (replacements[nextLetter] && medials.indexOf(currentLetter) >= 0) {
                letterToReplace = nextLetter;
              } else {
                letterToReplace = currentLetter;
              }
              replaced = syllable.replace(letterToReplace, replacements[letterToReplace][tone - 1]);
              syllables[i] = replaced.slice(0, replaced.length - 1);
              break;
            }
          }
        }
      }
      return syllables.join(" ");
    };
    module2.exports.prettify = prettify;
  }
});

// node_modules/chinese-tokenizer/src/trie.js
var require_trie = __commonJS({
  "node_modules/chinese-tokenizer/src/trie.js"(exports, module2) {
    var Trie = class {
      constructor() {
        this.content = {};
      }
      getKeyObject(key, create = false) {
        key = key.toString();
        let chars = key === "" ? [key] : Array.from(key);
        let obj = this.content;
        for (let char of chars) {
          if (obj[char] == null) {
            if (create)
              obj[char] = {};
            else
              return {};
          }
          obj = obj[char];
        }
        return obj;
      }
      get(key) {
        let obj = this.getKeyObject(key);
        return obj.values || [];
      }
      getPrefix(key) {
        let inner = (key2, obj = null) => {
          if (obj == null)
            obj = this.getKeyObject(key2);
          let result = obj.values ? [...obj.values] : [];
          for (let char in obj) {
            if (char === "values" || obj[char] == null)
              continue;
            result.push(...inner(key2 + char, obj[char]));
          }
          return result;
        };
        return inner(key);
      }
      push(key, value) {
        let obj = this.getKeyObject(key, true);
        if (obj.values == null)
          obj.values = [];
        if (!obj.values.includes(value))
          obj.values.push(value);
        return this;
      }
    };
    module2.exports = Trie;
  }
});

// node_modules/chinese-tokenizer/src/cedict.js
var require_cedict = __commonJS({
  "node_modules/chinese-tokenizer/src/cedict.js"(exports, module2) {
    var { prettify } = require_prettify_pinyin();
    var Trie = require_trie();
    function parseLine(line) {
      let match = line.match(/^(\S+)\s(\S+)\s\[([^\]]+)\]\s\/(.+)\//);
      if (match == null)
        return;
      let [, traditional, simplified, pinyin, english] = match;
      pinyin = pinyin.replace(/u:/g, "\xFC");
      let pinyinPretty = prettify(pinyin);
      return { traditional, simplified, pinyin, pinyinPretty, english };
    }
    var Cedict = class {
      load(contents) {
        this.simplifiedTrie = new Trie();
        this.traditionalTrie = new Trie();
        let lines = contents.split("\n");
        for (let line of lines) {
          if (line.trim() === "" || line[0] === "#")
            continue;
          let entry = parseLine(line);
          if (entry == null)
            continue;
          this.simplifiedTrie.push(entry.simplified, entry);
          this.traditionalTrie.push(entry.traditional, entry);
        }
      }
      get(word, traditional = false) {
        return traditional ? this.traditionalTrie.get(word) : this.simplifiedTrie.get(word);
      }
      getPrefix(word, traditional = false) {
        return traditional ? this.traditionalTrie.getPrefix(word) : this.simplifiedTrie.getPrefix(word);
      }
    };
    module2.exports = Cedict;
  }
});

// node_modules/chinese-tokenizer/src/main.js
var require_main = __commonJS({
  "node_modules/chinese-tokenizer/src/main.js"(exports) {
    var Cedict = require_cedict();
    var chinesePunctuation = [
      "\xB7",
      "\xD7",
      "\u2014",
      "\u2018",
      "\u2019",
      "\u201C",
      "\u201D",
      "\u2026",
      "\u3001",
      "\u3002",
      "\u300A",
      "\u300B",
      "\u300E",
      "\u300F",
      "\u3010",
      "\u3011",
      "\uFF01",
      "\uFF08",
      "\uFF09",
      "\uFF0C",
      "\uFF1A",
      "\uFF1B",
      "\uFF1F"
    ];
    exports.load = function(contents) {
      let dictionary = new Cedict();
      dictionary.load(contents);
      return function tokenize(text2) {
        text2 = Array.from(text2.replace(/\r/g, ""));
        let result = [];
        let i = 0;
        let [offset, line, column] = [0, 1, 1];
        let [simplifiedPreference, traditionalPreference] = [0, 0];
        let pushToken = (word) => {
          let simplifiedEntries = dictionary.get(word, false);
          let traditionalEntries = dictionary.get(word, true);
          let entries = simplifiedEntries.length === 0 ? traditionalEntries : traditionalEntries.length === 0 ? simplifiedEntries : simplifiedPreference < traditionalPreference ? traditionalEntries : simplifiedPreference > traditionalPreference ? simplifiedEntries : traditionalEntries;
          if (traditionalEntries.length === 0 && simplifiedEntries.length > 0) {
            simplifiedPreference++;
          } else if (simplifiedEntries.length === 0 && traditionalEntries.length > 0) {
            traditionalPreference++;
          }
          result.push({
            text: word,
            traditional: entries[0] ? entries[0].traditional : word,
            simplified: entries[0] ? entries[0].simplified : word,
            position: {
              offset,
              line,
              column
            },
            matches: entries.map(({ pinyin, pinyinPretty, english }) => ({
              pinyin,
              pinyinPretty,
              english
            }))
          });
          let wordArr = Array.from(word);
          let lastLineBreakIndex = word.lastIndexOf("\n");
          i += wordArr.length;
          offset += word.length;
          line += wordArr.filter((x) => x === "\n").length;
          column = lastLineBreakIndex >= 0 ? word.length - lastLineBreakIndex : column + word.length;
        };
        while (i < text2.length) {
          if (i !== text2.length - 1) {
            let getTwo = text2.slice(i, i + 2).join("");
            let simplifiedEntries = dictionary.getPrefix(getTwo, false);
            let traditionalEntries = dictionary.getPrefix(getTwo, true);
            let foundWord = null;
            let foundEntries = null;
            for (let entries of [traditionalEntries, simplifiedEntries]) {
              for (let entry of entries) {
                let matchText = entries === traditionalEntries ? entry.traditional : entry.simplified;
                let word2 = text2.slice(i, i + Array.from(matchText).length).join("");
                if (matchText === word2 && (foundWord == null || Array.from(word2).length > Array.from(foundWord).length)) {
                  foundWord = word2;
                  foundEntries = entries;
                }
              }
            }
            if (foundWord != null) {
              pushToken(foundWord);
              if (foundEntries === simplifiedEntries) {
                simplifiedPreference++;
              } else if (foundEntries === traditionalEntries) {
                traditionalPreference++;
              }
              continue;
            }
          }
          let character = text2[i];
          let isChinese = (character2) => chinesePunctuation.includes(character2) || dictionary.get(character2, false).length > 0 || dictionary.get(character2, true).length > 0;
          if (isChinese(character) || character.match(/\s/) != null) {
            pushToken(character);
            continue;
          }
          let end = i + 1;
          for (; end < text2.length; end++) {
            if (text2[end].match(/\s/) != null || isChinese(text2[end]))
              break;
          }
          let word = text2.slice(i, end).join("");
          pushToken(word);
        }
        return result;
      };
    };
  }
});

// node_modules/ts-deepmerge/dist/index.js
var require_dist = __commonJS({
  "node_modules/ts-deepmerge/dist/index.js"(exports) {
    "use strict";
    var __assign = exports && exports.__assign || function() {
      __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p))
              t[p] = s[p];
        }
        return t;
      };
      return __assign.apply(this, arguments);
    };
    var __read = exports && exports.__read || function(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m)
        return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
          ar.push(r.value);
      } catch (error) {
        e = { error };
      } finally {
        try {
          if (r && !r.done && (m = i["return"]))
            m.call(i);
        } finally {
          if (e)
            throw e.error;
        }
      }
      return ar;
    };
    var __spreadArray = exports && exports.__spreadArray || function(to, from, pack) {
      if (pack || arguments.length === 2)
        for (var i = 0, l = from.length, ar; i < l; i++) {
          if (ar || !(i in from)) {
            if (!ar)
              ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
          }
        }
      return to.concat(ar || Array.prototype.slice.call(from));
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    var isObject = function(obj) {
      if (typeof obj === "object" && obj !== null) {
        if (typeof Object.getPrototypeOf === "function") {
          var prototype = Object.getPrototypeOf(obj);
          return prototype === Object.prototype || prototype === null;
        }
        return Object.prototype.toString.call(obj) === "[object Object]";
      }
      return false;
    };
    var merge2 = function() {
      var objects = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        objects[_i] = arguments[_i];
      }
      return objects.reduce(function(result, current) {
        if (Array.isArray(current)) {
          throw new TypeError("Arguments provided to ts-deepmerge must be objects, not arrays.");
        }
        Object.keys(current).forEach(function(key) {
          if (["__proto__", "constructor", "prototype"].includes(key)) {
            return;
          }
          if (Array.isArray(result[key]) && Array.isArray(current[key])) {
            result[key] = merge2.options.mergeArrays ? Array.from(new Set(result[key].concat(current[key]))) : current[key];
          } else if (isObject(result[key]) && isObject(current[key])) {
            result[key] = merge2(result[key], current[key]);
          } else {
            result[key] = current[key];
          }
        });
        return result;
      }, {});
    };
    var defaultOptions = {
      mergeArrays: true
    };
    merge2.options = defaultOptions;
    merge2.withOptions = function(options) {
      var objects = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        objects[_i - 1] = arguments[_i];
      }
      merge2.options = __assign({ mergeArrays: true }, options);
      var result = merge2.apply(void 0, __spreadArray([], __read(objects), false));
      merge2.options = defaultOptions;
      return result;
    };
    exports.default = merge2;
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => VariousComponents
});
module.exports = __toCommonJS(main_exports);
var import_obsidian6 = require("obsidian");

// src/ui/AutoCompleteSuggest.ts
var import_obsidian3 = require("obsidian");

// src/util/strings.ts
var regEmoji = new RegExp(
  /[\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF]|[\uFE0E-\uFE0F]/,
  "g"
);
function allAlphabets(text2) {
  return Boolean(text2.match(/^[a-zA-Z0-9_-]+$/));
}
function excludeEmoji(text2) {
  return text2.replace(regEmoji, "");
}
function encodeSpace(text2) {
  return text2.replace(/ /g, "%20");
}
function lowerIncludes(one, other) {
  return one.toLowerCase().includes(other.toLowerCase());
}
function lowerStartsWith(a, b) {
  return a.toLowerCase().startsWith(b.toLowerCase());
}
function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
function startsSmallLetterOnlyFirst(str) {
  return Boolean(str.match(/^[A-Z][^A-Z]+$/));
}
function* splitRaw(text2, regexp) {
  let previousIndex = 0;
  for (let r of text2.matchAll(regexp)) {
    if (previousIndex !== r.index) {
      yield text2.slice(previousIndex, r.index);
    }
    yield text2[r.index];
    previousIndex = r.index + 1;
  }
  if (previousIndex !== text2.length) {
    yield text2.slice(previousIndex, text2.length);
  }
}

// src/tokenizer/tokenizers/DefaultTokenizer.ts
function pickTokens(content, trimPattern) {
  return content.split(trimPattern).filter((x) => x !== "");
}
var TRIM_CHAR_PATTERN = /[\n\t\[\]$/:?!=()<>"'.,|;*~ `]/g;
var DefaultTokenizer = class {
  tokenize(content, raw) {
    return raw ? Array.from(splitRaw(content, this.getTrimPattern())).filter(
      (x) => x !== " "
    ) : pickTokens(content, this.getTrimPattern());
  }
  recursiveTokenize(content) {
    const trimIndexes = Array.from(content.matchAll(this.getTrimPattern())).sort((a, b) => a.index - b.index).map((x) => x.index);
    return [
      { word: content, offset: 0 },
      ...trimIndexes.map((i) => ({
        word: content.slice(i + 1),
        offset: i + 1
      }))
    ];
  }
  getTrimPattern() {
    return TRIM_CHAR_PATTERN;
  }
  shouldIgnoreOnCurrent(str) {
    return false;
  }
};

// src/tokenizer/tokenizers/ArabicTokenizer.ts
var ARABIC_TRIM_CHAR_PATTERN = /[\n\t\[\]$/:?!=()<>"'.,|;*~ `،؛]/g;
var ArabicTokenizer = class extends DefaultTokenizer {
  getTrimPattern() {
    return ARABIC_TRIM_CHAR_PATTERN;
  }
};

// src/external/tiny-segmenter.ts
function TinySegmenter() {
  var patterns = {
    "[\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u767E\u5343\u4E07\u5104\u5146]": "M",
    "[\u4E00-\u9FA0\u3005\u3006\u30F5\u30F6]": "H",
    "[\u3041-\u3093]": "I",
    "[\u30A1-\u30F4\u30FC\uFF71-\uFF9D\uFF9E\uFF70]": "K",
    "[a-zA-Z\uFF41-\uFF5A\uFF21-\uFF3A]": "A",
    "[0-9\uFF10-\uFF19]": "N"
  };
  this.chartype_ = [];
  for (var i in patterns) {
    var regexp = new RegExp();
    regexp.compile(i);
    this.chartype_.push([regexp, patterns[i]]);
  }
  this.BIAS__ = -332;
  this.BC1__ = { HH: 6, II: 2461, KH: 406, OH: -1378 };
  this.BC2__ = {
    AA: -3267,
    AI: 2744,
    AN: -878,
    HH: -4070,
    HM: -1711,
    HN: 4012,
    HO: 3761,
    IA: 1327,
    IH: -1184,
    II: -1332,
    IK: 1721,
    IO: 5492,
    KI: 3831,
    KK: -8741,
    MH: -3132,
    MK: 3334,
    OO: -2920
  };
  this.BC3__ = {
    HH: 996,
    HI: 626,
    HK: -721,
    HN: -1307,
    HO: -836,
    IH: -301,
    KK: 2762,
    MK: 1079,
    MM: 4034,
    OA: -1652,
    OH: 266
  };
  this.BP1__ = { BB: 295, OB: 304, OO: -125, UB: 352 };
  this.BP2__ = { BO: 60, OO: -1762 };
  this.BQ1__ = {
    BHH: 1150,
    BHM: 1521,
    BII: -1158,
    BIM: 886,
    BMH: 1208,
    BNH: 449,
    BOH: -91,
    BOO: -2597,
    OHI: 451,
    OIH: -296,
    OKA: 1851,
    OKH: -1020,
    OKK: 904,
    OOO: 2965
  };
  this.BQ2__ = {
    BHH: 118,
    BHI: -1159,
    BHM: 466,
    BIH: -919,
    BKK: -1720,
    BKO: 864,
    OHH: -1139,
    OHM: -181,
    OIH: 153,
    UHI: -1146
  };
  this.BQ3__ = {
    BHH: -792,
    BHI: 2664,
    BII: -299,
    BKI: 419,
    BMH: 937,
    BMM: 8335,
    BNN: 998,
    BOH: 775,
    OHH: 2174,
    OHM: 439,
    OII: 280,
    OKH: 1798,
    OKI: -793,
    OKO: -2242,
    OMH: -2402,
    OOO: 11699
  };
  this.BQ4__ = {
    BHH: -3895,
    BIH: 3761,
    BII: -4654,
    BIK: 1348,
    BKK: -1806,
    BMI: -3385,
    BOO: -12396,
    OAH: 926,
    OHH: 266,
    OHK: -2036,
    ONN: -973
  };
  this.BW1__ = {
    ",\u3068": 660,
    ",\u540C": 727,
    B1\u3042: 1404,
    B1\u540C: 542,
    "\u3001\u3068": 660,
    "\u3001\u540C": 727,
    "\u300D\u3068": 1682,
    \u3042\u3063: 1505,
    \u3044\u3046: 1743,
    \u3044\u3063: -2055,
    \u3044\u308B: 672,
    \u3046\u3057: -4817,
    \u3046\u3093: 665,
    \u304B\u3089: 3472,
    \u304C\u3089: 600,
    \u3053\u3046: -790,
    \u3053\u3068: 2083,
    \u3053\u3093: -1262,
    \u3055\u3089: -4143,
    \u3055\u3093: 4573,
    \u3057\u305F: 2641,
    \u3057\u3066: 1104,
    \u3059\u3067: -3399,
    \u305D\u3053: 1977,
    \u305D\u308C: -871,
    \u305F\u3061: 1122,
    \u305F\u3081: 601,
    \u3063\u305F: 3463,
    \u3064\u3044: -802,
    \u3066\u3044: 805,
    \u3066\u304D: 1249,
    \u3067\u304D: 1127,
    \u3067\u3059: 3445,
    \u3067\u306F: 844,
    \u3068\u3044: -4915,
    \u3068\u307F: 1922,
    \u3069\u3053: 3887,
    \u306A\u3044: 5713,
    \u306A\u3063: 3015,
    \u306A\u3069: 7379,
    \u306A\u3093: -1113,
    \u306B\u3057: 2468,
    \u306B\u306F: 1498,
    \u306B\u3082: 1671,
    \u306B\u5BFE: -912,
    \u306E\u4E00: -501,
    \u306E\u4E2D: 741,
    \u307E\u305B: 2448,
    \u307E\u3067: 1711,
    \u307E\u307E: 2600,
    \u307E\u308B: -2155,
    \u3084\u3080: -1947,
    \u3088\u3063: -2565,
    \u308C\u305F: 2369,
    \u308C\u3067: -913,
    \u3092\u3057: 1860,
    \u3092\u898B: 731,
    \u4EA1\u304F: -1886,
    \u4EAC\u90FD: 2558,
    \u53D6\u308A: -2784,
    \u5927\u304D: -2604,
    \u5927\u962A: 1497,
    \u5E73\u65B9: -2314,
    \u5F15\u304D: -1336,
    \u65E5\u672C: -195,
    \u672C\u5F53: -2423,
    \u6BCE\u65E5: -2113,
    \u76EE\u6307: -724,
    \uFF22\uFF11\u3042: 1404,
    \uFF22\uFF11\u540C: 542,
    "\uFF63\u3068": 1682
  };
  this.BW2__ = {
    "..": -11822,
    11: -669,
    "\u2015\u2015": -5730,
    "\u2212\u2212": -13175,
    \u3044\u3046: -1609,
    \u3046\u304B: 2490,
    \u304B\u3057: -1350,
    \u304B\u3082: -602,
    \u304B\u3089: -7194,
    \u304B\u308C: 4612,
    \u304C\u3044: 853,
    \u304C\u3089: -3198,
    \u304D\u305F: 1941,
    \u304F\u306A: -1597,
    \u3053\u3068: -8392,
    \u3053\u306E: -4193,
    \u3055\u305B: 4533,
    \u3055\u308C: 13168,
    \u3055\u3093: -3977,
    \u3057\u3044: -1819,
    \u3057\u304B: -545,
    \u3057\u305F: 5078,
    \u3057\u3066: 972,
    \u3057\u306A: 939,
    \u305D\u306E: -3744,
    \u305F\u3044: -1253,
    \u305F\u305F: -662,
    \u305F\u3060: -3857,
    \u305F\u3061: -786,
    \u305F\u3068: 1224,
    \u305F\u306F: -939,
    \u3063\u305F: 4589,
    \u3063\u3066: 1647,
    \u3063\u3068: -2094,
    \u3066\u3044: 6144,
    \u3066\u304D: 3640,
    \u3066\u304F: 2551,
    \u3066\u306F: -3110,
    \u3066\u3082: -3065,
    \u3067\u3044: 2666,
    \u3067\u304D: -1528,
    \u3067\u3057: -3828,
    \u3067\u3059: -4761,
    \u3067\u3082: -4203,
    \u3068\u3044: 1890,
    \u3068\u3053: -1746,
    \u3068\u3068: -2279,
    \u3068\u306E: 720,
    \u3068\u307F: 5168,
    \u3068\u3082: -3941,
    \u306A\u3044: -2488,
    \u306A\u304C: -1313,
    \u306A\u3069: -6509,
    \u306A\u306E: 2614,
    \u306A\u3093: 3099,
    \u306B\u304A: -1615,
    \u306B\u3057: 2748,
    \u306B\u306A: 2454,
    \u306B\u3088: -7236,
    \u306B\u5BFE: -14943,
    \u306B\u5F93: -4688,
    \u306B\u95A2: -11388,
    \u306E\u304B: 2093,
    \u306E\u3067: -7059,
    \u306E\u306B: -6041,
    \u306E\u306E: -6125,
    \u306F\u3044: 1073,
    \u306F\u304C: -1033,
    \u306F\u305A: -2532,
    \u3070\u308C: 1813,
    \u307E\u3057: -1316,
    \u307E\u3067: -6621,
    \u307E\u308C: 5409,
    \u3081\u3066: -3153,
    \u3082\u3044: 2230,
    \u3082\u306E: -10713,
    \u3089\u304B: -944,
    \u3089\u3057: -1611,
    \u3089\u306B: -1897,
    \u308A\u3057: 651,
    \u308A\u307E: 1620,
    \u308C\u305F: 4270,
    \u308C\u3066: 849,
    \u308C\u3070: 4114,
    \u308D\u3046: 6067,
    \u308F\u308C: 7901,
    \u3092\u901A: -11877,
    \u3093\u3060: 728,
    \u3093\u306A: -4115,
    \u4E00\u4EBA: 602,
    \u4E00\u65B9: -1375,
    \u4E00\u65E5: 970,
    \u4E00\u90E8: -1051,
    \u4E0A\u304C: -4479,
    \u4F1A\u793E: -1116,
    \u51FA\u3066: 2163,
    \u5206\u306E: -7758,
    \u540C\u515A: 970,
    \u540C\u65E5: -913,
    \u5927\u962A: -2471,
    \u59D4\u54E1: -1250,
    \u5C11\u306A: -1050,
    \u5E74\u5EA6: -8669,
    \u5E74\u9593: -1626,
    \u5E9C\u770C: -2363,
    \u624B\u6A29: -1982,
    \u65B0\u805E: -4066,
    \u65E5\u65B0: -722,
    \u65E5\u672C: -7068,
    \u65E5\u7C73: 3372,
    \u66DC\u65E5: -601,
    \u671D\u9BAE: -2355,
    \u672C\u4EBA: -2697,
    \u6771\u4EAC: -1543,
    \u7136\u3068: -1384,
    \u793E\u4F1A: -1276,
    \u7ACB\u3066: -990,
    \u7B2C\u306B: -1612,
    \u7C73\u56FD: -4268,
    "\uFF11\uFF11": -669
  };
  this.BW3__ = {
    \u3042\u305F: -2194,
    \u3042\u308A: 719,
    \u3042\u308B: 3846,
    "\u3044.": -1185,
    "\u3044\u3002": -1185,
    \u3044\u3044: 5308,
    \u3044\u3048: 2079,
    \u3044\u304F: 3029,
    \u3044\u305F: 2056,
    \u3044\u3063: 1883,
    \u3044\u308B: 5600,
    \u3044\u308F: 1527,
    \u3046\u3061: 1117,
    \u3046\u3068: 4798,
    \u3048\u3068: 1454,
    "\u304B.": 2857,
    "\u304B\u3002": 2857,
    \u304B\u3051: -743,
    \u304B\u3063: -4098,
    \u304B\u306B: -669,
    \u304B\u3089: 6520,
    \u304B\u308A: -2670,
    "\u304C,": 1816,
    "\u304C\u3001": 1816,
    \u304C\u304D: -4855,
    \u304C\u3051: -1127,
    \u304C\u3063: -913,
    \u304C\u3089: -4977,
    \u304C\u308A: -2064,
    \u304D\u305F: 1645,
    \u3051\u3069: 1374,
    \u3053\u3068: 7397,
    \u3053\u306E: 1542,
    \u3053\u308D: -2757,
    \u3055\u3044: -714,
    \u3055\u3092: 976,
    "\u3057,": 1557,
    "\u3057\u3001": 1557,
    \u3057\u3044: -3714,
    \u3057\u305F: 3562,
    \u3057\u3066: 1449,
    \u3057\u306A: 2608,
    \u3057\u307E: 1200,
    "\u3059.": -1310,
    "\u3059\u3002": -1310,
    \u3059\u308B: 6521,
    "\u305A,": 3426,
    "\u305A\u3001": 3426,
    \u305A\u306B: 841,
    \u305D\u3046: 428,
    "\u305F.": 8875,
    "\u305F\u3002": 8875,
    \u305F\u3044: -594,
    \u305F\u306E: 812,
    \u305F\u308A: -1183,
    \u305F\u308B: -853,
    "\u3060.": 4098,
    "\u3060\u3002": 4098,
    \u3060\u3063: 1004,
    \u3063\u305F: -4748,
    \u3063\u3066: 300,
    \u3066\u3044: 6240,
    \u3066\u304A: 855,
    \u3066\u3082: 302,
    \u3067\u3059: 1437,
    \u3067\u306B: -1482,
    \u3067\u306F: 2295,
    \u3068\u3046: -1387,
    \u3068\u3057: 2266,
    \u3068\u306E: 541,
    \u3068\u3082: -3543,
    \u3069\u3046: 4664,
    \u306A\u3044: 1796,
    \u306A\u304F: -903,
    \u306A\u3069: 2135,
    "\u306B,": -1021,
    "\u306B\u3001": -1021,
    \u306B\u3057: 1771,
    \u306B\u306A: 1906,
    \u306B\u306F: 2644,
    "\u306E,": -724,
    "\u306E\u3001": -724,
    \u306E\u5B50: -1e3,
    "\u306F,": 1337,
    "\u306F\u3001": 1337,
    \u3079\u304D: 2181,
    \u307E\u3057: 1113,
    \u307E\u3059: 6943,
    \u307E\u3063: -1549,
    \u307E\u3067: 6154,
    \u307E\u308C: -793,
    \u3089\u3057: 1479,
    \u3089\u308C: 6820,
    \u308B\u308B: 3818,
    "\u308C,": 854,
    "\u308C\u3001": 854,
    \u308C\u305F: 1850,
    \u308C\u3066: 1375,
    \u308C\u3070: -3246,
    \u308C\u308B: 1091,
    \u308F\u308C: -605,
    \u3093\u3060: 606,
    \u3093\u3067: 798,
    \u30AB\u6708: 990,
    \u4F1A\u8B70: 860,
    \u5165\u308A: 1232,
    \u5927\u4F1A: 2217,
    \u59CB\u3081: 1681,
    \u5E02: 965,
    \u65B0\u805E: -5055,
    "\u65E5,": 974,
    "\u65E5\u3001": 974,
    \u793E\u4F1A: 2024,
    \uFF76\u6708: 990
  };
  this.TC1__ = {
    AAA: 1093,
    HHH: 1029,
    HHM: 580,
    HII: 998,
    HOH: -390,
    HOM: -331,
    IHI: 1169,
    IOH: -142,
    IOI: -1015,
    IOM: 467,
    MMH: 187,
    OOI: -1832
  };
  this.TC2__ = {
    HHO: 2088,
    HII: -1023,
    HMM: -1154,
    IHI: -1965,
    KKH: 703,
    OII: -2649
  };
  this.TC3__ = {
    AAA: -294,
    HHH: 346,
    HHI: -341,
    HII: -1088,
    HIK: 731,
    HOH: -1486,
    IHH: 128,
    IHI: -3041,
    IHO: -1935,
    IIH: -825,
    IIM: -1035,
    IOI: -542,
    KHH: -1216,
    KKA: 491,
    KKH: -1217,
    KOK: -1009,
    MHH: -2694,
    MHM: -457,
    MHO: 123,
    MMH: -471,
    NNH: -1689,
    NNO: 662,
    OHO: -3393
  };
  this.TC4__ = {
    HHH: -203,
    HHI: 1344,
    HHK: 365,
    HHM: -122,
    HHN: 182,
    HHO: 669,
    HIH: 804,
    HII: 679,
    HOH: 446,
    IHH: 695,
    IHO: -2324,
    IIH: 321,
    III: 1497,
    IIO: 656,
    IOO: 54,
    KAK: 4845,
    KKA: 3386,
    KKK: 3065,
    MHH: -405,
    MHI: 201,
    MMH: -241,
    MMM: 661,
    MOM: 841
  };
  this.TQ1__ = {
    BHHH: -227,
    BHHI: 316,
    BHIH: -132,
    BIHH: 60,
    BIII: 1595,
    BNHH: -744,
    BOHH: 225,
    BOOO: -908,
    OAKK: 482,
    OHHH: 281,
    OHIH: 249,
    OIHI: 200,
    OIIH: -68
  };
  this.TQ2__ = { BIHH: -1401, BIII: -1033, BKAK: -543, BOOO: -5591 };
  this.TQ3__ = {
    BHHH: 478,
    BHHM: -1073,
    BHIH: 222,
    BHII: -504,
    BIIH: -116,
    BIII: -105,
    BMHI: -863,
    BMHM: -464,
    BOMH: 620,
    OHHH: 346,
    OHHI: 1729,
    OHII: 997,
    OHMH: 481,
    OIHH: 623,
    OIIH: 1344,
    OKAK: 2792,
    OKHH: 587,
    OKKA: 679,
    OOHH: 110,
    OOII: -685
  };
  this.TQ4__ = {
    BHHH: -721,
    BHHM: -3604,
    BHII: -966,
    BIIH: -607,
    BIII: -2181,
    OAAA: -2763,
    OAKK: 180,
    OHHH: -294,
    OHHI: 2446,
    OHHO: 480,
    OHIH: -1573,
    OIHH: 1935,
    OIHI: -493,
    OIIH: 626,
    OIII: -4007,
    OKAK: -8156
  };
  this.TW1__ = { \u306B\u3064\u3044: -4681, \u6771\u4EAC\u90FD: 2026 };
  this.TW2__ = {
    \u3042\u308B\u7A0B: -2049,
    \u3044\u3063\u305F: -1256,
    \u3053\u308D\u304C: -2434,
    \u3057\u3087\u3046: 3873,
    \u305D\u306E\u5F8C: -4430,
    \u3060\u3063\u3066: -1049,
    \u3066\u3044\u305F: 1833,
    \u3068\u3057\u3066: -4657,
    \u3068\u3082\u306B: -4517,
    \u3082\u306E\u3067: 1882,
    \u4E00\u6C17\u306B: -792,
    \u521D\u3081\u3066: -1512,
    \u540C\u6642\u306B: -8097,
    \u5927\u304D\u306A: -1255,
    \u5BFE\u3057\u3066: -2721,
    \u793E\u4F1A\u515A: -3216
  };
  this.TW3__ = {
    \u3044\u305F\u3060: -1734,
    \u3057\u3066\u3044: 1314,
    \u3068\u3057\u3066: -4314,
    \u306B\u3064\u3044: -5483,
    \u306B\u3068\u3063: -5989,
    \u306B\u5F53\u305F: -6247,
    "\u306E\u3067,": -727,
    "\u306E\u3067\u3001": -727,
    \u306E\u3082\u306E: -600,
    \u308C\u304B\u3089: -3752,
    \u5341\u4E8C\u6708: -2287
  };
  this.TW4__ = {
    "\u3044\u3046.": 8576,
    "\u3044\u3046\u3002": 8576,
    \u304B\u3089\u306A: -2348,
    \u3057\u3066\u3044: 2958,
    "\u305F\u304C,": 1516,
    "\u305F\u304C\u3001": 1516,
    \u3066\u3044\u308B: 1538,
    \u3068\u3044\u3046: 1349,
    \u307E\u3057\u305F: 5543,
    \u307E\u305B\u3093: 1097,
    \u3088\u3046\u3068: -4258,
    \u3088\u308B\u3068: 5865
  };
  this.UC1__ = { A: 484, K: 93, M: 645, O: -505 };
  this.UC2__ = { A: 819, H: 1059, I: 409, M: 3987, N: 5775, O: 646 };
  this.UC3__ = { A: -1370, I: 2311 };
  this.UC4__ = {
    A: -2643,
    H: 1809,
    I: -1032,
    K: -3450,
    M: 3565,
    N: 3876,
    O: 6646
  };
  this.UC5__ = { H: 313, I: -1238, K: -799, M: 539, O: -831 };
  this.UC6__ = { H: -506, I: -253, K: 87, M: 247, O: -387 };
  this.UP1__ = { O: -214 };
  this.UP2__ = { B: 69, O: 935 };
  this.UP3__ = { B: 189 };
  this.UQ1__ = {
    BH: 21,
    BI: -12,
    BK: -99,
    BN: 142,
    BO: -56,
    OH: -95,
    OI: 477,
    OK: 410,
    OO: -2422
  };
  this.UQ2__ = { BH: 216, BI: 113, OK: 1759 };
  this.UQ3__ = {
    BA: -479,
    BH: 42,
    BI: 1913,
    BK: -7198,
    BM: 3160,
    BN: 6427,
    BO: 14761,
    OI: -827,
    ON: -3212
  };
  this.UW1__ = {
    ",": 156,
    "\u3001": 156,
    "\u300C": -463,
    \u3042: -941,
    \u3046: -127,
    \u304C: -553,
    \u304D: 121,
    \u3053: 505,
    \u3067: -201,
    \u3068: -547,
    \u3069: -123,
    \u306B: -789,
    \u306E: -185,
    \u306F: -847,
    \u3082: -466,
    \u3084: -470,
    \u3088: 182,
    \u3089: -292,
    \u308A: 208,
    \u308C: 169,
    \u3092: -446,
    \u3093: -137,
    "\u30FB": -135,
    \u4E3B: -402,
    \u4EAC: -268,
    \u533A: -912,
    \u5348: 871,
    \u56FD: -460,
    \u5927: 561,
    \u59D4: 729,
    \u5E02: -411,
    \u65E5: -141,
    \u7406: 361,
    \u751F: -408,
    \u770C: -386,
    \u90FD: -718,
    "\uFF62": -463,
    "\uFF65": -135
  };
  this.UW2__ = {
    ",": -829,
    "\u3001": -829,
    "\u3007": 892,
    "\u300C": -645,
    "\u300D": 3145,
    \u3042: -538,
    \u3044: 505,
    \u3046: 134,
    \u304A: -502,
    \u304B: 1454,
    \u304C: -856,
    \u304F: -412,
    \u3053: 1141,
    \u3055: 878,
    \u3056: 540,
    \u3057: 1529,
    \u3059: -675,
    \u305B: 300,
    \u305D: -1011,
    \u305F: 188,
    \u3060: 1837,
    \u3064: -949,
    \u3066: -291,
    \u3067: -268,
    \u3068: -981,
    \u3069: 1273,
    \u306A: 1063,
    \u306B: -1764,
    \u306E: 130,
    \u306F: -409,
    \u3072: -1273,
    \u3079: 1261,
    \u307E: 600,
    \u3082: -1263,
    \u3084: -402,
    \u3088: 1639,
    \u308A: -579,
    \u308B: -694,
    \u308C: 571,
    \u3092: -2516,
    \u3093: 2095,
    \u30A2: -587,
    \u30AB: 306,
    \u30AD: 568,
    \u30C3: 831,
    \u4E09: -758,
    \u4E0D: -2150,
    \u4E16: -302,
    \u4E2D: -968,
    \u4E3B: -861,
    \u4E8B: 492,
    \u4EBA: -123,
    \u4F1A: 978,
    \u4FDD: 362,
    \u5165: 548,
    \u521D: -3025,
    \u526F: -1566,
    \u5317: -3414,
    \u533A: -422,
    \u5927: -1769,
    \u5929: -865,
    \u592A: -483,
    \u5B50: -1519,
    \u5B66: 760,
    \u5B9F: 1023,
    \u5C0F: -2009,
    \u5E02: -813,
    \u5E74: -1060,
    \u5F37: 1067,
    \u624B: -1519,
    \u63FA: -1033,
    \u653F: 1522,
    \u6587: -1355,
    \u65B0: -1682,
    \u65E5: -1815,
    \u660E: -1462,
    \u6700: -630,
    \u671D: -1843,
    \u672C: -1650,
    \u6771: -931,
    \u679C: -665,
    \u6B21: -2378,
    \u6C11: -180,
    \u6C17: -1740,
    \u7406: 752,
    \u767A: 529,
    \u76EE: -1584,
    \u76F8: -242,
    \u770C: -1165,
    \u7ACB: -763,
    \u7B2C: 810,
    \u7C73: 509,
    \u81EA: -1353,
    \u884C: 838,
    \u897F: -744,
    \u898B: -3874,
    \u8ABF: 1010,
    \u8B70: 1198,
    \u8FBC: 3041,
    \u958B: 1758,
    \u9593: -1257,
    "\uFF62": -645,
    "\uFF63": 3145,
    \uFF6F: 831,
    \uFF71: -587,
    \uFF76: 306,
    \uFF77: 568
  };
  this.UW3__ = {
    ",": 4889,
    1: -800,
    "\u2212": -1723,
    "\u3001": 4889,
    \u3005: -2311,
    "\u3007": 5827,
    "\u300D": 2670,
    "\u3013": -3573,
    \u3042: -2696,
    \u3044: 1006,
    \u3046: 2342,
    \u3048: 1983,
    \u304A: -4864,
    \u304B: -1163,
    \u304C: 3271,
    \u304F: 1004,
    \u3051: 388,
    \u3052: 401,
    \u3053: -3552,
    \u3054: -3116,
    \u3055: -1058,
    \u3057: -395,
    \u3059: 584,
    \u305B: 3685,
    \u305D: -5228,
    \u305F: 842,
    \u3061: -521,
    \u3063: -1444,
    \u3064: -1081,
    \u3066: 6167,
    \u3067: 2318,
    \u3068: 1691,
    \u3069: -899,
    \u306A: -2788,
    \u306B: 2745,
    \u306E: 4056,
    \u306F: 4555,
    \u3072: -2171,
    \u3075: -1798,
    \u3078: 1199,
    \u307B: -5516,
    \u307E: -4384,
    \u307F: -120,
    \u3081: 1205,
    \u3082: 2323,
    \u3084: -788,
    \u3088: -202,
    \u3089: 727,
    \u308A: 649,
    \u308B: 5905,
    \u308C: 2773,
    \u308F: -1207,
    \u3092: 6620,
    \u3093: -518,
    \u30A2: 551,
    \u30B0: 1319,
    \u30B9: 874,
    \u30C3: -1350,
    \u30C8: 521,
    \u30E0: 1109,
    \u30EB: 1591,
    \u30ED: 2201,
    \u30F3: 278,
    "\u30FB": -3794,
    \u4E00: -1619,
    \u4E0B: -1759,
    \u4E16: -2087,
    \u4E21: 3815,
    \u4E2D: 653,
    \u4E3B: -758,
    \u4E88: -1193,
    \u4E8C: 974,
    \u4EBA: 2742,
    \u4ECA: 792,
    \u4ED6: 1889,
    \u4EE5: -1368,
    \u4F4E: 811,
    \u4F55: 4265,
    \u4F5C: -361,
    \u4FDD: -2439,
    \u5143: 4858,
    \u515A: 3593,
    \u5168: 1574,
    \u516C: -3030,
    \u516D: 755,
    \u5171: -1880,
    \u5186: 5807,
    \u518D: 3095,
    \u5206: 457,
    \u521D: 2475,
    \u5225: 1129,
    \u524D: 2286,
    \u526F: 4437,
    \u529B: 365,
    \u52D5: -949,
    \u52D9: -1872,
    \u5316: 1327,
    \u5317: -1038,
    \u533A: 4646,
    \u5343: -2309,
    \u5348: -783,
    \u5354: -1006,
    \u53E3: 483,
    \u53F3: 1233,
    \u5404: 3588,
    \u5408: -241,
    \u540C: 3906,
    \u548C: -837,
    \u54E1: 4513,
    \u56FD: 642,
    \u578B: 1389,
    \u5834: 1219,
    \u5916: -241,
    \u59BB: 2016,
    \u5B66: -1356,
    \u5B89: -423,
    \u5B9F: -1008,
    \u5BB6: 1078,
    \u5C0F: -513,
    \u5C11: -3102,
    \u5DDE: 1155,
    \u5E02: 3197,
    \u5E73: -1804,
    \u5E74: 2416,
    \u5E83: -1030,
    \u5E9C: 1605,
    \u5EA6: 1452,
    \u5EFA: -2352,
    \u5F53: -3885,
    \u5F97: 1905,
    \u601D: -1291,
    \u6027: 1822,
    \u6238: -488,
    \u6307: -3973,
    \u653F: -2013,
    \u6559: -1479,
    \u6570: 3222,
    \u6587: -1489,
    \u65B0: 1764,
    \u65E5: 2099,
    \u65E7: 5792,
    \u6628: -661,
    \u6642: -1248,
    \u66DC: -951,
    \u6700: -937,
    \u6708: 4125,
    \u671F: 360,
    \u674E: 3094,
    \u6751: 364,
    \u6771: -805,
    \u6838: 5156,
    \u68EE: 2438,
    \u696D: 484,
    \u6C0F: 2613,
    \u6C11: -1694,
    \u6C7A: -1073,
    \u6CD5: 1868,
    \u6D77: -495,
    \u7121: 979,
    \u7269: 461,
    \u7279: -3850,
    \u751F: -273,
    \u7528: 914,
    \u753A: 1215,
    \u7684: 7313,
    \u76F4: -1835,
    \u7701: 792,
    \u770C: 6293,
    \u77E5: -1528,
    \u79C1: 4231,
    \u7A0E: 401,
    \u7ACB: -960,
    \u7B2C: 1201,
    \u7C73: 7767,
    \u7CFB: 3066,
    \u7D04: 3663,
    \u7D1A: 1384,
    \u7D71: -4229,
    \u7DCF: 1163,
    \u7DDA: 1255,
    \u8005: 6457,
    \u80FD: 725,
    \u81EA: -2869,
    \u82F1: 785,
    \u898B: 1044,
    \u8ABF: -562,
    \u8CA1: -733,
    \u8CBB: 1777,
    \u8ECA: 1835,
    \u8ECD: 1375,
    \u8FBC: -1504,
    \u901A: -1136,
    \u9078: -681,
    \u90CE: 1026,
    \u90E1: 4404,
    \u90E8: 1200,
    \u91D1: 2163,
    \u9577: 421,
    \u958B: -1432,
    \u9593: 1302,
    \u95A2: -1282,
    \u96E8: 2009,
    \u96FB: -1045,
    \u975E: 2066,
    \u99C5: 1620,
    "\uFF11": -800,
    "\uFF63": 2670,
    "\uFF65": -3794,
    \uFF6F: -1350,
    \uFF71: 551,
    \uFF78\uFF9E: 1319,
    \uFF7D: 874,
    \uFF84: 521,
    \uFF91: 1109,
    \uFF99: 1591,
    \uFF9B: 2201,
    \uFF9D: 278
  };
  this.UW4__ = {
    ",": 3930,
    ".": 3508,
    "\u2015": -4841,
    "\u3001": 3930,
    "\u3002": 3508,
    "\u3007": 4999,
    "\u300C": 1895,
    "\u300D": 3798,
    "\u3013": -5156,
    \u3042: 4752,
    \u3044: -3435,
    \u3046: -640,
    \u3048: -2514,
    \u304A: 2405,
    \u304B: 530,
    \u304C: 6006,
    \u304D: -4482,
    \u304E: -3821,
    \u304F: -3788,
    \u3051: -4376,
    \u3052: -4734,
    \u3053: 2255,
    \u3054: 1979,
    \u3055: 2864,
    \u3057: -843,
    \u3058: -2506,
    \u3059: -731,
    \u305A: 1251,
    \u305B: 181,
    \u305D: 4091,
    \u305F: 5034,
    \u3060: 5408,
    \u3061: -3654,
    \u3063: -5882,
    \u3064: -1659,
    \u3066: 3994,
    \u3067: 7410,
    \u3068: 4547,
    \u306A: 5433,
    \u306B: 6499,
    \u306C: 1853,
    \u306D: 1413,
    \u306E: 7396,
    \u306F: 8578,
    \u3070: 1940,
    \u3072: 4249,
    \u3073: -4134,
    \u3075: 1345,
    \u3078: 6665,
    \u3079: -744,
    \u307B: 1464,
    \u307E: 1051,
    \u307F: -2082,
    \u3080: -882,
    \u3081: -5046,
    \u3082: 4169,
    \u3083: -2666,
    \u3084: 2795,
    \u3087: -1544,
    \u3088: 3351,
    \u3089: -2922,
    \u308A: -9726,
    \u308B: -14896,
    \u308C: -2613,
    \u308D: -4570,
    \u308F: -1783,
    \u3092: 13150,
    \u3093: -2352,
    \u30AB: 2145,
    \u30B3: 1789,
    \u30BB: 1287,
    \u30C3: -724,
    \u30C8: -403,
    \u30E1: -1635,
    \u30E9: -881,
    \u30EA: -541,
    \u30EB: -856,
    \u30F3: -3637,
    "\u30FB": -4371,
    \u30FC: -11870,
    \u4E00: -2069,
    \u4E2D: 2210,
    \u4E88: 782,
    \u4E8B: -190,
    \u4E95: -1768,
    \u4EBA: 1036,
    \u4EE5: 544,
    \u4F1A: 950,
    \u4F53: -1286,
    \u4F5C: 530,
    \u5074: 4292,
    \u5148: 601,
    \u515A: -2006,
    \u5171: -1212,
    \u5185: 584,
    \u5186: 788,
    \u521D: 1347,
    \u524D: 1623,
    \u526F: 3879,
    \u529B: -302,
    \u52D5: -740,
    \u52D9: -2715,
    \u5316: 776,
    \u533A: 4517,
    \u5354: 1013,
    \u53C2: 1555,
    \u5408: -1834,
    \u548C: -681,
    \u54E1: -910,
    \u5668: -851,
    \u56DE: 1500,
    \u56FD: -619,
    \u5712: -1200,
    \u5730: 866,
    \u5834: -1410,
    \u5841: -2094,
    \u58EB: -1413,
    \u591A: 1067,
    \u5927: 571,
    \u5B50: -4802,
    \u5B66: -1397,
    \u5B9A: -1057,
    \u5BFA: -809,
    \u5C0F: 1910,
    \u5C4B: -1328,
    \u5C71: -1500,
    \u5CF6: -2056,
    \u5DDD: -2667,
    \u5E02: 2771,
    \u5E74: 374,
    \u5E81: -4556,
    \u5F8C: 456,
    \u6027: 553,
    \u611F: 916,
    \u6240: -1566,
    \u652F: 856,
    \u6539: 787,
    \u653F: 2182,
    \u6559: 704,
    \u6587: 522,
    \u65B9: -856,
    \u65E5: 1798,
    \u6642: 1829,
    \u6700: 845,
    \u6708: -9066,
    \u6728: -485,
    \u6765: -442,
    \u6821: -360,
    \u696D: -1043,
    \u6C0F: 5388,
    \u6C11: -2716,
    \u6C17: -910,
    \u6CA2: -939,
    \u6E08: -543,
    \u7269: -735,
    \u7387: 672,
    \u7403: -1267,
    \u751F: -1286,
    \u7523: -1101,
    \u7530: -2900,
    \u753A: 1826,
    \u7684: 2586,
    \u76EE: 922,
    \u7701: -3485,
    \u770C: 2997,
    \u7A7A: -867,
    \u7ACB: -2112,
    \u7B2C: 788,
    \u7C73: 2937,
    \u7CFB: 786,
    \u7D04: 2171,
    \u7D4C: 1146,
    \u7D71: -1169,
    \u7DCF: 940,
    \u7DDA: -994,
    \u7F72: 749,
    \u8005: 2145,
    \u80FD: -730,
    \u822C: -852,
    \u884C: -792,
    \u898F: 792,
    \u8B66: -1184,
    \u8B70: -244,
    \u8C37: -1e3,
    \u8CDE: 730,
    \u8ECA: -1481,
    \u8ECD: 1158,
    \u8F2A: -1433,
    \u8FBC: -3370,
    \u8FD1: 929,
    \u9053: -1291,
    \u9078: 2596,
    \u90CE: -4866,
    \u90FD: 1192,
    \u91CE: -1100,
    \u9280: -2213,
    \u9577: 357,
    \u9593: -2344,
    \u9662: -2297,
    \u969B: -2604,
    \u96FB: -878,
    \u9818: -1659,
    \u984C: -792,
    \u9928: -1984,
    \u9996: 1749,
    \u9AD8: 2120,
    "\uFF62": 1895,
    "\uFF63": 3798,
    "\uFF65": -4371,
    \uFF6F: -724,
    \uFF70: -11870,
    \uFF76: 2145,
    \uFF7A: 1789,
    \uFF7E: 1287,
    \uFF84: -403,
    \uFF92: -1635,
    \uFF97: -881,
    \uFF98: -541,
    \uFF99: -856,
    \uFF9D: -3637
  };
  this.UW5__ = {
    ",": 465,
    ".": -299,
    1: -514,
    E2: -32768,
    "]": -2762,
    "\u3001": 465,
    "\u3002": -299,
    "\u300C": 363,
    \u3042: 1655,
    \u3044: 331,
    \u3046: -503,
    \u3048: 1199,
    \u304A: 527,
    \u304B: 647,
    \u304C: -421,
    \u304D: 1624,
    \u304E: 1971,
    \u304F: 312,
    \u3052: -983,
    \u3055: -1537,
    \u3057: -1371,
    \u3059: -852,
    \u3060: -1186,
    \u3061: 1093,
    \u3063: 52,
    \u3064: 921,
    \u3066: -18,
    \u3067: -850,
    \u3068: -127,
    \u3069: 1682,
    \u306A: -787,
    \u306B: -1224,
    \u306E: -635,
    \u306F: -578,
    \u3079: 1001,
    \u307F: 502,
    \u3081: 865,
    \u3083: 3350,
    \u3087: 854,
    \u308A: -208,
    \u308B: 429,
    \u308C: 504,
    \u308F: 419,
    \u3092: -1264,
    \u3093: 327,
    \u30A4: 241,
    \u30EB: 451,
    \u30F3: -343,
    \u4E2D: -871,
    \u4EAC: 722,
    \u4F1A: -1153,
    \u515A: -654,
    \u52D9: 3519,
    \u533A: -901,
    \u544A: 848,
    \u54E1: 2104,
    \u5927: -1296,
    \u5B66: -548,
    \u5B9A: 1785,
    \u5D50: -1304,
    \u5E02: -2991,
    \u5E2D: 921,
    \u5E74: 1763,
    \u601D: 872,
    \u6240: -814,
    \u6319: 1618,
    \u65B0: -1682,
    \u65E5: 218,
    \u6708: -4353,
    \u67FB: 932,
    \u683C: 1356,
    \u6A5F: -1508,
    \u6C0F: -1347,
    \u7530: 240,
    \u753A: -3912,
    \u7684: -3149,
    \u76F8: 1319,
    \u7701: -1052,
    \u770C: -4003,
    \u7814: -997,
    \u793E: -278,
    \u7A7A: -813,
    \u7D71: 1955,
    \u8005: -2233,
    \u8868: 663,
    \u8A9E: -1073,
    \u8B70: 1219,
    \u9078: -1018,
    \u90CE: -368,
    \u9577: 786,
    \u9593: 1191,
    \u984C: 2368,
    \u9928: -689,
    "\uFF11": -514,
    \uFF25\uFF12: -32768,
    "\uFF62": 363,
    \uFF72: 241,
    \uFF99: 451,
    \uFF9D: -343
  };
  this.UW6__ = {
    ",": 227,
    ".": 808,
    1: -270,
    E1: 306,
    "\u3001": 227,
    "\u3002": 808,
    \u3042: -307,
    \u3046: 189,
    \u304B: 241,
    \u304C: -73,
    \u304F: -121,
    \u3053: -200,
    \u3058: 1782,
    \u3059: 383,
    \u305F: -428,
    \u3063: 573,
    \u3066: -1014,
    \u3067: 101,
    \u3068: -105,
    \u306A: -253,
    \u306B: -149,
    \u306E: -417,
    \u306F: -236,
    \u3082: -206,
    \u308A: 187,
    \u308B: -135,
    \u3092: 195,
    \u30EB: -673,
    \u30F3: -496,
    \u4E00: -277,
    \u4E2D: 201,
    \u4EF6: -800,
    \u4F1A: 624,
    \u524D: 302,
    \u533A: 1792,
    \u54E1: -1212,
    \u59D4: 798,
    \u5B66: -960,
    \u5E02: 887,
    \u5E83: -695,
    \u5F8C: 535,
    \u696D: -697,
    \u76F8: 753,
    \u793E: -507,
    \u798F: 974,
    \u7A7A: -822,
    \u8005: 1811,
    \u9023: 463,
    \u90CE: 1082,
    "\uFF11": -270,
    \uFF25\uFF11: 306,
    \uFF99: -673,
    \uFF9D: -496
  };
  return this;
}
TinySegmenter.prototype.ctype_ = function(str) {
  for (var i in this.chartype_) {
    if (str.match(this.chartype_[i][0])) {
      return this.chartype_[i][1];
    }
  }
  return "O";
};
TinySegmenter.prototype.ts_ = function(v) {
  if (v) {
    return v;
  }
  return 0;
};
TinySegmenter.prototype.segment = function(input) {
  if (input == null || input == void 0 || input == "") {
    return [];
  }
  var result = [];
  var seg = ["B3", "B2", "B1"];
  var ctype = ["O", "O", "O"];
  var o = input.split("");
  for (i = 0; i < o.length; ++i) {
    seg.push(o[i]);
    ctype.push(this.ctype_(o[i]));
  }
  seg.push("E1");
  seg.push("E2");
  seg.push("E3");
  ctype.push("O");
  ctype.push("O");
  ctype.push("O");
  var word = seg[3];
  var p1 = "U";
  var p2 = "U";
  var p3 = "U";
  for (var i = 4; i < seg.length - 3; ++i) {
    var score = this.BIAS__;
    var w1 = seg[i - 3];
    var w2 = seg[i - 2];
    var w3 = seg[i - 1];
    var w4 = seg[i];
    var w5 = seg[i + 1];
    var w6 = seg[i + 2];
    var c1 = ctype[i - 3];
    var c2 = ctype[i - 2];
    var c3 = ctype[i - 1];
    var c4 = ctype[i];
    var c5 = ctype[i + 1];
    var c6 = ctype[i + 2];
    score += this.ts_(this.UP1__[p1]);
    score += this.ts_(this.UP2__[p2]);
    score += this.ts_(this.UP3__[p3]);
    score += this.ts_(this.BP1__[p1 + p2]);
    score += this.ts_(this.BP2__[p2 + p3]);
    score += this.ts_(this.UW1__[w1]);
    score += this.ts_(this.UW2__[w2]);
    score += this.ts_(this.UW3__[w3]);
    score += this.ts_(this.UW4__[w4]);
    score += this.ts_(this.UW5__[w5]);
    score += this.ts_(this.UW6__[w6]);
    score += this.ts_(this.BW1__[w2 + w3]);
    score += this.ts_(this.BW2__[w3 + w4]);
    score += this.ts_(this.BW3__[w4 + w5]);
    score += this.ts_(this.TW1__[w1 + w2 + w3]);
    score += this.ts_(this.TW2__[w2 + w3 + w4]);
    score += this.ts_(this.TW3__[w3 + w4 + w5]);
    score += this.ts_(this.TW4__[w4 + w5 + w6]);
    score += this.ts_(this.UC1__[c1]);
    score += this.ts_(this.UC2__[c2]);
    score += this.ts_(this.UC3__[c3]);
    score += this.ts_(this.UC4__[c4]);
    score += this.ts_(this.UC5__[c5]);
    score += this.ts_(this.UC6__[c6]);
    score += this.ts_(this.BC1__[c2 + c3]);
    score += this.ts_(this.BC2__[c3 + c4]);
    score += this.ts_(this.BC3__[c4 + c5]);
    score += this.ts_(this.TC1__[c1 + c2 + c3]);
    score += this.ts_(this.TC2__[c2 + c3 + c4]);
    score += this.ts_(this.TC3__[c3 + c4 + c5]);
    score += this.ts_(this.TC4__[c4 + c5 + c6]);
    score += this.ts_(this.UQ1__[p1 + c1]);
    score += this.ts_(this.UQ2__[p2 + c2]);
    score += this.ts_(this.UQ3__[p3 + c3]);
    score += this.ts_(this.BQ1__[p2 + c2 + c3]);
    score += this.ts_(this.BQ2__[p2 + c3 + c4]);
    score += this.ts_(this.BQ3__[p3 + c2 + c3]);
    score += this.ts_(this.BQ4__[p3 + c3 + c4]);
    score += this.ts_(this.TQ1__[p2 + c1 + c2 + c3]);
    score += this.ts_(this.TQ2__[p2 + c2 + c3 + c4]);
    score += this.ts_(this.TQ3__[p3 + c1 + c2 + c3]);
    score += this.ts_(this.TQ4__[p3 + c2 + c3 + c4]);
    var p = "O";
    if (score > 0) {
      result.push(word);
      word = "";
      p = "B";
    }
    p1 = p2;
    p2 = p3;
    p3 = p;
    word += seg[i];
  }
  result.push(word);
  return result;
};
var tiny_segmenter_default = TinySegmenter;

// src/tokenizer/tokenizers/JapaneseTokenizer.ts
var segmenter = new tiny_segmenter_default();
function pickTokensAsJapanese(content, trimPattern) {
  return content.split(trimPattern).filter((x) => x !== "").flatMap((x) => segmenter.segment(x));
}
var JapaneseTokenizer = class {
  tokenize(content, raw) {
    return pickTokensAsJapanese(content, raw ? / /g : this.getTrimPattern());
  }
  recursiveTokenize(content) {
    const tokens = segmenter.segment(content).flatMap(
      (x) => x === " " ? x : x.split(" ").map((t) => t === "" ? " " : t)
    );
    const ret = [];
    for (let i = 0; i < tokens.length; i++) {
      if (i === 0 || tokens[i].length !== 1 || !Boolean(tokens[i].match(this.getTrimPattern()))) {
        ret.push({
          word: tokens.slice(i).join(""),
          offset: tokens.slice(0, i).join("").length
        });
      }
    }
    return ret;
  }
  getTrimPattern() {
    return TRIM_CHAR_PATTERN;
  }
  shouldIgnoreOnCurrent(str) {
    return Boolean(str.match(/^[ぁ-んa-zA-Z。、ー ]*$/));
  }
};

// src/tokenizer/tokenizers/EnglishOnlyTokenizer.ts
var ENGLISH_PATTERN = /[a-zA-Z0-9_\-\\]/;
var EnglishOnlyTokenizer = class extends DefaultTokenizer {
  tokenize(content, raw) {
    const tokenized = Array.from(this._tokenize(content)).filter(
      (x) => x.word.match(ENGLISH_PATTERN)
    );
    return raw ? tokenized.map((x) => x.word) : tokenized.map((x) => x.word).filter((x) => !x.match(this.getTrimPattern()));
  }
  recursiveTokenize(content) {
    const offsets = Array.from(this._tokenize(content)).filter((x) => !x.word.match(this.getTrimPattern())).map((x) => x.offset);
    return [
      ...offsets.map((i) => ({
        word: content.slice(i),
        offset: i
      }))
    ];
  }
  *_tokenize(content) {
    let startIndex = 0;
    let previousType = "none";
    for (let i = 0; i < content.length; i++) {
      if (content[i].match(super.getTrimPattern())) {
        yield { word: content.slice(startIndex, i), offset: startIndex };
        previousType = "trim";
        startIndex = i;
        continue;
      }
      if (content[i].match(ENGLISH_PATTERN)) {
        if (previousType === "english" || previousType === "none") {
          previousType = "english";
          continue;
        }
        yield { word: content.slice(startIndex, i), offset: startIndex };
        previousType = "english";
        startIndex = i;
        continue;
      }
      if (previousType === "others" || previousType === "none") {
        previousType = "others";
        continue;
      }
      yield { word: content.slice(startIndex, i), offset: startIndex };
      previousType = "others";
      startIndex = i;
    }
    yield {
      word: content.slice(startIndex, content.length),
      offset: startIndex
    };
  }
};

// src/tokenizer/tokenizers/ChineseTokenizer.ts
var import_chinese_tokenizer = __toESM(require_main());
var ChineseTokenizer = class {
  static create(dict) {
    const ins = new ChineseTokenizer();
    ins._tokenize = import_chinese_tokenizer.default.load(dict);
    return ins;
  }
  tokenize(content, raw) {
    return content.split(raw ? / /g : this.getTrimPattern()).filter((x) => x !== "").flatMap((x) => this._tokenize(x)).map((x) => x.text);
  }
  recursiveTokenize(content) {
    const tokens = this._tokenize(content).map((x) => x.text);
    const ret = [];
    for (let i = 0; i < tokens.length; i++) {
      if (i === 0 || tokens[i].length !== 1 || !Boolean(tokens[i].match(this.getTrimPattern()))) {
        ret.push({
          word: tokens.slice(i).join(""),
          offset: tokens.slice(0, i).join("").length
        });
      }
    }
    return ret;
  }
  getTrimPattern() {
    return TRIM_CHAR_PATTERN;
  }
  shouldIgnoreOnCurrent(str) {
    return false;
  }
};

// src/tokenizer/tokenizer.ts
async function createTokenizer(strategy, app) {
  switch (strategy.name) {
    case "default":
      return new DefaultTokenizer();
    case "english-only":
      return new EnglishOnlyTokenizer();
    case "arabic":
      return new ArabicTokenizer();
    case "japanese":
      return new JapaneseTokenizer();
    case "chinese":
      const hasCedict = await app.vault.adapter.exists("./cedict_ts.u8");
      if (!hasCedict) {
        return Promise.reject(
          new Error("cedict_ts.U8 doesn't exist in your vault root.")
        );
      }
      const dict = await app.vault.adapter.read("./cedict_ts.u8");
      return ChineseTokenizer.create(dict);
  }
}

// src/tokenizer/TokenizeStrategy.ts
var _TokenizeStrategy = class {
  constructor(name, triggerThreshold, indexingThreshold) {
    this.name = name;
    this.triggerThreshold = triggerThreshold;
    this.indexingThreshold = indexingThreshold;
    _TokenizeStrategy._values.push(this);
  }
  static fromName(name) {
    return _TokenizeStrategy._values.find((x) => x.name === name);
  }
  static values() {
    return _TokenizeStrategy._values;
  }
};
var TokenizeStrategy = _TokenizeStrategy;
TokenizeStrategy._values = [];
TokenizeStrategy.DEFAULT = new _TokenizeStrategy("default", 3, 5);
TokenizeStrategy.ENGLISH_ONLY = new _TokenizeStrategy("english-only", 3, 5);
TokenizeStrategy.JAPANESE = new _TokenizeStrategy("japanese", 2, 2);
TokenizeStrategy.ARABIC = new _TokenizeStrategy("arabic", 3, 3);
TokenizeStrategy.CHINESE = new _TokenizeStrategy("chinese", 1, 2);

// src/app-helper.ts
var import_obsidian = require("obsidian");
var AppHelper = class {
  constructor(app) {
    this.unsafeApp = app;
  }
  equalsAsEditorPostion(one, other) {
    return one.line === other.line && one.ch === other.ch;
  }
  getAliases(file) {
    var _a, _b;
    return (_b = (0, import_obsidian.parseFrontMatterAliases)(
      (_a = this.unsafeApp.metadataCache.getFileCache(file)) == null ? void 0 : _a.frontmatter
    )) != null ? _b : [];
  }
  getFrontMatter(file) {
    var _a, _b, _c, _d;
    const frontMatter = (_a = this.unsafeApp.metadataCache.getFileCache(file)) == null ? void 0 : _a.frontmatter;
    if (!frontMatter) {
      return void 0;
    }
    const tags = (_c = (_b = (0, import_obsidian.parseFrontMatterTags)(frontMatter)) == null ? void 0 : _b.map((x) => x.slice(1))) != null ? _c : [];
    const aliases = (_d = (0, import_obsidian.parseFrontMatterAliases)(frontMatter)) != null ? _d : [];
    const { position, ...rest } = frontMatter;
    return {
      ...Object.fromEntries(
        Object.entries(rest).map(([k, _v]) => [
          k,
          (0, import_obsidian.parseFrontMatterStringArray)(frontMatter, k)
        ])
      ),
      tags,
      tag: tags,
      aliases,
      alias: aliases
    };
  }
  getMarkdownViewInActiveLeaf() {
    if (!this.unsafeApp.workspace.getActiveViewOfType(import_obsidian.MarkdownView)) {
      return null;
    }
    return this.unsafeApp.workspace.activeLeaf.view;
  }
  getActiveFile() {
    return this.unsafeApp.workspace.getActiveFile();
  }
  isActiveFile(file) {
    var _a;
    return ((_a = this.getActiveFile()) == null ? void 0 : _a.path) === file.path;
  }
  getPreviousFile() {
    var _a;
    const fName = (_a = this.unsafeApp.workspace.getLastOpenFiles()) == null ? void 0 : _a[1];
    if (!fName) {
      return null;
    }
    return this.getMarkdownFileByPath(fName);
  }
  getCurrentDirname() {
    var _a, _b;
    return (_b = (_a = this.getActiveFile()) == null ? void 0 : _a.parent.path) != null ? _b : null;
  }
  getCurrentEditor() {
    var _a, _b;
    return (_b = (_a = this.getMarkdownViewInActiveLeaf()) == null ? void 0 : _a.editor) != null ? _b : null;
  }
  getSelection() {
    var _a;
    return (_a = this.getCurrentEditor()) == null ? void 0 : _a.getSelection();
  }
  getCurrentOffset(editor) {
    return editor.posToOffset(editor.getCursor());
  }
  getCurrentLine(editor) {
    return editor.getLine(editor.getCursor().line);
  }
  getCurrentLineUntilCursor(editor) {
    return this.getCurrentLine(editor).slice(0, editor.getCursor().ch);
  }
  optimizeMarkdownLinkText(linkText) {
    const activeFile = this.getActiveFile();
    if (!activeFile) {
      return null;
    }
    const path = this.linkText2Path(linkText);
    if (!path) {
      return linkText;
    }
    const file = this.getMarkdownFileByPath(path);
    if (!file) {
      return null;
    }
    const markdownLink = this.unsafeApp.fileManager.generateMarkdownLink(
      file,
      activeFile.path
    );
    return markdownLink.startsWith("[[") ? markdownLink.replace("[[", "").replace("]]", "") : markdownLink.replace("[", "").replace(/\]\(.+\)/g, "");
  }
  linkText2Path(linkText) {
    var _a, _b;
    const activeFile = this.getActiveFile();
    if (!activeFile) {
      return null;
    }
    return (_b = (_a = this.unsafeApp.metadataCache.getFirstLinkpathDest(
      linkText,
      activeFile.path
    )) == null ? void 0 : _a.path) != null ? _b : null;
  }
  searchPhantomLinks() {
    return Object.entries(this.unsafeApp.metadataCache.unresolvedLinks).flatMap(
      ([path, obj]) => Object.keys(obj).map((link) => ({ path, link }))
    );
  }
  getMarkdownFileByPath(path) {
    if (!path.endsWith(".md")) {
      return null;
    }
    const abstractFile = this.unsafeApp.vault.getAbstractFileByPath(path);
    if (!abstractFile) {
      return null;
    }
    return abstractFile;
  }
  openMarkdownFile(file, newLeaf, offset = 0) {
    var _a;
    const leaf = this.unsafeApp.workspace.getLeaf(newLeaf);
    leaf.openFile(file, (_a = this.unsafeApp.workspace.activeLeaf) == null ? void 0 : _a.getViewState()).then(() => {
      this.unsafeApp.workspace.setActiveLeaf(leaf, true, true);
      const viewOfType = this.unsafeApp.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
      if (viewOfType) {
        const editor = viewOfType.editor;
        const pos = editor.offsetToPos(offset);
        editor.setCursor(pos);
        editor.scrollIntoView({ from: pos, to: pos }, true);
      }
    });
  }
  getCurrentFrontMatter() {
    const editor = this.getCurrentEditor();
    if (!editor) {
      return null;
    }
    if (!this.getActiveFile()) {
      return null;
    }
    if (editor.getLine(0) !== "---") {
      return null;
    }
    const endPosition = editor.getValue().indexOf("---", 3);
    const currentOffset = this.getCurrentOffset(editor);
    if (endPosition !== -1 && currentOffset >= endPosition) {
      return null;
    }
    const keyLocations = Array.from(editor.getValue().matchAll(/.+:/g));
    if (keyLocations.length === 0) {
      return null;
    }
    const currentKeyLocation = keyLocations.filter((x) => x.index < currentOffset).last();
    if (!currentKeyLocation) {
      return null;
    }
    return currentKeyLocation[0].split(":")[0];
  }
  isIMEOn() {
    var _a, _b, _c;
    if (!this.unsafeApp.workspace.getActiveViewOfType(import_obsidian.MarkdownView)) {
      return false;
    }
    const markdownView = this.unsafeApp.workspace.activeLeaf.view;
    const cm5or6 = markdownView.editor.cm;
    if (((_a = cm5or6 == null ? void 0 : cm5or6.inputState) == null ? void 0 : _a.composing) > 0) {
      return true;
    }
    return !!((_c = (_b = cm5or6 == null ? void 0 : cm5or6.display) == null ? void 0 : _b.input) == null ? void 0 : _c.composing);
  }
  async writeLog(log) {
    await this.unsafeApp.vault.adapter.append((0, import_obsidian.normalizePath)("log.md"), log);
  }
  get useWikiLinks() {
    return !this.unsafeApp.vault.config.useMarkdownLinks;
  }
};

// src/provider/CustomDictionaryWordProvider.ts
var import_obsidian2 = require("obsidian");

// src/util/collection-helper.ts
var groupBy = (values, toKey) => values.reduce(
  (prev, cur, _1, _2, k = toKey(cur)) => ((prev[k] || (prev[k] = [])).push(cur), prev),
  {}
);
function uniq(values) {
  return [...new Set(values)];
}
function uniqBy(values, fn) {
  const m = /* @__PURE__ */ new Map();
  values.forEach((x) => {
    const k = fn(x);
    if (!m.has(k)) {
      m.set(k, x);
    }
  });
  return Array.from(m.values());
}
function uniqWith(arr, fn) {
  return arr.filter(
    (element2, index) => arr.findIndex((step) => fn(element2, step)) === index
  );
}
function mirrorMap(collection, toValue) {
  return collection.reduce((p, c) => ({ ...p, [toValue(c)]: toValue(c) }), {});
}
function max(collection, emptyValue) {
  const select = (a, b) => a >= b ? a : b;
  return collection.reduce(select, emptyValue);
}

// src/model/Word.ts
var _WordTypeMeta = class {
  constructor(type, priority, group) {
    this.type = type;
    this.priority = priority;
    this.group = group;
    _WordTypeMeta._values.push(this);
    _WordTypeMeta._dict[type] = this;
  }
  static of(type) {
    return _WordTypeMeta._dict[type];
  }
  static values() {
    return _WordTypeMeta._values;
  }
};
var WordTypeMeta = _WordTypeMeta;
WordTypeMeta._values = [];
WordTypeMeta._dict = {};
WordTypeMeta.FRONT_MATTER = new _WordTypeMeta(
  "frontMatter",
  100,
  "frontMatter"
);
WordTypeMeta.INTERNAL_LINK = new _WordTypeMeta(
  "internalLink",
  90,
  "internalLink"
);
WordTypeMeta.CUSTOM_DICTIONARY = new _WordTypeMeta(
  "customDictionary",
  80,
  "suggestion"
);
WordTypeMeta.CURRENT_FILE = new _WordTypeMeta(
  "currentFile",
  70,
  "suggestion"
);
WordTypeMeta.CURRENT_VAULT = new _WordTypeMeta(
  "currentVault",
  60,
  "suggestion"
);

// src/provider/suggester.ts
function suggestionUniqPredicate(a, b) {
  if (a.value !== b.value) {
    return false;
  }
  if (WordTypeMeta.of(a.type).group !== WordTypeMeta.of(b.type).group) {
    return false;
  }
  if (a.type === "internalLink" && !a.phantom && a.createdPath !== b.createdPath) {
    return false;
  }
  return true;
}
function pushWord(wordsByFirstLetter, key, word) {
  if (wordsByFirstLetter[key] === void 0) {
    wordsByFirstLetter[key] = [word];
    return;
  }
  wordsByFirstLetter[key].push(word);
}
function judge(word, query, queryStartWithUpper) {
  var _a;
  if (query === "") {
    return {
      word: {
        ...word,
        hit: word.value
      },
      value: word.value,
      alias: false
    };
  }
  if (lowerStartsWith(word.value, query)) {
    if (queryStartWithUpper && word.type !== "internalLink" && word.type !== "frontMatter") {
      const c = capitalizeFirstLetter(word.value);
      return {
        word: {
          ...word,
          value: c,
          hit: c
        },
        value: c,
        alias: false
      };
    } else {
      return {
        word: {
          ...word,
          hit: word.value
        },
        value: word.value,
        alias: false
      };
    }
  }
  const matchedAlias = (_a = word.aliases) == null ? void 0 : _a.find((a) => lowerStartsWith(a, query));
  if (matchedAlias) {
    return {
      word: {
        ...word,
        hit: matchedAlias
      },
      value: matchedAlias,
      alias: true
    };
  }
  return {
    word,
    alias: false
  };
}
function suggestWords(indexedWords, query, maxNum, option = {}) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
  const { frontMatter, selectionHistoryStorage } = option;
  const queryStartWithUpper = capitalizeFirstLetter(query) === query;
  const flattenFrontMatterWords = () => {
    var _a2, _b2;
    if (frontMatter === "alias" || frontMatter === "aliases") {
      return [];
    }
    if (frontMatter && ((_a2 = indexedWords.frontMatter) == null ? void 0 : _a2[frontMatter])) {
      return Object.values((_b2 = indexedWords.frontMatter) == null ? void 0 : _b2[frontMatter]).flat();
    }
    return [];
  };
  const words = queryStartWithUpper ? frontMatter ? flattenFrontMatterWords() : [
    ...(_a = indexedWords.currentFile[query.charAt(0)]) != null ? _a : [],
    ...(_b = indexedWords.currentFile[query.charAt(0).toLowerCase()]) != null ? _b : [],
    ...(_c = indexedWords.currentVault[query.charAt(0)]) != null ? _c : [],
    ...(_d = indexedWords.currentVault[query.charAt(0).toLowerCase()]) != null ? _d : [],
    ...(_e = indexedWords.customDictionary[query.charAt(0)]) != null ? _e : [],
    ...(_f = indexedWords.customDictionary[query.charAt(0).toLowerCase()]) != null ? _f : [],
    ...(_g = indexedWords.internalLink[query.charAt(0)]) != null ? _g : [],
    ...(_h = indexedWords.internalLink[query.charAt(0).toLowerCase()]) != null ? _h : []
  ] : frontMatter ? flattenFrontMatterWords() : [
    ...(_i = indexedWords.currentFile[query.charAt(0)]) != null ? _i : [],
    ...(_j = indexedWords.currentFile[query.charAt(0).toUpperCase()]) != null ? _j : [],
    ...(_k = indexedWords.currentVault[query.charAt(0)]) != null ? _k : [],
    ...(_l = indexedWords.currentVault[query.charAt(0).toUpperCase()]) != null ? _l : [],
    ...(_m = indexedWords.customDictionary[query.charAt(0)]) != null ? _m : [],
    ...(_n = indexedWords.customDictionary[query.charAt(0).toUpperCase()]) != null ? _n : [],
    ...(_o = indexedWords.internalLink[query.charAt(0)]) != null ? _o : [],
    ...(_p = indexedWords.internalLink[query.charAt(0).toUpperCase()]) != null ? _p : []
  ];
  const filteredJudgement = Array.from(words).map((x) => judge(x, query, queryStartWithUpper)).filter((x) => x.value !== void 0);
  const latestUpdated = max(
    filteredJudgement.map(
      (x) => {
        var _a2, _b2;
        return (_b2 = (_a2 = selectionHistoryStorage == null ? void 0 : selectionHistoryStorage.getSelectionHistory(x.word)) == null ? void 0 : _a2.lastUpdated) != null ? _b2 : 0;
      }
    ),
    0
  );
  const candidate = filteredJudgement.sort((a, b) => {
    const aWord = a.word;
    const bWord = b.word;
    const notSameWordType = aWord.type !== bWord.type;
    if (frontMatter && notSameWordType) {
      return bWord.type === "frontMatter" ? 1 : -1;
    }
    if (selectionHistoryStorage) {
      const ret = selectionHistoryStorage.compare(
        aWord,
        bWord,
        latestUpdated
      );
      if (ret !== 0) {
        return ret;
      }
    }
    if (a.value.length !== b.value.length) {
      return a.value.length > b.value.length ? 1 : -1;
    }
    if (notSameWordType) {
      return WordTypeMeta.of(bWord.type).priority > WordTypeMeta.of(aWord.type).priority ? 1 : -1;
    }
    if (a.alias !== b.alias) {
      return a.alias ? 1 : -1;
    }
    return 0;
  }).map((x) => x.word).slice(0, maxNum);
  return uniqWith(candidate, suggestionUniqPredicate);
}
function judgeByPartialMatch(word, query, queryStartWithUpper) {
  var _a, _b;
  if (query === "") {
    return {
      word: { ...word, hit: word.value },
      value: word.value,
      alias: false
    };
  }
  if (lowerStartsWith(word.value, query)) {
    if (queryStartWithUpper && word.type !== "internalLink" && word.type !== "frontMatter") {
      const c = capitalizeFirstLetter(word.value);
      return { word: { ...word, value: c, hit: c }, value: c, alias: false };
    } else {
      return {
        word: { ...word, hit: word.value },
        value: word.value,
        alias: false
      };
    }
  }
  const matchedAliasStarts = (_a = word.aliases) == null ? void 0 : _a.find(
    (a) => lowerStartsWith(a, query)
  );
  if (matchedAliasStarts) {
    return {
      word: { ...word, hit: matchedAliasStarts },
      value: matchedAliasStarts,
      alias: true
    };
  }
  if (lowerIncludes(word.value, query)) {
    return {
      word: { ...word, hit: word.value },
      value: word.value,
      alias: false
    };
  }
  const matchedAliasIncluded = (_b = word.aliases) == null ? void 0 : _b.find(
    (a) => lowerIncludes(a, query)
  );
  if (matchedAliasIncluded) {
    return {
      word: { ...word, hit: matchedAliasIncluded },
      value: matchedAliasIncluded,
      alias: true
    };
  }
  return { word, alias: false };
}
function suggestWordsByPartialMatch(indexedWords, query, maxNum, option = {}) {
  const { frontMatter, selectionHistoryStorage } = option;
  const queryStartWithUpper = capitalizeFirstLetter(query) === query;
  const flatObjectValues = (object) => Object.values(object).flat();
  const flattenFrontMatterWords = () => {
    var _a, _b;
    if (frontMatter === "alias" || frontMatter === "aliases") {
      return [];
    }
    if (frontMatter && ((_a = indexedWords.frontMatter) == null ? void 0 : _a[frontMatter])) {
      return Object.values((_b = indexedWords.frontMatter) == null ? void 0 : _b[frontMatter]).flat();
    }
    return [];
  };
  const words = frontMatter ? flattenFrontMatterWords() : [
    ...flatObjectValues(indexedWords.currentFile),
    ...flatObjectValues(indexedWords.currentVault),
    ...flatObjectValues(indexedWords.customDictionary),
    ...flatObjectValues(indexedWords.internalLink)
  ];
  const filteredJudgement = Array.from(words).map((x) => judgeByPartialMatch(x, query, queryStartWithUpper)).filter((x) => x.value !== void 0);
  const latestUpdated = max(
    filteredJudgement.map(
      (x) => {
        var _a, _b;
        return (_b = (_a = selectionHistoryStorage == null ? void 0 : selectionHistoryStorage.getSelectionHistory(x.word)) == null ? void 0 : _a.lastUpdated) != null ? _b : 0;
      }
    ),
    0
  );
  const candidate = filteredJudgement.sort((a, b) => {
    const aWord = a.word;
    const bWord = b.word;
    const notSameWordType = aWord.type !== bWord.type;
    if (frontMatter && notSameWordType) {
      return bWord.type === "frontMatter" ? 1 : -1;
    }
    if (selectionHistoryStorage) {
      const ret = selectionHistoryStorage.compare(
        aWord,
        bWord,
        latestUpdated
      );
      if (ret !== 0) {
        return ret;
      }
    }
    const as = lowerStartsWith(a.value, query);
    const bs = lowerStartsWith(b.value, query);
    if (as !== bs) {
      return bs ? 1 : -1;
    }
    if (a.value.length !== b.value.length) {
      return a.value.length > b.value.length ? 1 : -1;
    }
    if (notSameWordType) {
      return WordTypeMeta.of(bWord.type).priority > WordTypeMeta.of(aWord.type).priority ? 1 : -1;
    }
    if (a.alias !== b.alias) {
      return a.alias ? 1 : -1;
    }
    return 0;
  }).map((x) => x.word).slice(0, maxNum);
  return uniqWith(candidate, suggestionUniqPredicate);
}

// src/util/path.ts
function basename(path, ext) {
  var _a, _b;
  const name = (_b = (_a = path.match(/.+[\\/]([^\\/]+)[\\/]?$/)) == null ? void 0 : _a[1]) != null ? _b : path;
  return ext && name.endsWith(ext) ? name.replace(ext, "") : name;
}
function dirname(path) {
  var _a, _b;
  return (_b = (_a = path.match(/(.+)[\\/].+$/)) == null ? void 0 : _a[1]) != null ? _b : ".";
}
function isURL(path) {
  return Boolean(path.match(new RegExp("^https?://")));
}

// src/provider/CustomDictionaryWordProvider.ts
function escape(value) {
  return value.replace(/\\/g, "__VariousComplementsEscape__").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/__VariousComplementsEscape__/g, "\\\\");
}
function unescape(value) {
  return value.replace(/\\\\/g, "__VariousComplementsEscape__").replace(/\\n/g, "\n").replace(/\\t/g, "	").replace(/__VariousComplementsEscape__/g, "\\");
}
function jsonToWords(json, path, systemCaretSymbol) {
  return json.words.map((x) => {
    var _a;
    return {
      value: x.displayed || x.value,
      description: x.description,
      aliases: x.aliases,
      type: "customDictionary",
      createdPath: path,
      insertedText: x.displayed ? x.value : void 0,
      caretSymbol: (_a = json.caretSymbol) != null ? _a : systemCaretSymbol,
      ignoreSpaceAfterCompletion: json.ignoreSpaceAfterCompletion
    };
  });
}
function lineToWord(line, delimiter, path, delimiterForDisplay, delimiterForHide, systemCaretSymbol) {
  const [v, description, ...aliases] = line.split(delimiter.value);
  let value = unescape(v);
  let insertedText;
  let displayedText = value;
  if (delimiterForDisplay && value.includes(delimiterForDisplay)) {
    [displayedText, insertedText] = value.split(delimiterForDisplay);
  }
  if (delimiterForHide && value.includes(delimiterForHide)) {
    insertedText = value.replace(delimiterForHide, "");
    displayedText = `${value.split(delimiterForHide)[0]} ...`;
  }
  return {
    value: displayedText,
    description,
    aliases,
    type: "customDictionary",
    createdPath: path,
    insertedText,
    caretSymbol: systemCaretSymbol
  };
}
function wordToLine(word, delimiter, dividerForDisplay) {
  const value = word.insertedText && dividerForDisplay ? `${word.value}${dividerForDisplay}${word.insertedText}` : word.value;
  const escapedValue = escape(value);
  if (!word.description && !word.aliases) {
    return escapedValue;
  }
  if (!word.aliases) {
    return [escapedValue, word.description].join(delimiter.value);
  }
  return [escapedValue, word.description, ...word.aliases].join(
    delimiter.value
  );
}
function synonymAliases(name) {
  const lessEmojiValue = excludeEmoji(name);
  return name === lessEmojiValue ? [] : [lessEmojiValue];
}
var CustomDictionaryWordProvider = class {
  constructor(app, appHelper) {
    this.words = [];
    this.wordByValue = {};
    this.wordsByFirstLetter = {};
    this.appHelper = appHelper;
    this.fileSystemAdapter = app.vault.adapter;
  }
  get editablePaths() {
    return this.paths.filter((x) => !isURL(x) && !x.endsWith(".json"));
  }
  async loadWords(path, option) {
    const contents = isURL(path) ? await (0, import_obsidian2.request)({ url: path }) : await this.fileSystemAdapter.read(path);
    const words = path.endsWith(".json") ? jsonToWords(JSON.parse(contents), path, option.caretSymbol) : contents.split(/\r\n|\n/).map((x) => x.replace(/%%.*%%/g, "")).filter((x) => x).map(
      (x) => lineToWord(
        x,
        this.delimiter,
        path,
        option.delimiterForDisplay,
        option.delimiterForHide,
        option.caretSymbol
      )
    );
    return words.filter(
      (x) => !option.regexp || x.value.match(new RegExp(option.regexp))
    );
  }
  async refreshCustomWords(option) {
    this.clearWords();
    for (const path of this.paths) {
      try {
        const words = await this.loadWords(path, option);
        words.forEach((x) => this.addWord(x));
      } catch (e) {
        new import_obsidian2.Notice(
          `\u26A0 Fail to load ${path} -- Various Complements Plugin -- 
 ${e}`,
          0
        );
      }
    }
  }
  async addWordWithDictionary(word, dictionaryPath) {
    this.addWord(word);
    await this.fileSystemAdapter.append(
      dictionaryPath,
      "\n" + wordToLine(word, this.delimiter, this.dividerForDisplay)
    );
  }
  addWord(word) {
    var _a, _b;
    this.words.push(word);
    const wordWithSynonym = {
      ...word,
      aliases: [...(_a = word.aliases) != null ? _a : [], ...synonymAliases(word.value)]
    };
    this.wordByValue[wordWithSynonym.value] = wordWithSynonym;
    pushWord(
      this.wordsByFirstLetter,
      wordWithSynonym.value.charAt(0),
      wordWithSynonym
    );
    (_b = wordWithSynonym.aliases) == null ? void 0 : _b.forEach(
      (a) => pushWord(this.wordsByFirstLetter, a.charAt(0), wordWithSynonym)
    );
  }
  clearWords() {
    this.words = [];
    this.wordByValue = {};
    this.wordsByFirstLetter = {};
  }
  get wordCount() {
    return this.words.length;
  }
  setSettings(paths, delimiter, dividerForDisplay) {
    this.paths = paths;
    this.delimiter = delimiter;
    this.dividerForDisplay = dividerForDisplay;
  }
};

// src/provider/CurrentFileWordProvider.ts
var CurrentFileWordProvider = class {
  constructor(app, appHelper) {
    this.app = app;
    this.appHelper = appHelper;
    this.wordsByFirstLetter = {};
    this.words = [];
  }
  async refreshWords(onlyEnglish, minNumberOfCharacters) {
    this.clearWords();
    const editor = this.appHelper.getCurrentEditor();
    if (!editor) {
      return;
    }
    const file = this.app.workspace.getActiveFile();
    if (!file) {
      return;
    }
    const currentToken = this.tokenizer.tokenize(
      editor.getLine(editor.getCursor().line).slice(0, editor.getCursor().ch)
    ).last();
    const content = await this.app.vault.cachedRead(file);
    const tokens = this.tokenizer.tokenize(content).filter((x) => {
      if (x.length < minNumberOfCharacters) {
        return false;
      }
      if (this.tokenizer.shouldIgnoreOnCurrent(x)) {
        return false;
      }
      return onlyEnglish ? allAlphabets(x) : true;
    }).map((x) => startsSmallLetterOnlyFirst(x) ? x.toLowerCase() : x);
    this.words = uniq(tokens).filter((x) => x !== currentToken).map((x) => ({
      value: x,
      type: "currentFile",
      createdPath: file.path
    }));
    this.wordsByFirstLetter = groupBy(this.words, (x) => x.value.charAt(0));
  }
  clearWords() {
    this.words = [];
    this.wordsByFirstLetter = {};
  }
  get wordCount() {
    return this.words.length;
  }
  setSettings(tokenizer) {
    this.tokenizer = tokenizer;
  }
};

// src/provider/InternalLinkWordProvider.ts
var InternalLinkWordProvider = class {
  constructor(app, appHelper) {
    this.app = app;
    this.appHelper = appHelper;
    this.words = [];
    this.wordsByFirstLetter = {};
  }
  refreshWords(wordAsInternalLinkAlias, excludePathPrefixPatterns) {
    var _a;
    this.clearWords();
    const synonymAliases3 = (name) => {
      const lessEmojiValue = excludeEmoji(name);
      return name === lessEmojiValue ? [] : [lessEmojiValue];
    };
    const resolvedInternalLinkWords = this.app.vault.getMarkdownFiles().filter(
      (f) => excludePathPrefixPatterns.every((x) => !f.path.startsWith(x))
    ).flatMap((x) => {
      const aliases = this.appHelper.getAliases(x);
      if (wordAsInternalLinkAlias) {
        return [
          {
            value: x.basename,
            type: "internalLink",
            createdPath: x.path,
            aliases: synonymAliases3(x.basename),
            description: x.path
          },
          ...aliases.map((a) => ({
            value: a,
            type: "internalLink",
            createdPath: x.path,
            aliases: synonymAliases3(a),
            description: x.path,
            aliasMeta: {
              origin: x.path
            }
          }))
        ];
      } else {
        return [
          {
            value: x.basename,
            type: "internalLink",
            createdPath: x.path,
            aliases: [
              ...synonymAliases3(x.basename),
              ...aliases,
              ...aliases.flatMap(synonymAliases3)
            ],
            description: x.path
          }
        ];
      }
    });
    const unresolvedInternalLinkWords = this.appHelper.searchPhantomLinks().map(({ path, link }) => {
      return {
        value: link,
        type: "internalLink",
        createdPath: path,
        aliases: synonymAliases3(link),
        description: `Appeared in -> ${path}`,
        phantom: true
      };
    });
    this.words = [...resolvedInternalLinkWords, ...unresolvedInternalLinkWords];
    for (const word of this.words) {
      pushWord(this.wordsByFirstLetter, word.value.charAt(0), word);
      (_a = word.aliases) == null ? void 0 : _a.forEach(
        (a) => pushWord(this.wordsByFirstLetter, a.charAt(0), word)
      );
    }
  }
  clearWords() {
    this.words = [];
    this.wordsByFirstLetter = {};
  }
  get wordCount() {
    return this.words.length;
  }
};

// src/provider/MatchStrategy.ts
var _MatchStrategy = class {
  constructor(name, handler) {
    this.name = name;
    this.handler = handler;
    _MatchStrategy._values.push(this);
  }
  static fromName(name) {
    return _MatchStrategy._values.find((x) => x.name === name);
  }
  static values() {
    return _MatchStrategy._values;
  }
};
var MatchStrategy = _MatchStrategy;
MatchStrategy._values = [];
MatchStrategy.PREFIX = new _MatchStrategy("prefix", suggestWords);
MatchStrategy.PARTIAL = new _MatchStrategy(
  "partial",
  suggestWordsByPartialMatch
);

// src/option/CycleThroughSuggestionsKeys.ts
var _CycleThroughSuggestionsKeys = class {
  constructor(name, nextKey, previousKey) {
    this.name = name;
    this.nextKey = nextKey;
    this.previousKey = previousKey;
    _CycleThroughSuggestionsKeys._values.push(this);
  }
  static fromName(name) {
    return _CycleThroughSuggestionsKeys._values.find((x) => x.name === name);
  }
  static values() {
    return _CycleThroughSuggestionsKeys._values;
  }
};
var CycleThroughSuggestionsKeys = _CycleThroughSuggestionsKeys;
CycleThroughSuggestionsKeys._values = [];
CycleThroughSuggestionsKeys.NONE = new _CycleThroughSuggestionsKeys(
  "None",
  { modifiers: [], key: null },
  { modifiers: [], key: null }
);
CycleThroughSuggestionsKeys.TAB = new _CycleThroughSuggestionsKeys(
  "Tab, Shift+Tab",
  { modifiers: [], key: "Tab" },
  { modifiers: ["Shift"], key: "Tab" }
);
CycleThroughSuggestionsKeys.EMACS = new _CycleThroughSuggestionsKeys(
  "Ctrl/Cmd+N, Ctrl/Cmd+P",
  { modifiers: ["Mod"], key: "N" },
  { modifiers: ["Mod"], key: "P" }
);
CycleThroughSuggestionsKeys.VIM = new _CycleThroughSuggestionsKeys(
  "Ctrl/Cmd+J, Ctrl/Cmd+K",
  { modifiers: ["Mod"], key: "J" },
  { modifiers: ["Mod"], key: "K" }
);

// src/option/ColumnDelimiter.ts
var _ColumnDelimiter = class {
  constructor(name, value) {
    this.name = name;
    this.value = value;
    _ColumnDelimiter._values.push(this);
  }
  static fromName(name) {
    return _ColumnDelimiter._values.find((x) => x.name === name);
  }
  static values() {
    return _ColumnDelimiter._values;
  }
};
var ColumnDelimiter = _ColumnDelimiter;
ColumnDelimiter._values = [];
ColumnDelimiter.TAB = new _ColumnDelimiter("Tab", "	");
ColumnDelimiter.COMMA = new _ColumnDelimiter("Comma", ",");
ColumnDelimiter.PIPE = new _ColumnDelimiter("Pipe", "|");

// src/option/SelectSuggestionKey.ts
var _SelectSuggestionKey = class {
  constructor(name, keyBind) {
    this.name = name;
    this.keyBind = keyBind;
    _SelectSuggestionKey._values.push(this);
  }
  static fromName(name) {
    return _SelectSuggestionKey._values.find((x) => x.name === name);
  }
  static values() {
    return _SelectSuggestionKey._values;
  }
};
var SelectSuggestionKey = _SelectSuggestionKey;
SelectSuggestionKey._values = [];
SelectSuggestionKey.ENTER = new _SelectSuggestionKey("Enter", {
  modifiers: [],
  key: "Enter"
});
SelectSuggestionKey.TAB = new _SelectSuggestionKey("Tab", {
  modifiers: [],
  key: "Tab"
});
SelectSuggestionKey.MOD_ENTER = new _SelectSuggestionKey("Ctrl/Cmd+Enter", {
  modifiers: ["Mod"],
  key: "Enter"
});
SelectSuggestionKey.ALT_ENTER = new _SelectSuggestionKey("Alt+Enter", {
  modifiers: ["Alt"],
  key: "Enter"
});
SelectSuggestionKey.SHIFT_ENTER = new _SelectSuggestionKey("Shift+Enter", {
  modifiers: ["Shift"],
  key: "Enter"
});
SelectSuggestionKey.SPACE = new _SelectSuggestionKey("Space", {
  modifiers: [],
  key: " "
});
SelectSuggestionKey.SHIFT_SPACE = new _SelectSuggestionKey("Shift+Space", {
  modifiers: ["Shift"],
  key: " "
});
SelectSuggestionKey.BACKQUOTE = new _SelectSuggestionKey("Backquote", {
  modifiers: [],
  key: "`"
});
SelectSuggestionKey.None = new _SelectSuggestionKey("None", {
  modifiers: [],
  key: ""
});

// src/provider/CurrentVaultWordProvider.ts
var CurrentVaultWordProvider = class {
  constructor(app, appHelper) {
    this.app = app;
    this.appHelper = appHelper;
    this.wordsByFirstLetter = {};
    this.words = [];
  }
  async refreshWords(minNumberOfCharacters) {
    this.clearWords();
    const currentDirname = this.appHelper.getCurrentDirname();
    const markdownFilePaths = this.app.vault.getMarkdownFiles().map((x) => x.path).filter((p) => this.includePrefixPatterns.every((x) => p.startsWith(x))).filter((p) => this.excludePrefixPatterns.every((x) => !p.startsWith(x))).filter(
      (p) => !this.onlyUnderCurrentDirectory || dirname(p) === currentDirname
    );
    let wordByValue = {};
    for (const path of markdownFilePaths) {
      const content = await this.app.vault.adapter.read(path);
      const tokens = this.tokenizer.tokenize(content).filter(
        (x) => x.length >= minNumberOfCharacters && !this.tokenizer.shouldIgnoreOnCurrent(x)
      ).map((x) => startsSmallLetterOnlyFirst(x) ? x.toLowerCase() : x);
      for (const token of tokens) {
        wordByValue[token] = {
          value: token,
          type: "currentVault",
          createdPath: path,
          description: path
        };
      }
    }
    this.words = Object.values(wordByValue);
    this.wordsByFirstLetter = groupBy(this.words, (x) => x.value.charAt(0));
  }
  clearWords() {
    this.words = [];
    this.wordsByFirstLetter = {};
  }
  get wordCount() {
    return this.words.length;
  }
  setSettings(tokenizer, includePrefixPatterns, excludePrefixPatterns, onlyUnderCurrentDirectory) {
    this.tokenizer = tokenizer;
    this.includePrefixPatterns = includePrefixPatterns;
    this.excludePrefixPatterns = excludePrefixPatterns;
    this.onlyUnderCurrentDirectory = onlyUnderCurrentDirectory;
  }
};

// src/option/OpenSourceFileKeys.ts
var _OpenSourceFileKeys = class {
  constructor(name, keyBind) {
    this.name = name;
    this.keyBind = keyBind;
    _OpenSourceFileKeys._values.push(this);
  }
  static fromName(name) {
    return _OpenSourceFileKeys._values.find((x) => x.name === name);
  }
  static values() {
    return _OpenSourceFileKeys._values;
  }
};
var OpenSourceFileKeys = _OpenSourceFileKeys;
OpenSourceFileKeys._values = [];
OpenSourceFileKeys.NONE = new _OpenSourceFileKeys("None", {
  modifiers: [],
  key: null
});
OpenSourceFileKeys.MOD_ENTER = new _OpenSourceFileKeys("Ctrl/Cmd+Enter", {
  modifiers: ["Mod"],
  key: "Enter"
});
OpenSourceFileKeys.ALT_ENTER = new _OpenSourceFileKeys("Alt+Enter", {
  modifiers: ["Alt"],
  key: "Enter"
});
OpenSourceFileKeys.SHIFT_ENTER = new _OpenSourceFileKeys("Shift+Enter", {
  modifiers: ["Shift"],
  key: "Enter"
});

// src/option/DescriptionOnSuggestion.ts
var _DescriptionOnSuggestion = class {
  constructor(name, toDisplay) {
    this.name = name;
    this.toDisplay = toDisplay;
    _DescriptionOnSuggestion._values.push(this);
  }
  static fromName(name) {
    return _DescriptionOnSuggestion._values.find((x) => x.name === name);
  }
  static values() {
    return _DescriptionOnSuggestion._values;
  }
};
var DescriptionOnSuggestion = _DescriptionOnSuggestion;
DescriptionOnSuggestion._values = [];
DescriptionOnSuggestion.NONE = new _DescriptionOnSuggestion("None", () => null);
DescriptionOnSuggestion.SHORT = new _DescriptionOnSuggestion("Short", (word) => {
  if (!word.description) {
    return null;
  }
  return word.type === "customDictionary" ? word.description : basename(word.description);
});
DescriptionOnSuggestion.FULL = new _DescriptionOnSuggestion(
  "Full",
  (word) => {
    var _a;
    return (_a = word.description) != null ? _a : null;
  }
);

// src/provider/FrontMatterWordProvider.ts
function synonymAliases2(name) {
  const lessEmojiValue = excludeEmoji(name);
  return name === lessEmojiValue ? [] : [lessEmojiValue];
}
function frontMatterToWords(file, key, values) {
  return values.map((x) => ({
    key,
    value: x,
    type: "frontMatter",
    createdPath: file.path,
    aliases: synonymAliases2(x)
  }));
}
function pickWords(file, fm) {
  return Object.entries(fm).filter(
    ([_key, value]) => value != null && (typeof value === "string" || typeof value[0] === "string")
  ).flatMap(([key, value]) => frontMatterToWords(file, key, value));
}
function extractAndUniqWords(wordsByCreatedPath) {
  return uniqBy(
    Object.values(wordsByCreatedPath).flat(),
    (w) => w.key + w.value.toLowerCase()
  );
}
function indexingWords(words) {
  const wordsByKey = groupBy(words, (x) => x.key);
  return Object.fromEntries(
    Object.entries(wordsByKey).map(
      ([key, words2]) => [
        key,
        groupBy(words2, (w) => w.value.charAt(0))
      ]
    )
  );
}
var FrontMatterWordProvider = class {
  constructor(app, appHelper) {
    this.app = app;
    this.appHelper = appHelper;
    this.wordsByCreatedPath = {};
  }
  refreshWords() {
    this.clearWords();
    this.app.vault.getMarkdownFiles().forEach((f) => {
      const fm = this.appHelper.getFrontMatter(f);
      if (!fm) {
        return;
      }
      this.wordsByCreatedPath[f.path] = pickWords(f, fm);
    });
    this.words = extractAndUniqWords(this.wordsByCreatedPath);
    this.wordsByFirstLetterByKey = indexingWords(this.words);
  }
  updateWordIndex(file) {
    const fm = this.appHelper.getFrontMatter(file);
    if (!fm) {
      return;
    }
    this.wordsByCreatedPath[file.path] = pickWords(file, fm);
  }
  updateWords() {
    this.words = extractAndUniqWords(this.wordsByCreatedPath);
    this.wordsByFirstLetterByKey = indexingWords(this.words);
  }
  clearWords() {
    this.wordsByCreatedPath = {};
    this.words = [];
    this.wordsByFirstLetterByKey = {};
  }
  get wordCount() {
    return this.words.length;
  }
};

// src/provider/SpecificMatchStrategy.ts
var neverUsedHandler = (..._args) => [];
var _SpecificMatchStrategy = class {
  constructor(name, handler) {
    this.name = name;
    this.handler = handler;
    _SpecificMatchStrategy._values.push(this);
  }
  static fromName(name) {
    return _SpecificMatchStrategy._values.find((x) => x.name === name);
  }
  static values() {
    return _SpecificMatchStrategy._values;
  }
};
var SpecificMatchStrategy = _SpecificMatchStrategy;
SpecificMatchStrategy._values = [];
SpecificMatchStrategy.INHERIT = new _SpecificMatchStrategy(
  "inherit",
  neverUsedHandler
);
SpecificMatchStrategy.PREFIX = new _SpecificMatchStrategy("prefix", suggestWords);
SpecificMatchStrategy.PARTIAL = new _SpecificMatchStrategy(
  "partial",
  suggestWordsByPartialMatch
);

// src/storage/SelectionHistoryStorage.ts
var SEC = 1e3;
var MIN = SEC * 60;
var HOUR = MIN * 60;
var DAY = HOUR * 24;
var WEEK = DAY * 7;
function calcScore(history, latestUpdated) {
  if (!history) {
    return 0;
  }
  if (history.lastUpdated === latestUpdated) {
    return Number.MAX_SAFE_INTEGER;
  }
  const behind = Date.now() - history.lastUpdated;
  if (behind < MIN) {
    return 8 * history.count;
  } else if (behind < HOUR) {
    return 4 * history.count;
  } else if (behind < DAY) {
    return 2 * history.count;
  } else if (behind < WEEK) {
    return 0.5 * history.count;
  } else {
    return 0.25 * history.count;
  }
}
var SelectionHistoryStorage = class {
  constructor(data = {}, maxDaysToKeepHistory, maxNumberOfHistoryToKeep) {
    this.data = data;
    const now = Date.now();
    this.version = now;
    this.persistedVersion = now;
    this.maxDaysToKeepHistory = maxDaysToKeepHistory;
    this.maxNumberOfHistoryToKeep = maxNumberOfHistoryToKeep;
  }
  purge() {
    var _a;
    const now = Date.now();
    const times = [];
    for (const hit of Object.keys(this.data)) {
      for (const value of Object.keys(this.data[hit])) {
        for (const kind of Object.keys(this.data[hit][value])) {
          if (this.maxDaysToKeepHistory && now - this.data[hit][value][kind].lastUpdated > this.maxDaysToKeepHistory * DAY) {
            delete this.data[hit][value][kind];
          } else {
            times.push(this.data[hit][value][kind].lastUpdated);
          }
        }
        if (Object.isEmpty(this.data[hit][value])) {
          delete this.data[hit][value];
        }
      }
      if (Object.isEmpty(this.data[hit])) {
        delete this.data[hit];
      }
    }
    if (this.maxNumberOfHistoryToKeep) {
      const threshold = (_a = times.sort((a, b) => a > b ? -1 : 1).slice(0, this.maxNumberOfHistoryToKeep).at(-1)) != null ? _a : 0;
      for (const hit of Object.keys(this.data)) {
        for (const value of Object.keys(this.data[hit])) {
          for (const kind of Object.keys(this.data[hit][value])) {
            if (this.data[hit][value][kind].lastUpdated < threshold) {
              delete this.data[hit][value][kind];
            }
          }
          if (Object.isEmpty(this.data[hit][value])) {
            delete this.data[hit][value];
          }
        }
        if (Object.isEmpty(this.data[hit])) {
          delete this.data[hit];
        }
      }
    }
  }
  getSelectionHistory(word) {
    var _a, _b;
    return (_b = (_a = this.data[word.hit]) == null ? void 0 : _a[word.value]) == null ? void 0 : _b[word.type];
  }
  increment(word) {
    if (!this.data[word.hit]) {
      this.data[word.hit] = {};
    }
    if (!this.data[word.hit][word.value]) {
      this.data[word.hit][word.value] = {};
    }
    if (this.data[word.hit][word.value][word.type]) {
      this.data[word.hit][word.value][word.type] = {
        count: this.data[word.hit][word.value][word.type].count + 1,
        lastUpdated: Date.now()
      };
    } else {
      this.data[word.hit][word.value][word.type] = {
        count: 1,
        lastUpdated: Date.now()
      };
    }
    this.version = Date.now();
  }
  compare(w1, w2, latestUpdated) {
    const score1 = calcScore(this.getSelectionHistory(w1), latestUpdated);
    const score2 = calcScore(this.getSelectionHistory(w2), latestUpdated);
    if (score1 === score2) {
      return 0;
    }
    return score1 > score2 ? -1 : 1;
  }
  get shouldPersist() {
    return this.version > this.persistedVersion;
  }
  syncPersistVersion() {
    this.persistedVersion = this.version;
  }
};

// src/ui/AutoCompleteSuggest.ts
function buildLogMessage(message, msec) {
  return `${message}: ${Math.round(msec)}[ms]`;
}
var AutoCompleteSuggest = class extends import_obsidian3.EditorSuggest {
  constructor(app, statusBar) {
    super(app);
    this.previousCurrentLine = "";
    this.keymapEventHandler = [];
    this.appHelper = new AppHelper(app);
    this.statusBar = statusBar;
  }
  triggerComplete() {
    const editor = this.appHelper.getCurrentEditor();
    const activeFile = this.app.workspace.getActiveFile();
    if (!editor || !activeFile) {
      return;
    }
    this.runManually = true;
    this.trigger(editor, activeFile, true);
  }
  hideCompletion() {
    this.close();
  }
  static async new(app, settings, statusBar, onPersistSelectionHistory) {
    const ins = new AutoCompleteSuggest(app, statusBar);
    ins.currentFileWordProvider = new CurrentFileWordProvider(
      ins.app,
      ins.appHelper
    );
    ins.currentVaultWordProvider = new CurrentVaultWordProvider(
      ins.app,
      ins.appHelper
    );
    ins.customDictionaryWordProvider = new CustomDictionaryWordProvider(
      ins.app,
      ins.appHelper
    );
    ins.internalLinkWordProvider = new InternalLinkWordProvider(
      ins.app,
      ins.appHelper
    );
    ins.frontMatterWordProvider = new FrontMatterWordProvider(
      ins.app,
      ins.appHelper
    );
    ins.selectionHistoryStorage = new SelectionHistoryStorage(
      settings.selectionHistoryTree,
      settings.intelligentSuggestionPrioritization.maxDaysToKeepHistory,
      settings.intelligentSuggestionPrioritization.maxNumberOfHistoryToKeep
    );
    ins.selectionHistoryStorage.purge();
    await ins.updateSettings(settings);
    ins.modifyEventRef = app.vault.on("modify", async (_) => {
      var _a;
      await ins.refreshCurrentFileTokens();
      if ((_a = ins.selectionHistoryStorage) == null ? void 0 : _a.shouldPersist) {
        ins.settings.selectionHistoryTree = ins.selectionHistoryStorage.data;
        ins.selectionHistoryStorage.syncPersistVersion();
        onPersistSelectionHistory();
      }
    });
    ins.activeLeafChangeRef = app.workspace.on(
      "active-leaf-change",
      async (_) => {
        await ins.refreshCurrentFileTokens();
        ins.refreshInternalLinkTokens();
        ins.updateFrontMatterToken();
      }
    );
    ins.metadataCacheChangeRef = app.metadataCache.on("changed", (f) => {
      ins.updateFrontMatterTokenIndex(f);
      if (!ins.appHelper.isActiveFile(f)) {
        ins.updateFrontMatterToken();
      }
    });
    const cacheResolvedRef = app.metadataCache.on("resolved", async () => {
      ins.refreshInternalLinkTokens();
      ins.refreshFrontMatterTokens();
      ins.refreshCustomDictionaryTokens();
      ins.refreshCurrentVaultTokens();
      ins.app.metadataCache.offref(cacheResolvedRef);
    });
    return ins;
  }
  predictableComplete() {
    const editor = this.appHelper.getCurrentEditor();
    if (!editor) {
      return;
    }
    const cursor = editor.getCursor();
    const currentToken = this.tokenizer.tokenize(editor.getLine(cursor.line).slice(0, cursor.ch)).last();
    if (!currentToken) {
      return;
    }
    let suggestion = this.tokenizer.tokenize(
      editor.getRange({ line: Math.max(cursor.line - 50, 0), ch: 0 }, cursor)
    ).reverse().slice(1).find((x) => x.startsWith(currentToken));
    if (!suggestion) {
      suggestion = this.tokenizer.tokenize(
        editor.getRange(cursor, {
          line: Math.min(cursor.line + 50, editor.lineCount() - 1),
          ch: 0
        })
      ).find((x) => x.startsWith(currentToken));
    }
    if (!suggestion) {
      return;
    }
    editor.replaceRange(
      suggestion,
      { line: cursor.line, ch: cursor.ch - currentToken.length },
      { line: cursor.line, ch: cursor.ch }
    );
    this.close();
    this.debounceClose();
  }
  unregister() {
    this.app.vault.offref(this.modifyEventRef);
    this.app.workspace.offref(this.activeLeafChangeRef);
    this.app.metadataCache.offref(this.metadataCacheChangeRef);
  }
  get tokenizerStrategy() {
    return TokenizeStrategy.fromName(this.settings.strategy);
  }
  get matchStrategy() {
    return MatchStrategy.fromName(this.settings.matchStrategy);
  }
  get frontMatterComplementStrategy() {
    return SpecificMatchStrategy.fromName(
      this.settings.frontMatterComplementMatchStrategy
    );
  }
  get minNumberTriggered() {
    return this.settings.minNumberOfCharactersTriggered || this.tokenizerStrategy.triggerThreshold;
  }
  get currentFileMinNumberOfCharacters() {
    return this.settings.currentFileMinNumberOfCharacters || this.tokenizerStrategy.indexingThreshold;
  }
  get currentVaultMinNumberOfCharacters() {
    return this.settings.currentVaultMinNumberOfCharacters || this.tokenizerStrategy.indexingThreshold;
  }
  get descriptionOnSuggestion() {
    return DescriptionOnSuggestion.fromName(
      this.settings.descriptionOnSuggestion
    );
  }
  get excludeInternalLinkPrefixPathPatterns() {
    return this.settings.excludeInternalLinkPathPrefixPatterns.split("\n").filter((x) => x);
  }
  get indexedWords() {
    return {
      currentFile: this.currentFileWordProvider.wordsByFirstLetter,
      currentVault: this.currentVaultWordProvider.wordsByFirstLetter,
      customDictionary: this.customDictionaryWordProvider.wordsByFirstLetter,
      internalLink: this.internalLinkWordProvider.wordsByFirstLetter,
      frontMatter: this.frontMatterWordProvider.wordsByFirstLetterByKey
    };
  }
  async updateSettings(settings) {
    this.settings = settings;
    this.statusBar.setMatchStrategy(this.matchStrategy);
    this.statusBar.setComplementAutomatically(
      this.settings.complementAutomatically
    );
    try {
      this.tokenizer = await createTokenizer(this.tokenizerStrategy, this.app);
    } catch (e) {
      new import_obsidian3.Notice(e.message, 0);
    }
    this.currentFileWordProvider.setSettings(this.tokenizer);
    this.currentVaultWordProvider.setSettings(
      this.tokenizer,
      settings.includeCurrentVaultPathPrefixPatterns.split("\n").filter((x) => x),
      settings.excludeCurrentVaultPathPrefixPatterns.split("\n").filter((x) => x),
      settings.includeCurrentVaultOnlyFilesUnderCurrentDirectory
    );
    this.customDictionaryWordProvider.setSettings(
      settings.customDictionaryPaths.split("\n").filter((x) => x),
      ColumnDelimiter.fromName(settings.columnDelimiter),
      settings.delimiterToDivideSuggestionsForDisplayFromInsertion || null
    );
    this.debounceGetSuggestions = (0, import_obsidian3.debounce)(
      (context, cb) => {
        const start = performance.now();
        this.showDebugLog(() => `[context.query]: ${context.query}`);
        const parsedQuery = JSON.parse(context.query);
        const words = parsedQuery.queries.filter(
          (x, i, xs) => parsedQuery.currentFrontMatter || this.settings.minNumberOfWordsTriggeredPhrase + i - 1 < xs.length && x.word.length >= this.minNumberTriggered && !x.word.endsWith(" ")
        ).map((q) => {
          const handler = parsedQuery.currentFrontMatter && this.frontMatterComplementStrategy !== SpecificMatchStrategy.INHERIT ? this.frontMatterComplementStrategy.handler : this.matchStrategy.handler;
          return handler(
            this.indexedWords,
            q.word,
            this.settings.maxNumberOfSuggestions,
            {
              frontMatter: parsedQuery.currentFrontMatter,
              selectionHistoryStorage: this.selectionHistoryStorage
            }
          ).map((word) => ({ ...word, offset: q.offset }));
        }).flat();
        cb(
          uniqWith(words, suggestionUniqPredicate).slice(
            0,
            this.settings.maxNumberOfSuggestions
          )
        );
        this.showDebugLog(
          () => buildLogMessage("Get suggestions", performance.now() - start)
        );
      },
      this.settings.delayMilliSeconds,
      true
    );
    this.debounceClose = (0, import_obsidian3.debounce)(() => {
      this.close();
    }, this.settings.delayMilliSeconds + 50);
    this.registerKeymaps();
  }
  registerKeymaps() {
    const registerKeyAsIgnored = (modifiers, key) => {
      this.keymapEventHandler.push(
        this.scope.register(modifiers, key, () => {
          this.close();
          return true;
        })
      );
    };
    this.keymapEventHandler.forEach((x) => this.scope.unregister(x));
    this.keymapEventHandler = [];
    this.scope.unregister(this.scope.keys.find((x) => x.key === "Enter"));
    this.scope.unregister(this.scope.keys.find((x) => x.key === "ArrowUp"));
    this.scope.unregister(this.scope.keys.find((x) => x.key === "ArrowDown"));
    const selectSuggestionKey = SelectSuggestionKey.fromName(
      this.settings.selectSuggestionKeys
    );
    if (selectSuggestionKey !== SelectSuggestionKey.ENTER) {
      registerKeyAsIgnored(
        SelectSuggestionKey.ENTER.keyBind.modifiers,
        SelectSuggestionKey.ENTER.keyBind.key
      );
    }
    if (selectSuggestionKey !== SelectSuggestionKey.TAB) {
      registerKeyAsIgnored(
        SelectSuggestionKey.TAB.keyBind.modifiers,
        SelectSuggestionKey.TAB.keyBind.key
      );
    }
    if (selectSuggestionKey !== SelectSuggestionKey.None) {
      this.keymapEventHandler.push(
        this.scope.register(
          selectSuggestionKey.keyBind.modifiers,
          selectSuggestionKey.keyBind.key,
          () => {
            this.suggestions.useSelectedItem({});
            return false;
          }
        )
      );
    }
    this.scope.keys.find((x) => x.key === "Escape").func = () => {
      this.close();
      return this.settings.propagateEsc;
    };
    const selectNext = (evt) => {
      this.suggestions.setSelectedItem(this.suggestions.selectedItem + 1, evt);
      return false;
    };
    const selectPrevious = (evt) => {
      this.suggestions.setSelectedItem(this.suggestions.selectedItem - 1, evt);
      return false;
    };
    const cycleThroughSuggestionsKeys = CycleThroughSuggestionsKeys.fromName(
      this.settings.additionalCycleThroughSuggestionsKeys
    );
    if (this.settings.disableUpDownKeysForCycleThroughSuggestionsKeys) {
      this.keymapEventHandler.push(
        this.scope.register([], "ArrowDown", () => {
          this.close();
          return true;
        }),
        this.scope.register([], "ArrowUp", () => {
          this.close();
          return true;
        })
      );
    } else {
      this.keymapEventHandler.push(
        this.scope.register([], "ArrowDown", selectNext),
        this.scope.register([], "ArrowUp", selectPrevious)
      );
    }
    if (cycleThroughSuggestionsKeys !== CycleThroughSuggestionsKeys.NONE) {
      if (cycleThroughSuggestionsKeys === CycleThroughSuggestionsKeys.TAB) {
        this.scope.unregister(
          this.scope.keys.find((x) => x.modifiers === "" && x.key === "Tab")
        );
      }
      this.keymapEventHandler.push(
        this.scope.register(
          cycleThroughSuggestionsKeys.nextKey.modifiers,
          cycleThroughSuggestionsKeys.nextKey.key,
          selectNext
        ),
        this.scope.register(
          cycleThroughSuggestionsKeys.previousKey.modifiers,
          cycleThroughSuggestionsKeys.previousKey.key,
          selectPrevious
        )
      );
    }
    const openSourceFileKey = OpenSourceFileKeys.fromName(
      this.settings.openSourceFileKey
    );
    if (openSourceFileKey !== OpenSourceFileKeys.NONE) {
      this.keymapEventHandler.push(
        this.scope.register(
          openSourceFileKey.keyBind.modifiers,
          openSourceFileKey.keyBind.key,
          () => {
            const item = this.suggestions.values[this.suggestions.selectedItem];
            if (item.type !== "currentVault" && item.type !== "internalLink" && item.type !== "frontMatter") {
              return false;
            }
            const markdownFile = this.appHelper.getMarkdownFileByPath(
              item.createdPath
            );
            if (!markdownFile) {
              new import_obsidian3.Notice(`Can't open ${item.createdPath}`);
              return false;
            }
            this.appHelper.openMarkdownFile(markdownFile, true);
            return false;
          }
        )
      );
    }
  }
  async refreshCurrentFileTokens() {
    const start = performance.now();
    this.statusBar.setCurrentFileIndexing();
    if (!this.settings.enableCurrentFileComplement) {
      this.statusBar.setCurrentFileDisabled();
      this.currentFileWordProvider.clearWords();
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462} Skip: Index current file tokens",
          performance.now() - start
        )
      );
      return;
    }
    await this.currentFileWordProvider.refreshWords(
      this.settings.onlyComplementEnglishOnCurrentFileComplement,
      this.currentFileMinNumberOfCharacters
    );
    this.statusBar.setCurrentFileIndexed(
      this.currentFileWordProvider.wordCount
    );
    this.showDebugLog(
      () => buildLogMessage("Index current file tokens", performance.now() - start)
    );
  }
  async refreshCurrentVaultTokens() {
    const start = performance.now();
    this.statusBar.setCurrentVaultIndexing();
    if (!this.settings.enableCurrentVaultComplement) {
      this.statusBar.setCurrentVaultDisabled();
      this.currentVaultWordProvider.clearWords();
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462} Skip: Index current vault tokens",
          performance.now() - start
        )
      );
      return;
    }
    await this.currentVaultWordProvider.refreshWords(
      this.currentVaultMinNumberOfCharacters
    );
    this.statusBar.setCurrentVaultIndexed(
      this.currentVaultWordProvider.wordCount
    );
    this.showDebugLog(
      () => buildLogMessage("Index current vault tokens", performance.now() - start)
    );
  }
  async refreshCustomDictionaryTokens() {
    const start = performance.now();
    this.statusBar.setCustomDictionaryIndexing();
    if (!this.settings.enableCustomDictionaryComplement) {
      this.statusBar.setCustomDictionaryDisabled();
      this.customDictionaryWordProvider.clearWords();
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462}Skip: Index custom dictionary tokens",
          performance.now() - start
        )
      );
      return;
    }
    await this.customDictionaryWordProvider.refreshCustomWords({
      regexp: this.settings.customDictionaryWordRegexPattern,
      delimiterForHide: this.settings.delimiterToHideSuggestion || void 0,
      delimiterForDisplay: this.settings.delimiterToDivideSuggestionsForDisplayFromInsertion || void 0,
      caretSymbol: this.settings.caretLocationSymbolAfterComplement || void 0
    });
    this.statusBar.setCustomDictionaryIndexed(
      this.customDictionaryWordProvider.wordCount
    );
    this.showDebugLog(
      () => buildLogMessage(
        "Index custom dictionary tokens",
        performance.now() - start
      )
    );
  }
  refreshInternalLinkTokens() {
    const start = performance.now();
    this.statusBar.setInternalLinkIndexing();
    if (!this.settings.enableInternalLinkComplement) {
      this.statusBar.setInternalLinkDisabled();
      this.internalLinkWordProvider.clearWords();
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462}Skip: Index internal link tokens",
          performance.now() - start
        )
      );
      return;
    }
    this.internalLinkWordProvider.refreshWords(
      this.settings.suggestInternalLinkWithAlias,
      this.excludeInternalLinkPrefixPathPatterns
    );
    this.statusBar.setInternalLinkIndexed(
      this.internalLinkWordProvider.wordCount
    );
    this.showDebugLog(
      () => buildLogMessage("Index internal link tokens", performance.now() - start)
    );
  }
  refreshFrontMatterTokens() {
    const start = performance.now();
    this.statusBar.setFrontMatterIndexing();
    if (!this.settings.enableFrontMatterComplement) {
      this.statusBar.setFrontMatterDisabled();
      this.frontMatterWordProvider.clearWords();
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462}Skip: Index front matter tokens",
          performance.now() - start
        )
      );
      return;
    }
    this.frontMatterWordProvider.refreshWords();
    this.statusBar.setFrontMatterIndexed(
      this.frontMatterWordProvider.wordCount
    );
    this.showDebugLog(
      () => buildLogMessage("Index front matter tokens", performance.now() - start)
    );
  }
  updateFrontMatterTokenIndex(file) {
    const start = performance.now();
    if (!this.settings.enableFrontMatterComplement) {
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462}Skip: Update front matter token index",
          performance.now() - start
        )
      );
      return;
    }
    this.frontMatterWordProvider.updateWordIndex(file);
    this.showDebugLog(
      () => buildLogMessage(
        "Update front matter token index",
        performance.now() - start
      )
    );
  }
  updateFrontMatterToken() {
    const start = performance.now();
    if (!this.settings.enableFrontMatterComplement) {
      this.showDebugLog(
        () => buildLogMessage(
          "\u{1F462}Skip: Update front matter token",
          performance.now() - start
        )
      );
      return;
    }
    this.frontMatterWordProvider.updateWords();
    this.statusBar.setFrontMatterIndexed(
      this.frontMatterWordProvider.wordCount
    );
    this.showDebugLog(
      () => buildLogMessage("Update front matter token", performance.now() - start)
    );
  }
  onTrigger(cursor, editor, file) {
    var _a, _b, _c, _d, _e, _f;
    const start = performance.now();
    const showDebugLog = (message) => {
      this.showDebugLog(() => `[onTrigger] ${message}`);
    };
    const onReturnNull = (message) => {
      showDebugLog(message);
      this.runManually = false;
      this.close();
    };
    if (!this.settings.complementAutomatically && !this.isOpen && !this.runManually) {
      onReturnNull("Don't show suggestions");
      return null;
    }
    if (this.settings.disableSuggestionsDuringImeOn && this.appHelper.isIMEOn() && !this.runManually) {
      onReturnNull("Don't show suggestions for IME");
      return null;
    }
    const cl = this.appHelper.getCurrentLine(editor);
    if (this.previousCurrentLine === cl && !this.runManually) {
      this.previousCurrentLine = cl;
      onReturnNull("Don't show suggestions because there are no changes");
      return null;
    }
    this.previousCurrentLine = cl;
    const currentLineUntilCursor = this.appHelper.getCurrentLineUntilCursor(editor);
    if (currentLineUntilCursor.startsWith("---")) {
      onReturnNull(
        "Don't show suggestions because it supposes front matter or horizontal line"
      );
      return null;
    }
    if (currentLineUntilCursor.startsWith("~~~") || currentLineUntilCursor.startsWith("```")) {
      onReturnNull(
        "Don't show suggestions because it supposes front code block"
      );
      return null;
    }
    const tokens = this.tokenizer.tokenize(currentLineUntilCursor, true);
    showDebugLog(`tokens is ${tokens}`);
    const tokenized = this.tokenizer.recursiveTokenize(currentLineUntilCursor);
    const currentTokens = tokenized.slice(
      tokenized.length > this.settings.maxNumberOfWordsAsPhrase ? tokenized.length - this.settings.maxNumberOfWordsAsPhrase : 0
    );
    showDebugLog(`currentTokens is ${JSON.stringify(currentTokens)}`);
    const currentToken = (_a = currentTokens[0]) == null ? void 0 : _a.word;
    showDebugLog(`currentToken is ${currentToken}`);
    if (!currentToken) {
      onReturnNull(`Don't show suggestions because currentToken is empty`);
      return null;
    }
    const currentTokenSeparatedWhiteSpace = (_b = currentLineUntilCursor.split(" ").last()) != null ? _b : "";
    if (new RegExp(`^[${this.settings.firstCharactersDisableSuggestions}]`).test(
      currentTokenSeparatedWhiteSpace
    )) {
      onReturnNull(
        `Don't show suggestions for avoiding to conflict with the other commands.`
      );
      return null;
    }
    if (currentToken.length === 1 && Boolean(currentToken.match(this.tokenizer.getTrimPattern()))) {
      onReturnNull(
        `Don't show suggestions because currentToken is TRIM_PATTERN`
      );
      return null;
    }
    const currentFrontMatter = this.settings.enableFrontMatterComplement ? this.appHelper.getCurrentFrontMatter() : void 0;
    showDebugLog(`Current front matter is ${currentFrontMatter}`);
    if (!this.runManually && !currentFrontMatter && currentToken.length < this.minNumberTriggered) {
      onReturnNull(
        "Don't show suggestions because currentToken is less than minNumberTriggered option"
      );
      return null;
    }
    showDebugLog(buildLogMessage("onTrigger", performance.now() - start));
    this.runManually = false;
    if (currentFrontMatter && ((_c = currentTokens.last()) == null ? void 0 : _c.word.match(/[^ ] $/))) {
      currentTokens.push({ word: "", offset: currentLineUntilCursor.length });
    }
    this.contextStartCh = cursor.ch - currentToken.length;
    return {
      start: {
        ch: cursor.ch - ((_f = (_e = (_d = currentTokens.last()) == null ? void 0 : _d.word) == null ? void 0 : _e.length) != null ? _f : 0),
        line: cursor.line
      },
      end: cursor,
      query: JSON.stringify({
        currentFrontMatter,
        queries: currentTokens.map((x) => ({
          ...x,
          offset: x.offset - currentTokens[0].offset
        }))
      })
    };
  }
  getSuggestions(context) {
    return new Promise((resolve) => {
      this.debounceGetSuggestions(context, (words) => {
        resolve(words);
      });
    });
  }
  renderSuggestion(word, el) {
    const base = createDiv();
    let text2 = word.value;
    if (word.type === "customDictionary" && word.insertedText && this.settings.displayedTextSuffix) {
      text2 += this.settings.displayedTextSuffix;
    }
    base.createDiv({
      text: text2,
      cls: word.type === "internalLink" && word.aliasMeta ? "various-complements__suggestion-item__content__alias" : void 0
    });
    const description = this.descriptionOnSuggestion.toDisplay(word);
    if (description) {
      base.createDiv({
        cls: "various-complements__suggestion-item__description",
        text: `${description}`
      });
    }
    el.appendChild(base);
    el.addClass("various-complements__suggestion-item");
    switch (word.type) {
      case "currentFile":
        el.addClass("various-complements__suggestion-item__current-file");
        break;
      case "currentVault":
        el.addClass("various-complements__suggestion-item__current-vault");
        break;
      case "customDictionary":
        el.addClass("various-complements__suggestion-item__custom-dictionary");
        break;
      case "internalLink":
        el.addClass("various-complements__suggestion-item__internal-link");
        if (word.phantom) {
          el.addClass("various-complements__suggestion-item__phantom");
        }
        break;
      case "frontMatter":
        el.addClass("various-complements__suggestion-item__front-matter");
        break;
    }
  }
  selectSuggestion(word, evt) {
    var _a, _b;
    if (!this.context) {
      return;
    }
    let insertedText = word.value;
    if (word.type === "internalLink") {
      if (this.settings.suggestInternalLinkWithAlias && word.aliasMeta) {
        const linkText = this.appHelper.optimizeMarkdownLinkText(
          word.aliasMeta.origin
        );
        insertedText = this.appHelper.useWikiLinks ? `[[${linkText}|${word.value}]]` : `[${word.value}](${encodeSpace(linkText)}.md)`;
      } else {
        const linkText = this.appHelper.optimizeMarkdownLinkText(
          word.phantom ? word.value : word.createdPath
        );
        insertedText = this.appHelper.useWikiLinks ? `[[${linkText}]]` : `[${linkText}](${encodeSpace(linkText)}.md)`;
      }
    }
    if (word.type === "frontMatter" && this.settings.insertCommaAfterFrontMatterCompletion) {
      insertedText = `${insertedText}, `;
    } else {
      if (this.settings.insertAfterCompletion && !(word.type === "customDictionary" && word.ignoreSpaceAfterCompletion)) {
        insertedText = `${insertedText} `;
      }
    }
    let positionToMove = -1;
    if (word.type === "customDictionary") {
      if (word.insertedText) {
        insertedText = word.insertedText;
      }
      const caret = word.caretSymbol;
      if (caret) {
        positionToMove = insertedText.indexOf(caret);
        insertedText = insertedText.replace(caret, "");
      }
    }
    const editor = this.context.editor;
    editor.replaceRange(
      insertedText,
      {
        ...this.context.start,
        ch: this.contextStartCh + word.offset
      },
      this.context.end
    );
    if (positionToMove !== -1) {
      editor.setCursor(
        editor.offsetToPos(
          editor.posToOffset(editor.getCursor()) - insertedText.length + positionToMove
        )
      );
    }
    if (this.appHelper.equalsAsEditorPostion(this.context.start, this.context.end)) {
      editor.setCursor(
        editor.offsetToPos(
          editor.posToOffset(editor.getCursor()) + insertedText.length
        )
      );
    }
    (_a = this.selectionHistoryStorage) == null ? void 0 : _a.increment(word);
    if (this.settings.showLogAboutPerformanceInConsole) {
      console.log("--- history ---");
      console.log((_b = this.selectionHistoryStorage) == null ? void 0 : _b.data);
    }
    this.close();
    this.debounceClose();
  }
  showDebugLog(toMessage) {
    if (this.settings.showLogAboutPerformanceInConsole) {
      console.log(toMessage());
    }
  }
};

// src/setting/settings.ts
var import_obsidian4 = require("obsidian");
var DEFAULT_SETTINGS = {
  strategy: "default",
  matchStrategy: "prefix",
  maxNumberOfSuggestions: 5,
  maxNumberOfWordsAsPhrase: 3,
  minNumberOfCharactersTriggered: 0,
  minNumberOfWordsTriggeredPhrase: 1,
  complementAutomatically: true,
  delayMilliSeconds: 0,
  disableSuggestionsDuringImeOn: false,
  insertAfterCompletion: true,
  firstCharactersDisableSuggestions: ":/^",
  showMatchStrategy: true,
  showComplementAutomatically: true,
  showIndexingStatus: true,
  descriptionOnSuggestion: "Short",
  selectSuggestionKeys: "Enter",
  additionalCycleThroughSuggestionsKeys: "None",
  disableUpDownKeysForCycleThroughSuggestionsKeys: false,
  openSourceFileKey: "None",
  propagateEsc: false,
  enableCurrentFileComplement: true,
  currentFileMinNumberOfCharacters: 0,
  onlyComplementEnglishOnCurrentFileComplement: false,
  enableCurrentVaultComplement: false,
  currentVaultMinNumberOfCharacters: 0,
  includeCurrentVaultPathPrefixPatterns: "",
  excludeCurrentVaultPathPrefixPatterns: "",
  includeCurrentVaultOnlyFilesUnderCurrentDirectory: false,
  enableCustomDictionaryComplement: false,
  customDictionaryPaths: `https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english-no-swears.txt`,
  columnDelimiter: "Tab",
  customDictionaryWordRegexPattern: "",
  delimiterToHideSuggestion: "",
  delimiterToDivideSuggestionsForDisplayFromInsertion: "",
  caretLocationSymbolAfterComplement: "",
  displayedTextSuffix: " => ...",
  enableInternalLinkComplement: true,
  suggestInternalLinkWithAlias: false,
  excludeInternalLinkPathPrefixPatterns: "",
  enableFrontMatterComplement: true,
  frontMatterComplementMatchStrategy: "inherit",
  insertCommaAfterFrontMatterCompletion: false,
  intelligentSuggestionPrioritization: {
    maxDaysToKeepHistory: 30,
    maxNumberOfHistoryToKeep: 0
  },
  showLogAboutPerformanceInConsole: false,
  selectionHistoryTree: {}
};
var VariousComplementsSettingTab = class extends import_obsidian4.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.plugin = plugin;
  }
  display() {
    let { containerEl } = this;
    containerEl.empty();
    containerEl.createEl("h2", { text: "Various Complements - Settings" });
    this.addMainSettings(containerEl);
    this.addAppearanceSettings(containerEl);
    this.addKeyCustomizationSettings(containerEl);
    this.addCurrentFileComplementSettings(containerEl);
    this.addCurrentVaultComplementSettings(containerEl);
    this.addCustomDictionaryComplementSettings(containerEl);
    this.addInternalLinkComplementSettings(containerEl);
    this.addFrontMatterComplementSettings(containerEl);
    this.addIntelligentSuggestionPrioritizationSettings(containerEl);
    this.addDebugSettings(containerEl);
  }
  addMainSettings(containerEl) {
    containerEl.createEl("h3", { text: "Main" });
    new import_obsidian4.Setting(containerEl).setName("Strategy").addDropdown(
      (tc) => tc.addOptions(mirrorMap(TokenizeStrategy.values(), (x) => x.name)).setValue(this.plugin.settings.strategy).onChange(async (value) => {
        this.plugin.settings.strategy = value;
        this.display();
        await this.plugin.saveSettings({
          currentFile: true,
          currentVault: true
        });
      })
    );
    if (this.plugin.settings.strategy === TokenizeStrategy.CHINESE.name) {
      const el = containerEl.createEl("div", {
        cls: "various-complements__settings__warning"
      });
      el.createSpan({
        text: "\u26A0 You need to download `cedict_ts.u8` from"
      });
      el.createEl("a", {
        href: "https://www.mdbg.net/chinese/dictionary?page=cc-cedict",
        text: " the site "
      });
      el.createSpan({
        text: "and store it in vault root."
      });
    }
    new import_obsidian4.Setting(containerEl).setName("Match strategy").addDropdown(
      (tc) => tc.addOptions(mirrorMap(MatchStrategy.values(), (x) => x.name)).setValue(this.plugin.settings.matchStrategy).onChange(async (value) => {
        this.plugin.settings.matchStrategy = value;
        await this.plugin.saveSettings();
        this.display();
      })
    );
    if (this.plugin.settings.matchStrategy === MatchStrategy.PARTIAL.name) {
      containerEl.createEl("div", {
        text: "\u26A0 `partial` is more than 10 times slower than `prefix`",
        cls: "various-complements__settings__warning"
      });
    }
    new import_obsidian4.Setting(containerEl).setName("Max number of suggestions").addSlider(
      (sc) => sc.setLimits(1, 255, 1).setValue(this.plugin.settings.maxNumberOfSuggestions).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.maxNumberOfSuggestions = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Max number of words as a phrase").setDesc(`[\u26A0Warning] It makes slower more than N times (N is set value)`).addSlider(
      (sc) => sc.setLimits(1, 10, 1).setValue(this.plugin.settings.maxNumberOfWordsAsPhrase).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.maxNumberOfWordsAsPhrase = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Min number of characters for trigger").setDesc("It uses a default value of Strategy if set 0.").addSlider(
      (sc) => sc.setLimits(0, 10, 1).setValue(this.plugin.settings.minNumberOfCharactersTriggered).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.minNumberOfCharactersTriggered = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Min number of words for trigger").addSlider(
      (sc) => sc.setLimits(1, 10, 1).setValue(this.plugin.settings.minNumberOfWordsTriggeredPhrase).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.minNumberOfWordsTriggeredPhrase = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Complement automatically").addToggle((tc) => {
      tc.setValue(this.plugin.settings.complementAutomatically).onChange(
        async (value) => {
          this.plugin.settings.complementAutomatically = value;
          await this.plugin.saveSettings();
        }
      );
    });
    new import_obsidian4.Setting(containerEl).setName("Delay milli-seconds for trigger").addSlider(
      (sc) => sc.setLimits(0, 1e3, 10).setValue(this.plugin.settings.delayMilliSeconds).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.delayMilliSeconds = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Disable suggestions during IME on").addToggle((tc) => {
      tc.setValue(
        this.plugin.settings.disableSuggestionsDuringImeOn
      ).onChange(async (value) => {
        this.plugin.settings.disableSuggestionsDuringImeOn = value;
        await this.plugin.saveSettings();
      });
    });
    new import_obsidian4.Setting(containerEl).setName("Insert space after completion").addToggle((tc) => {
      tc.setValue(this.plugin.settings.insertAfterCompletion).onChange(
        async (value) => {
          this.plugin.settings.insertAfterCompletion = value;
          await this.plugin.saveSettings();
        }
      );
    });
    new import_obsidian4.Setting(containerEl).setName("First characters to disable suggestions").addText((cb) => {
      cb.setValue(
        this.plugin.settings.firstCharactersDisableSuggestions
      ).onChange(async (value) => {
        this.plugin.settings.firstCharactersDisableSuggestions = value;
        await this.plugin.saveSettings();
      });
    });
  }
  addAppearanceSettings(containerEl) {
    containerEl.createEl("h3", { text: "Appearance" });
    new import_obsidian4.Setting(containerEl).setName("Show Match strategy").setDesc(
      "Show Match strategy at the status bar. Changing this option requires a restart to take effect."
    ).addToggle((tc) => {
      tc.setValue(this.plugin.settings.showMatchStrategy).onChange(
        async (value) => {
          this.plugin.settings.showMatchStrategy = value;
          await this.plugin.saveSettings();
        }
      );
    });
    new import_obsidian4.Setting(containerEl).setName("Show Complement automatically").setDesc(
      "Show complement automatically at the status bar. Changing this option requires a restart to take effect."
    ).addToggle((tc) => {
      tc.setValue(this.plugin.settings.showComplementAutomatically).onChange(
        async (value) => {
          this.plugin.settings.showComplementAutomatically = value;
          await this.plugin.saveSettings();
        }
      );
    });
    new import_obsidian4.Setting(containerEl).setName("Show Indexing status").setDesc(
      "Show indexing status at the status bar. Changing this option requires a restart to take effect."
    ).addToggle((tc) => {
      tc.setValue(this.plugin.settings.showIndexingStatus).onChange(
        async (value) => {
          this.plugin.settings.showIndexingStatus = value;
          await this.plugin.saveSettings();
        }
      );
    });
    new import_obsidian4.Setting(containerEl).setName("Description on a suggestion").addDropdown(
      (tc) => tc.addOptions(
        mirrorMap(DescriptionOnSuggestion.values(), (x) => x.name)
      ).setValue(this.plugin.settings.descriptionOnSuggestion).onChange(async (value) => {
        this.plugin.settings.descriptionOnSuggestion = value;
        await this.plugin.saveSettings();
      })
    );
  }
  addKeyCustomizationSettings(containerEl) {
    containerEl.createEl("h3", { text: "Key customization" });
    new import_obsidian4.Setting(containerEl).setName("Select a suggestion key").addDropdown(
      (tc) => tc.addOptions(mirrorMap(SelectSuggestionKey.values(), (x) => x.name)).setValue(this.plugin.settings.selectSuggestionKeys).onChange(async (value) => {
        this.plugin.settings.selectSuggestionKeys = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Additional cycle through suggestions keys").addDropdown(
      (tc) => tc.addOptions(
        mirrorMap(CycleThroughSuggestionsKeys.values(), (x) => x.name)
      ).setValue(this.plugin.settings.additionalCycleThroughSuggestionsKeys).onChange(async (value) => {
        this.plugin.settings.additionalCycleThroughSuggestionsKeys = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Disable the up/down keys for cycle through suggestions keys").addToggle((tc) => {
      tc.setValue(
        this.plugin.settings.disableUpDownKeysForCycleThroughSuggestionsKeys
      ).onChange(async (value) => {
        this.plugin.settings.disableUpDownKeysForCycleThroughSuggestionsKeys = value;
        await this.plugin.saveSettings();
      });
    });
    new import_obsidian4.Setting(containerEl).setName("Open source file key").addDropdown(
      (tc) => tc.addOptions(mirrorMap(OpenSourceFileKeys.values(), (x) => x.name)).setValue(this.plugin.settings.openSourceFileKey).onChange(async (value) => {
        this.plugin.settings.openSourceFileKey = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Propagate ESC").setDesc(
      "It is handy if you use Vim mode because you can switch to Normal mode by one ESC, whether it shows suggestions or not."
    ).addToggle((tc) => {
      tc.setValue(this.plugin.settings.propagateEsc).onChange(
        async (value) => {
          this.plugin.settings.propagateEsc = value;
          await this.plugin.saveSettings();
        }
      );
    });
  }
  addCurrentFileComplementSettings(containerEl) {
    containerEl.createEl("h3", {
      text: "Current file complement",
      cls: "various-complements__settings__header various-complements__settings__header__current-file"
    });
    new import_obsidian4.Setting(containerEl).setName("Enable Current file complement").addToggle((tc) => {
      tc.setValue(this.plugin.settings.enableCurrentFileComplement).onChange(
        async (value) => {
          this.plugin.settings.enableCurrentFileComplement = value;
          await this.plugin.saveSettings({ currentFile: true });
          this.display();
        }
      );
    });
    if (this.plugin.settings.enableCurrentFileComplement) {
      new import_obsidian4.Setting(containerEl).setName("Min number of characters for indexing").setDesc("It uses a default value of Strategy if set 0.").addSlider(
        (sc) => sc.setLimits(0, 15, 1).setValue(this.plugin.settings.currentFileMinNumberOfCharacters).setDynamicTooltip().onChange(async (value) => {
          this.plugin.settings.currentFileMinNumberOfCharacters = value;
          await this.plugin.saveSettings({ currentFile: true });
        })
      );
      new import_obsidian4.Setting(containerEl).setName("Only complement English on current file complement").addToggle((tc) => {
        tc.setValue(
          this.plugin.settings.onlyComplementEnglishOnCurrentFileComplement
        ).onChange(async (value) => {
          this.plugin.settings.onlyComplementEnglishOnCurrentFileComplement = value;
          await this.plugin.saveSettings({ currentFile: true });
        });
      });
    }
  }
  addCurrentVaultComplementSettings(containerEl) {
    containerEl.createEl("h3", {
      text: "Current vault complement",
      cls: "various-complements__settings__header various-complements__settings__header__current-vault"
    });
    new import_obsidian4.Setting(containerEl).setName("Enable Current vault complement").addToggle((tc) => {
      tc.setValue(this.plugin.settings.enableCurrentVaultComplement).onChange(
        async (value) => {
          this.plugin.settings.enableCurrentVaultComplement = value;
          this.display();
          await this.plugin.saveSettings({ currentVault: true });
        }
      );
    });
    if (this.plugin.settings.enableCurrentVaultComplement) {
      new import_obsidian4.Setting(containerEl).setName("Min number of characters for indexing").setDesc("It uses a default value of Strategy if set 0.").addSlider(
        (sc) => sc.setLimits(0, 15, 1).setValue(this.plugin.settings.currentVaultMinNumberOfCharacters).setDynamicTooltip().onChange(async (value) => {
          this.plugin.settings.currentVaultMinNumberOfCharacters = value;
          await this.plugin.saveSettings();
        })
      );
      new import_obsidian4.Setting(containerEl).setName("Include prefix path patterns").setDesc("Prefix match path patterns to include files.").addTextArea((tac) => {
        const el = tac.setValue(
          this.plugin.settings.includeCurrentVaultPathPrefixPatterns
        ).setPlaceholder("Private/").onChange(async (value) => {
          this.plugin.settings.includeCurrentVaultPathPrefixPatterns = value;
          await this.plugin.saveSettings();
        });
        el.inputEl.className = "various-complements__settings__text-area-path";
        return el;
      });
      new import_obsidian4.Setting(containerEl).setName("Exclude prefix path patterns").setDesc("Prefix match path patterns to exclude files.").addTextArea((tac) => {
        const el = tac.setValue(
          this.plugin.settings.excludeCurrentVaultPathPrefixPatterns
        ).setPlaceholder("Private/").onChange(async (value) => {
          this.plugin.settings.excludeCurrentVaultPathPrefixPatterns = value;
          await this.plugin.saveSettings();
        });
        el.inputEl.className = "various-complements__settings__text-area-path";
        return el;
      });
      new import_obsidian4.Setting(containerEl).setName("Include only files under current directory").addToggle((tc) => {
        tc.setValue(
          this.plugin.settings.includeCurrentVaultOnlyFilesUnderCurrentDirectory
        ).onChange(async (value) => {
          this.plugin.settings.includeCurrentVaultOnlyFilesUnderCurrentDirectory = value;
          await this.plugin.saveSettings();
        });
      });
    }
  }
  addCustomDictionaryComplementSettings(containerEl) {
    containerEl.createEl("h3", {
      text: "Custom dictionary complement",
      cls: "various-complements__settings__header various-complements__settings__header__custom-dictionary"
    });
    new import_obsidian4.Setting(containerEl).setName("Enable Custom dictionary complement").addToggle((tc) => {
      tc.setValue(
        this.plugin.settings.enableCustomDictionaryComplement
      ).onChange(async (value) => {
        this.plugin.settings.enableCustomDictionaryComplement = value;
        await this.plugin.saveSettings({ customDictionary: true });
        this.display();
      });
    });
    if (this.plugin.settings.enableCustomDictionaryComplement) {
      new import_obsidian4.Setting(containerEl).setName("Custom dictionary paths").setDesc(
        "Specify either a relative path from Vault root or URL for each line."
      ).addTextArea((tac) => {
        const el = tac.setValue(this.plugin.settings.customDictionaryPaths).setPlaceholder("dictionary.md").onChange(async (value) => {
          this.plugin.settings.customDictionaryPaths = value;
          await this.plugin.saveSettings();
        });
        el.inputEl.className = "various-complements__settings__text-area-path";
        return el;
      });
      new import_obsidian4.Setting(containerEl).setName("Column delimiter").addDropdown(
        (tc) => tc.addOptions(mirrorMap(ColumnDelimiter.values(), (x) => x.name)).setValue(this.plugin.settings.columnDelimiter).onChange(async (value) => {
          this.plugin.settings.columnDelimiter = value;
          await this.plugin.saveSettings();
        })
      );
      new import_obsidian4.Setting(containerEl).setName("Word regex pattern").setDesc("Only load words that match the regular expression pattern.").addText((cb) => {
        cb.setValue(
          this.plugin.settings.customDictionaryWordRegexPattern
        ).onChange(async (value) => {
          this.plugin.settings.customDictionaryWordRegexPattern = value;
          await this.plugin.saveSettings();
        });
      });
      new import_obsidian4.Setting(containerEl).setName("Delimiter to hide a suggestion").setDesc(
        "If set ';;;', 'abcd;;;efg' is shown as 'abcd' on suggestions, but completes to 'abcdefg'."
      ).addText((cb) => {
        cb.setValue(this.plugin.settings.delimiterToHideSuggestion).onChange(
          async (value) => {
            this.plugin.settings.delimiterToHideSuggestion = value;
            await this.plugin.saveSettings();
          }
        );
      });
      new import_obsidian4.Setting(containerEl).setName(
        "Delimiter to divide suggestions for display from ones for insertion"
      ).setDesc(
        "If set ' >>> ', 'displayed >>> inserted' is shown as 'displayed' on suggestions, but completes to 'inserted'."
      ).addText((cb) => {
        cb.setValue(
          this.plugin.settings.delimiterToDivideSuggestionsForDisplayFromInsertion
        ).onChange(async (value) => {
          this.plugin.settings.delimiterToDivideSuggestionsForDisplayFromInsertion = value;
          await this.plugin.saveSettings();
        });
      });
      new import_obsidian4.Setting(containerEl).setName("Caret location symbol after complement").setDesc(
        "If set '<CARET>' and there is '<li><CARET></li>' in custom dictionary, it complements '<li></li>' and move a caret where between '<li>' and `</li>`."
      ).addText((cb) => {
        cb.setValue(
          this.plugin.settings.caretLocationSymbolAfterComplement
        ).onChange(async (value) => {
          this.plugin.settings.caretLocationSymbolAfterComplement = value;
          await this.plugin.saveSettings();
        });
      });
      new import_obsidian4.Setting(containerEl).setName("Displayed text suffix").setDesc(
        "It shows as a suffix of displayed text if there is a difference between displayed and inserted"
      ).addText((cb) => {
        cb.setValue(this.plugin.settings.displayedTextSuffix).onChange(
          async (value) => {
            this.plugin.settings.displayedTextSuffix = value;
            await this.plugin.saveSettings();
          }
        );
      });
    }
  }
  addInternalLinkComplementSettings(containerEl) {
    containerEl.createEl("h3", {
      text: "Internal link complement",
      cls: "various-complements__settings__header various-complements__settings__header__internal-link"
    });
    new import_obsidian4.Setting(containerEl).setName("Enable Internal link complement").addToggle((tc) => {
      tc.setValue(this.plugin.settings.enableInternalLinkComplement).onChange(
        async (value) => {
          this.plugin.settings.enableInternalLinkComplement = value;
          await this.plugin.saveSettings({ internalLink: true });
          this.display();
        }
      );
    });
    if (this.plugin.settings.enableInternalLinkComplement) {
      new import_obsidian4.Setting(containerEl).setName("Suggest with an alias").addToggle((tc) => {
        tc.setValue(
          this.plugin.settings.suggestInternalLinkWithAlias
        ).onChange(async (value) => {
          this.plugin.settings.suggestInternalLinkWithAlias = value;
          await this.plugin.saveSettings({ internalLink: true });
        });
      });
      new import_obsidian4.Setting(containerEl).setName("Exclude prefix path patterns").setDesc("Prefix match path patterns to exclude files.").addTextArea((tac) => {
        const el = tac.setValue(
          this.plugin.settings.excludeInternalLinkPathPrefixPatterns
        ).setPlaceholder("Private/").onChange(async (value) => {
          this.plugin.settings.excludeInternalLinkPathPrefixPatterns = value;
          await this.plugin.saveSettings();
        });
        el.inputEl.className = "various-complements__settings__text-area-path";
        return el;
      });
    }
  }
  addFrontMatterComplementSettings(containerEl) {
    containerEl.createEl("h3", {
      text: "Front matter complement",
      cls: "various-complements__settings__header various-complements__settings__header__front-matter"
    });
    new import_obsidian4.Setting(containerEl).setName("Enable Front matter complement").addToggle((tc) => {
      tc.setValue(this.plugin.settings.enableFrontMatterComplement).onChange(
        async (value) => {
          this.plugin.settings.enableFrontMatterComplement = value;
          await this.plugin.saveSettings({ frontMatter: true });
          this.display();
        }
      );
    });
    if (this.plugin.settings.enableFrontMatterComplement) {
      new import_obsidian4.Setting(containerEl).setName("Match strategy in the front matter").addDropdown(
        (tc) => tc.addOptions(
          mirrorMap(SpecificMatchStrategy.values(), (x) => x.name)
        ).setValue(this.plugin.settings.frontMatterComplementMatchStrategy).onChange(async (value) => {
          this.plugin.settings.frontMatterComplementMatchStrategy = value;
          await this.plugin.saveSettings();
        })
      );
      new import_obsidian4.Setting(containerEl).setName("Insert comma after completion").addToggle((tc) => {
        tc.setValue(
          this.plugin.settings.insertCommaAfterFrontMatterCompletion
        ).onChange(async (value) => {
          this.plugin.settings.insertCommaAfterFrontMatterCompletion = value;
          await this.plugin.saveSettings();
        });
      });
    }
  }
  addIntelligentSuggestionPrioritizationSettings(containerEl) {
    containerEl.createEl("h3", {
      text: "Intelligent suggestion prioritization",
      cls: "various-complements__settings__header various-complements__settings__header__intelligent-suggestion-prioritization"
    });
    new import_obsidian4.Setting(containerEl).setName("Max days to keep history").setDesc("If set 0, it will never remove").addSlider(
      (sc) => sc.setLimits(0, 365, 1).setValue(
        this.plugin.settings.intelligentSuggestionPrioritization.maxDaysToKeepHistory
      ).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.intelligentSuggestionPrioritization.maxDaysToKeepHistory = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian4.Setting(containerEl).setName("Max number of history to keep").setDesc("If set 0, it will never remove").addSlider(
      (sc) => sc.setLimits(0, 1e4, 1).setValue(
        this.plugin.settings.intelligentSuggestionPrioritization.maxNumberOfHistoryToKeep
      ).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.intelligentSuggestionPrioritization.maxNumberOfHistoryToKeep = value;
        await this.plugin.saveSettings();
      })
    );
  }
  addDebugSettings(containerEl) {
    containerEl.createEl("h3", { text: "Debug" });
    new import_obsidian4.Setting(containerEl).setName("Show log about performance in a console").addToggle((tc) => {
      tc.setValue(
        this.plugin.settings.showLogAboutPerformanceInConsole
      ).onChange(async (value) => {
        this.plugin.settings.showLogAboutPerformanceInConsole = value;
        await this.plugin.saveSettings();
      });
    });
  }
  async toggleMatchStrategy() {
    switch (this.plugin.settings.matchStrategy) {
      case "prefix":
        this.plugin.settings.matchStrategy = "partial";
        break;
      case "partial":
        this.plugin.settings.matchStrategy = "prefix";
        break;
      default:
        new import_obsidian4.Notice("\u26A0Unexpected error");
    }
    await this.plugin.saveSettings();
  }
  async toggleComplementAutomatically() {
    this.plugin.settings.complementAutomatically = !this.plugin.settings.complementAutomatically;
    await this.plugin.saveSettings();
  }
  async ensureCustomDictionaryPath(path, state) {
    const paths = this.plugin.settings.customDictionaryPaths.split("\n");
    const exists = paths.some((x) => x === path);
    if (exists && state === "present" || !exists && state === "absent") {
      return false;
    }
    const newPaths = state === "present" ? [...paths, path] : paths.filter((x) => x !== path);
    this.plugin.settings.customDictionaryPaths = newPaths.join("\n");
    await this.plugin.saveSettings({ customDictionary: true });
    return true;
  }
  getPluginSettingsAsJsonString() {
    return JSON.stringify(
      {
        version: this.plugin.manifest.version,
        mobile: this.app.isMobile,
        settings: { ...this.plugin.settings, selectionHistoryTree: null }
      },
      null,
      4
    );
  }
};

// src/ui/ProviderStatusBar.ts
var ProviderStatusBar = class {
  constructor(currentFile, currentVault, customDictionary, internalLink, frontMatter, matchStrategy, complementAutomatically) {
    this.currentFile = currentFile;
    this.currentVault = currentVault;
    this.customDictionary = customDictionary;
    this.internalLink = internalLink;
    this.frontMatter = frontMatter;
    this.matchStrategy = matchStrategy;
    this.complementAutomatically = complementAutomatically;
  }
  static new(statusBar, showMatchStrategy, showIndexingStatus, showComplementAutomatically) {
    const currentFile = showIndexingStatus ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__current-file"
    }) : null;
    const currentVault = showIndexingStatus ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__current-vault"
    }) : null;
    const customDictionary = showIndexingStatus ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__custom-dictionary"
    }) : null;
    const internalLink = showIndexingStatus ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__internal-link"
    }) : null;
    const frontMatter = showIndexingStatus ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__front-matter"
    }) : null;
    const matchStrategy = showMatchStrategy ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__match-strategy"
    }) : null;
    const complementAutomatically = showComplementAutomatically ? statusBar.createEl("span", {
      text: "---",
      cls: "various-complements__footer various-complements__footer__complement-automatically"
    }) : null;
    return new ProviderStatusBar(
      currentFile,
      currentVault,
      customDictionary,
      internalLink,
      frontMatter,
      matchStrategy,
      complementAutomatically
    );
  }
  setOnClickStrategyListener(listener) {
    var _a;
    (_a = this.matchStrategy) == null ? void 0 : _a.addEventListener("click", listener);
  }
  setOnClickComplementAutomatically(listener) {
    var _a;
    (_a = this.complementAutomatically) == null ? void 0 : _a.addEventListener("click", listener);
  }
  setCurrentFileDisabled() {
    var _a;
    (_a = this.currentFile) == null ? void 0 : _a.setText("---");
  }
  setCurrentVaultDisabled() {
    var _a;
    (_a = this.currentVault) == null ? void 0 : _a.setText("---");
  }
  setCustomDictionaryDisabled() {
    var _a;
    (_a = this.customDictionary) == null ? void 0 : _a.setText("---");
  }
  setInternalLinkDisabled() {
    var _a;
    (_a = this.internalLink) == null ? void 0 : _a.setText("---");
  }
  setFrontMatterDisabled() {
    var _a;
    (_a = this.frontMatter) == null ? void 0 : _a.setText("---");
  }
  setCurrentFileIndexing() {
    var _a;
    (_a = this.currentFile) == null ? void 0 : _a.setText("indexing...");
  }
  setCurrentVaultIndexing() {
    var _a;
    (_a = this.currentVault) == null ? void 0 : _a.setText("indexing...");
  }
  setCustomDictionaryIndexing() {
    var _a;
    (_a = this.customDictionary) == null ? void 0 : _a.setText("indexing...");
  }
  setInternalLinkIndexing() {
    var _a;
    (_a = this.internalLink) == null ? void 0 : _a.setText("indexing...");
  }
  setFrontMatterIndexing() {
    var _a;
    (_a = this.frontMatter) == null ? void 0 : _a.setText("indexing...");
  }
  setCurrentFileIndexed(count) {
    var _a;
    (_a = this.currentFile) == null ? void 0 : _a.setText(String(count));
  }
  setCurrentVaultIndexed(count) {
    var _a;
    (_a = this.currentVault) == null ? void 0 : _a.setText(String(count));
  }
  setCustomDictionaryIndexed(count) {
    var _a;
    (_a = this.customDictionary) == null ? void 0 : _a.setText(String(count));
  }
  setInternalLinkIndexed(count) {
    var _a;
    (_a = this.internalLink) == null ? void 0 : _a.setText(String(count));
  }
  setFrontMatterIndexed(count) {
    var _a;
    (_a = this.frontMatter) == null ? void 0 : _a.setText(String(count));
  }
  setMatchStrategy(strategy) {
    var _a;
    (_a = this.matchStrategy) == null ? void 0 : _a.setText(strategy.name);
  }
  setComplementAutomatically(automatically) {
    var _a;
    (_a = this.complementAutomatically) == null ? void 0 : _a.setText(automatically ? "auto" : "manual");
  }
};

// src/ui/CustomDictionaryWordAddModal.ts
var import_obsidian5 = require("obsidian");

// node_modules/svelte/internal/index.mjs
function noop() {
}
function assign(tar, src) {
  for (const k in src)
    tar[k] = src[k];
  return tar;
}
function run(fn) {
  return fn();
}
function blank_object() {
  return /* @__PURE__ */ Object.create(null);
}
function run_all(fns) {
  fns.forEach(run);
}
function is_function(thing) {
  return typeof thing === "function";
}
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function");
}
function is_empty(obj) {
  return Object.keys(obj).length === 0;
}
function create_slot(definition, ctx, $$scope, fn) {
  if (definition) {
    const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
    return definition[0](slot_ctx);
  }
}
function get_slot_context(definition, ctx, $$scope, fn) {
  return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
  if (definition[2] && fn) {
    const lets = definition[2](fn(dirty));
    if ($$scope.dirty === void 0) {
      return lets;
    }
    if (typeof lets === "object") {
      const merged = [];
      const len = Math.max($$scope.dirty.length, lets.length);
      for (let i = 0; i < len; i += 1) {
        merged[i] = $$scope.dirty[i] | lets[i];
      }
      return merged;
    }
    return $$scope.dirty | lets;
  }
  return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
  if (slot_changes) {
    const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
    slot.p(slot_context, slot_changes);
  }
}
function get_all_dirty_from_scope($$scope) {
  if ($$scope.ctx.length > 32) {
    const dirty = [];
    const length = $$scope.ctx.length / 32;
    for (let i = 0; i < length; i++) {
      dirty[i] = -1;
    }
    return dirty;
  }
  return -1;
}
function exclude_internal_props(props) {
  const result = {};
  for (const k in props)
    if (k[0] !== "$")
      result[k] = props[k];
  return result;
}
function compute_rest_props(props, keys) {
  const rest = {};
  keys = new Set(keys);
  for (const k in props)
    if (!keys.has(k) && k[0] !== "$")
      rest[k] = props[k];
  return rest;
}
function null_to_empty(value) {
  return value == null ? "" : value;
}
var is_hydrating = false;
function start_hydrating() {
  is_hydrating = true;
}
function end_hydrating() {
  is_hydrating = false;
}
function append(target, node) {
  target.appendChild(node);
}
function append_styles(target, style_sheet_id, styles) {
  const append_styles_to = get_root_for_style(target);
  if (!append_styles_to.getElementById(style_sheet_id)) {
    const style = element("style");
    style.id = style_sheet_id;
    style.textContent = styles;
    append_stylesheet(append_styles_to, style);
  }
}
function get_root_for_style(node) {
  if (!node)
    return document;
  const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
  if (root && root.host) {
    return root;
  }
  return node.ownerDocument;
}
function append_stylesheet(node, style) {
  append(node.head || node, style);
  return style.sheet;
}
function insert(target, node, anchor) {
  target.insertBefore(node, anchor || null);
}
function detach(node) {
  node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
  for (let i = 0; i < iterations.length; i += 1) {
    if (iterations[i])
      iterations[i].d(detaching);
  }
}
function element(name) {
  return document.createElement(name);
}
function svg_element(name) {
  return document.createElementNS("http://www.w3.org/2000/svg", name);
}
function text(data) {
  return document.createTextNode(data);
}
function space() {
  return text(" ");
}
function listen(node, event, handler, options) {
  node.addEventListener(event, handler, options);
  return () => node.removeEventListener(event, handler, options);
}
function attr(node, attribute, value) {
  if (value == null)
    node.removeAttribute(attribute);
  else if (node.getAttribute(attribute) !== value)
    node.setAttribute(attribute, value);
}
function set_svg_attributes(node, attributes) {
  for (const key in attributes) {
    attr(node, key, attributes[key]);
  }
}
function children(element2) {
  return Array.from(element2.childNodes);
}
function set_data(text2, data) {
  data = "" + data;
  if (text2.wholeText !== data)
    text2.data = data;
}
function set_input_value(input, value) {
  input.value = value == null ? "" : value;
}
function set_style(node, key, value, important) {
  if (value === null) {
    node.style.removeProperty(key);
  } else {
    node.style.setProperty(key, value, important ? "important" : "");
  }
}
function select_option(select, value) {
  for (let i = 0; i < select.options.length; i += 1) {
    const option = select.options[i];
    if (option.__value === value) {
      option.selected = true;
      return;
    }
  }
  select.selectedIndex = -1;
}
function select_value(select) {
  const selected_option = select.querySelector(":checked") || select.options[0];
  return selected_option && selected_option.__value;
}
function toggle_class(element2, name, toggle) {
  element2.classList[toggle ? "add" : "remove"](name);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  const e = document.createEvent("CustomEvent");
  e.initCustomEvent(type, bubbles, cancelable, detail);
  return e;
}
var current_component;
function set_current_component(component) {
  current_component = component;
}
function get_current_component() {
  if (!current_component)
    throw new Error("Function called outside component initialization");
  return current_component;
}
function onMount(fn) {
  get_current_component().$$.on_mount.push(fn);
}
function createEventDispatcher() {
  const component = get_current_component();
  return (type, detail, { cancelable = false } = {}) => {
    const callbacks = component.$$.callbacks[type];
    if (callbacks) {
      const event = custom_event(type, detail, { cancelable });
      callbacks.slice().forEach((fn) => {
        fn.call(component, event);
      });
      return !event.defaultPrevented;
    }
    return true;
  };
}
var dirty_components = [];
var binding_callbacks = [];
var render_callbacks = [];
var flush_callbacks = [];
var resolved_promise = Promise.resolve();
var update_scheduled = false;
function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}
function add_render_callback(fn) {
  render_callbacks.push(fn);
}
var seen_callbacks = /* @__PURE__ */ new Set();
var flushidx = 0;
function flush() {
  const saved_component = current_component;
  do {
    while (flushidx < dirty_components.length) {
      const component = dirty_components[flushidx];
      flushidx++;
      set_current_component(component);
      update(component.$$);
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    while (binding_callbacks.length)
      binding_callbacks.pop()();
    for (let i = 0; i < render_callbacks.length; i += 1) {
      const callback = render_callbacks[i];
      if (!seen_callbacks.has(callback)) {
        seen_callbacks.add(callback);
        callback();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  while (flush_callbacks.length) {
    flush_callbacks.pop()();
  }
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(saved_component);
}
function update($$) {
  if ($$.fragment !== null) {
    $$.update();
    run_all($$.before_update);
    const dirty = $$.dirty;
    $$.dirty = [-1];
    $$.fragment && $$.fragment.p($$.ctx, dirty);
    $$.after_update.forEach(add_render_callback);
  }
}
var outroing = /* @__PURE__ */ new Set();
var outros;
function transition_in(block, local) {
  if (block && block.i) {
    outroing.delete(block);
    block.i(local);
  }
}
function transition_out(block, local, detach2, callback) {
  if (block && block.o) {
    if (outroing.has(block))
      return;
    outroing.add(block);
    outros.c.push(() => {
      outroing.delete(block);
      if (callback) {
        if (detach2)
          block.d(1);
        callback();
      }
    });
    block.o(local);
  } else if (callback) {
    callback();
  }
}
var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global;
function get_spread_update(levels, updates) {
  const update2 = {};
  const to_null_out = {};
  const accounted_for = { $$scope: 1 };
  let i = levels.length;
  while (i--) {
    const o = levels[i];
    const n = updates[i];
    if (n) {
      for (const key in o) {
        if (!(key in n))
          to_null_out[key] = 1;
      }
      for (const key in n) {
        if (!accounted_for[key]) {
          update2[key] = n[key];
          accounted_for[key] = 1;
        }
      }
      levels[i] = n;
    } else {
      for (const key in o) {
        accounted_for[key] = 1;
      }
    }
  }
  for (const key in to_null_out) {
    if (!(key in update2))
      update2[key] = void 0;
  }
  return update2;
}
function create_component(block) {
  block && block.c();
}
function mount_component(component, target, anchor, customElement) {
  const { fragment, after_update } = component.$$;
  fragment && fragment.m(target, anchor);
  if (!customElement) {
    add_render_callback(() => {
      const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
      if (component.$$.on_destroy) {
        component.$$.on_destroy.push(...new_on_destroy);
      } else {
        run_all(new_on_destroy);
      }
      component.$$.on_mount = [];
    });
  }
  after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
  const $$ = component.$$;
  if ($$.fragment !== null) {
    run_all($$.on_destroy);
    $$.fragment && $$.fragment.d(detaching);
    $$.on_destroy = $$.fragment = null;
    $$.ctx = [];
  }
}
function make_dirty(component, i) {
  if (component.$$.dirty[0] === -1) {
    dirty_components.push(component);
    schedule_update();
    component.$$.dirty.fill(0);
  }
  component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}
function init(component, options, instance5, create_fragment5, not_equal, props, append_styles2, dirty = [-1]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    props,
    update: noop,
    not_equal,
    bound: blank_object(),
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options.target || parent_component.$$.root
  };
  append_styles2 && append_styles2($$.root);
  let ready = false;
  $$.ctx = instance5 ? instance5(component, options.props || {}, (i, ret, ...rest) => {
    const value = rest.length ? rest[0] : ret;
    if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
      if (!$$.skip_bound && $$.bound[i])
        $$.bound[i](value);
      if (ready)
        make_dirty(component, i);
    }
    return ret;
  }) : [];
  $$.update();
  ready = true;
  run_all($$.before_update);
  $$.fragment = create_fragment5 ? create_fragment5($$.ctx) : false;
  if (options.target) {
    if (options.hydrate) {
      start_hydrating();
      const nodes = children(options.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else {
      $$.fragment && $$.fragment.c();
    }
    if (options.intro)
      transition_in(component.$$.fragment);
    mount_component(component, options.target, options.anchor, options.customElement);
    end_hydrating();
    flush();
  }
  set_current_component(parent_component);
}
var SvelteElement;
if (typeof HTMLElement === "function") {
  SvelteElement = class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: "open" });
    }
    connectedCallback() {
      const { on_mount } = this.$$;
      this.$$.on_disconnect = on_mount.map(run).filter(is_function);
      for (const key in this.$$.slotted) {
        this.appendChild(this.$$.slotted[key]);
      }
    }
    attributeChangedCallback(attr2, _oldValue, newValue) {
      this[attr2] = newValue;
    }
    disconnectedCallback() {
      run_all(this.$$.on_disconnect);
    }
    $destroy() {
      destroy_component(this, 1);
      this.$destroy = noop;
    }
    $on(type, callback) {
      if (!is_function(callback)) {
        return noop;
      }
      const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
      callbacks.push(callback);
      return () => {
        const index = callbacks.indexOf(callback);
        if (index !== -1)
          callbacks.splice(index, 1);
      };
    }
    $set($$props) {
      if (this.$$set && !is_empty($$props)) {
        this.$$.skip_bound = true;
        this.$$set($$props);
        this.$$.skip_bound = false;
      }
    }
  };
}
var SvelteComponent = class {
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  $on(type, callback) {
    if (!is_function(callback)) {
      return noop;
    }
    const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
    callbacks.push(callback);
    return () => {
      const index = callbacks.indexOf(callback);
      if (index !== -1)
        callbacks.splice(index, 1);
    };
  }
  $set($$props) {
    if (this.$$set && !is_empty($$props)) {
      this.$$.skip_bound = true;
      this.$$set($$props);
      this.$$.skip_bound = false;
    }
  }
};

// src/ui/component/ObsidianButton.svelte
function create_fragment(ctx) {
  let button;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = ctx[4].default;
  const default_slot = create_slot(default_slot_template, ctx, ctx[3], null);
  return {
    c() {
      button = element("button");
      if (default_slot)
        default_slot.c();
      attr(button, "aria-label", ctx[0]);
      button.disabled = ctx[1];
      toggle_class(button, "mod-cta", !ctx[1]);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (default_slot) {
        default_slot.m(button, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(button, "click", ctx[2]);
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 8)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            ctx2[3],
            !current ? get_all_dirty_from_scope(ctx2[3]) : get_slot_changes(default_slot_template, ctx2[3], dirty, null),
            null
          );
        }
      }
      if (!current || dirty & 1) {
        attr(button, "aria-label", ctx2[0]);
      }
      if (!current || dirty & 2) {
        button.disabled = ctx2[1];
      }
      if (!current || dirty & 2) {
        toggle_class(button, "mod-cta", !ctx2[1]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if (default_slot)
        default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { popup } = $$props;
  let { disabled = false } = $$props;
  const dispatcher = createEventDispatcher();
  const handleClick = () => {
    dispatcher("click");
  };
  $$self.$$set = ($$props2) => {
    if ("popup" in $$props2)
      $$invalidate(0, popup = $$props2.popup);
    if ("disabled" in $$props2)
      $$invalidate(1, disabled = $$props2.disabled);
    if ("$$scope" in $$props2)
      $$invalidate(3, $$scope = $$props2.$$scope);
  };
  return [popup, disabled, handleClick, $$scope, slots];
}
var ObsidianButton = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance, create_fragment, safe_not_equal, { popup: 0, disabled: 1 });
  }
};
var ObsidianButton_default = ObsidianButton;

// node_modules/svelte-lucide-icons/icons/File.svelte
function create_fragment2(ctx) {
  let svg;
  let path;
  let polyline;
  let current;
  const default_slot_template = ctx[3].default;
  const default_slot = create_slot(default_slot_template, ctx, ctx[2], null);
  let svg_levels = [
    { xmlns: "http://www.w3.org/2000/svg" },
    { width: ctx[0] },
    { height: ctx[0] },
    { viewBox: "0 0 24 24" },
    { fill: "none" },
    { stroke: "currentColor" },
    { "stroke-width": "2" },
    { "stroke-linecap": "round" },
    { "stroke-linejoin": "round" },
    ctx[1]
  ];
  let svg_data = {};
  for (let i = 0; i < svg_levels.length; i += 1) {
    svg_data = assign(svg_data, svg_levels[i]);
  }
  return {
    c() {
      svg = svg_element("svg");
      if (default_slot)
        default_slot.c();
      path = svg_element("path");
      polyline = svg_element("polyline");
      attr(path, "d", "M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z");
      attr(polyline, "points", "14 2 14 8 20 8");
      set_svg_attributes(svg, svg_data);
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      if (default_slot) {
        default_slot.m(svg, null);
      }
      append(svg, path);
      append(svg, polyline);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 4)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            ctx2[2],
            !current ? get_all_dirty_from_scope(ctx2[2]) : get_slot_changes(default_slot_template, ctx2[2], dirty, null),
            null
          );
        }
      }
      set_svg_attributes(svg, svg_data = get_spread_update(svg_levels, [
        { xmlns: "http://www.w3.org/2000/svg" },
        (!current || dirty & 1) && { width: ctx2[0] },
        (!current || dirty & 1) && { height: ctx2[0] },
        { viewBox: "0 0 24 24" },
        { fill: "none" },
        { stroke: "currentColor" },
        { "stroke-width": "2" },
        { "stroke-linecap": "round" },
        { "stroke-linejoin": "round" },
        dirty & 2 && ctx2[1]
      ]));
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(svg);
      if (default_slot)
        default_slot.d(detaching);
    }
  };
}
function instance2($$self, $$props, $$invalidate) {
  const omit_props_names = ["size"];
  let $$restProps = compute_rest_props($$props, omit_props_names);
  let { $$slots: slots = {}, $$scope } = $$props;
  let { size = 24 } = $$props;
  $$self.$$set = ($$new_props) => {
    $$props = assign(assign({}, $$props), exclude_internal_props($$new_props));
    $$invalidate(1, $$restProps = compute_rest_props($$props, omit_props_names));
    if ("size" in $$new_props)
      $$invalidate(0, size = $$new_props.size);
    if ("$$scope" in $$new_props)
      $$invalidate(2, $$scope = $$new_props.$$scope);
  };
  return [size, $$restProps, $$scope, slots];
}
var File = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance2, create_fragment2, safe_not_equal, { size: 0 });
  }
};
var File_default = File;

// src/ui/component/ObsidianIconButton.svelte
function add_css(target) {
  append_styles(target, "svelte-12yh6aw", ".wrapper.svelte-12yh6aw{display:flex;justify-content:center;margin:0}.button-enabled.svelte-12yh6aw:hover{color:var(--interactive-accent)}.button-disabled.svelte-12yh6aw{color:var(--text-muted)}");
}
function create_fragment3(ctx) {
  let div;
  let button;
  let button_class_value;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = ctx[4].default;
  const default_slot = create_slot(default_slot_template, ctx, ctx[3], null);
  return {
    c() {
      div = element("div");
      button = element("button");
      if (default_slot)
        default_slot.c();
      attr(button, "aria-label", ctx[0]);
      button.disabled = ctx[1];
      attr(button, "class", button_class_value = null_to_empty(ctx[1] ? "button-disabled" : "button-enabled") + " svelte-12yh6aw");
      set_style(button, "background-color", "transparent");
      set_style(button, "padding", "0");
      attr(div, "class", "wrapper svelte-12yh6aw");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button);
      if (default_slot) {
        default_slot.m(button, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(button, "click", ctx[2]);
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 8)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            ctx2[3],
            !current ? get_all_dirty_from_scope(ctx2[3]) : get_slot_changes(default_slot_template, ctx2[3], dirty, null),
            null
          );
        }
      }
      if (!current || dirty & 1) {
        attr(button, "aria-label", ctx2[0]);
      }
      if (!current || dirty & 2) {
        button.disabled = ctx2[1];
      }
      if (!current || dirty & 2 && button_class_value !== (button_class_value = null_to_empty(ctx2[1] ? "button-disabled" : "button-enabled") + " svelte-12yh6aw")) {
        attr(button, "class", button_class_value);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (default_slot)
        default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance3($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { popup } = $$props;
  let { disabled = false } = $$props;
  const dispatcher = createEventDispatcher();
  const handleClick = () => {
    if (!disabled) {
      dispatcher("click");
    }
  };
  $$self.$$set = ($$props2) => {
    if ("popup" in $$props2)
      $$invalidate(0, popup = $$props2.popup);
    if ("disabled" in $$props2)
      $$invalidate(1, disabled = $$props2.disabled);
    if ("$$scope" in $$props2)
      $$invalidate(3, $$scope = $$props2.$$scope);
  };
  return [popup, disabled, handleClick, $$scope, slots];
}
var ObsidianIconButton = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance3, create_fragment3, safe_not_equal, { popup: 0, disabled: 1 }, add_css);
  }
};
var ObsidianIconButton_default = ObsidianIconButton;

// src/ui/component/CustomDictionaryWordAdd.svelte
function get_each_context(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[26] = list[i];
  return child_ctx;
}
function create_each_block(ctx) {
  let option;
  let t0_value = ctx[26].path + "";
  let t0;
  let t1;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = option_value_value = ctx[26];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p(ctx2, dirty) {
      if (dirty & 32 && t0_value !== (t0_value = ctx2[26].path + ""))
        set_data(t0, t0_value);
      if (dirty & 32 && option_value_value !== (option_value_value = ctx2[26])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
function create_default_slot_1(ctx) {
  let file;
  let current;
  file = new File_default({});
  return {
    c() {
      create_component(file.$$.fragment);
    },
    m(target, anchor) {
      mount_component(file, target, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      transition_in(file.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(file.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(file, detaching);
    }
  };
}
function create_if_block_1(ctx) {
  let label;
  let input;
  let t;
  let mounted;
  let dispose;
  return {
    c() {
      label = element("label");
      input = element("input");
      t = text("\n      Distinguish between display and insertion");
      attr(input, "type", "checkbox");
    },
    m(target, anchor) {
      insert(target, label, anchor);
      append(label, input);
      input.checked = ctx[1];
      append(label, t);
      if (!mounted) {
        dispose = listen(input, "change", ctx[21]);
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & 2) {
        input.checked = ctx2[1];
      }
    },
    d(detaching) {
      if (detaching)
        detach(label);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block(ctx) {
  let h3;
  let t1;
  let textarea;
  let mounted;
  let dispose;
  return {
    c() {
      h3 = element("h3");
      h3.textContent = "Displayed Word";
      t1 = space();
      textarea = element("textarea");
      set_style(textarea, "width", "100%");
      attr(textarea, "rows", "3");
    },
    m(target, anchor) {
      insert(target, h3, anchor);
      insert(target, t1, anchor);
      insert(target, textarea, anchor);
      set_input_value(textarea, ctx[3]);
      ctx[23](textarea);
      if (!mounted) {
        dispose = listen(textarea, "input", ctx[22]);
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & 8) {
        set_input_value(textarea, ctx2[3]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(h3);
      if (detaching)
        detach(t1);
      if (detaching)
        detach(textarea);
      ctx[23](null);
      mounted = false;
      dispose();
    }
  };
}
function create_default_slot(ctx) {
  let t;
  return {
    c() {
      t = text("Submit");
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    d(detaching) {
      if (detaching)
        detach(t);
    }
  };
}
function create_fragment4(ctx) {
  let div2;
  let h2;
  let t1;
  let h30;
  let t3;
  let div0;
  let select;
  let t4;
  let obsidianiconbutton;
  let t5;
  let h31;
  let t6;
  let t7;
  let textarea0;
  let t8;
  let t9;
  let t10;
  let h32;
  let t12;
  let input;
  let t13;
  let h33;
  let t15;
  let textarea1;
  let t16;
  let div1;
  let obsidianbutton;
  let current;
  let mounted;
  let dispose;
  let each_value = ctx[5];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
  }
  obsidianiconbutton = new ObsidianIconButton_default({
    props: {
      popup: "Open the file",
      $$slots: { default: [create_default_slot_1] },
      $$scope: { ctx }
    }
  });
  obsidianiconbutton.$on("click", ctx[18]);
  let if_block0 = ctx[11] && create_if_block_1(ctx);
  let if_block1 = ctx[1] && create_if_block(ctx);
  obsidianbutton = new ObsidianButton_default({
    props: {
      disabled: !ctx[12],
      $$slots: { default: [create_default_slot] },
      $$scope: { ctx }
    }
  });
  obsidianbutton.$on("click", ctx[13]);
  return {
    c() {
      div2 = element("div");
      h2 = element("h2");
      h2.textContent = "Add a word to a custom dictionary";
      t1 = space();
      h30 = element("h3");
      h30.textContent = "Dictionary";
      t3 = space();
      div0 = element("div");
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t4 = space();
      create_component(obsidianiconbutton.$$.fragment);
      t5 = space();
      h31 = element("h3");
      t6 = text(ctx[10]);
      t7 = space();
      textarea0 = element("textarea");
      t8 = space();
      if (if_block0)
        if_block0.c();
      t9 = space();
      if (if_block1)
        if_block1.c();
      t10 = space();
      h32 = element("h3");
      h32.textContent = "Description";
      t12 = space();
      input = element("input");
      t13 = space();
      h33 = element("h3");
      h33.textContent = "Aliases (for each line)";
      t15 = space();
      textarea1 = element("textarea");
      t16 = space();
      div1 = element("div");
      create_component(obsidianbutton.$$.fragment);
      attr(select, "class", "dropdown");
      if (ctx[2] === void 0)
        add_render_callback(() => ctx[17].call(select));
      set_style(div0, "display", "flex");
      set_style(div0, "gap", "10px");
      set_style(textarea0, "width", "100%");
      attr(textarea0, "rows", "3");
      attr(input, "type", "text");
      set_style(input, "width", "100%");
      set_style(textarea1, "width", "100%");
      attr(textarea1, "rows", "3");
      set_style(div1, "text-align", "center");
      set_style(div1, "width", "100%");
      set_style(div1, "padding-top", "15px");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, h2);
      append(div2, t1);
      append(div2, h30);
      append(div2, t3);
      append(div2, div0);
      append(div0, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(select, null);
      }
      select_option(select, ctx[2]);
      append(div0, t4);
      mount_component(obsidianiconbutton, div0, null);
      append(div2, t5);
      append(div2, h31);
      append(h31, t6);
      append(div2, t7);
      append(div2, textarea0);
      set_input_value(textarea0, ctx[0]);
      ctx[20](textarea0);
      append(div2, t8);
      if (if_block0)
        if_block0.m(div2, null);
      append(div2, t9);
      if (if_block1)
        if_block1.m(div2, null);
      append(div2, t10);
      append(div2, h32);
      append(div2, t12);
      append(div2, input);
      set_input_value(input, ctx[4]);
      append(div2, t13);
      append(div2, h33);
      append(div2, t15);
      append(div2, textarea1);
      set_input_value(textarea1, ctx[8]);
      append(div2, t16);
      append(div2, div1);
      mount_component(obsidianbutton, div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(select, "change", ctx[17]),
          listen(textarea0, "input", ctx[19]),
          listen(input, "input", ctx[24]),
          listen(textarea1, "input", ctx[25])
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & 32) {
        each_value = ctx2[5];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 36) {
        select_option(select, ctx2[2]);
      }
      const obsidianiconbutton_changes = {};
      if (dirty & 536870912) {
        obsidianiconbutton_changes.$$scope = { dirty, ctx: ctx2 };
      }
      obsidianiconbutton.$set(obsidianiconbutton_changes);
      if (!current || dirty & 1024)
        set_data(t6, ctx2[10]);
      if (dirty & 1) {
        set_input_value(textarea0, ctx2[0]);
      }
      if (ctx2[11]) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1(ctx2);
          if_block0.c();
          if_block0.m(div2, t9);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (ctx2[1]) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block(ctx2);
          if_block1.c();
          if_block1.m(div2, t10);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty & 16 && input.value !== ctx2[4]) {
        set_input_value(input, ctx2[4]);
      }
      if (dirty & 256) {
        set_input_value(textarea1, ctx2[8]);
      }
      const obsidianbutton_changes = {};
      if (dirty & 4096)
        obsidianbutton_changes.disabled = !ctx2[12];
      if (dirty & 536870912) {
        obsidianbutton_changes.$$scope = { dirty, ctx: ctx2 };
      }
      obsidianbutton.$set(obsidianbutton_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(obsidianiconbutton.$$.fragment, local);
      transition_in(obsidianbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(obsidianiconbutton.$$.fragment, local);
      transition_out(obsidianbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      destroy_each(each_blocks, detaching);
      destroy_component(obsidianiconbutton);
      ctx[20](null);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      destroy_component(obsidianbutton);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance4($$self, $$props, $$invalidate) {
  let enableSubmit;
  let enableDisplayedWord;
  let firstWordTitle;
  let { dictionaries } = $$props;
  let { selectedDictionary } = $$props;
  let { inputWord = "" } = $$props;
  let { useDisplayedWord = false } = $$props;
  let { displayedWord = "" } = $$props;
  let { description = "" } = $$props;
  let { aliases = [] } = $$props;
  let { dividerForDisplay = "" } = $$props;
  let { onSubmit } = $$props;
  let { onClickFileIcon } = $$props;
  let aliasesStr = aliases.join("\n");
  let wordRef = null;
  let displayedWordRef = null;
  const handleSubmit = () => {
    onSubmit(selectedDictionary.path, {
      value: displayedWord || inputWord,
      description,
      aliases: aliasesStr.split("\n"),
      type: "customDictionary",
      createdPath: selectedDictionary.path,
      insertedText: displayedWord ? inputWord : void 0
    });
  };
  onMount(() => {
    setTimeout(() => wordRef.focus(), 50);
  });
  function select_change_handler() {
    selectedDictionary = select_value(this);
    $$invalidate(2, selectedDictionary);
    $$invalidate(5, dictionaries);
  }
  const click_handler = () => onClickFileIcon(selectedDictionary.path);
  function textarea0_input_handler() {
    inputWord = this.value;
    $$invalidate(0, inputWord);
  }
  function textarea0_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      wordRef = $$value;
      $$invalidate(9, wordRef);
    });
  }
  function input_change_handler() {
    useDisplayedWord = this.checked;
    $$invalidate(1, useDisplayedWord);
  }
  function textarea_input_handler() {
    displayedWord = this.value;
    $$invalidate(3, displayedWord);
  }
  function textarea_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      displayedWordRef = $$value;
      $$invalidate(7, displayedWordRef);
    });
  }
  function input_input_handler() {
    description = this.value;
    $$invalidate(4, description);
  }
  function textarea1_input_handler() {
    aliasesStr = this.value;
    $$invalidate(8, aliasesStr);
  }
  $$self.$$set = ($$props2) => {
    if ("dictionaries" in $$props2)
      $$invalidate(5, dictionaries = $$props2.dictionaries);
    if ("selectedDictionary" in $$props2)
      $$invalidate(2, selectedDictionary = $$props2.selectedDictionary);
    if ("inputWord" in $$props2)
      $$invalidate(0, inputWord = $$props2.inputWord);
    if ("useDisplayedWord" in $$props2)
      $$invalidate(1, useDisplayedWord = $$props2.useDisplayedWord);
    if ("displayedWord" in $$props2)
      $$invalidate(3, displayedWord = $$props2.displayedWord);
    if ("description" in $$props2)
      $$invalidate(4, description = $$props2.description);
    if ("aliases" in $$props2)
      $$invalidate(14, aliases = $$props2.aliases);
    if ("dividerForDisplay" in $$props2)
      $$invalidate(15, dividerForDisplay = $$props2.dividerForDisplay);
    if ("onSubmit" in $$props2)
      $$invalidate(16, onSubmit = $$props2.onSubmit);
    if ("onClickFileIcon" in $$props2)
      $$invalidate(6, onClickFileIcon = $$props2.onClickFileIcon);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(12, enableSubmit = inputWord.length > 0);
    }
    if ($$self.$$.dirty & 32768) {
      $:
        $$invalidate(11, enableDisplayedWord = Boolean(dividerForDisplay));
    }
    if ($$self.$$.dirty & 2) {
      $:
        $$invalidate(10, firstWordTitle = useDisplayedWord ? "Inserted word" : "Word");
    }
    if ($$self.$$.dirty & 130) {
      $: {
        if (useDisplayedWord) {
          displayedWordRef === null || displayedWordRef === void 0 ? void 0 : displayedWordRef.focus();
        }
      }
    }
  };
  return [
    inputWord,
    useDisplayedWord,
    selectedDictionary,
    displayedWord,
    description,
    dictionaries,
    onClickFileIcon,
    displayedWordRef,
    aliasesStr,
    wordRef,
    firstWordTitle,
    enableDisplayedWord,
    enableSubmit,
    handleSubmit,
    aliases,
    dividerForDisplay,
    onSubmit,
    select_change_handler,
    click_handler,
    textarea0_input_handler,
    textarea0_binding,
    input_change_handler,
    textarea_input_handler,
    textarea_binding,
    input_input_handler,
    textarea1_input_handler
  ];
}
var CustomDictionaryWordAdd = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance4, create_fragment4, safe_not_equal, {
      dictionaries: 5,
      selectedDictionary: 2,
      inputWord: 0,
      useDisplayedWord: 1,
      displayedWord: 3,
      description: 4,
      aliases: 14,
      dividerForDisplay: 15,
      onSubmit: 16,
      onClickFileIcon: 6
    });
  }
};
var CustomDictionaryWordAdd_default = CustomDictionaryWordAdd;

// src/ui/CustomDictionaryWordAddModal.ts
var CustomDictionaryWordAddModal = class extends import_obsidian5.Modal {
  constructor(app, dictionaryPaths, initialValue = "", dividerForDisplay = "", onSubmit) {
    super(app);
    const appHelper = new AppHelper(app);
    const dictionaries = dictionaryPaths.map((x) => ({ id: x, path: x }));
    const { contentEl } = this;
    this.component = new CustomDictionaryWordAdd_default({
      target: contentEl,
      props: {
        dictionaries,
        selectedDictionary: dictionaries[0],
        inputWord: initialValue,
        dividerForDisplay,
        onSubmit,
        onClickFileIcon: (dictionaryPath) => {
          const markdownFile = appHelper.getMarkdownFileByPath(dictionaryPath);
          if (!markdownFile) {
            new import_obsidian5.Notice(`Can't open ${dictionaryPath}`);
            return;
          }
          this.close();
          appHelper.openMarkdownFile(markdownFile, true);
        }
      }
    });
  }
  onClose() {
    super.onClose();
    this.component.$destroy();
  }
};

// src/main.ts
var import_ts_deepmerge = __toESM(require_dist());
var VariousComponents = class extends import_obsidian6.Plugin {
  onunload() {
    super.onunload();
    this.suggester.unregister();
  }
  async onload() {
    this.appHelper = new AppHelper(this.app);
    this.registerEvent(
      this.app.workspace.on("editor-menu", (menu) => {
        if (!this.appHelper.getSelection()) {
          return;
        }
        menu.addItem(
          (item) => item.setTitle("Add to custom dictionary").setIcon("stacked-levels").onClick(() => {
            this.addWordToCustomDictionary();
          })
        );
      })
    );
    await this.loadSettings();
    this.settingTab = new VariousComplementsSettingTab(this.app, this);
    this.addSettingTab(this.settingTab);
    this.statusBar = ProviderStatusBar.new(
      this.addStatusBarItem(),
      this.settings.showMatchStrategy,
      this.settings.showIndexingStatus,
      this.settings.showComplementAutomatically
    );
    this.statusBar.setOnClickStrategyListener(async () => {
      await this.settingTab.toggleMatchStrategy();
    });
    this.statusBar.setOnClickComplementAutomatically(async () => {
      await this.settingTab.toggleComplementAutomatically();
    });
    const debouncedSaveData = (0, import_obsidian6.debounce)(async () => {
      await this.saveData(this.settings);
    }, 5e3);
    this.suggester = await AutoCompleteSuggest.new(
      this.app,
      this.settings,
      this.statusBar,
      debouncedSaveData
    );
    this.registerEditorSuggest(this.suggester);
    this.addCommand({
      id: "reload-custom-dictionaries",
      name: "Reload custom dictionaries",
      hotkeys: [{ modifiers: ["Mod", "Shift"], key: "r" }],
      callback: async () => {
        await this.suggester.refreshCustomDictionaryTokens();
      }
    });
    this.addCommand({
      id: "reload-current-vault",
      name: "Reload current vault",
      callback: async () => {
        await this.suggester.refreshCurrentVaultTokens();
      }
    });
    this.addCommand({
      id: "toggle-match-strategy",
      name: "Toggle Match strategy",
      callback: async () => {
        await this.settingTab.toggleMatchStrategy();
      }
    });
    this.addCommand({
      id: "toggle-complement-automatically",
      name: "Toggle Complement automatically",
      callback: async () => {
        await this.settingTab.toggleComplementAutomatically();
      }
    });
    this.addCommand({
      id: "show-suggestions",
      name: "Show suggestions",
      hotkeys: [{ modifiers: ["Mod"], key: " " }],
      callback: async () => {
        this.suggester.triggerComplete();
      }
    });
    this.addCommand({
      id: "hide-suggestions",
      name: "Hide suggestions",
      callback: async () => {
        this.suggester.hideCompletion();
      }
    });
    this.addCommand({
      id: "add-word-custom-dictionary",
      name: "Add a word to a custom dictionary",
      hotkeys: [{ modifiers: ["Mod", "Shift"], key: " " }],
      callback: async () => {
        this.addWordToCustomDictionary();
      }
    });
    this.addCommand({
      id: "predictable-complements",
      name: "Predictable complement",
      callback: async () => {
        this.suggester.predictableComplete();
      }
    });
    this.addCommand({
      id: "copy-plugin-settings",
      name: "Copy plugin settings",
      callback: async () => {
        await navigator.clipboard.writeText(
          this.settingTab.getPluginSettingsAsJsonString()
        );
        new import_obsidian6.Notice("Copy settings of Various Complements");
      }
    });
  }
  async loadSettings() {
    const currentSettings = await this.loadData();
    this.settings = (0, import_ts_deepmerge.default)(DEFAULT_SETTINGS, currentSettings != null ? currentSettings : {});
  }
  async saveSettings(needUpdateTokens = {}) {
    await this.saveData(this.settings);
    await this.suggester.updateSettings(this.settings);
    if (needUpdateTokens.currentFile) {
      await this.suggester.refreshCurrentFileTokens();
    }
    if (needUpdateTokens.currentVault) {
      await this.suggester.refreshCurrentVaultTokens();
    }
    if (needUpdateTokens.customDictionary) {
      await this.suggester.refreshCustomDictionaryTokens();
    }
    if (needUpdateTokens.internalLink) {
      await this.suggester.refreshInternalLinkTokens();
    }
    if (needUpdateTokens.frontMatter) {
      await this.suggester.refreshFrontMatterTokens();
    }
  }
  addWordToCustomDictionary() {
    const selectedWord = this.appHelper.getSelection();
    const provider = this.suggester.customDictionaryWordProvider;
    const modal = new CustomDictionaryWordAddModal(
      this.app,
      provider.editablePaths,
      selectedWord,
      this.settings.delimiterToDivideSuggestionsForDisplayFromInsertion,
      async (dictionaryPath, _word) => {
        const word = {
          ..._word,
          caretSymbol: this.settings.caretLocationSymbolAfterComplement
        };
        if (provider.wordByValue[word.value]) {
          new import_obsidian6.Notice(`\u26A0 ${word.value} already exists`, 0);
          return;
        }
        await provider.addWordWithDictionary(word, dictionaryPath);
        new import_obsidian6.Notice(`Added ${word.value}`);
        modal.close();
      }
    );
    modal.open();
  }
};