(() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
  var __commonJS = (callback, module) => () => {
    if (!module) {
      module = {exports: {}};
      callback(module.exports, module);
    }
    return module.exports;
  };
  var __exportStar = (target, module, desc) => {
    __markAsModule(target);
    if (module && typeof module === "object" || typeof module === "function") {
      for (let key of __getOwnPropNames(module))
        if (!__hasOwnProp.call(target, key) && key !== "default")
          __defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable});
    }
    return target;
  };
  var __toModule = (module) => {
    if (module && module.__esModule)
      return module;
    return __exportStar(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", {value: module, enumerable: true}), module);
  };

  // node_modules/codemirror/lib/codemirror.js
  var require_codemirror = __commonJS((exports, module) => {
    (function(global2, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = global2 || self, global2.CodeMirror = factory());
    })(exports, function() {
      "use strict";
      var userAgent = navigator.userAgent;
      var platform = navigator.platform;
      var gecko = /gecko\/\d/i.test(userAgent);
      var ie_upto10 = /MSIE \d/.test(userAgent);
      var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
      var edge = /Edge\/(\d+)/.exec(userAgent);
      var ie = ie_upto10 || ie_11up || edge;
      var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
      var webkit = !edge && /WebKit\//.test(userAgent);
      var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
      var chrome = !edge && /Chrome\//.test(userAgent);
      var presto = /Opera\//.test(userAgent);
      var safari = /Apple Computer/.test(navigator.vendor);
      var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
      var phantom = /PhantomJS/.test(userAgent);
      var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
      var android = /Android/.test(userAgent);
      var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
      var mac = ios || /Mac/.test(platform);
      var chromeOS = /\bCrOS\b/.test(userAgent);
      var windows = /win/i.test(platform);
      var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
      if (presto_version) {
        presto_version = Number(presto_version[1]);
      }
      if (presto_version && presto_version >= 15) {
        presto = false;
        webkit = true;
      }
      var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
      var captureRightClick = gecko || ie && ie_version >= 9;
      function classTest(cls) {
        return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*");
      }
      var rmClass = function(node, cls) {
        var current = node.className;
        var match = classTest(cls).exec(current);
        if (match) {
          var after = current.slice(match.index + match[0].length);
          node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
        }
      };
      function removeChildren(e) {
        for (var count2 = e.childNodes.length; count2 > 0; --count2) {
          e.removeChild(e.firstChild);
        }
        return e;
      }
      function removeChildrenAndAdd(parent2, e) {
        return removeChildren(parent2).appendChild(e);
      }
      function elt(tag, content, className, style) {
        var e = document.createElement(tag);
        if (className) {
          e.className = className;
        }
        if (style) {
          e.style.cssText = style;
        }
        if (typeof content == "string") {
          e.appendChild(document.createTextNode(content));
        } else if (content) {
          for (var i2 = 0; i2 < content.length; ++i2) {
            e.appendChild(content[i2]);
          }
        }
        return e;
      }
      function eltP(tag, content, className, style) {
        var e = elt(tag, content, className, style);
        e.setAttribute("role", "presentation");
        return e;
      }
      var range;
      if (document.createRange) {
        range = function(node, start, end, endNode) {
          var r = document.createRange();
          r.setEnd(endNode || node, end);
          r.setStart(node, start);
          return r;
        };
      } else {
        range = function(node, start, end) {
          var r = document.body.createTextRange();
          try {
            r.moveToElementText(node.parentNode);
          } catch (e) {
            return r;
          }
          r.collapse(true);
          r.moveEnd("character", end);
          r.moveStart("character", start);
          return r;
        };
      }
      function contains(parent2, child) {
        if (child.nodeType == 3) {
          child = child.parentNode;
        }
        if (parent2.contains) {
          return parent2.contains(child);
        }
        do {
          if (child.nodeType == 11) {
            child = child.host;
          }
          if (child == parent2) {
            return true;
          }
        } while (child = child.parentNode);
      }
      function activeElt() {
        var activeElement;
        try {
          activeElement = document.activeElement;
        } catch (e) {
          activeElement = document.body || null;
        }
        while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
          activeElement = activeElement.shadowRoot.activeElement;
        }
        return activeElement;
      }
      function addClass(node, cls) {
        var current = node.className;
        if (!classTest(cls).test(current)) {
          node.className += (current ? " " : "") + cls;
        }
      }
      function joinClasses(a, b) {
        var as = a.split(" ");
        for (var i2 = 0; i2 < as.length; i2++) {
          if (as[i2] && !classTest(as[i2]).test(b)) {
            b += " " + as[i2];
          }
        }
        return b;
      }
      var selectInput = function(node) {
        node.select();
      };
      if (ios) {
        selectInput = function(node) {
          node.selectionStart = 0;
          node.selectionEnd = node.value.length;
        };
      } else if (ie) {
        selectInput = function(node) {
          try {
            node.select();
          } catch (_e) {
          }
        };
      }
      function bind2(f) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function() {
          return f.apply(null, args);
        };
      }
      function copyObj(obj, target, overwrite) {
        if (!target) {
          target = {};
        }
        for (var prop2 in obj) {
          if (obj.hasOwnProperty(prop2) && (overwrite !== false || !target.hasOwnProperty(prop2))) {
            target[prop2] = obj[prop2];
          }
        }
        return target;
      }
      function countColumn(string2, end, tabSize, startIndex, startValue) {
        if (end == null) {
          end = string2.search(/[^\s\u00a0]/);
          if (end == -1) {
            end = string2.length;
          }
        }
        for (var i2 = startIndex || 0, n = startValue || 0; ; ) {
          var nextTab = string2.indexOf("	", i2);
          if (nextTab < 0 || nextTab >= end) {
            return n + (end - i2);
          }
          n += nextTab - i2;
          n += tabSize - n % tabSize;
          i2 = nextTab + 1;
        }
      }
      var Delayed = function() {
        this.id = null;
        this.f = null;
        this.time = 0;
        this.handler = bind2(this.onTimeout, this);
      };
      Delayed.prototype.onTimeout = function(self3) {
        self3.id = 0;
        if (self3.time <= +new Date()) {
          self3.f();
        } else {
          setTimeout(self3.handler, self3.time - +new Date());
        }
      };
      Delayed.prototype.set = function(ms, f) {
        this.f = f;
        var time = +new Date() + ms;
        if (!this.id || time < this.time) {
          clearTimeout(this.id);
          this.id = setTimeout(this.handler, ms);
          this.time = time;
        }
      };
      function indexOf(array2, elt2) {
        for (var i2 = 0; i2 < array2.length; ++i2) {
          if (array2[i2] == elt2) {
            return i2;
          }
        }
        return -1;
      }
      var scrollerGap = 50;
      var Pass = {toString: function() {
        return "CodeMirror.Pass";
      }};
      var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
      function findColumn(string2, goal, tabSize) {
        for (var pos = 0, col = 0; ; ) {
          var nextTab = string2.indexOf("	", pos);
          if (nextTab == -1) {
            nextTab = string2.length;
          }
          var skipped = nextTab - pos;
          if (nextTab == string2.length || col + skipped >= goal) {
            return pos + Math.min(skipped, goal - col);
          }
          col += nextTab - pos;
          col += tabSize - col % tabSize;
          pos = nextTab + 1;
          if (col >= goal) {
            return pos;
          }
        }
      }
      var spaceStrs = [""];
      function spaceStr(n) {
        while (spaceStrs.length <= n) {
          spaceStrs.push(lst(spaceStrs) + " ");
        }
        return spaceStrs[n];
      }
      function lst(arr) {
        return arr[arr.length - 1];
      }
      function map2(array2, f) {
        var out = [];
        for (var i2 = 0; i2 < array2.length; i2++) {
          out[i2] = f(array2[i2], i2);
        }
        return out;
      }
      function insertSorted(array2, value, score) {
        var pos = 0, priority = score(value);
        while (pos < array2.length && score(array2[pos]) <= priority) {
          pos++;
        }
        array2.splice(pos, 0, value);
      }
      function nothing() {
      }
      function createObj(base, props) {
        var inst;
        if (Object.create) {
          inst = Object.create(base);
        } else {
          nothing.prototype = base;
          inst = new nothing();
        }
        if (props) {
          copyObj(props, inst);
        }
        return inst;
      }
      var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
      function isWordCharBasic(ch) {
        return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
      }
      function isWordChar(ch, helper) {
        if (!helper) {
          return isWordCharBasic(ch);
        }
        if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) {
          return true;
        }
        return helper.test(ch);
      }
      function isEmpty(obj) {
        for (var n in obj) {
          if (obj.hasOwnProperty(n) && obj[n]) {
            return false;
          }
        }
        return true;
      }
      var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
      function isExtendingChar(ch) {
        return ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
      }
      function skipExtendingChars(str, pos, dir) {
        while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) {
          pos += dir;
        }
        return pos;
      }
      function findFirst(pred, from, to) {
        var dir = from > to ? -1 : 1;
        for (; ; ) {
          if (from == to) {
            return from;
          }
          var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
          if (mid == from) {
            return pred(mid) ? from : to;
          }
          if (pred(mid)) {
            to = mid;
          } else {
            from = mid + dir;
          }
        }
      }
      function iterateBidiSections(order, from, to, f) {
        if (!order) {
          return f(from, to, "ltr", 0);
        }
        var found = false;
        for (var i2 = 0; i2 < order.length; ++i2) {
          var part = order[i2];
          if (part.from < to && part.to > from || from == to && part.to == from) {
            f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2);
            found = true;
          }
        }
        if (!found) {
          f(from, to, "ltr");
        }
      }
      var bidiOther = null;
      function getBidiPartAt(order, ch, sticky) {
        var found;
        bidiOther = null;
        for (var i2 = 0; i2 < order.length; ++i2) {
          var cur = order[i2];
          if (cur.from < ch && cur.to > ch) {
            return i2;
          }
          if (cur.to == ch) {
            if (cur.from != cur.to && sticky == "before") {
              found = i2;
            } else {
              bidiOther = i2;
            }
          }
          if (cur.from == ch) {
            if (cur.from != cur.to && sticky != "before") {
              found = i2;
            } else {
              bidiOther = i2;
            }
          }
        }
        return found != null ? found : bidiOther;
      }
      var bidiOrdering = function() {
        var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
        var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
        function charType(code) {
          if (code <= 247) {
            return lowTypes.charAt(code);
          } else if (1424 <= code && code <= 1524) {
            return "R";
          } else if (1536 <= code && code <= 1785) {
            return arabicTypes.charAt(code - 1536);
          } else if (1774 <= code && code <= 2220) {
            return "r";
          } else if (8192 <= code && code <= 8203) {
            return "w";
          } else if (code == 8204) {
            return "b";
          } else {
            return "L";
          }
        }
        var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
        var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
        function BidiSpan(level, from, to) {
          this.level = level;
          this.from = from;
          this.to = to;
        }
        return function(str, direction) {
          var outerType = direction == "ltr" ? "L" : "R";
          if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) {
            return false;
          }
          var len = str.length, types = [];
          for (var i2 = 0; i2 < len; ++i2) {
            types.push(charType(str.charCodeAt(i2)));
          }
          for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) {
            var type = types[i$12];
            if (type == "m") {
              types[i$12] = prev;
            } else {
              prev = type;
            }
          }
          for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) {
            var type$1 = types[i$22];
            if (type$1 == "1" && cur == "r") {
              types[i$22] = "n";
            } else if (isStrong.test(type$1)) {
              cur = type$1;
              if (type$1 == "r") {
                types[i$22] = "R";
              }
            }
          }
          for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
            var type$2 = types[i$3];
            if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") {
              types[i$3] = "1";
            } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) {
              types[i$3] = prev$1;
            }
            prev$1 = type$2;
          }
          for (var i$4 = 0; i$4 < len; ++i$4) {
            var type$3 = types[i$4];
            if (type$3 == ",") {
              types[i$4] = "N";
            } else if (type$3 == "%") {
              var end = void 0;
              for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {
              }
              var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N";
              for (var j = i$4; j < end; ++j) {
                types[j] = replace;
              }
              i$4 = end - 1;
            }
          }
          for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
            var type$4 = types[i$5];
            if (cur$1 == "L" && type$4 == "1") {
              types[i$5] = "L";
            } else if (isStrong.test(type$4)) {
              cur$1 = type$4;
            }
          }
          for (var i$6 = 0; i$6 < len; ++i$6) {
            if (isNeutral.test(types[i$6])) {
              var end$1 = void 0;
              for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {
              }
              var before = (i$6 ? types[i$6 - 1] : outerType) == "L";
              var after = (end$1 < len ? types[end$1] : outerType) == "L";
              var replace$1 = before == after ? before ? "L" : "R" : outerType;
              for (var j$1 = i$6; j$1 < end$1; ++j$1) {
                types[j$1] = replace$1;
              }
              i$6 = end$1 - 1;
            }
          }
          var order = [], m;
          for (var i$7 = 0; i$7 < len; ) {
            if (countsAsLeft.test(types[i$7])) {
              var start = i$7;
              for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {
              }
              order.push(new BidiSpan(0, start, i$7));
            } else {
              var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
              for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {
              }
              for (var j$2 = pos; j$2 < i$7; ) {
                if (countsAsNum.test(types[j$2])) {
                  if (pos < j$2) {
                    order.splice(at, 0, new BidiSpan(1, pos, j$2));
                    at += isRTL;
                  }
                  var nstart = j$2;
                  for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {
                  }
                  order.splice(at, 0, new BidiSpan(2, nstart, j$2));
                  at += isRTL;
                  pos = j$2;
                } else {
                  ++j$2;
                }
              }
              if (pos < i$7) {
                order.splice(at, 0, new BidiSpan(1, pos, i$7));
              }
            }
          }
          if (direction == "ltr") {
            if (order[0].level == 1 && (m = str.match(/^\s+/))) {
              order[0].from = m[0].length;
              order.unshift(new BidiSpan(0, 0, m[0].length));
            }
            if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
              lst(order).to -= m[0].length;
              order.push(new BidiSpan(0, len - m[0].length, len));
            }
          }
          return direction == "rtl" ? order.reverse() : order;
        };
      }();
      function getOrder(line, direction) {
        var order = line.order;
        if (order == null) {
          order = line.order = bidiOrdering(line.text, direction);
        }
        return order;
      }
      var noHandlers = [];
      var on = function(emitter, type, f) {
        if (emitter.addEventListener) {
          emitter.addEventListener(type, f, false);
        } else if (emitter.attachEvent) {
          emitter.attachEvent("on" + type, f);
        } else {
          var map3 = emitter._handlers || (emitter._handlers = {});
          map3[type] = (map3[type] || noHandlers).concat(f);
        }
      };
      function getHandlers(emitter, type) {
        return emitter._handlers && emitter._handlers[type] || noHandlers;
      }
      function off(emitter, type, f) {
        if (emitter.removeEventListener) {
          emitter.removeEventListener(type, f, false);
        } else if (emitter.detachEvent) {
          emitter.detachEvent("on" + type, f);
        } else {
          var map3 = emitter._handlers, arr = map3 && map3[type];
          if (arr) {
            var index = indexOf(arr, f);
            if (index > -1) {
              map3[type] = arr.slice(0, index).concat(arr.slice(index + 1));
            }
          }
        }
      }
      function signal(emitter, type) {
        var handlers = getHandlers(emitter, type);
        if (!handlers.length) {
          return;
        }
        var args = Array.prototype.slice.call(arguments, 2);
        for (var i2 = 0; i2 < handlers.length; ++i2) {
          handlers[i2].apply(null, args);
        }
      }
      function signalDOMEvent(cm, e, override) {
        if (typeof e == "string") {
          e = {type: e, preventDefault: function() {
            this.defaultPrevented = true;
          }};
        }
        signal(cm, override || e.type, cm, e);
        return e_defaultPrevented(e) || e.codemirrorIgnore;
      }
      function signalCursorActivity(cm) {
        var arr = cm._handlers && cm._handlers.cursorActivity;
        if (!arr) {
          return;
        }
        var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
        for (var i2 = 0; i2 < arr.length; ++i2) {
          if (indexOf(set, arr[i2]) == -1) {
            set.push(arr[i2]);
          }
        }
      }
      function hasHandler(emitter, type) {
        return getHandlers(emitter, type).length > 0;
      }
      function eventMixin(ctor) {
        ctor.prototype.on = function(type, f) {
          on(this, type, f);
        };
        ctor.prototype.off = function(type, f) {
          off(this, type, f);
        };
      }
      function e_preventDefault(e) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
      function e_stopPropagation(e) {
        if (e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBubble = true;
        }
      }
      function e_defaultPrevented(e) {
        return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
      }
      function e_stop(e) {
        e_preventDefault(e);
        e_stopPropagation(e);
      }
      function e_target(e) {
        return e.target || e.srcElement;
      }
      function e_button(e) {
        var b = e.which;
        if (b == null) {
          if (e.button & 1) {
            b = 1;
          } else if (e.button & 2) {
            b = 3;
          } else if (e.button & 4) {
            b = 2;
          }
        }
        if (mac && e.ctrlKey && b == 1) {
          b = 3;
        }
        return b;
      }
      var dragAndDrop = function() {
        if (ie && ie_version < 9) {
          return false;
        }
        var div = elt("div");
        return "draggable" in div || "dragDrop" in div;
      }();
      var zwspSupported;
      function zeroWidthElement(measure) {
        if (zwspSupported == null) {
          var test = elt("span", "\u200B");
          removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
          if (measure.firstChild.offsetHeight != 0) {
            zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
          }
        }
        var node = zwspSupported ? elt("span", "\u200B") : elt("span", "\xA0", null, "display: inline-block; width: 1px; margin-right: -1px");
        node.setAttribute("cm-text", "");
        return node;
      }
      var badBidiRects;
      function hasBadBidiRects(measure) {
        if (badBidiRects != null) {
          return badBidiRects;
        }
        var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062EA"));
        var r0 = range(txt, 0, 1).getBoundingClientRect();
        var r1 = range(txt, 1, 2).getBoundingClientRect();
        removeChildren(measure);
        if (!r0 || r0.left == r0.right) {
          return false;
        }
        return badBidiRects = r1.right - r0.right < 3;
      }
      var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function(string2) {
        var pos = 0, result = [], l = string2.length;
        while (pos <= l) {
          var nl = string2.indexOf("\n", pos);
          if (nl == -1) {
            nl = string2.length;
          }
          var line = string2.slice(pos, string2.charAt(nl - 1) == "\r" ? nl - 1 : nl);
          var rt = line.indexOf("\r");
          if (rt != -1) {
            result.push(line.slice(0, rt));
            pos += rt + 1;
          } else {
            result.push(line);
            pos = nl + 1;
          }
        }
        return result;
      } : function(string2) {
        return string2.split(/\r\n?|\n/);
      };
      var hasSelection = window.getSelection ? function(te) {
        try {
          return te.selectionStart != te.selectionEnd;
        } catch (e) {
          return false;
        }
      } : function(te) {
        var range2;
        try {
          range2 = te.ownerDocument.selection.createRange();
        } catch (e) {
        }
        if (!range2 || range2.parentElement() != te) {
          return false;
        }
        return range2.compareEndPoints("StartToEnd", range2) != 0;
      };
      var hasCopyEvent = function() {
        var e = elt("div");
        if ("oncopy" in e) {
          return true;
        }
        e.setAttribute("oncopy", "return;");
        return typeof e.oncopy == "function";
      }();
      var badZoomedRects = null;
      function hasBadZoomedRects(measure) {
        if (badZoomedRects != null) {
          return badZoomedRects;
        }
        var node = removeChildrenAndAdd(measure, elt("span", "x"));
        var normal = node.getBoundingClientRect();
        var fromRange = range(node, 0, 1).getBoundingClientRect();
        return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
      }
      var modes = {}, mimeModes = {};
      function defineMode(name, mode) {
        if (arguments.length > 2) {
          mode.dependencies = Array.prototype.slice.call(arguments, 2);
        }
        modes[name] = mode;
      }
      function defineMIME(mime, spec) {
        mimeModes[mime] = spec;
      }
      function resolveMode(spec) {
        if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
          spec = mimeModes[spec];
        } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
          var found = mimeModes[spec.name];
          if (typeof found == "string") {
            found = {name: found};
          }
          spec = createObj(found, spec);
          spec.name = found.name;
        } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
          return resolveMode("application/xml");
        } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
          return resolveMode("application/json");
        }
        if (typeof spec == "string") {
          return {name: spec};
        } else {
          return spec || {name: "null"};
        }
      }
      function getMode(options, spec) {
        spec = resolveMode(spec);
        var mfactory = modes[spec.name];
        if (!mfactory) {
          return getMode(options, "text/plain");
        }
        var modeObj = mfactory(options, spec);
        if (modeExtensions.hasOwnProperty(spec.name)) {
          var exts = modeExtensions[spec.name];
          for (var prop2 in exts) {
            if (!exts.hasOwnProperty(prop2)) {
              continue;
            }
            if (modeObj.hasOwnProperty(prop2)) {
              modeObj["_" + prop2] = modeObj[prop2];
            }
            modeObj[prop2] = exts[prop2];
          }
        }
        modeObj.name = spec.name;
        if (spec.helperType) {
          modeObj.helperType = spec.helperType;
        }
        if (spec.modeProps) {
          for (var prop$1 in spec.modeProps) {
            modeObj[prop$1] = spec.modeProps[prop$1];
          }
        }
        return modeObj;
      }
      var modeExtensions = {};
      function extendMode(mode, properties) {
        var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {};
        copyObj(properties, exts);
      }
      function copyState(mode, state) {
        if (state === true) {
          return state;
        }
        if (mode.copyState) {
          return mode.copyState(state);
        }
        var nstate = {};
        for (var n in state) {
          var val = state[n];
          if (val instanceof Array) {
            val = val.concat([]);
          }
          nstate[n] = val;
        }
        return nstate;
      }
      function innerMode(mode, state) {
        var info;
        while (mode.innerMode) {
          info = mode.innerMode(state);
          if (!info || info.mode == mode) {
            break;
          }
          state = info.state;
          mode = info.mode;
        }
        return info || {mode, state};
      }
      function startState(mode, a1, a2) {
        return mode.startState ? mode.startState(a1, a2) : true;
      }
      var StringStream = function(string2, tabSize, lineOracle) {
        this.pos = this.start = 0;
        this.string = string2;
        this.tabSize = tabSize || 8;
        this.lastColumnPos = this.lastColumnValue = 0;
        this.lineStart = 0;
        this.lineOracle = lineOracle;
      };
      StringStream.prototype.eol = function() {
        return this.pos >= this.string.length;
      };
      StringStream.prototype.sol = function() {
        return this.pos == this.lineStart;
      };
      StringStream.prototype.peek = function() {
        return this.string.charAt(this.pos) || void 0;
      };
      StringStream.prototype.next = function() {
        if (this.pos < this.string.length) {
          return this.string.charAt(this.pos++);
        }
      };
      StringStream.prototype.eat = function(match) {
        var ch = this.string.charAt(this.pos);
        var ok;
        if (typeof match == "string") {
          ok = ch == match;
        } else {
          ok = ch && (match.test ? match.test(ch) : match(ch));
        }
        if (ok) {
          ++this.pos;
          return ch;
        }
      };
      StringStream.prototype.eatWhile = function(match) {
        var start = this.pos;
        while (this.eat(match)) {
        }
        return this.pos > start;
      };
      StringStream.prototype.eatSpace = function() {
        var start = this.pos;
        while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) {
          ++this.pos;
        }
        return this.pos > start;
      };
      StringStream.prototype.skipToEnd = function() {
        this.pos = this.string.length;
      };
      StringStream.prototype.skipTo = function(ch) {
        var found = this.string.indexOf(ch, this.pos);
        if (found > -1) {
          this.pos = found;
          return true;
        }
      };
      StringStream.prototype.backUp = function(n) {
        this.pos -= n;
      };
      StringStream.prototype.column = function() {
        if (this.lastColumnPos < this.start) {
          this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
          this.lastColumnPos = this.start;
        }
        return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
      };
      StringStream.prototype.indentation = function() {
        return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
      };
      StringStream.prototype.match = function(pattern, consume, caseInsensitive) {
        if (typeof pattern == "string") {
          var cased = function(str) {
            return caseInsensitive ? str.toLowerCase() : str;
          };
          var substr = this.string.substr(this.pos, pattern.length);
          if (cased(substr) == cased(pattern)) {
            if (consume !== false) {
              this.pos += pattern.length;
            }
            return true;
          }
        } else {
          var match = this.string.slice(this.pos).match(pattern);
          if (match && match.index > 0) {
            return null;
          }
          if (match && consume !== false) {
            this.pos += match[0].length;
          }
          return match;
        }
      };
      StringStream.prototype.current = function() {
        return this.string.slice(this.start, this.pos);
      };
      StringStream.prototype.hideFirstChars = function(n, inner) {
        this.lineStart += n;
        try {
          return inner();
        } finally {
          this.lineStart -= n;
        }
      };
      StringStream.prototype.lookAhead = function(n) {
        var oracle = this.lineOracle;
        return oracle && oracle.lookAhead(n);
      };
      StringStream.prototype.baseToken = function() {
        var oracle = this.lineOracle;
        return oracle && oracle.baseToken(this.pos);
      };
      function getLine(doc, n) {
        n -= doc.first;
        if (n < 0 || n >= doc.size) {
          throw new Error("There is no line " + (n + doc.first) + " in the document.");
        }
        var chunk = doc;
        while (!chunk.lines) {
          for (var i2 = 0; ; ++i2) {
            var child = chunk.children[i2], sz = child.chunkSize();
            if (n < sz) {
              chunk = child;
              break;
            }
            n -= sz;
          }
        }
        return chunk.lines[n];
      }
      function getBetween(doc, start, end) {
        var out = [], n = start.line;
        doc.iter(start.line, end.line + 1, function(line) {
          var text2 = line.text;
          if (n == end.line) {
            text2 = text2.slice(0, end.ch);
          }
          if (n == start.line) {
            text2 = text2.slice(start.ch);
          }
          out.push(text2);
          ++n;
        });
        return out;
      }
      function getLines(doc, from, to) {
        var out = [];
        doc.iter(from, to, function(line) {
          out.push(line.text);
        });
        return out;
      }
      function updateLineHeight(line, height4) {
        var diff = height4 - line.height;
        if (diff) {
          for (var n = line; n; n = n.parent) {
            n.height += diff;
          }
        }
      }
      function lineNo(line) {
        if (line.parent == null) {
          return null;
        }
        var cur = line.parent, no = indexOf(cur.lines, line);
        for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
          for (var i2 = 0; ; ++i2) {
            if (chunk.children[i2] == cur) {
              break;
            }
            no += chunk.children[i2].chunkSize();
          }
        }
        return no + cur.first;
      }
      function lineAtHeight(chunk, h) {
        var n = chunk.first;
        outer:
          do {
            for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) {
              var child = chunk.children[i$12], ch = child.height;
              if (h < ch) {
                chunk = child;
                continue outer;
              }
              h -= ch;
              n += child.chunkSize();
            }
            return n;
          } while (!chunk.lines);
        var i2 = 0;
        for (; i2 < chunk.lines.length; ++i2) {
          var line = chunk.lines[i2], lh = line.height;
          if (h < lh) {
            break;
          }
          h -= lh;
        }
        return n + i2;
      }
      function isLine(doc, l) {
        return l >= doc.first && l < doc.first + doc.size;
      }
      function lineNumberFor(options, i2) {
        return String(options.lineNumberFormatter(i2 + options.firstLineNumber));
      }
      function Pos(line, ch, sticky) {
        if (sticky === void 0)
          sticky = null;
        if (!(this instanceof Pos)) {
          return new Pos(line, ch, sticky);
        }
        this.line = line;
        this.ch = ch;
        this.sticky = sticky;
      }
      function cmp(a, b) {
        return a.line - b.line || a.ch - b.ch;
      }
      function equalCursorPos(a, b) {
        return a.sticky == b.sticky && cmp(a, b) == 0;
      }
      function copyPos(x2) {
        return Pos(x2.line, x2.ch);
      }
      function maxPos(a, b) {
        return cmp(a, b) < 0 ? b : a;
      }
      function minPos(a, b) {
        return cmp(a, b) < 0 ? a : b;
      }
      function clipLine(doc, n) {
        return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));
      }
      function clipPos(doc, pos) {
        if (pos.line < doc.first) {
          return Pos(doc.first, 0);
        }
        var last = doc.first + doc.size - 1;
        if (pos.line > last) {
          return Pos(last, getLine(doc, last).text.length);
        }
        return clipToLen(pos, getLine(doc, pos.line).text.length);
      }
      function clipToLen(pos, linelen) {
        var ch = pos.ch;
        if (ch == null || ch > linelen) {
          return Pos(pos.line, linelen);
        } else if (ch < 0) {
          return Pos(pos.line, 0);
        } else {
          return pos;
        }
      }
      function clipPosArray(doc, array2) {
        var out = [];
        for (var i2 = 0; i2 < array2.length; i2++) {
          out[i2] = clipPos(doc, array2[i2]);
        }
        return out;
      }
      var SavedContext = function(state, lookAhead) {
        this.state = state;
        this.lookAhead = lookAhead;
      };
      var Context2 = function(doc, state, line, lookAhead) {
        this.state = state;
        this.doc = doc;
        this.line = line;
        this.maxLookAhead = lookAhead || 0;
        this.baseTokens = null;
        this.baseTokenPos = 1;
      };
      Context2.prototype.lookAhead = function(n) {
        var line = this.doc.getLine(this.line + n);
        if (line != null && n > this.maxLookAhead) {
          this.maxLookAhead = n;
        }
        return line;
      };
      Context2.prototype.baseToken = function(n) {
        if (!this.baseTokens) {
          return null;
        }
        while (this.baseTokens[this.baseTokenPos] <= n) {
          this.baseTokenPos += 2;
        }
        var type = this.baseTokens[this.baseTokenPos + 1];
        return {
          type: type && type.replace(/( |^)overlay .*/, ""),
          size: this.baseTokens[this.baseTokenPos] - n
        };
      };
      Context2.prototype.nextLine = function() {
        this.line++;
        if (this.maxLookAhead > 0) {
          this.maxLookAhead--;
        }
      };
      Context2.fromSaved = function(doc, saved, line) {
        if (saved instanceof SavedContext) {
          return new Context2(doc, copyState(doc.mode, saved.state), line, saved.lookAhead);
        } else {
          return new Context2(doc, copyState(doc.mode, saved), line);
        }
      };
      Context2.prototype.save = function(copy2) {
        var state = copy2 !== false ? copyState(this.doc.mode, this.state) : this.state;
        return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state;
      };
      function highlightLine(cm, line, context, forceToEnd) {
        var st = [cm.state.modeGen], lineClasses = {};
        runMode(cm, line.text, cm.doc.mode, context, function(end, style) {
          return st.push(end, style);
        }, lineClasses, forceToEnd);
        var state = context.state;
        var loop = function(o2) {
          context.baseTokens = st;
          var overlay = cm.state.overlays[o2], i2 = 1, at = 0;
          context.state = true;
          runMode(cm, line.text, overlay.mode, context, function(end, style) {
            var start = i2;
            while (at < end) {
              var i_end = st[i2];
              if (i_end > end) {
                st.splice(i2, 1, end, st[i2 + 1], i_end);
              }
              i2 += 2;
              at = Math.min(end, i_end);
            }
            if (!style) {
              return;
            }
            if (overlay.opaque) {
              st.splice(start, i2 - start, end, "overlay " + style);
              i2 = start + 2;
            } else {
              for (; start < i2; start += 2) {
                var cur = st[start + 1];
                st[start + 1] = (cur ? cur + " " : "") + "overlay " + style;
              }
            }
          }, lineClasses);
          context.state = state;
          context.baseTokens = null;
          context.baseTokenPos = 1;
        };
        for (var o = 0; o < cm.state.overlays.length; ++o)
          loop(o);
        return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
      }
      function getLineStyles(cm, line, updateFrontier) {
        if (!line.styles || line.styles[0] != cm.state.modeGen) {
          var context = getContextBefore(cm, lineNo(line));
          var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
          var result = highlightLine(cm, line, context);
          if (resetState) {
            context.state = resetState;
          }
          line.stateAfter = context.save(!resetState);
          line.styles = result.styles;
          if (result.classes) {
            line.styleClasses = result.classes;
          } else if (line.styleClasses) {
            line.styleClasses = null;
          }
          if (updateFrontier === cm.doc.highlightFrontier) {
            cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier);
          }
        }
        return line.styles;
      }
      function getContextBefore(cm, n, precise) {
        var doc = cm.doc, display = cm.display;
        if (!doc.mode.startState) {
          return new Context2(doc, true, n);
        }
        var start = findStartLine(cm, n, precise);
        var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
        var context = saved ? Context2.fromSaved(doc, saved, start) : new Context2(doc, startState(doc.mode), start);
        doc.iter(start, n, function(line) {
          processLine(cm, line.text, context);
          var pos = context.line;
          line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
          context.nextLine();
        });
        if (precise) {
          doc.modeFrontier = context.line;
        }
        return context;
      }
      function processLine(cm, text2, context, startAt) {
        var mode = cm.doc.mode;
        var stream = new StringStream(text2, cm.options.tabSize, context);
        stream.start = stream.pos = startAt || 0;
        if (text2 == "") {
          callBlankLine(mode, context.state);
        }
        while (!stream.eol()) {
          readToken(mode, stream, context.state);
          stream.start = stream.pos;
        }
      }
      function callBlankLine(mode, state) {
        if (mode.blankLine) {
          return mode.blankLine(state);
        }
        if (!mode.innerMode) {
          return;
        }
        var inner = innerMode(mode, state);
        if (inner.mode.blankLine) {
          return inner.mode.blankLine(inner.state);
        }
      }
      function readToken(mode, stream, state, inner) {
        for (var i2 = 0; i2 < 10; i2++) {
          if (inner) {
            inner[0] = innerMode(mode, state).mode;
          }
          var style = mode.token(stream, state);
          if (stream.pos > stream.start) {
            return style;
          }
        }
        throw new Error("Mode " + mode.name + " failed to advance stream.");
      }
      var Token = function(stream, type, state) {
        this.start = stream.start;
        this.end = stream.pos;
        this.string = stream.current();
        this.type = type || null;
        this.state = state;
      };
      function takeToken(cm, pos, precise, asArray) {
        var doc = cm.doc, mode = doc.mode, style;
        pos = clipPos(doc, pos);
        var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
        var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
        if (asArray) {
          tokens = [];
        }
        while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
          stream.start = stream.pos;
          style = readToken(mode, stream, context.state);
          if (asArray) {
            tokens.push(new Token(stream, style, copyState(doc.mode, context.state)));
          }
        }
        return asArray ? tokens : new Token(stream, style, context.state);
      }
      function extractLineClasses(type, output) {
        if (type) {
          for (; ; ) {
            var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
            if (!lineClass) {
              break;
            }
            type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
            var prop2 = lineClass[1] ? "bgClass" : "textClass";
            if (output[prop2] == null) {
              output[prop2] = lineClass[2];
            } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop2])) {
              output[prop2] += " " + lineClass[2];
            }
          }
        }
        return type;
      }
      function runMode(cm, text2, mode, context, f, lineClasses, forceToEnd) {
        var flattenSpans = mode.flattenSpans;
        if (flattenSpans == null) {
          flattenSpans = cm.options.flattenSpans;
        }
        var curStart = 0, curStyle = null;
        var stream = new StringStream(text2, cm.options.tabSize, context), style;
        var inner = cm.options.addModeClass && [null];
        if (text2 == "") {
          extractLineClasses(callBlankLine(mode, context.state), lineClasses);
        }
        while (!stream.eol()) {
          if (stream.pos > cm.options.maxHighlightLength) {
            flattenSpans = false;
            if (forceToEnd) {
              processLine(cm, text2, context, stream.pos);
            }
            stream.pos = text2.length;
            style = null;
          } else {
            style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
          }
          if (inner) {
            var mName = inner[0].name;
            if (mName) {
              style = "m-" + (style ? mName + " " + style : mName);
            }
          }
          if (!flattenSpans || curStyle != style) {
            while (curStart < stream.start) {
              curStart = Math.min(stream.start, curStart + 5e3);
              f(curStart, curStyle);
            }
            curStyle = style;
          }
          stream.start = stream.pos;
        }
        while (curStart < stream.pos) {
          var pos = Math.min(stream.pos, curStart + 5e3);
          f(pos, curStyle);
          curStart = pos;
        }
      }
      function findStartLine(cm, n, precise) {
        var minindent, minline, doc = cm.doc;
        var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100);
        for (var search = n; search > lim; --search) {
          if (search <= doc.first) {
            return doc.first;
          }
          var line = getLine(doc, search - 1), after = line.stateAfter;
          if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) {
            return search;
          }
          var indented = countColumn(line.text, null, cm.options.tabSize);
          if (minline == null || minindent > indented) {
            minline = search - 1;
            minindent = indented;
          }
        }
        return minline;
      }
      function retreatFrontier(doc, n) {
        doc.modeFrontier = Math.min(doc.modeFrontier, n);
        if (doc.highlightFrontier < n - 10) {
          return;
        }
        var start = doc.first;
        for (var line = n - 1; line > start; line--) {
          var saved = getLine(doc, line).stateAfter;
          if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
            start = line + 1;
            break;
          }
        }
        doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
      }
      var sawReadOnlySpans = false, sawCollapsedSpans = false;
      function seeReadOnlySpans() {
        sawReadOnlySpans = true;
      }
      function seeCollapsedSpans() {
        sawCollapsedSpans = true;
      }
      function MarkedSpan(marker, from, to) {
        this.marker = marker;
        this.from = from;
        this.to = to;
      }
      function getMarkedSpanFor(spans, marker) {
        if (spans) {
          for (var i2 = 0; i2 < spans.length; ++i2) {
            var span = spans[i2];
            if (span.marker == marker) {
              return span;
            }
          }
        }
      }
      function removeMarkedSpan(spans, span) {
        var r;
        for (var i2 = 0; i2 < spans.length; ++i2) {
          if (spans[i2] != span) {
            (r || (r = [])).push(spans[i2]);
          }
        }
        return r;
      }
      function addMarkedSpan(line, span) {
        line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
        span.marker.attachLine(line);
      }
      function markedSpansBefore(old, startCh, isInsert) {
        var nw;
        if (old) {
          for (var i2 = 0; i2 < old.length; ++i2) {
            var span = old[i2], marker = span.marker;
            var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
            if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
              var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
              (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
            }
          }
        }
        return nw;
      }
      function markedSpansAfter(old, endCh, isInsert) {
        var nw;
        if (old) {
          for (var i2 = 0; i2 < old.length; ++i2) {
            var span = old[i2], marker = span.marker;
            var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
            if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
              var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
              (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh));
            }
          }
        }
        return nw;
      }
      function stretchSpansOverChange(doc, change) {
        if (change.full) {
          return null;
        }
        var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
        var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
        if (!oldFirst && !oldLast) {
          return null;
        }
        var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
        var first = markedSpansBefore(oldFirst, startCh, isInsert);
        var last = markedSpansAfter(oldLast, endCh, isInsert);
        var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
        if (first) {
          for (var i2 = 0; i2 < first.length; ++i2) {
            var span = first[i2];
            if (span.to == null) {
              var found = getMarkedSpanFor(last, span.marker);
              if (!found) {
                span.to = startCh;
              } else if (sameLine) {
                span.to = found.to == null ? null : found.to + offset;
              }
            }
          }
        }
        if (last) {
          for (var i$12 = 0; i$12 < last.length; ++i$12) {
            var span$1 = last[i$12];
            if (span$1.to != null) {
              span$1.to += offset;
            }
            if (span$1.from == null) {
              var found$1 = getMarkedSpanFor(first, span$1.marker);
              if (!found$1) {
                span$1.from = offset;
                if (sameLine) {
                  (first || (first = [])).push(span$1);
                }
              }
            } else {
              span$1.from += offset;
              if (sameLine) {
                (first || (first = [])).push(span$1);
              }
            }
          }
        }
        if (first) {
          first = clearEmptySpans(first);
        }
        if (last && last != first) {
          last = clearEmptySpans(last);
        }
        var newMarkers = [first];
        if (!sameLine) {
          var gap = change.text.length - 2, gapMarkers;
          if (gap > 0 && first) {
            for (var i$22 = 0; i$22 < first.length; ++i$22) {
              if (first[i$22].to == null) {
                (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null));
              }
            }
          }
          for (var i$3 = 0; i$3 < gap; ++i$3) {
            newMarkers.push(gapMarkers);
          }
          newMarkers.push(last);
        }
        return newMarkers;
      }
      function clearEmptySpans(spans) {
        for (var i2 = 0; i2 < spans.length; ++i2) {
          var span = spans[i2];
          if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {
            spans.splice(i2--, 1);
          }
        }
        if (!spans.length) {
          return null;
        }
        return spans;
      }
      function removeReadOnlyRanges(doc, from, to) {
        var markers = null;
        doc.iter(from.line, to.line + 1, function(line) {
          if (line.markedSpans) {
            for (var i3 = 0; i3 < line.markedSpans.length; ++i3) {
              var mark = line.markedSpans[i3].marker;
              if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {
                (markers || (markers = [])).push(mark);
              }
            }
          }
        });
        if (!markers) {
          return null;
        }
        var parts = [{from, to}];
        for (var i2 = 0; i2 < markers.length; ++i2) {
          var mk = markers[i2], m = mk.find(0);
          for (var j = 0; j < parts.length; ++j) {
            var p = parts[j];
            if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) {
              continue;
            }
            var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
            if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {
              newParts.push({from: p.from, to: m.from});
            }
            if (dto > 0 || !mk.inclusiveRight && !dto) {
              newParts.push({from: m.to, to: p.to});
            }
            parts.splice.apply(parts, newParts);
            j += newParts.length - 3;
          }
        }
        return parts;
      }
      function detachMarkedSpans(line) {
        var spans = line.markedSpans;
        if (!spans) {
          return;
        }
        for (var i2 = 0; i2 < spans.length; ++i2) {
          spans[i2].marker.detachLine(line);
        }
        line.markedSpans = null;
      }
      function attachMarkedSpans(line, spans) {
        if (!spans) {
          return;
        }
        for (var i2 = 0; i2 < spans.length; ++i2) {
          spans[i2].marker.attachLine(line);
        }
        line.markedSpans = spans;
      }
      function extraLeft(marker) {
        return marker.inclusiveLeft ? -1 : 0;
      }
      function extraRight(marker) {
        return marker.inclusiveRight ? 1 : 0;
      }
      function compareCollapsedMarkers(a, b) {
        var lenDiff = a.lines.length - b.lines.length;
        if (lenDiff != 0) {
          return lenDiff;
        }
        var aPos = a.find(), bPos = b.find();
        var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
        if (fromCmp) {
          return -fromCmp;
        }
        var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
        if (toCmp) {
          return toCmp;
        }
        return b.id - a.id;
      }
      function collapsedSpanAtSide(line, start) {
        var sps = sawCollapsedSpans && line.markedSpans, found;
        if (sps) {
          for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) {
            sp = sps[i2];
            if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
              found = sp.marker;
            }
          }
        }
        return found;
      }
      function collapsedSpanAtStart(line) {
        return collapsedSpanAtSide(line, true);
      }
      function collapsedSpanAtEnd(line) {
        return collapsedSpanAtSide(line, false);
      }
      function collapsedSpanAround(line, ch) {
        var sps = sawCollapsedSpans && line.markedSpans, found;
        if (sps) {
          for (var i2 = 0; i2 < sps.length; ++i2) {
            var sp = sps[i2];
            if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
              found = sp.marker;
            }
          }
        }
        return found;
      }
      function conflictingCollapsedRange(doc, lineNo2, from, to, marker) {
        var line = getLine(doc, lineNo2);
        var sps = sawCollapsedSpans && line.markedSpans;
        if (sps) {
          for (var i2 = 0; i2 < sps.length; ++i2) {
            var sp = sps[i2];
            if (!sp.marker.collapsed) {
              continue;
            }
            var found = sp.marker.find(0);
            var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
            var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
            if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) {
              continue;
            }
            if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) {
              return true;
            }
          }
        }
      }
      function visualLine(line) {
        var merged;
        while (merged = collapsedSpanAtStart(line)) {
          line = merged.find(-1, true).line;
        }
        return line;
      }
      function visualLineEnd(line) {
        var merged;
        while (merged = collapsedSpanAtEnd(line)) {
          line = merged.find(1, true).line;
        }
        return line;
      }
      function visualLineContinued(line) {
        var merged, lines;
        while (merged = collapsedSpanAtEnd(line)) {
          line = merged.find(1, true).line;
          (lines || (lines = [])).push(line);
        }
        return lines;
      }
      function visualLineNo(doc, lineN) {
        var line = getLine(doc, lineN), vis = visualLine(line);
        if (line == vis) {
          return lineN;
        }
        return lineNo(vis);
      }
      function visualLineEndNo(doc, lineN) {
        if (lineN > doc.lastLine()) {
          return lineN;
        }
        var line = getLine(doc, lineN), merged;
        if (!lineIsHidden(doc, line)) {
          return lineN;
        }
        while (merged = collapsedSpanAtEnd(line)) {
          line = merged.find(1, true).line;
        }
        return lineNo(line) + 1;
      }
      function lineIsHidden(doc, line) {
        var sps = sawCollapsedSpans && line.markedSpans;
        if (sps) {
          for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) {
            sp = sps[i2];
            if (!sp.marker.collapsed) {
              continue;
            }
            if (sp.from == null) {
              return true;
            }
            if (sp.marker.widgetNode) {
              continue;
            }
            if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {
              return true;
            }
          }
        }
      }
      function lineIsHiddenInner(doc, line, span) {
        if (span.to == null) {
          var end = span.marker.find(1, true);
          return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
        }
        if (span.marker.inclusiveRight && span.to == line.text.length) {
          return true;
        }
        for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) {
          sp = line.markedSpans[i2];
          if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) {
            return true;
          }
        }
      }
      function heightAtLine(lineObj) {
        lineObj = visualLine(lineObj);
        var h = 0, chunk = lineObj.parent;
        for (var i2 = 0; i2 < chunk.lines.length; ++i2) {
          var line = chunk.lines[i2];
          if (line == lineObj) {
            break;
          } else {
            h += line.height;
          }
        }
        for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
          for (var i$12 = 0; i$12 < p.children.length; ++i$12) {
            var cur = p.children[i$12];
            if (cur == chunk) {
              break;
            } else {
              h += cur.height;
            }
          }
        }
        return h;
      }
      function lineLength(line) {
        if (line.height == 0) {
          return 0;
        }
        var len = line.text.length, merged, cur = line;
        while (merged = collapsedSpanAtStart(cur)) {
          var found = merged.find(0, true);
          cur = found.from.line;
          len += found.from.ch - found.to.ch;
        }
        cur = line;
        while (merged = collapsedSpanAtEnd(cur)) {
          var found$1 = merged.find(0, true);
          len -= cur.text.length - found$1.from.ch;
          cur = found$1.to.line;
          len += cur.text.length - found$1.to.ch;
        }
        return len;
      }
      function findMaxLine(cm) {
        var d = cm.display, doc = cm.doc;
        d.maxLine = getLine(doc, doc.first);
        d.maxLineLength = lineLength(d.maxLine);
        d.maxLineChanged = true;
        doc.iter(function(line) {
          var len = lineLength(line);
          if (len > d.maxLineLength) {
            d.maxLineLength = len;
            d.maxLine = line;
          }
        });
      }
      var Line = function(text2, markedSpans, estimateHeight2) {
        this.text = text2;
        attachMarkedSpans(this, markedSpans);
        this.height = estimateHeight2 ? estimateHeight2(this) : 1;
      };
      Line.prototype.lineNo = function() {
        return lineNo(this);
      };
      eventMixin(Line);
      function updateLine(line, text2, markedSpans, estimateHeight2) {
        line.text = text2;
        if (line.stateAfter) {
          line.stateAfter = null;
        }
        if (line.styles) {
          line.styles = null;
        }
        if (line.order != null) {
          line.order = null;
        }
        detachMarkedSpans(line);
        attachMarkedSpans(line, markedSpans);
        var estHeight = estimateHeight2 ? estimateHeight2(line) : 1;
        if (estHeight != line.height) {
          updateLineHeight(line, estHeight);
        }
      }
      function cleanUpLine(line) {
        line.parent = null;
        detachMarkedSpans(line);
      }
      var styleToClassCache = {}, styleToClassCacheWithMode = {};
      function interpretTokenStyle(style, options) {
        if (!style || /^\s*$/.test(style)) {
          return null;
        }
        var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
        return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&"));
      }
      function buildLineContent(cm, lineView) {
        var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
        var builder = {
          pre: eltP("pre", [content], "CodeMirror-line"),
          content,
          col: 0,
          pos: 0,
          cm,
          trailingSpace: false,
          splitSpaces: cm.getOption("lineWrapping")
        };
        lineView.measure = {};
        for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) {
          var line = i2 ? lineView.rest[i2 - 1] : lineView.line, order = void 0;
          builder.pos = 0;
          builder.addToken = buildToken;
          if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) {
            builder.addToken = buildTokenBadBidi(builder.addToken, order);
          }
          builder.map = [];
          var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
          insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
          if (line.styleClasses) {
            if (line.styleClasses.bgClass) {
              builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
            }
            if (line.styleClasses.textClass) {
              builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
            }
          }
          if (builder.map.length == 0) {
            builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
          }
          if (i2 == 0) {
            lineView.measure.map = builder.map;
            lineView.measure.cache = {};
          } else {
            (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
            (lineView.measure.caches || (lineView.measure.caches = [])).push({});
          }
        }
        if (webkit) {
          var last = builder.content.lastChild;
          if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) {
            builder.content.className = "cm-tab-wrap-hack";
          }
        }
        signal(cm, "renderLine", cm, lineView.line, builder.pre);
        if (builder.pre.className) {
          builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
        }
        return builder;
      }
      function defaultSpecialCharPlaceholder(ch) {
        var token = elt("span", "\u2022", "cm-invalidchar");
        token.title = "\\u" + ch.charCodeAt(0).toString(16);
        token.setAttribute("aria-label", token.title);
        return token;
      }
      function buildToken(builder, text2, style, startStyle, endStyle, css, attributes) {
        if (!text2) {
          return;
        }
        var displayText = builder.splitSpaces ? splitSpaces(text2, builder.trailingSpace) : text2;
        var special = builder.cm.state.specialChars, mustWrap = false;
        var content;
        if (!special.test(text2)) {
          builder.col += text2.length;
          content = document.createTextNode(displayText);
          builder.map.push(builder.pos, builder.pos + text2.length, content);
          if (ie && ie_version < 9) {
            mustWrap = true;
          }
          builder.pos += text2.length;
        } else {
          content = document.createDocumentFragment();
          var pos = 0;
          while (true) {
            special.lastIndex = pos;
            var m = special.exec(text2);
            var skipped = m ? m.index - pos : text2.length - pos;
            if (skipped) {
              var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
              if (ie && ie_version < 9) {
                content.appendChild(elt("span", [txt]));
              } else {
                content.appendChild(txt);
              }
              builder.map.push(builder.pos, builder.pos + skipped, txt);
              builder.col += skipped;
              builder.pos += skipped;
            }
            if (!m) {
              break;
            }
            pos += skipped + 1;
            var txt$1 = void 0;
            if (m[0] == "	") {
              var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
              txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
              txt$1.setAttribute("role", "presentation");
              txt$1.setAttribute("cm-text", "	");
              builder.col += tabWidth;
            } else if (m[0] == "\r" || m[0] == "\n") {
              txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240D" : "\u2424", "cm-invalidchar"));
              txt$1.setAttribute("cm-text", m[0]);
              builder.col += 1;
            } else {
              txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
              txt$1.setAttribute("cm-text", m[0]);
              if (ie && ie_version < 9) {
                content.appendChild(elt("span", [txt$1]));
              } else {
                content.appendChild(txt$1);
              }
              builder.col += 1;
            }
            builder.map.push(builder.pos, builder.pos + 1, txt$1);
            builder.pos++;
          }
        }
        builder.trailingSpace = displayText.charCodeAt(text2.length - 1) == 32;
        if (style || startStyle || endStyle || mustWrap || css || attributes) {
          var fullStyle = style || "";
          if (startStyle) {
            fullStyle += startStyle;
          }
          if (endStyle) {
            fullStyle += endStyle;
          }
          var token = elt("span", [content], fullStyle, css);
          if (attributes) {
            for (var attr2 in attributes) {
              if (attributes.hasOwnProperty(attr2) && attr2 != "style" && attr2 != "class") {
                token.setAttribute(attr2, attributes[attr2]);
              }
            }
          }
          return builder.content.appendChild(token);
        }
        builder.content.appendChild(content);
      }
      function splitSpaces(text2, trailingBefore) {
        if (text2.length > 1 && !/  /.test(text2)) {
          return text2;
        }
        var spaceBefore = trailingBefore, result = "";
        for (var i2 = 0; i2 < text2.length; i2++) {
          var ch = text2.charAt(i2);
          if (ch == " " && spaceBefore && (i2 == text2.length - 1 || text2.charCodeAt(i2 + 1) == 32)) {
            ch = "\xA0";
          }
          result += ch;
          spaceBefore = ch == " ";
        }
        return result;
      }
      function buildTokenBadBidi(inner, order) {
        return function(builder, text2, style, startStyle, endStyle, css, attributes) {
          style = style ? style + " cm-force-border" : "cm-force-border";
          var start = builder.pos, end = start + text2.length;
          for (; ; ) {
            var part = void 0;
            for (var i2 = 0; i2 < order.length; i2++) {
              part = order[i2];
              if (part.to > start && part.from <= start) {
                break;
              }
            }
            if (part.to >= end) {
              return inner(builder, text2, style, startStyle, endStyle, css, attributes);
            }
            inner(builder, text2.slice(0, part.to - start), style, startStyle, null, css, attributes);
            startStyle = null;
            text2 = text2.slice(part.to - start);
            start = part.to;
          }
        };
      }
      function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
        var widget = !ignoreWidget && marker.widgetNode;
        if (widget) {
          builder.map.push(builder.pos, builder.pos + size, widget);
        }
        if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
          if (!widget) {
            widget = builder.content.appendChild(document.createElement("span"));
          }
          widget.setAttribute("cm-marker", marker.id);
        }
        if (widget) {
          builder.cm.display.input.setUneditable(widget);
          builder.content.appendChild(widget);
        }
        builder.pos += size;
        builder.trailingSpace = false;
      }
      function insertLineContent(line, builder, styles) {
        var spans = line.markedSpans, allText = line.text, at = 0;
        if (!spans) {
          for (var i$12 = 1; i$12 < styles.length; i$12 += 2) {
            builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options));
          }
          return;
        }
        var len = allText.length, pos = 0, i2 = 1, text2 = "", style, css;
        var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
        for (; ; ) {
          if (nextChange == pos) {
            spanStyle = spanEndStyle = spanStartStyle = css = "";
            attributes = null;
            collapsed = null;
            nextChange = Infinity;
            var foundBookmarks = [], endStyles = void 0;
            for (var j = 0; j < spans.length; ++j) {
              var sp = spans[j], m = sp.marker;
              if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
                foundBookmarks.push(m);
              } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
                if (sp.to != null && sp.to != pos && nextChange > sp.to) {
                  nextChange = sp.to;
                  spanEndStyle = "";
                }
                if (m.className) {
                  spanStyle += " " + m.className;
                }
                if (m.css) {
                  css = (css ? css + ";" : "") + m.css;
                }
                if (m.startStyle && sp.from == pos) {
                  spanStartStyle += " " + m.startStyle;
                }
                if (m.endStyle && sp.to == nextChange) {
                  (endStyles || (endStyles = [])).push(m.endStyle, sp.to);
                }
                if (m.title) {
                  (attributes || (attributes = {})).title = m.title;
                }
                if (m.attributes) {
                  for (var attr2 in m.attributes) {
                    (attributes || (attributes = {}))[attr2] = m.attributes[attr2];
                  }
                }
                if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {
                  collapsed = sp;
                }
              } else if (sp.from > pos && nextChange > sp.from) {
                nextChange = sp.from;
              }
            }
            if (endStyles) {
              for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) {
                if (endStyles[j$1 + 1] == nextChange) {
                  spanEndStyle += " " + endStyles[j$1];
                }
              }
            }
            if (!collapsed || collapsed.from == pos) {
              for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) {
                buildCollapsedSpan(builder, 0, foundBookmarks[j$2]);
              }
            }
            if (collapsed && (collapsed.from || 0) == pos) {
              buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null);
              if (collapsed.to == null) {
                return;
              }
              if (collapsed.to == pos) {
                collapsed = false;
              }
            }
          }
          if (pos >= len) {
            break;
          }
          var upto = Math.min(len, nextChange);
          while (true) {
            if (text2) {
              var end = pos + text2.length;
              if (!collapsed) {
                var tokenText = end > upto ? text2.slice(0, upto - pos) : text2;
                builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
              }
              if (end >= upto) {
                text2 = text2.slice(upto - pos);
                pos = upto;
                break;
              }
              pos = end;
              spanStartStyle = "";
            }
            text2 = allText.slice(at, at = styles[i2++]);
            style = interpretTokenStyle(styles[i2++], builder.cm.options);
          }
        }
      }
      function LineView(doc, line, lineN) {
        this.line = line;
        this.rest = visualLineContinued(line);
        this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
        this.node = this.text = null;
        this.hidden = lineIsHidden(doc, line);
      }
      function buildViewArray(cm, from, to) {
        var array2 = [], nextPos;
        for (var pos = from; pos < to; pos = nextPos) {
          var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
          nextPos = pos + view.size;
          array2.push(view);
        }
        return array2;
      }
      var operationGroup = null;
      function pushOperation(op) {
        if (operationGroup) {
          operationGroup.ops.push(op);
        } else {
          op.ownsGroup = operationGroup = {
            ops: [op],
            delayedCallbacks: []
          };
        }
      }
      function fireCallbacksForOps(group) {
        var callbacks = group.delayedCallbacks, i2 = 0;
        do {
          for (; i2 < callbacks.length; i2++) {
            callbacks[i2].call(null);
          }
          for (var j = 0; j < group.ops.length; j++) {
            var op = group.ops[j];
            if (op.cursorActivityHandlers) {
              while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {
                op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
              }
            }
          }
        } while (i2 < callbacks.length);
      }
      function finishOperation(op, endCb) {
        var group = op.ownsGroup;
        if (!group) {
          return;
        }
        try {
          fireCallbacksForOps(group);
        } finally {
          operationGroup = null;
          endCb(group);
        }
      }
      var orphanDelayedCallbacks = null;
      function signalLater(emitter, type) {
        var arr = getHandlers(emitter, type);
        if (!arr.length) {
          return;
        }
        var args = Array.prototype.slice.call(arguments, 2), list;
        if (operationGroup) {
          list = operationGroup.delayedCallbacks;
        } else if (orphanDelayedCallbacks) {
          list = orphanDelayedCallbacks;
        } else {
          list = orphanDelayedCallbacks = [];
          setTimeout(fireOrphanDelayed, 0);
        }
        var loop = function(i3) {
          list.push(function() {
            return arr[i3].apply(null, args);
          });
        };
        for (var i2 = 0; i2 < arr.length; ++i2)
          loop(i2);
      }
      function fireOrphanDelayed() {
        var delayed = orphanDelayedCallbacks;
        orphanDelayedCallbacks = null;
        for (var i2 = 0; i2 < delayed.length; ++i2) {
          delayed[i2]();
        }
      }
      function updateLineForChanges(cm, lineView, lineN, dims) {
        for (var j = 0; j < lineView.changes.length; j++) {
          var type = lineView.changes[j];
          if (type == "text") {
            updateLineText(cm, lineView);
          } else if (type == "gutter") {
            updateLineGutter(cm, lineView, lineN, dims);
          } else if (type == "class") {
            updateLineClasses(cm, lineView);
          } else if (type == "widget") {
            updateLineWidgets(cm, lineView, dims);
          }
        }
        lineView.changes = null;
      }
      function ensureLineWrapped(lineView) {
        if (lineView.node == lineView.text) {
          lineView.node = elt("div", null, null, "position: relative");
          if (lineView.text.parentNode) {
            lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
          }
          lineView.node.appendChild(lineView.text);
          if (ie && ie_version < 8) {
            lineView.node.style.zIndex = 2;
          }
        }
        return lineView.node;
      }
      function updateLineBackground(cm, lineView) {
        var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
        if (cls) {
          cls += " CodeMirror-linebackground";
        }
        if (lineView.background) {
          if (cls) {
            lineView.background.className = cls;
          } else {
            lineView.background.parentNode.removeChild(lineView.background);
            lineView.background = null;
          }
        } else if (cls) {
          var wrap = ensureLineWrapped(lineView);
          lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
          cm.display.input.setUneditable(lineView.background);
        }
      }
      function getLineContent(cm, lineView) {
        var ext2 = cm.display.externalMeasured;
        if (ext2 && ext2.line == lineView.line) {
          cm.display.externalMeasured = null;
          lineView.measure = ext2.measure;
          return ext2.built;
        }
        return buildLineContent(cm, lineView);
      }
      function updateLineText(cm, lineView) {
        var cls = lineView.text.className;
        var built = getLineContent(cm, lineView);
        if (lineView.text == lineView.node) {
          lineView.node = built.pre;
        }
        lineView.text.parentNode.replaceChild(built.pre, lineView.text);
        lineView.text = built.pre;
        if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
          lineView.bgClass = built.bgClass;
          lineView.textClass = built.textClass;
          updateLineClasses(cm, lineView);
        } else if (cls) {
          lineView.text.className = cls;
        }
      }
      function updateLineClasses(cm, lineView) {
        updateLineBackground(cm, lineView);
        if (lineView.line.wrapClass) {
          ensureLineWrapped(lineView).className = lineView.line.wrapClass;
        } else if (lineView.node != lineView.text) {
          lineView.node.className = "";
        }
        var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
        lineView.text.className = textClass || "";
      }
      function updateLineGutter(cm, lineView, lineN, dims) {
        if (lineView.gutter) {
          lineView.node.removeChild(lineView.gutter);
          lineView.gutter = null;
        }
        if (lineView.gutterBackground) {
          lineView.node.removeChild(lineView.gutterBackground);
          lineView.gutterBackground = null;
        }
        if (lineView.line.gutterClass) {
          var wrap = ensureLineWrapped(lineView);
          lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px");
          cm.display.input.setUneditable(lineView.gutterBackground);
          wrap.insertBefore(lineView.gutterBackground, lineView.text);
        }
        var markers = lineView.line.gutterMarkers;
        if (cm.options.lineNumbers || markers) {
          var wrap$1 = ensureLineWrapped(lineView);
          var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
          cm.display.input.setUneditable(gutterWrap);
          wrap$1.insertBefore(gutterWrap, lineView.text);
          if (lineView.line.gutterClass) {
            gutterWrap.className += " " + lineView.line.gutterClass;
          }
          if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) {
            lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px"));
          }
          if (markers) {
            for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
              var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
              if (found) {
                gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
              }
            }
          }
        }
      }
      function updateLineWidgets(cm, lineView, dims) {
        if (lineView.alignable) {
          lineView.alignable = null;
        }
        var isWidget = classTest("CodeMirror-linewidget");
        for (var node = lineView.node.firstChild, next = void 0; node; node = next) {
          next = node.nextSibling;
          if (isWidget.test(node.className)) {
            lineView.node.removeChild(node);
          }
        }
        insertLineWidgets(cm, lineView, dims);
      }
      function buildLineElement(cm, lineView, lineN, dims) {
        var built = getLineContent(cm, lineView);
        lineView.text = lineView.node = built.pre;
        if (built.bgClass) {
          lineView.bgClass = built.bgClass;
        }
        if (built.textClass) {
          lineView.textClass = built.textClass;
        }
        updateLineClasses(cm, lineView);
        updateLineGutter(cm, lineView, lineN, dims);
        insertLineWidgets(cm, lineView, dims);
        return lineView.node;
      }
      function insertLineWidgets(cm, lineView, dims) {
        insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
        if (lineView.rest) {
          for (var i2 = 0; i2 < lineView.rest.length; i2++) {
            insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false);
          }
        }
      }
      function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
        if (!line.widgets) {
          return;
        }
        var wrap = ensureLineWrapped(lineView);
        for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) {
          var widget = ws[i2], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
          if (!widget.handleMouseEvents) {
            node.setAttribute("cm-ignore-events", "true");
          }
          positionLineWidget(widget, node, lineView, dims);
          cm.display.input.setUneditable(node);
          if (allowAbove && widget.above) {
            wrap.insertBefore(node, lineView.gutter || lineView.text);
          } else {
            wrap.appendChild(node);
          }
          signalLater(widget, "redraw");
        }
      }
      function positionLineWidget(widget, node, lineView, dims) {
        if (widget.noHScroll) {
          (lineView.alignable || (lineView.alignable = [])).push(node);
          var width = dims.wrapperWidth;
          node.style.left = dims.fixedPos + "px";
          if (!widget.coverGutter) {
            width -= dims.gutterTotalWidth;
            node.style.paddingLeft = dims.gutterTotalWidth + "px";
          }
          node.style.width = width + "px";
        }
        if (widget.coverGutter) {
          node.style.zIndex = 5;
          node.style.position = "relative";
          if (!widget.noHScroll) {
            node.style.marginLeft = -dims.gutterTotalWidth + "px";
          }
        }
      }
      function widgetHeight(widget) {
        if (widget.height != null) {
          return widget.height;
        }
        var cm = widget.doc.cm;
        if (!cm) {
          return 0;
        }
        if (!contains(document.body, widget.node)) {
          var parentStyle = "position: relative;";
          if (widget.coverGutter) {
            parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
          }
          if (widget.noHScroll) {
            parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
          }
          removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
        }
        return widget.height = widget.node.parentNode.offsetHeight;
      }
      function eventInWidget(display, e) {
        for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
          if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) {
            return true;
          }
        }
      }
      function paddingTop(display) {
        return display.lineSpace.offsetTop;
      }
      function paddingVert(display) {
        return display.mover.offsetHeight - display.lineSpace.offsetHeight;
      }
      function paddingH(display) {
        if (display.cachedPaddingH) {
          return display.cachedPaddingH;
        }
        var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
        var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
        var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
        if (!isNaN(data.left) && !isNaN(data.right)) {
          display.cachedPaddingH = data;
        }
        return data;
      }
      function scrollGap(cm) {
        return scrollerGap - cm.display.nativeBarWidth;
      }
      function displayWidth(cm) {
        return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
      }
      function displayHeight(cm) {
        return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
      }
      function ensureLineHeights(cm, lineView, rect) {
        var wrapping = cm.options.lineWrapping;
        var curWidth = wrapping && displayWidth(cm);
        if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
          var heights = lineView.measure.heights = [];
          if (wrapping) {
            lineView.measure.width = curWidth;
            var rects = lineView.text.firstChild.getClientRects();
            for (var i2 = 0; i2 < rects.length - 1; i2++) {
              var cur = rects[i2], next = rects[i2 + 1];
              if (Math.abs(cur.bottom - next.bottom) > 2) {
                heights.push((cur.bottom + next.top) / 2 - rect.top);
              }
            }
          }
          heights.push(rect.bottom - rect.top);
        }
      }
      function mapFromLineView(lineView, line, lineN) {
        if (lineView.line == line) {
          return {map: lineView.measure.map, cache: lineView.measure.cache};
        }
        for (var i2 = 0; i2 < lineView.rest.length; i2++) {
          if (lineView.rest[i2] == line) {
            return {map: lineView.measure.maps[i2], cache: lineView.measure.caches[i2]};
          }
        }
        for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) {
          if (lineNo(lineView.rest[i$12]) > lineN) {
            return {map: lineView.measure.maps[i$12], cache: lineView.measure.caches[i$12], before: true};
          }
        }
      }
      function updateExternalMeasurement(cm, line) {
        line = visualLine(line);
        var lineN = lineNo(line);
        var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
        view.lineN = lineN;
        var built = view.built = buildLineContent(cm, view);
        view.text = built.pre;
        removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
        return view;
      }
      function measureChar(cm, line, ch, bias) {
        return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
      }
      function findViewForLine(cm, lineN) {
        if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {
          return cm.display.view[findViewIndex(cm, lineN)];
        }
        var ext2 = cm.display.externalMeasured;
        if (ext2 && lineN >= ext2.lineN && lineN < ext2.lineN + ext2.size) {
          return ext2;
        }
      }
      function prepareMeasureForLine(cm, line) {
        var lineN = lineNo(line);
        var view = findViewForLine(cm, lineN);
        if (view && !view.text) {
          view = null;
        } else if (view && view.changes) {
          updateLineForChanges(cm, view, lineN, getDimensions(cm));
          cm.curOp.forceUpdate = true;
        }
        if (!view) {
          view = updateExternalMeasurement(cm, line);
        }
        var info = mapFromLineView(view, line, lineN);
        return {
          line,
          view,
          rect: null,
          map: info.map,
          cache: info.cache,
          before: info.before,
          hasHeights: false
        };
      }
      function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
        if (prepared.before) {
          ch = -1;
        }
        var key = ch + (bias || ""), found;
        if (prepared.cache.hasOwnProperty(key)) {
          found = prepared.cache[key];
        } else {
          if (!prepared.rect) {
            prepared.rect = prepared.view.text.getBoundingClientRect();
          }
          if (!prepared.hasHeights) {
            ensureLineHeights(cm, prepared.view, prepared.rect);
            prepared.hasHeights = true;
          }
          found = measureCharInner(cm, prepared, ch, bias);
          if (!found.bogus) {
            prepared.cache[key] = found;
          }
        }
        return {
          left: found.left,
          right: found.right,
          top: varHeight ? found.rtop : found.top,
          bottom: varHeight ? found.rbottom : found.bottom
        };
      }
      var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
      function nodeAndOffsetInLineMap(map3, ch, bias) {
        var node, start, end, collapse, mStart, mEnd;
        for (var i2 = 0; i2 < map3.length; i2 += 3) {
          mStart = map3[i2];
          mEnd = map3[i2 + 1];
          if (ch < mStart) {
            start = 0;
            end = 1;
            collapse = "left";
          } else if (ch < mEnd) {
            start = ch - mStart;
            end = start + 1;
          } else if (i2 == map3.length - 3 || ch == mEnd && map3[i2 + 3] > ch) {
            end = mEnd - mStart;
            start = end - 1;
            if (ch >= mEnd) {
              collapse = "right";
            }
          }
          if (start != null) {
            node = map3[i2 + 2];
            if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {
              collapse = bias;
            }
            if (bias == "left" && start == 0) {
              while (i2 && map3[i2 - 2] == map3[i2 - 3] && map3[i2 - 1].insertLeft) {
                node = map3[(i2 -= 3) + 2];
                collapse = "left";
              }
            }
            if (bias == "right" && start == mEnd - mStart) {
              while (i2 < map3.length - 3 && map3[i2 + 3] == map3[i2 + 4] && !map3[i2 + 5].insertLeft) {
                node = map3[(i2 += 3) + 2];
                collapse = "right";
              }
            }
            break;
          }
        }
        return {node, start, end, collapse, coverStart: mStart, coverEnd: mEnd};
      }
      function getUsefulRect(rects, bias) {
        var rect = nullRect;
        if (bias == "left") {
          for (var i2 = 0; i2 < rects.length; i2++) {
            if ((rect = rects[i2]).left != rect.right) {
              break;
            }
          }
        } else {
          for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) {
            if ((rect = rects[i$12]).left != rect.right) {
              break;
            }
          }
        }
        return rect;
      }
      function measureCharInner(cm, prepared, ch, bias) {
        var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
        var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
        var rect;
        if (node.nodeType == 3) {
          for (var i$12 = 0; i$12 < 4; i$12++) {
            while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) {
              --start;
            }
            while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) {
              ++end;
            }
            if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
              rect = node.parentNode.getBoundingClientRect();
            } else {
              rect = getUsefulRect(range(node, start, end).getClientRects(), bias);
            }
            if (rect.left || rect.right || start == 0) {
              break;
            }
            end = start;
            start = start - 1;
            collapse = "right";
          }
          if (ie && ie_version < 11) {
            rect = maybeUpdateRectForZooming(cm.display.measure, rect);
          }
        } else {
          if (start > 0) {
            collapse = bias = "right";
          }
          var rects;
          if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {
            rect = rects[bias == "right" ? rects.length - 1 : 0];
          } else {
            rect = node.getBoundingClientRect();
          }
        }
        if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
          var rSpan = node.parentNode.getClientRects()[0];
          if (rSpan) {
            rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
          } else {
            rect = nullRect;
          }
        }
        var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
        var mid = (rtop + rbot) / 2;
        var heights = prepared.view.measure.heights;
        var i2 = 0;
        for (; i2 < heights.length - 1; i2++) {
          if (mid < heights[i2]) {
            break;
          }
        }
        var top2 = i2 ? heights[i2 - 1] : 0, bot = heights[i2];
        var result = {
          left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
          right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
          top: top2,
          bottom: bot
        };
        if (!rect.left && !rect.right) {
          result.bogus = true;
        }
        if (!cm.options.singleCursorHeightPerLine) {
          result.rtop = rtop;
          result.rbottom = rbot;
        }
        return result;
      }
      function maybeUpdateRectForZooming(measure, rect) {
        if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {
          return rect;
        }
        var scaleX = screen.logicalXDPI / screen.deviceXDPI;
        var scaleY = screen.logicalYDPI / screen.deviceYDPI;
        return {
          left: rect.left * scaleX,
          right: rect.right * scaleX,
          top: rect.top * scaleY,
          bottom: rect.bottom * scaleY
        };
      }
      function clearLineMeasurementCacheFor(lineView) {
        if (lineView.measure) {
          lineView.measure.cache = {};
          lineView.measure.heights = null;
          if (lineView.rest) {
            for (var i2 = 0; i2 < lineView.rest.length; i2++) {
              lineView.measure.caches[i2] = {};
            }
          }
        }
      }
      function clearLineMeasurementCache(cm) {
        cm.display.externalMeasure = null;
        removeChildren(cm.display.lineMeasure);
        for (var i2 = 0; i2 < cm.display.view.length; i2++) {
          clearLineMeasurementCacheFor(cm.display.view[i2]);
        }
      }
      function clearCaches(cm) {
        clearLineMeasurementCache(cm);
        cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
        if (!cm.options.lineWrapping) {
          cm.display.maxLineChanged = true;
        }
        cm.display.lineNumChars = null;
      }
      function pageScrollX() {
        if (chrome && android) {
          return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft));
        }
        return window.pageXOffset || (document.documentElement || document.body).scrollLeft;
      }
      function pageScrollY() {
        if (chrome && android) {
          return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop));
        }
        return window.pageYOffset || (document.documentElement || document.body).scrollTop;
      }
      function widgetTopHeight(lineObj) {
        var height4 = 0;
        if (lineObj.widgets) {
          for (var i2 = 0; i2 < lineObj.widgets.length; ++i2) {
            if (lineObj.widgets[i2].above) {
              height4 += widgetHeight(lineObj.widgets[i2]);
            }
          }
        }
        return height4;
      }
      function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
        if (!includeWidgets) {
          var height4 = widgetTopHeight(lineObj);
          rect.top += height4;
          rect.bottom += height4;
        }
        if (context == "line") {
          return rect;
        }
        if (!context) {
          context = "local";
        }
        var yOff = heightAtLine(lineObj);
        if (context == "local") {
          yOff += paddingTop(cm.display);
        } else {
          yOff -= cm.display.viewOffset;
        }
        if (context == "page" || context == "window") {
          var lOff = cm.display.lineSpace.getBoundingClientRect();
          yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
          var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
          rect.left += xOff;
          rect.right += xOff;
        }
        rect.top += yOff;
        rect.bottom += yOff;
        return rect;
      }
      function fromCoordSystem(cm, coords, context) {
        if (context == "div") {
          return coords;
        }
        var left2 = coords.left, top2 = coords.top;
        if (context == "page") {
          left2 -= pageScrollX();
          top2 -= pageScrollY();
        } else if (context == "local" || !context) {
          var localBox = cm.display.sizer.getBoundingClientRect();
          left2 += localBox.left;
          top2 += localBox.top;
        }
        var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
        return {left: left2 - lineSpaceBox.left, top: top2 - lineSpaceBox.top};
      }
      function charCoords(cm, pos, context, lineObj, bias) {
        if (!lineObj) {
          lineObj = getLine(cm.doc, pos.line);
        }
        return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
      }
      function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
        lineObj = lineObj || getLine(cm.doc, pos.line);
        if (!preparedMeasure) {
          preparedMeasure = prepareMeasureForLine(cm, lineObj);
        }
        function get2(ch2, right2) {
          var m = measureCharPrepared(cm, preparedMeasure, ch2, right2 ? "right" : "left", varHeight);
          if (right2) {
            m.left = m.right;
          } else {
            m.right = m.left;
          }
          return intoCoordSystem(cm, lineObj, m, context);
        }
        var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
        if (ch >= lineObj.text.length) {
          ch = lineObj.text.length;
          sticky = "before";
        } else if (ch <= 0) {
          ch = 0;
          sticky = "after";
        }
        if (!order) {
          return get2(sticky == "before" ? ch - 1 : ch, sticky == "before");
        }
        function getBidi(ch2, partPos2, invert) {
          var part = order[partPos2], right2 = part.level == 1;
          return get2(invert ? ch2 - 1 : ch2, right2 != invert);
        }
        var partPos = getBidiPartAt(order, ch, sticky);
        var other = bidiOther;
        var val = getBidi(ch, partPos, sticky == "before");
        if (other != null) {
          val.other = getBidi(ch, other, sticky != "before");
        }
        return val;
      }
      function estimateCoords(cm, pos) {
        var left2 = 0;
        pos = clipPos(cm.doc, pos);
        if (!cm.options.lineWrapping) {
          left2 = charWidth(cm.display) * pos.ch;
        }
        var lineObj = getLine(cm.doc, pos.line);
        var top2 = heightAtLine(lineObj) + paddingTop(cm.display);
        return {left: left2, right: left2, top: top2, bottom: top2 + lineObj.height};
      }
      function PosWithInfo(line, ch, sticky, outside, xRel) {
        var pos = Pos(line, ch, sticky);
        pos.xRel = xRel;
        if (outside) {
          pos.outside = outside;
        }
        return pos;
      }
      function coordsChar(cm, x2, y2) {
        var doc = cm.doc;
        y2 += cm.display.viewOffset;
        if (y2 < 0) {
          return PosWithInfo(doc.first, 0, null, -1, -1);
        }
        var lineN = lineAtHeight(doc, y2), last = doc.first + doc.size - 1;
        if (lineN > last) {
          return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1);
        }
        if (x2 < 0) {
          x2 = 0;
        }
        var lineObj = getLine(doc, lineN);
        for (; ; ) {
          var found = coordsCharInner(cm, lineObj, lineN, x2, y2);
          var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
          if (!collapsed) {
            return found;
          }
          var rangeEnd = collapsed.find(1);
          if (rangeEnd.line == lineN) {
            return rangeEnd;
          }
          lineObj = getLine(doc, lineN = rangeEnd.line);
        }
      }
      function wrappedLineExtent(cm, lineObj, preparedMeasure, y2) {
        y2 -= widgetTopHeight(lineObj);
        var end = lineObj.text.length;
        var begin = findFirst(function(ch) {
          return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y2;
        }, end, 0);
        end = findFirst(function(ch) {
          return measureCharPrepared(cm, preparedMeasure, ch).top > y2;
        }, begin, end);
        return {begin, end};
      }
      function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
        if (!preparedMeasure) {
          preparedMeasure = prepareMeasureForLine(cm, lineObj);
        }
        var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
        return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop);
      }
      function boxIsAfter(box, x2, y2, left2) {
        return box.bottom <= y2 ? false : box.top > y2 ? true : (left2 ? box.left : box.right) > x2;
      }
      function coordsCharInner(cm, lineObj, lineNo2, x2, y2) {
        y2 -= heightAtLine(lineObj);
        var preparedMeasure = prepareMeasureForLine(cm, lineObj);
        var widgetHeight2 = widgetTopHeight(lineObj);
        var begin = 0, end = lineObj.text.length, ltr = true;
        var order = getOrder(lineObj, cm.doc.direction);
        if (order) {
          var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x2, y2);
          ltr = part.level != 1;
          begin = ltr ? part.from : part.to - 1;
          end = ltr ? part.to : part.from - 1;
        }
        var chAround = null, boxAround = null;
        var ch = findFirst(function(ch2) {
          var box = measureCharPrepared(cm, preparedMeasure, ch2);
          box.top += widgetHeight2;
          box.bottom += widgetHeight2;
          if (!boxIsAfter(box, x2, y2, false)) {
            return false;
          }
          if (box.top <= y2 && box.left <= x2) {
            chAround = ch2;
            boxAround = box;
          }
          return true;
        }, begin, end);
        var baseX, sticky, outside = false;
        if (boxAround) {
          var atLeft = x2 - boxAround.left < boxAround.right - x2, atStart = atLeft == ltr;
          ch = chAround + (atStart ? 0 : 1);
          sticky = atStart ? "after" : "before";
          baseX = atLeft ? boxAround.left : boxAround.right;
        } else {
          if (!ltr && (ch == end || ch == begin)) {
            ch++;
          }
          sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y2 == ltr ? "after" : "before";
          var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure);
          baseX = coords.left;
          outside = y2 < coords.top ? -1 : y2 >= coords.bottom ? 1 : 0;
        }
        ch = skipExtendingChars(lineObj.text, ch, 1);
        return PosWithInfo(lineNo2, ch, sticky, outside, x2 - baseX);
      }
      function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x2, y2) {
        var index = findFirst(function(i2) {
          var part2 = order[i2], ltr2 = part2.level != 1;
          return boxIsAfter(cursorCoords(cm, Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"), "line", lineObj, preparedMeasure), x2, y2, true);
        }, 0, order.length - 1);
        var part = order[index];
        if (index > 0) {
          var ltr = part.level != 1;
          var start = cursorCoords(cm, Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure);
          if (boxIsAfter(start, x2, y2, true) && start.top > y2) {
            part = order[index - 1];
          }
        }
        return part;
      }
      function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x2, y2) {
        var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y2);
        var begin = ref.begin;
        var end = ref.end;
        if (/\s/.test(lineObj.text.charAt(end - 1))) {
          end--;
        }
        var part = null, closestDist = null;
        for (var i2 = 0; i2 < order.length; i2++) {
          var p = order[i2];
          if (p.from >= end || p.to <= begin) {
            continue;
          }
          var ltr = p.level != 1;
          var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
          var dist = endX < x2 ? x2 - endX + 1e9 : endX - x2;
          if (!part || closestDist > dist) {
            part = p;
            closestDist = dist;
          }
        }
        if (!part) {
          part = order[order.length - 1];
        }
        if (part.from < begin) {
          part = {from: begin, to: part.to, level: part.level};
        }
        if (part.to > end) {
          part = {from: part.from, to: end, level: part.level};
        }
        return part;
      }
      var measureText;
      function textHeight(display) {
        if (display.cachedTextHeight != null) {
          return display.cachedTextHeight;
        }
        if (measureText == null) {
          measureText = elt("pre", null, "CodeMirror-line-like");
          for (var i2 = 0; i2 < 49; ++i2) {
            measureText.appendChild(document.createTextNode("x"));
            measureText.appendChild(elt("br"));
          }
          measureText.appendChild(document.createTextNode("x"));
        }
        removeChildrenAndAdd(display.measure, measureText);
        var height4 = measureText.offsetHeight / 50;
        if (height4 > 3) {
          display.cachedTextHeight = height4;
        }
        removeChildren(display.measure);
        return height4 || 1;
      }
      function charWidth(display) {
        if (display.cachedCharWidth != null) {
          return display.cachedCharWidth;
        }
        var anchor = elt("span", "xxxxxxxxxx");
        var pre = elt("pre", [anchor], "CodeMirror-line-like");
        removeChildrenAndAdd(display.measure, pre);
        var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
        if (width > 2) {
          display.cachedCharWidth = width;
        }
        return width || 10;
      }
      function getDimensions(cm) {
        var d = cm.display, left2 = {}, width = {};
        var gutterLeft = d.gutters.clientLeft;
        for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) {
          var id = cm.display.gutterSpecs[i2].className;
          left2[id] = n.offsetLeft + n.clientLeft + gutterLeft;
          width[id] = n.clientWidth;
        }
        return {
          fixedPos: compensateForHScroll(d),
          gutterTotalWidth: d.gutters.offsetWidth,
          gutterLeft: left2,
          gutterWidth: width,
          wrapperWidth: d.wrapper.clientWidth
        };
      }
      function compensateForHScroll(display) {
        return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
      }
      function estimateHeight(cm) {
        var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
        var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
        return function(line) {
          if (lineIsHidden(cm.doc, line)) {
            return 0;
          }
          var widgetsHeight = 0;
          if (line.widgets) {
            for (var i2 = 0; i2 < line.widgets.length; i2++) {
              if (line.widgets[i2].height) {
                widgetsHeight += line.widgets[i2].height;
              }
            }
          }
          if (wrapping) {
            return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
          } else {
            return widgetsHeight + th;
          }
        };
      }
      function estimateLineHeights(cm) {
        var doc = cm.doc, est = estimateHeight(cm);
        doc.iter(function(line) {
          var estHeight = est(line);
          if (estHeight != line.height) {
            updateLineHeight(line, estHeight);
          }
        });
      }
      function posFromMouse(cm, e, liberal, forRect) {
        var display = cm.display;
        if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") {
          return null;
        }
        var x2, y2, space2 = display.lineSpace.getBoundingClientRect();
        try {
          x2 = e.clientX - space2.left;
          y2 = e.clientY - space2.top;
        } catch (e$1) {
          return null;
        }
        var coords = coordsChar(cm, x2, y2), line;
        if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
          var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
          coords = Pos(coords.line, Math.max(0, Math.round((x2 - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
        }
        return coords;
      }
      function findViewIndex(cm, n) {
        if (n >= cm.display.viewTo) {
          return null;
        }
        n -= cm.display.viewFrom;
        if (n < 0) {
          return null;
        }
        var view = cm.display.view;
        for (var i2 = 0; i2 < view.length; i2++) {
          n -= view[i2].size;
          if (n < 0) {
            return i2;
          }
        }
      }
      function regChange(cm, from, to, lendiff) {
        if (from == null) {
          from = cm.doc.first;
        }
        if (to == null) {
          to = cm.doc.first + cm.doc.size;
        }
        if (!lendiff) {
          lendiff = 0;
        }
        var display = cm.display;
        if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) {
          display.updateLineNumbers = from;
        }
        cm.curOp.viewChanged = true;
        if (from >= display.viewTo) {
          if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {
            resetView(cm);
          }
        } else if (to <= display.viewFrom) {
          if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
            resetView(cm);
          } else {
            display.viewFrom += lendiff;
            display.viewTo += lendiff;
          }
        } else if (from <= display.viewFrom && to >= display.viewTo) {
          resetView(cm);
        } else if (from <= display.viewFrom) {
          var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
          if (cut) {
            display.view = display.view.slice(cut.index);
            display.viewFrom = cut.lineN;
            display.viewTo += lendiff;
          } else {
            resetView(cm);
          }
        } else if (to >= display.viewTo) {
          var cut$1 = viewCuttingPoint(cm, from, from, -1);
          if (cut$1) {
            display.view = display.view.slice(0, cut$1.index);
            display.viewTo = cut$1.lineN;
          } else {
            resetView(cm);
          }
        } else {
          var cutTop = viewCuttingPoint(cm, from, from, -1);
          var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
          if (cutTop && cutBot) {
            display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index));
            display.viewTo += lendiff;
          } else {
            resetView(cm);
          }
        }
        var ext2 = display.externalMeasured;
        if (ext2) {
          if (to < ext2.lineN) {
            ext2.lineN += lendiff;
          } else if (from < ext2.lineN + ext2.size) {
            display.externalMeasured = null;
          }
        }
      }
      function regLineChange(cm, line, type) {
        cm.curOp.viewChanged = true;
        var display = cm.display, ext2 = cm.display.externalMeasured;
        if (ext2 && line >= ext2.lineN && line < ext2.lineN + ext2.size) {
          display.externalMeasured = null;
        }
        if (line < display.viewFrom || line >= display.viewTo) {
          return;
        }
        var lineView = display.view[findViewIndex(cm, line)];
        if (lineView.node == null) {
          return;
        }
        var arr = lineView.changes || (lineView.changes = []);
        if (indexOf(arr, type) == -1) {
          arr.push(type);
        }
      }
      function resetView(cm) {
        cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
        cm.display.view = [];
        cm.display.viewOffset = 0;
      }
      function viewCuttingPoint(cm, oldN, newN, dir) {
        var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
        if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {
          return {index, lineN: newN};
        }
        var n = cm.display.viewFrom;
        for (var i2 = 0; i2 < index; i2++) {
          n += view[i2].size;
        }
        if (n != oldN) {
          if (dir > 0) {
            if (index == view.length - 1) {
              return null;
            }
            diff = n + view[index].size - oldN;
            index++;
          } else {
            diff = n - oldN;
          }
          oldN += diff;
          newN += diff;
        }
        while (visualLineNo(cm.doc, newN) != newN) {
          if (index == (dir < 0 ? 0 : view.length - 1)) {
            return null;
          }
          newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
          index += dir;
        }
        return {index, lineN: newN};
      }
      function adjustView(cm, from, to) {
        var display = cm.display, view = display.view;
        if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
          display.view = buildViewArray(cm, from, to);
          display.viewFrom = from;
        } else {
          if (display.viewFrom > from) {
            display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
          } else if (display.viewFrom < from) {
            display.view = display.view.slice(findViewIndex(cm, from));
          }
          display.viewFrom = from;
          if (display.viewTo < to) {
            display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
          } else if (display.viewTo > to) {
            display.view = display.view.slice(0, findViewIndex(cm, to));
          }
        }
        display.viewTo = to;
      }
      function countDirtyView(cm) {
        var view = cm.display.view, dirty = 0;
        for (var i2 = 0; i2 < view.length; i2++) {
          var lineView = view[i2];
          if (!lineView.hidden && (!lineView.node || lineView.changes)) {
            ++dirty;
          }
        }
        return dirty;
      }
      function updateSelection(cm) {
        cm.display.input.showSelection(cm.display.input.prepareSelection());
      }
      function prepareSelection(cm, primary) {
        if (primary === void 0)
          primary = true;
        var doc = cm.doc, result = {};
        var curFragment = result.cursors = document.createDocumentFragment();
        var selFragment = result.selection = document.createDocumentFragment();
        for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) {
          if (!primary && i2 == doc.sel.primIndex) {
            continue;
          }
          var range2 = doc.sel.ranges[i2];
          if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) {
            continue;
          }
          var collapsed = range2.empty();
          if (collapsed || cm.options.showCursorWhenSelecting) {
            drawSelectionCursor(cm, range2.head, curFragment);
          }
          if (!collapsed) {
            drawSelectionRange(cm, range2, selFragment);
          }
        }
        return result;
      }
      function drawSelectionCursor(cm, head, output) {
        var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
        var cursor = output.appendChild(elt("div", "\xA0", "CodeMirror-cursor"));
        cursor.style.left = pos.left + "px";
        cursor.style.top = pos.top + "px";
        cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
        if (pos.other) {
          var otherCursor = output.appendChild(elt("div", "\xA0", "CodeMirror-cursor CodeMirror-secondarycursor"));
          otherCursor.style.display = "";
          otherCursor.style.left = pos.other.left + "px";
          otherCursor.style.top = pos.other.top + "px";
          otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px";
        }
      }
      function cmpCoords(a, b) {
        return a.top - b.top || a.left - b.left;
      }
      function drawSelectionRange(cm, range2, output) {
        var display = cm.display, doc = cm.doc;
        var fragment = document.createDocumentFragment();
        var padding = paddingH(cm.display), leftSide = padding.left;
        var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
        var docLTR = doc.direction == "ltr";
        function add2(left2, top2, width, bottom2) {
          if (top2 < 0) {
            top2 = 0;
          }
          top2 = Math.round(top2);
          bottom2 = Math.round(bottom2);
          fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left2 + "px;\n                             top: " + top2 + "px; width: " + (width == null ? rightSide - left2 : width) + "px;\n                             height: " + (bottom2 - top2) + "px"));
        }
        function drawForLine(line, fromArg, toArg) {
          var lineObj = getLine(doc, line);
          var lineLen = lineObj.text.length;
          var start, end;
          function coords(ch, bias) {
            return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
          }
          function wrapX(pos, dir, side) {
            var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
            var prop2 = dir == "ltr" == (side == "after") ? "left" : "right";
            var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
            return coords(ch, prop2)[prop2];
          }
          var order = getOrder(lineObj, doc.direction);
          iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir, i2) {
            var ltr = dir == "ltr";
            var fromPos = coords(from, ltr ? "left" : "right");
            var toPos = coords(to - 1, ltr ? "right" : "left");
            var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
            var first = i2 == 0, last = !order || i2 == order.length - 1;
            if (toPos.top - fromPos.top <= 3) {
              var openLeft = (docLTR ? openStart : openEnd) && first;
              var openRight = (docLTR ? openEnd : openStart) && last;
              var left2 = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
              var right2 = openRight ? rightSide : (ltr ? toPos : fromPos).right;
              add2(left2, fromPos.top, right2 - left2, fromPos.bottom);
            } else {
              var topLeft, topRight, botLeft, botRight;
              if (ltr) {
                topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
                topRight = docLTR ? rightSide : wrapX(from, dir, "before");
                botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
                botRight = docLTR && openEnd && last ? rightSide : toPos.right;
              } else {
                topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
                topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
                botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
                botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
              }
              add2(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
              if (fromPos.bottom < toPos.top) {
                add2(leftSide, fromPos.bottom, null, toPos.top);
              }
              add2(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
            }
            if (!start || cmpCoords(fromPos, start) < 0) {
              start = fromPos;
            }
            if (cmpCoords(toPos, start) < 0) {
              start = toPos;
            }
            if (!end || cmpCoords(fromPos, end) < 0) {
              end = fromPos;
            }
            if (cmpCoords(toPos, end) < 0) {
              end = toPos;
            }
          });
          return {start, end};
        }
        var sFrom = range2.from(), sTo = range2.to();
        if (sFrom.line == sTo.line) {
          drawForLine(sFrom.line, sFrom.ch, sTo.ch);
        } else {
          var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
          var singleVLine = visualLine(fromLine) == visualLine(toLine);
          var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
          var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
          if (singleVLine) {
            if (leftEnd.top < rightStart.top - 2) {
              add2(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
              add2(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
            } else {
              add2(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
            }
          }
          if (leftEnd.bottom < rightStart.top) {
            add2(leftSide, leftEnd.bottom, null, rightStart.top);
          }
        }
        output.appendChild(fragment);
      }
      function restartBlink(cm) {
        if (!cm.state.focused) {
          return;
        }
        var display = cm.display;
        clearInterval(display.blinker);
        var on2 = true;
        display.cursorDiv.style.visibility = "";
        if (cm.options.cursorBlinkRate > 0) {
          display.blinker = setInterval(function() {
            if (!cm.hasFocus()) {
              onBlur(cm);
            }
            display.cursorDiv.style.visibility = (on2 = !on2) ? "" : "hidden";
          }, cm.options.cursorBlinkRate);
        } else if (cm.options.cursorBlinkRate < 0) {
          display.cursorDiv.style.visibility = "hidden";
        }
      }
      function ensureFocus(cm) {
        if (!cm.hasFocus()) {
          cm.display.input.focus();
          if (!cm.state.focused) {
            onFocus(cm);
          }
        }
      }
      function delayBlurEvent(cm) {
        cm.state.delayingBlurEvent = true;
        setTimeout(function() {
          if (cm.state.delayingBlurEvent) {
            cm.state.delayingBlurEvent = false;
            if (cm.state.focused) {
              onBlur(cm);
            }
          }
        }, 100);
      }
      function onFocus(cm, e) {
        if (cm.state.delayingBlurEvent && !cm.state.draggingText) {
          cm.state.delayingBlurEvent = false;
        }
        if (cm.options.readOnly == "nocursor") {
          return;
        }
        if (!cm.state.focused) {
          signal(cm, "focus", cm, e);
          cm.state.focused = true;
          addClass(cm.display.wrapper, "CodeMirror-focused");
          if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
            cm.display.input.reset();
            if (webkit) {
              setTimeout(function() {
                return cm.display.input.reset(true);
              }, 20);
            }
          }
          cm.display.input.receivedFocus();
        }
        restartBlink(cm);
      }
      function onBlur(cm, e) {
        if (cm.state.delayingBlurEvent) {
          return;
        }
        if (cm.state.focused) {
          signal(cm, "blur", cm, e);
          cm.state.focused = false;
          rmClass(cm.display.wrapper, "CodeMirror-focused");
        }
        clearInterval(cm.display.blinker);
        setTimeout(function() {
          if (!cm.state.focused) {
            cm.display.shift = false;
          }
        }, 150);
      }
      function updateHeightsInViewport(cm) {
        var display = cm.display;
        var prevBottom = display.lineDiv.offsetTop;
        for (var i2 = 0; i2 < display.view.length; i2++) {
          var cur = display.view[i2], wrapping = cm.options.lineWrapping;
          var height4 = void 0, width = 0;
          if (cur.hidden) {
            continue;
          }
          if (ie && ie_version < 8) {
            var bot = cur.node.offsetTop + cur.node.offsetHeight;
            height4 = bot - prevBottom;
            prevBottom = bot;
          } else {
            var box = cur.node.getBoundingClientRect();
            height4 = box.bottom - box.top;
            if (!wrapping && cur.text.firstChild) {
              width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1;
            }
          }
          var diff = cur.line.height - height4;
          if (diff > 5e-3 || diff < -5e-3) {
            updateLineHeight(cur.line, height4);
            updateWidgetHeight(cur.line);
            if (cur.rest) {
              for (var j = 0; j < cur.rest.length; j++) {
                updateWidgetHeight(cur.rest[j]);
              }
            }
          }
          if (width > cm.display.sizerWidth) {
            var chWidth = Math.ceil(width / charWidth(cm.display));
            if (chWidth > cm.display.maxLineLength) {
              cm.display.maxLineLength = chWidth;
              cm.display.maxLine = cur.line;
              cm.display.maxLineChanged = true;
            }
          }
        }
      }
      function updateWidgetHeight(line) {
        if (line.widgets) {
          for (var i2 = 0; i2 < line.widgets.length; ++i2) {
            var w = line.widgets[i2], parent2 = w.node.parentNode;
            if (parent2) {
              w.height = parent2.offsetHeight;
            }
          }
        }
      }
      function visibleLines(display, doc, viewport) {
        var top2 = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
        top2 = Math.floor(top2 - paddingTop(display));
        var bottom2 = viewport && viewport.bottom != null ? viewport.bottom : top2 + display.wrapper.clientHeight;
        var from = lineAtHeight(doc, top2), to = lineAtHeight(doc, bottom2);
        if (viewport && viewport.ensure) {
          var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
          if (ensureFrom < from) {
            from = ensureFrom;
            to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
          } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
            from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
            to = ensureTo;
          }
        }
        return {from, to: Math.max(to, from + 1)};
      }
      function maybeScrollWindow(cm, rect) {
        if (signalDOMEvent(cm, "scrollCursorIntoView")) {
          return;
        }
        var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
        if (rect.top + box.top < 0) {
          doScroll = true;
        } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) {
          doScroll = false;
        }
        if (doScroll != null && !phantom) {
          var scrollNode = elt("div", "\u200B", null, "position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;");
          cm.display.lineSpace.appendChild(scrollNode);
          scrollNode.scrollIntoView(doScroll);
          cm.display.lineSpace.removeChild(scrollNode);
        }
      }
      function scrollPosIntoView(cm, pos, end, margin) {
        if (margin == null) {
          margin = 0;
        }
        var rect;
        if (!cm.options.lineWrapping && pos == end) {
          pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
          end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
        }
        for (var limit = 0; limit < 5; limit++) {
          var changed = false;
          var coords = cursorCoords(cm, pos);
          var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
          rect = {
            left: Math.min(coords.left, endCoords.left),
            top: Math.min(coords.top, endCoords.top) - margin,
            right: Math.max(coords.left, endCoords.left),
            bottom: Math.max(coords.bottom, endCoords.bottom) + margin
          };
          var scrollPos = calculateScrollPos(cm, rect);
          var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
          if (scrollPos.scrollTop != null) {
            updateScrollTop(cm, scrollPos.scrollTop);
            if (Math.abs(cm.doc.scrollTop - startTop) > 1) {
              changed = true;
            }
          }
          if (scrollPos.scrollLeft != null) {
            setScrollLeft(cm, scrollPos.scrollLeft);
            if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) {
              changed = true;
            }
          }
          if (!changed) {
            break;
          }
        }
        return rect;
      }
      function scrollIntoView(cm, rect) {
        var scrollPos = calculateScrollPos(cm, rect);
        if (scrollPos.scrollTop != null) {
          updateScrollTop(cm, scrollPos.scrollTop);
        }
        if (scrollPos.scrollLeft != null) {
          setScrollLeft(cm, scrollPos.scrollLeft);
        }
      }
      function calculateScrollPos(cm, rect) {
        var display = cm.display, snapMargin = textHeight(cm.display);
        if (rect.top < 0) {
          rect.top = 0;
        }
        var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
        var screen2 = displayHeight(cm), result = {};
        if (rect.bottom - rect.top > screen2) {
          rect.bottom = rect.top + screen2;
        }
        var docBottom = cm.doc.height + paddingVert(display);
        var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
        if (rect.top < screentop) {
          result.scrollTop = atTop ? 0 : rect.top;
        } else if (rect.bottom > screentop + screen2) {
          var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2);
          if (newTop != screentop) {
            result.scrollTop = newTop;
          }
        }
        var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
        var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
        var screenw = displayWidth(cm) - display.gutters.offsetWidth;
        var tooWide = rect.right - rect.left > screenw;
        if (tooWide) {
          rect.right = rect.left + screenw;
        }
        if (rect.left < 10) {
          result.scrollLeft = 0;
        } else if (rect.left < screenleft) {
          result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10));
        } else if (rect.right > screenw + screenleft - 3) {
          result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw;
        }
        return result;
      }
      function addToScrollTop(cm, top2) {
        if (top2 == null) {
          return;
        }
        resolveScrollToPos(cm);
        cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top2;
      }
      function ensureCursorVisible(cm) {
        resolveScrollToPos(cm);
        var cur = cm.getCursor();
        cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
      }
      function scrollToCoords(cm, x2, y2) {
        if (x2 != null || y2 != null) {
          resolveScrollToPos(cm);
        }
        if (x2 != null) {
          cm.curOp.scrollLeft = x2;
        }
        if (y2 != null) {
          cm.curOp.scrollTop = y2;
        }
      }
      function scrollToRange(cm, range2) {
        resolveScrollToPos(cm);
        cm.curOp.scrollToPos = range2;
      }
      function resolveScrollToPos(cm) {
        var range2 = cm.curOp.scrollToPos;
        if (range2) {
          cm.curOp.scrollToPos = null;
          var from = estimateCoords(cm, range2.from), to = estimateCoords(cm, range2.to);
          scrollToCoordsRange(cm, from, to, range2.margin);
        }
      }
      function scrollToCoordsRange(cm, from, to, margin) {
        var sPos = calculateScrollPos(cm, {
          left: Math.min(from.left, to.left),
          top: Math.min(from.top, to.top) - margin,
          right: Math.max(from.right, to.right),
          bottom: Math.max(from.bottom, to.bottom) + margin
        });
        scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
      }
      function updateScrollTop(cm, val) {
        if (Math.abs(cm.doc.scrollTop - val) < 2) {
          return;
        }
        if (!gecko) {
          updateDisplaySimple(cm, {top: val});
        }
        setScrollTop(cm, val, true);
        if (gecko) {
          updateDisplaySimple(cm);
        }
        startWorker(cm, 100);
      }
      function setScrollTop(cm, val, forceScroll) {
        val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
        if (cm.display.scroller.scrollTop == val && !forceScroll) {
          return;
        }
        cm.doc.scrollTop = val;
        cm.display.scrollbars.setScrollTop(val);
        if (cm.display.scroller.scrollTop != val) {
          cm.display.scroller.scrollTop = val;
        }
      }
      function setScrollLeft(cm, val, isScroller, forceScroll) {
        val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
        if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) {
          return;
        }
        cm.doc.scrollLeft = val;
        alignHorizontally(cm);
        if (cm.display.scroller.scrollLeft != val) {
          cm.display.scroller.scrollLeft = val;
        }
        cm.display.scrollbars.setScrollLeft(val);
      }
      function measureForScrollbars(cm) {
        var d = cm.display, gutterW = d.gutters.offsetWidth;
        var docH = Math.round(cm.doc.height + paddingVert(cm.display));
        return {
          clientHeight: d.scroller.clientHeight,
          viewHeight: d.wrapper.clientHeight,
          scrollWidth: d.scroller.scrollWidth,
          clientWidth: d.scroller.clientWidth,
          viewWidth: d.wrapper.clientWidth,
          barLeft: cm.options.fixedGutter ? gutterW : 0,
          docHeight: docH,
          scrollHeight: docH + scrollGap(cm) + d.barHeight,
          nativeBarWidth: d.nativeBarWidth,
          gutterWidth: gutterW
        };
      }
      var NativeScrollbars = function(place, scroll, cm) {
        this.cm = cm;
        var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
        var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
        vert.tabIndex = horiz.tabIndex = -1;
        place(vert);
        place(horiz);
        on(vert, "scroll", function() {
          if (vert.clientHeight) {
            scroll(vert.scrollTop, "vertical");
          }
        });
        on(horiz, "scroll", function() {
          if (horiz.clientWidth) {
            scroll(horiz.scrollLeft, "horizontal");
          }
        });
        this.checkedZeroWidth = false;
        if (ie && ie_version < 8) {
          this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
        }
      };
      NativeScrollbars.prototype.update = function(measure) {
        var needsH = measure.scrollWidth > measure.clientWidth + 1;
        var needsV = measure.scrollHeight > measure.clientHeight + 1;
        var sWidth = measure.nativeBarWidth;
        if (needsV) {
          this.vert.style.display = "block";
          this.vert.style.bottom = needsH ? sWidth + "px" : "0";
          var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
          this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
        } else {
          this.vert.style.display = "";
          this.vert.firstChild.style.height = "0";
        }
        if (needsH) {
          this.horiz.style.display = "block";
          this.horiz.style.right = needsV ? sWidth + "px" : "0";
          this.horiz.style.left = measure.barLeft + "px";
          var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
          this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
        } else {
          this.horiz.style.display = "";
          this.horiz.firstChild.style.width = "0";
        }
        if (!this.checkedZeroWidth && measure.clientHeight > 0) {
          if (sWidth == 0) {
            this.zeroWidthHack();
          }
          this.checkedZeroWidth = true;
        }
        return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
      };
      NativeScrollbars.prototype.setScrollLeft = function(pos) {
        if (this.horiz.scrollLeft != pos) {
          this.horiz.scrollLeft = pos;
        }
        if (this.disableHoriz) {
          this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz");
        }
      };
      NativeScrollbars.prototype.setScrollTop = function(pos) {
        if (this.vert.scrollTop != pos) {
          this.vert.scrollTop = pos;
        }
        if (this.disableVert) {
          this.enableZeroWidthBar(this.vert, this.disableVert, "vert");
        }
      };
      NativeScrollbars.prototype.zeroWidthHack = function() {
        var w = mac && !mac_geMountainLion ? "12px" : "18px";
        this.horiz.style.height = this.vert.style.width = w;
        this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
        this.disableHoriz = new Delayed();
        this.disableVert = new Delayed();
      };
      NativeScrollbars.prototype.enableZeroWidthBar = function(bar2, delay, type) {
        bar2.style.pointerEvents = "auto";
        function maybeDisable() {
          var box = bar2.getBoundingClientRect();
          var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
          if (elt2 != bar2) {
            bar2.style.pointerEvents = "none";
          } else {
            delay.set(1e3, maybeDisable);
          }
        }
        delay.set(1e3, maybeDisable);
      };
      NativeScrollbars.prototype.clear = function() {
        var parent2 = this.horiz.parentNode;
        parent2.removeChild(this.horiz);
        parent2.removeChild(this.vert);
      };
      var NullScrollbars = function() {
      };
      NullScrollbars.prototype.update = function() {
        return {bottom: 0, right: 0};
      };
      NullScrollbars.prototype.setScrollLeft = function() {
      };
      NullScrollbars.prototype.setScrollTop = function() {
      };
      NullScrollbars.prototype.clear = function() {
      };
      function updateScrollbars(cm, measure) {
        if (!measure) {
          measure = measureForScrollbars(cm);
        }
        var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
        updateScrollbarsInner(cm, measure);
        for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) {
          if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {
            updateHeightsInViewport(cm);
          }
          updateScrollbarsInner(cm, measureForScrollbars(cm));
          startWidth = cm.display.barWidth;
          startHeight = cm.display.barHeight;
        }
      }
      function updateScrollbarsInner(cm, measure) {
        var d = cm.display;
        var sizes = d.scrollbars.update(measure);
        d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
        d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
        d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
        if (sizes.right && sizes.bottom) {
          d.scrollbarFiller.style.display = "block";
          d.scrollbarFiller.style.height = sizes.bottom + "px";
          d.scrollbarFiller.style.width = sizes.right + "px";
        } else {
          d.scrollbarFiller.style.display = "";
        }
        if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
          d.gutterFiller.style.display = "block";
          d.gutterFiller.style.height = sizes.bottom + "px";
          d.gutterFiller.style.width = measure.gutterWidth + "px";
        } else {
          d.gutterFiller.style.display = "";
        }
      }
      var scrollbarModel = {native: NativeScrollbars, null: NullScrollbars};
      function initScrollbars(cm) {
        if (cm.display.scrollbars) {
          cm.display.scrollbars.clear();
          if (cm.display.scrollbars.addClass) {
            rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
          }
        }
        cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function(node) {
          cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
          on(node, "mousedown", function() {
            if (cm.state.focused) {
              setTimeout(function() {
                return cm.display.input.focus();
              }, 0);
            }
          });
          node.setAttribute("cm-not-content", "true");
        }, function(pos, axis3) {
          if (axis3 == "horizontal") {
            setScrollLeft(cm, pos);
          } else {
            updateScrollTop(cm, pos);
          }
        }, cm);
        if (cm.display.scrollbars.addClass) {
          addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
        }
      }
      var nextOpId = 0;
      function startOperation(cm) {
        cm.curOp = {
          cm,
          viewChanged: false,
          startHeight: cm.doc.height,
          forceUpdate: false,
          updateInput: 0,
          typing: false,
          changeObjs: null,
          cursorActivityHandlers: null,
          cursorActivityCalled: 0,
          selectionChanged: false,
          updateMaxLine: false,
          scrollLeft: null,
          scrollTop: null,
          scrollToPos: null,
          focus: false,
          id: ++nextOpId
        };
        pushOperation(cm.curOp);
      }
      function endOperation(cm) {
        var op = cm.curOp;
        if (op) {
          finishOperation(op, function(group) {
            for (var i2 = 0; i2 < group.ops.length; i2++) {
              group.ops[i2].cm.curOp = null;
            }
            endOperations(group);
          });
        }
      }
      function endOperations(group) {
        var ops = group.ops;
        for (var i2 = 0; i2 < ops.length; i2++) {
          endOperation_R1(ops[i2]);
        }
        for (var i$12 = 0; i$12 < ops.length; i$12++) {
          endOperation_W1(ops[i$12]);
        }
        for (var i$22 = 0; i$22 < ops.length; i$22++) {
          endOperation_R2(ops[i$22]);
        }
        for (var i$3 = 0; i$3 < ops.length; i$3++) {
          endOperation_W2(ops[i$3]);
        }
        for (var i$4 = 0; i$4 < ops.length; i$4++) {
          endOperation_finish(ops[i$4]);
        }
      }
      function endOperation_R1(op) {
        var cm = op.cm, display = cm.display;
        maybeClipScrollbars(cm);
        if (op.updateMaxLine) {
          findMaxLine(cm);
        }
        op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping;
        op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
      }
      function endOperation_W1(op) {
        op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
      }
      function endOperation_R2(op) {
        var cm = op.cm, display = cm.display;
        if (op.updatedDisplay) {
          updateHeightsInViewport(cm);
        }
        op.barMeasure = measureForScrollbars(cm);
        if (display.maxLineChanged && !cm.options.lineWrapping) {
          op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
          cm.display.sizerWidth = op.adjustWidthTo;
          op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
          op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
        }
        if (op.updatedDisplay || op.selectionChanged) {
          op.preparedSelection = display.input.prepareSelection();
        }
      }
      function endOperation_W2(op) {
        var cm = op.cm;
        if (op.adjustWidthTo != null) {
          cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
          if (op.maxScrollLeft < cm.doc.scrollLeft) {
            setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
          }
          cm.display.maxLineChanged = false;
        }
        var takeFocus = op.focus && op.focus == activeElt();
        if (op.preparedSelection) {
          cm.display.input.showSelection(op.preparedSelection, takeFocus);
        }
        if (op.updatedDisplay || op.startHeight != cm.doc.height) {
          updateScrollbars(cm, op.barMeasure);
        }
        if (op.updatedDisplay) {
          setDocumentHeight(cm, op.barMeasure);
        }
        if (op.selectionChanged) {
          restartBlink(cm);
        }
        if (cm.state.focused && op.updateInput) {
          cm.display.input.reset(op.typing);
        }
        if (takeFocus) {
          ensureFocus(op.cm);
        }
      }
      function endOperation_finish(op) {
        var cm = op.cm, display = cm.display, doc = cm.doc;
        if (op.updatedDisplay) {
          postUpdateDisplay(cm, op.update);
        }
        if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {
          display.wheelStartX = display.wheelStartY = null;
        }
        if (op.scrollTop != null) {
          setScrollTop(cm, op.scrollTop, op.forceScroll);
        }
        if (op.scrollLeft != null) {
          setScrollLeft(cm, op.scrollLeft, true, true);
        }
        if (op.scrollToPos) {
          var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
          maybeScrollWindow(cm, rect);
        }
        var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
        if (hidden) {
          for (var i2 = 0; i2 < hidden.length; ++i2) {
            if (!hidden[i2].lines.length) {
              signal(hidden[i2], "hide");
            }
          }
        }
        if (unhidden) {
          for (var i$12 = 0; i$12 < unhidden.length; ++i$12) {
            if (unhidden[i$12].lines.length) {
              signal(unhidden[i$12], "unhide");
            }
          }
        }
        if (display.wrapper.offsetHeight) {
          doc.scrollTop = cm.display.scroller.scrollTop;
        }
        if (op.changeObjs) {
          signal(cm, "changes", cm, op.changeObjs);
        }
        if (op.update) {
          op.update.finish();
        }
      }
      function runInOp(cm, f) {
        if (cm.curOp) {
          return f();
        }
        startOperation(cm);
        try {
          return f();
        } finally {
          endOperation(cm);
        }
      }
      function operation(cm, f) {
        return function() {
          if (cm.curOp) {
            return f.apply(cm, arguments);
          }
          startOperation(cm);
          try {
            return f.apply(cm, arguments);
          } finally {
            endOperation(cm);
          }
        };
      }
      function methodOp(f) {
        return function() {
          if (this.curOp) {
            return f.apply(this, arguments);
          }
          startOperation(this);
          try {
            return f.apply(this, arguments);
          } finally {
            endOperation(this);
          }
        };
      }
      function docMethodOp(f) {
        return function() {
          var cm = this.cm;
          if (!cm || cm.curOp) {
            return f.apply(this, arguments);
          }
          startOperation(cm);
          try {
            return f.apply(this, arguments);
          } finally {
            endOperation(cm);
          }
        };
      }
      function startWorker(cm, time) {
        if (cm.doc.highlightFrontier < cm.display.viewTo) {
          cm.state.highlight.set(time, bind2(highlightWorker, cm));
        }
      }
      function highlightWorker(cm) {
        var doc = cm.doc;
        if (doc.highlightFrontier >= cm.display.viewTo) {
          return;
        }
        var end = +new Date() + cm.options.workTime;
        var context = getContextBefore(cm, doc.highlightFrontier);
        var changedLines = [];
        doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
          if (context.line >= cm.display.viewFrom) {
            var oldStyles = line.styles;
            var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
            var highlighted = highlightLine(cm, line, context, true);
            if (resetState) {
              context.state = resetState;
            }
            line.styles = highlighted.styles;
            var oldCls = line.styleClasses, newCls = highlighted.classes;
            if (newCls) {
              line.styleClasses = newCls;
            } else if (oldCls) {
              line.styleClasses = null;
            }
            var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
            for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) {
              ischange = oldStyles[i2] != line.styles[i2];
            }
            if (ischange) {
              changedLines.push(context.line);
            }
            line.stateAfter = context.save();
            context.nextLine();
          } else {
            if (line.text.length <= cm.options.maxHighlightLength) {
              processLine(cm, line.text, context);
            }
            line.stateAfter = context.line % 5 == 0 ? context.save() : null;
            context.nextLine();
          }
          if (+new Date() > end) {
            startWorker(cm, cm.options.workDelay);
            return true;
          }
        });
        doc.highlightFrontier = context.line;
        doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
        if (changedLines.length) {
          runInOp(cm, function() {
            for (var i2 = 0; i2 < changedLines.length; i2++) {
              regLineChange(cm, changedLines[i2], "text");
            }
          });
        }
      }
      var DisplayUpdate = function(cm, viewport, force) {
        var display = cm.display;
        this.viewport = viewport;
        this.visible = visibleLines(display, cm.doc, viewport);
        this.editorIsHidden = !display.wrapper.offsetWidth;
        this.wrapperHeight = display.wrapper.clientHeight;
        this.wrapperWidth = display.wrapper.clientWidth;
        this.oldDisplayWidth = displayWidth(cm);
        this.force = force;
        this.dims = getDimensions(cm);
        this.events = [];
      };
      DisplayUpdate.prototype.signal = function(emitter, type) {
        if (hasHandler(emitter, type)) {
          this.events.push(arguments);
        }
      };
      DisplayUpdate.prototype.finish = function() {
        for (var i2 = 0; i2 < this.events.length; i2++) {
          signal.apply(null, this.events[i2]);
        }
      };
      function maybeClipScrollbars(cm) {
        var display = cm.display;
        if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
          display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
          display.heightForcer.style.height = scrollGap(cm) + "px";
          display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
          display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
          display.scrollbarsClipped = true;
        }
      }
      function selectionSnapshot(cm) {
        if (cm.hasFocus()) {
          return null;
        }
        var active = activeElt();
        if (!active || !contains(cm.display.lineDiv, active)) {
          return null;
        }
        var result = {activeElt: active};
        if (window.getSelection) {
          var sel = window.getSelection();
          if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
            result.anchorNode = sel.anchorNode;
            result.anchorOffset = sel.anchorOffset;
            result.focusNode = sel.focusNode;
            result.focusOffset = sel.focusOffset;
          }
        }
        return result;
      }
      function restoreSelection(snapshot) {
        if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) {
          return;
        }
        snapshot.activeElt.focus();
        if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
          var sel = window.getSelection(), range2 = document.createRange();
          range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
          range2.collapse(false);
          sel.removeAllRanges();
          sel.addRange(range2);
          sel.extend(snapshot.focusNode, snapshot.focusOffset);
        }
      }
      function updateDisplayIfNeeded(cm, update2) {
        var display = cm.display, doc = cm.doc;
        if (update2.editorIsHidden) {
          resetView(cm);
          return false;
        }
        if (!update2.force && update2.visible.from >= display.viewFrom && update2.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) {
          return false;
        }
        if (maybeUpdateLineNumberWidth(cm)) {
          resetView(cm);
          update2.dims = getDimensions(cm);
        }
        var end = doc.first + doc.size;
        var from = Math.max(update2.visible.from - cm.options.viewportMargin, doc.first);
        var to = Math.min(end, update2.visible.to + cm.options.viewportMargin);
        if (display.viewFrom < from && from - display.viewFrom < 20) {
          from = Math.max(doc.first, display.viewFrom);
        }
        if (display.viewTo > to && display.viewTo - to < 20) {
          to = Math.min(end, display.viewTo);
        }
        if (sawCollapsedSpans) {
          from = visualLineNo(cm.doc, from);
          to = visualLineEndNo(cm.doc, to);
        }
        var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update2.wrapperHeight || display.lastWrapWidth != update2.wrapperWidth;
        adjustView(cm, from, to);
        display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
        cm.display.mover.style.top = display.viewOffset + "px";
        var toUpdate = countDirtyView(cm);
        if (!different && toUpdate == 0 && !update2.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {
          return false;
        }
        var selSnapshot = selectionSnapshot(cm);
        if (toUpdate > 4) {
          display.lineDiv.style.display = "none";
        }
        patchDisplay(cm, display.updateLineNumbers, update2.dims);
        if (toUpdate > 4) {
          display.lineDiv.style.display = "";
        }
        display.renderedView = display.view;
        restoreSelection(selSnapshot);
        removeChildren(display.cursorDiv);
        removeChildren(display.selectionDiv);
        display.gutters.style.height = display.sizer.style.minHeight = 0;
        if (different) {
          display.lastWrapHeight = update2.wrapperHeight;
          display.lastWrapWidth = update2.wrapperWidth;
          startWorker(cm, 400);
        }
        display.updateLineNumbers = null;
        return true;
      }
      function postUpdateDisplay(cm, update2) {
        var viewport = update2.viewport;
        for (var first = true; ; first = false) {
          if (!first || !cm.options.lineWrapping || update2.oldDisplayWidth == displayWidth(cm)) {
            if (viewport && viewport.top != null) {
              viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
            }
            update2.visible = visibleLines(cm.display, cm.doc, viewport);
            if (update2.visible.from >= cm.display.viewFrom && update2.visible.to <= cm.display.viewTo) {
              break;
            }
          } else if (first) {
            update2.visible = visibleLines(cm.display, cm.doc, viewport);
          }
          if (!updateDisplayIfNeeded(cm, update2)) {
            break;
          }
          updateHeightsInViewport(cm);
          var barMeasure = measureForScrollbars(cm);
          updateSelection(cm);
          updateScrollbars(cm, barMeasure);
          setDocumentHeight(cm, barMeasure);
          update2.force = false;
        }
        update2.signal(cm, "update", cm);
        if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
          update2.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
          cm.display.reportedViewFrom = cm.display.viewFrom;
          cm.display.reportedViewTo = cm.display.viewTo;
        }
      }
      function updateDisplaySimple(cm, viewport) {
        var update2 = new DisplayUpdate(cm, viewport);
        if (updateDisplayIfNeeded(cm, update2)) {
          updateHeightsInViewport(cm);
          postUpdateDisplay(cm, update2);
          var barMeasure = measureForScrollbars(cm);
          updateSelection(cm);
          updateScrollbars(cm, barMeasure);
          setDocumentHeight(cm, barMeasure);
          update2.finish();
        }
      }
      function patchDisplay(cm, updateNumbersFrom, dims) {
        var display = cm.display, lineNumbers = cm.options.lineNumbers;
        var container = display.lineDiv, cur = container.firstChild;
        function rm(node2) {
          var next = node2.nextSibling;
          if (webkit && mac && cm.display.currentWheelTarget == node2) {
            node2.style.display = "none";
          } else {
            node2.parentNode.removeChild(node2);
          }
          return next;
        }
        var view = display.view, lineN = display.viewFrom;
        for (var i2 = 0; i2 < view.length; i2++) {
          var lineView = view[i2];
          if (lineView.hidden)
            ;
          else if (!lineView.node || lineView.node.parentNode != container) {
            var node = buildLineElement(cm, lineView, lineN, dims);
            container.insertBefore(node, cur);
          } else {
            while (cur != lineView.node) {
              cur = rm(cur);
            }
            var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber;
            if (lineView.changes) {
              if (indexOf(lineView.changes, "gutter") > -1) {
                updateNumber = false;
              }
              updateLineForChanges(cm, lineView, lineN, dims);
            }
            if (updateNumber) {
              removeChildren(lineView.lineNumber);
              lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
            }
            cur = lineView.node.nextSibling;
          }
          lineN += lineView.size;
        }
        while (cur) {
          cur = rm(cur);
        }
      }
      function updateGutterSpace(display) {
        var width = display.gutters.offsetWidth;
        display.sizer.style.marginLeft = width + "px";
      }
      function setDocumentHeight(cm, measure) {
        cm.display.sizer.style.minHeight = measure.docHeight + "px";
        cm.display.heightForcer.style.top = measure.docHeight + "px";
        cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px";
      }
      function alignHorizontally(cm) {
        var display = cm.display, view = display.view;
        if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) {
          return;
        }
        var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
        var gutterW = display.gutters.offsetWidth, left2 = comp + "px";
        for (var i2 = 0; i2 < view.length; i2++) {
          if (!view[i2].hidden) {
            if (cm.options.fixedGutter) {
              if (view[i2].gutter) {
                view[i2].gutter.style.left = left2;
              }
              if (view[i2].gutterBackground) {
                view[i2].gutterBackground.style.left = left2;
              }
            }
            var align = view[i2].alignable;
            if (align) {
              for (var j = 0; j < align.length; j++) {
                align[j].style.left = left2;
              }
            }
          }
        }
        if (cm.options.fixedGutter) {
          display.gutters.style.left = comp + gutterW + "px";
        }
      }
      function maybeUpdateLineNumberWidth(cm) {
        if (!cm.options.lineNumbers) {
          return false;
        }
        var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
        if (last.length != display.lineNumChars) {
          var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt"));
          var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
          display.lineGutter.style.width = "";
          display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
          display.lineNumWidth = display.lineNumInnerWidth + padding;
          display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
          display.lineGutter.style.width = display.lineNumWidth + "px";
          updateGutterSpace(cm.display);
          return true;
        }
        return false;
      }
      function getGutters(gutters, lineNumbers) {
        var result = [], sawLineNumbers = false;
        for (var i2 = 0; i2 < gutters.length; i2++) {
          var name = gutters[i2], style = null;
          if (typeof name != "string") {
            style = name.style;
            name = name.className;
          }
          if (name == "CodeMirror-linenumbers") {
            if (!lineNumbers) {
              continue;
            } else {
              sawLineNumbers = true;
            }
          }
          result.push({className: name, style});
        }
        if (lineNumbers && !sawLineNumbers) {
          result.push({className: "CodeMirror-linenumbers", style: null});
        }
        return result;
      }
      function renderGutters(display) {
        var gutters = display.gutters, specs = display.gutterSpecs;
        removeChildren(gutters);
        display.lineGutter = null;
        for (var i2 = 0; i2 < specs.length; ++i2) {
          var ref = specs[i2];
          var className = ref.className;
          var style = ref.style;
          var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
          if (style) {
            gElt.style.cssText = style;
          }
          if (className == "CodeMirror-linenumbers") {
            display.lineGutter = gElt;
            gElt.style.width = (display.lineNumWidth || 1) + "px";
          }
        }
        gutters.style.display = specs.length ? "" : "none";
        updateGutterSpace(display);
      }
      function updateGutters(cm) {
        renderGutters(cm.display);
        regChange(cm);
        alignHorizontally(cm);
      }
      function Display(place, doc, input, options) {
        var d = this;
        this.input = input;
        d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
        d.scrollbarFiller.setAttribute("cm-not-content", "true");
        d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
        d.gutterFiller.setAttribute("cm-not-content", "true");
        d.lineDiv = eltP("div", null, "CodeMirror-code");
        d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
        d.cursorDiv = elt("div", null, "CodeMirror-cursors");
        d.measure = elt("div", null, "CodeMirror-measure");
        d.lineMeasure = elt("div", null, "CodeMirror-measure");
        d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none");
        var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
        d.mover = elt("div", [lines], null, "position: relative");
        d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
        d.sizerWidth = null;
        d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
        d.gutters = elt("div", null, "CodeMirror-gutters");
        d.lineGutter = null;
        d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
        d.scroller.setAttribute("tabIndex", "-1");
        d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
        if (ie && ie_version < 8) {
          d.gutters.style.zIndex = -1;
          d.scroller.style.paddingRight = 0;
        }
        if (!webkit && !(gecko && mobile)) {
          d.scroller.draggable = true;
        }
        if (place) {
          if (place.appendChild) {
            place.appendChild(d.wrapper);
          } else {
            place(d.wrapper);
          }
        }
        d.viewFrom = d.viewTo = doc.first;
        d.reportedViewFrom = d.reportedViewTo = doc.first;
        d.view = [];
        d.renderedView = null;
        d.externalMeasured = null;
        d.viewOffset = 0;
        d.lastWrapHeight = d.lastWrapWidth = 0;
        d.updateLineNumbers = null;
        d.nativeBarWidth = d.barHeight = d.barWidth = 0;
        d.scrollbarsClipped = false;
        d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
        d.alignWidgets = false;
        d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
        d.maxLine = null;
        d.maxLineLength = 0;
        d.maxLineChanged = false;
        d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
        d.shift = false;
        d.selForContextMenu = null;
        d.activeTouch = null;
        d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
        renderGutters(d);
        input.init(d);
      }
      var wheelSamples = 0, wheelPixelsPerUnit = null;
      if (ie) {
        wheelPixelsPerUnit = -0.53;
      } else if (gecko) {
        wheelPixelsPerUnit = 15;
      } else if (chrome) {
        wheelPixelsPerUnit = -0.7;
      } else if (safari) {
        wheelPixelsPerUnit = -1 / 3;
      }
      function wheelEventDelta(e) {
        var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
        if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) {
          dx = e.detail;
        }
        if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) {
          dy = e.detail;
        } else if (dy == null) {
          dy = e.wheelDelta;
        }
        return {x: dx, y: dy};
      }
      function wheelEventPixels(e) {
        var delta = wheelEventDelta(e);
        delta.x *= wheelPixelsPerUnit;
        delta.y *= wheelPixelsPerUnit;
        return delta;
      }
      function onScrollWheel(cm, e) {
        var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
        var display = cm.display, scroll = display.scroller;
        var canScrollX = scroll.scrollWidth > scroll.clientWidth;
        var canScrollY = scroll.scrollHeight > scroll.clientHeight;
        if (!(dx && canScrollX || dy && canScrollY)) {
          return;
        }
        if (dy && mac && webkit) {
          outer:
            for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
              for (var i2 = 0; i2 < view.length; i2++) {
                if (view[i2].node == cur) {
                  cm.display.currentWheelTarget = cur;
                  break outer;
                }
              }
            }
        }
        if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
          if (dy && canScrollY) {
            updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit));
          }
          setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
          if (!dy || dy && canScrollY) {
            e_preventDefault(e);
          }
          display.wheelStartX = null;
          return;
        }
        if (dy && wheelPixelsPerUnit != null) {
          var pixels = dy * wheelPixelsPerUnit;
          var top2 = cm.doc.scrollTop, bot = top2 + display.wrapper.clientHeight;
          if (pixels < 0) {
            top2 = Math.max(0, top2 + pixels - 50);
          } else {
            bot = Math.min(cm.doc.height, bot + pixels + 50);
          }
          updateDisplaySimple(cm, {top: top2, bottom: bot});
        }
        if (wheelSamples < 20) {
          if (display.wheelStartX == null) {
            display.wheelStartX = scroll.scrollLeft;
            display.wheelStartY = scroll.scrollTop;
            display.wheelDX = dx;
            display.wheelDY = dy;
            setTimeout(function() {
              if (display.wheelStartX == null) {
                return;
              }
              var movedX = scroll.scrollLeft - display.wheelStartX;
              var movedY = scroll.scrollTop - display.wheelStartY;
              var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX;
              display.wheelStartX = display.wheelStartY = null;
              if (!sample) {
                return;
              }
              wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
              ++wheelSamples;
            }, 200);
          } else {
            display.wheelDX += dx;
            display.wheelDY += dy;
          }
        }
      }
      var Selection2 = function(ranges, primIndex) {
        this.ranges = ranges;
        this.primIndex = primIndex;
      };
      Selection2.prototype.primary = function() {
        return this.ranges[this.primIndex];
      };
      Selection2.prototype.equals = function(other) {
        if (other == this) {
          return true;
        }
        if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) {
          return false;
        }
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          var here = this.ranges[i2], there = other.ranges[i2];
          if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) {
            return false;
          }
        }
        return true;
      };
      Selection2.prototype.deepCopy = function() {
        var out = [];
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          out[i2] = new Range(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head));
        }
        return new Selection2(out, this.primIndex);
      };
      Selection2.prototype.somethingSelected = function() {
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          if (!this.ranges[i2].empty()) {
            return true;
          }
        }
        return false;
      };
      Selection2.prototype.contains = function(pos, end) {
        if (!end) {
          end = pos;
        }
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          var range2 = this.ranges[i2];
          if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) {
            return i2;
          }
        }
        return -1;
      };
      var Range = function(anchor, head) {
        this.anchor = anchor;
        this.head = head;
      };
      Range.prototype.from = function() {
        return minPos(this.anchor, this.head);
      };
      Range.prototype.to = function() {
        return maxPos(this.anchor, this.head);
      };
      Range.prototype.empty = function() {
        return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
      };
      function normalizeSelection(cm, ranges, primIndex) {
        var mayTouch = cm && cm.options.selectionsMayTouch;
        var prim = ranges[primIndex];
        ranges.sort(function(a, b) {
          return cmp(a.from(), b.from());
        });
        primIndex = indexOf(ranges, prim);
        for (var i2 = 1; i2 < ranges.length; i2++) {
          var cur = ranges[i2], prev = ranges[i2 - 1];
          var diff = cmp(prev.to(), cur.from());
          if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
            var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
            var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
            if (i2 <= primIndex) {
              --primIndex;
            }
            ranges.splice(--i2, 2, new Range(inv ? to : from, inv ? from : to));
          }
        }
        return new Selection2(ranges, primIndex);
      }
      function simpleSelection(anchor, head) {
        return new Selection2([new Range(anchor, head || anchor)], 0);
      }
      function changeEnd(change) {
        if (!change.text) {
          return change.to;
        }
        return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
      }
      function adjustForChange(pos, change) {
        if (cmp(pos, change.from) < 0) {
          return pos;
        }
        if (cmp(pos, change.to) <= 0) {
          return changeEnd(change);
        }
        var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
        if (pos.line == change.to.line) {
          ch += changeEnd(change).ch - change.to.ch;
        }
        return Pos(line, ch);
      }
      function computeSelAfterChange(doc, change) {
        var out = [];
        for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) {
          var range2 = doc.sel.ranges[i2];
          out.push(new Range(adjustForChange(range2.anchor, change), adjustForChange(range2.head, change)));
        }
        return normalizeSelection(doc.cm, out, doc.sel.primIndex);
      }
      function offsetPos(pos, old, nw) {
        if (pos.line == old.line) {
          return Pos(nw.line, pos.ch - old.ch + nw.ch);
        } else {
          return Pos(nw.line + (pos.line - old.line), pos.ch);
        }
      }
      function computeReplacedSel(doc, changes, hint) {
        var out = [];
        var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
        for (var i2 = 0; i2 < changes.length; i2++) {
          var change = changes[i2];
          var from = offsetPos(change.from, oldPrev, newPrev);
          var to = offsetPos(changeEnd(change), oldPrev, newPrev);
          oldPrev = change.to;
          newPrev = to;
          if (hint == "around") {
            var range2 = doc.sel.ranges[i2], inv = cmp(range2.head, range2.anchor) < 0;
            out[i2] = new Range(inv ? to : from, inv ? from : to);
          } else {
            out[i2] = new Range(from, from);
          }
        }
        return new Selection2(out, doc.sel.primIndex);
      }
      function loadMode(cm) {
        cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
        resetModeState(cm);
      }
      function resetModeState(cm) {
        cm.doc.iter(function(line) {
          if (line.stateAfter) {
            line.stateAfter = null;
          }
          if (line.styles) {
            line.styles = null;
          }
        });
        cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
        startWorker(cm, 100);
        cm.state.modeGen++;
        if (cm.curOp) {
          regChange(cm);
        }
      }
      function isWholeLineUpdate(doc, change) {
        return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
      }
      function updateDoc(doc, change, markedSpans, estimateHeight2) {
        function spansFor(n) {
          return markedSpans ? markedSpans[n] : null;
        }
        function update2(line, text3, spans) {
          updateLine(line, text3, spans, estimateHeight2);
          signalLater(line, "change", line, change);
        }
        function linesFor(start, end) {
          var result = [];
          for (var i2 = start; i2 < end; ++i2) {
            result.push(new Line(text2[i2], spansFor(i2), estimateHeight2));
          }
          return result;
        }
        var from = change.from, to = change.to, text2 = change.text;
        var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
        var lastText = lst(text2), lastSpans = spansFor(text2.length - 1), nlines = to.line - from.line;
        if (change.full) {
          doc.insert(0, linesFor(0, text2.length));
          doc.remove(text2.length, doc.size - text2.length);
        } else if (isWholeLineUpdate(doc, change)) {
          var added = linesFor(0, text2.length - 1);
          update2(lastLine, lastLine.text, lastSpans);
          if (nlines) {
            doc.remove(from.line, nlines);
          }
          if (added.length) {
            doc.insert(from.line, added);
          }
        } else if (firstLine == lastLine) {
          if (text2.length == 1) {
            update2(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
          } else {
            var added$1 = linesFor(1, text2.length - 1);
            added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2));
            update2(firstLine, firstLine.text.slice(0, from.ch) + text2[0], spansFor(0));
            doc.insert(from.line + 1, added$1);
          }
        } else if (text2.length == 1) {
          update2(firstLine, firstLine.text.slice(0, from.ch) + text2[0] + lastLine.text.slice(to.ch), spansFor(0));
          doc.remove(from.line + 1, nlines);
        } else {
          update2(firstLine, firstLine.text.slice(0, from.ch) + text2[0], spansFor(0));
          update2(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
          var added$2 = linesFor(1, text2.length - 1);
          if (nlines > 1) {
            doc.remove(from.line + 1, nlines - 1);
          }
          doc.insert(from.line + 1, added$2);
        }
        signalLater(doc, "change", doc, change);
      }
      function linkedDocs(doc, f, sharedHistOnly) {
        function propagate(doc2, skip, sharedHist) {
          if (doc2.linked) {
            for (var i2 = 0; i2 < doc2.linked.length; ++i2) {
              var rel = doc2.linked[i2];
              if (rel.doc == skip) {
                continue;
              }
              var shared = sharedHist && rel.sharedHist;
              if (sharedHistOnly && !shared) {
                continue;
              }
              f(rel.doc, shared);
              propagate(rel.doc, doc2, shared);
            }
          }
        }
        propagate(doc, null, true);
      }
      function attachDoc(cm, doc) {
        if (doc.cm) {
          throw new Error("This document is already in use.");
        }
        cm.doc = doc;
        doc.cm = cm;
        estimateLineHeights(cm);
        loadMode(cm);
        setDirectionClass(cm);
        if (!cm.options.lineWrapping) {
          findMaxLine(cm);
        }
        cm.options.mode = doc.modeOption;
        regChange(cm);
      }
      function setDirectionClass(cm) {
        (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
      }
      function directionChanged(cm) {
        runInOp(cm, function() {
          setDirectionClass(cm);
          regChange(cm);
        });
      }
      function History(startGen) {
        this.done = [];
        this.undone = [];
        this.undoDepth = Infinity;
        this.lastModTime = this.lastSelTime = 0;
        this.lastOp = this.lastSelOp = null;
        this.lastOrigin = this.lastSelOrigin = null;
        this.generation = this.maxGeneration = startGen || 1;
      }
      function historyChangeFromChange(doc, change) {
        var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
        attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
        linkedDocs(doc, function(doc2) {
          return attachLocalSpans(doc2, histChange, change.from.line, change.to.line + 1);
        }, true);
        return histChange;
      }
      function clearSelectionEvents(array2) {
        while (array2.length) {
          var last = lst(array2);
          if (last.ranges) {
            array2.pop();
          } else {
            break;
          }
        }
      }
      function lastChangeEvent(hist, force) {
        if (force) {
          clearSelectionEvents(hist.done);
          return lst(hist.done);
        } else if (hist.done.length && !lst(hist.done).ranges) {
          return lst(hist.done);
        } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
          hist.done.pop();
          return lst(hist.done);
        }
      }
      function addChangeToHistory(doc, change, selAfter, opId) {
        var hist = doc.history;
        hist.undone.length = 0;
        var time = +new Date(), cur;
        var last;
        if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
          last = lst(cur.changes);
          if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
            last.to = changeEnd(change);
          } else {
            cur.changes.push(historyChangeFromChange(doc, change));
          }
        } else {
          var before = lst(hist.done);
          if (!before || !before.ranges) {
            pushSelectionToHistory(doc.sel, hist.done);
          }
          cur = {
            changes: [historyChangeFromChange(doc, change)],
            generation: hist.generation
          };
          hist.done.push(cur);
          while (hist.done.length > hist.undoDepth) {
            hist.done.shift();
            if (!hist.done[0].ranges) {
              hist.done.shift();
            }
          }
        }
        hist.done.push(selAfter);
        hist.generation = ++hist.maxGeneration;
        hist.lastModTime = hist.lastSelTime = time;
        hist.lastOp = hist.lastSelOp = opId;
        hist.lastOrigin = hist.lastSelOrigin = change.origin;
        if (!last) {
          signal(doc, "historyAdded");
        }
      }
      function selectionEventCanBeMerged(doc, origin, prev, sel) {
        var ch = origin.charAt(0);
        return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
      }
      function addSelectionToHistory(doc, sel, opId, options) {
        var hist = doc.history, origin = options && options.origin;
        if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) {
          hist.done[hist.done.length - 1] = sel;
        } else {
          pushSelectionToHistory(sel, hist.done);
        }
        hist.lastSelTime = +new Date();
        hist.lastSelOrigin = origin;
        hist.lastSelOp = opId;
        if (options && options.clearRedo !== false) {
          clearSelectionEvents(hist.undone);
        }
      }
      function pushSelectionToHistory(sel, dest) {
        var top2 = lst(dest);
        if (!(top2 && top2.ranges && top2.equals(sel))) {
          dest.push(sel);
        }
      }
      function attachLocalSpans(doc, change, from, to) {
        var existing = change["spans_" + doc.id], n = 0;
        doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
          if (line.markedSpans) {
            (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
          }
          ++n;
        });
      }
      function removeClearedSpans(spans) {
        if (!spans) {
          return null;
        }
        var out;
        for (var i2 = 0; i2 < spans.length; ++i2) {
          if (spans[i2].marker.explicitlyCleared) {
            if (!out) {
              out = spans.slice(0, i2);
            }
          } else if (out) {
            out.push(spans[i2]);
          }
        }
        return !out ? spans : out.length ? out : null;
      }
      function getOldSpans(doc, change) {
        var found = change["spans_" + doc.id];
        if (!found) {
          return null;
        }
        var nw = [];
        for (var i2 = 0; i2 < change.text.length; ++i2) {
          nw.push(removeClearedSpans(found[i2]));
        }
        return nw;
      }
      function mergeOldSpans(doc, change) {
        var old = getOldSpans(doc, change);
        var stretched = stretchSpansOverChange(doc, change);
        if (!old) {
          return stretched;
        }
        if (!stretched) {
          return old;
        }
        for (var i2 = 0; i2 < old.length; ++i2) {
          var oldCur = old[i2], stretchCur = stretched[i2];
          if (oldCur && stretchCur) {
            spans:
              for (var j = 0; j < stretchCur.length; ++j) {
                var span = stretchCur[j];
                for (var k = 0; k < oldCur.length; ++k) {
                  if (oldCur[k].marker == span.marker) {
                    continue spans;
                  }
                }
                oldCur.push(span);
              }
          } else if (stretchCur) {
            old[i2] = stretchCur;
          }
        }
        return old;
      }
      function copyHistoryArray(events, newGroup, instantiateSel) {
        var copy2 = [];
        for (var i2 = 0; i2 < events.length; ++i2) {
          var event = events[i2];
          if (event.ranges) {
            copy2.push(instantiateSel ? Selection2.prototype.deepCopy.call(event) : event);
            continue;
          }
          var changes = event.changes, newChanges = [];
          copy2.push({changes: newChanges});
          for (var j = 0; j < changes.length; ++j) {
            var change = changes[j], m = void 0;
            newChanges.push({from: change.from, to: change.to, text: change.text});
            if (newGroup) {
              for (var prop2 in change) {
                if (m = prop2.match(/^spans_(\d+)$/)) {
                  if (indexOf(newGroup, Number(m[1])) > -1) {
                    lst(newChanges)[prop2] = change[prop2];
                    delete change[prop2];
                  }
                }
              }
            }
          }
        }
        return copy2;
      }
      function extendRange(range2, head, other, extend2) {
        if (extend2) {
          var anchor = range2.anchor;
          if (other) {
            var posBefore = cmp(head, anchor) < 0;
            if (posBefore != cmp(other, anchor) < 0) {
              anchor = head;
              head = other;
            } else if (posBefore != cmp(head, other) < 0) {
              head = other;
            }
          }
          return new Range(anchor, head);
        } else {
          return new Range(other || head, head);
        }
      }
      function extendSelection(doc, head, other, options, extend2) {
        if (extend2 == null) {
          extend2 = doc.cm && (doc.cm.display.shift || doc.extend);
        }
        setSelection(doc, new Selection2([extendRange(doc.sel.primary(), head, other, extend2)], 0), options);
      }
      function extendSelections(doc, heads, options) {
        var out = [];
        var extend2 = doc.cm && (doc.cm.display.shift || doc.extend);
        for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) {
          out[i2] = extendRange(doc.sel.ranges[i2], heads[i2], null, extend2);
        }
        var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
        setSelection(doc, newSel, options);
      }
      function replaceOneSelection(doc, i2, range2, options) {
        var ranges = doc.sel.ranges.slice(0);
        ranges[i2] = range2;
        setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
      }
      function setSimpleSelection(doc, anchor, head, options) {
        setSelection(doc, simpleSelection(anchor, head), options);
      }
      function filterSelectionChange(doc, sel, options) {
        var obj = {
          ranges: sel.ranges,
          update: function(ranges) {
            this.ranges = [];
            for (var i2 = 0; i2 < ranges.length; i2++) {
              this.ranges[i2] = new Range(clipPos(doc, ranges[i2].anchor), clipPos(doc, ranges[i2].head));
            }
          },
          origin: options && options.origin
        };
        signal(doc, "beforeSelectionChange", doc, obj);
        if (doc.cm) {
          signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
        }
        if (obj.ranges != sel.ranges) {
          return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1);
        } else {
          return sel;
        }
      }
      function setSelectionReplaceHistory(doc, sel, options) {
        var done = doc.history.done, last = lst(done);
        if (last && last.ranges) {
          done[done.length - 1] = sel;
          setSelectionNoUndo(doc, sel, options);
        } else {
          setSelection(doc, sel, options);
        }
      }
      function setSelection(doc, sel, options) {
        setSelectionNoUndo(doc, sel, options);
        addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
      }
      function setSelectionNoUndo(doc, sel, options) {
        if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
          sel = filterSelectionChange(doc, sel, options);
        }
        var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
        setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
        if (!(options && options.scroll === false) && doc.cm) {
          ensureCursorVisible(doc.cm);
        }
      }
      function setSelectionInner(doc, sel) {
        if (sel.equals(doc.sel)) {
          return;
        }
        doc.sel = sel;
        if (doc.cm) {
          doc.cm.curOp.updateInput = 1;
          doc.cm.curOp.selectionChanged = true;
          signalCursorActivity(doc.cm);
        }
        signalLater(doc, "cursorActivity", doc);
      }
      function reCheckSelection(doc) {
        setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
      }
      function skipAtomicInSelection(doc, sel, bias, mayClear) {
        var out;
        for (var i2 = 0; i2 < sel.ranges.length; i2++) {
          var range2 = sel.ranges[i2];
          var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i2];
          var newAnchor = skipAtomic(doc, range2.anchor, old && old.anchor, bias, mayClear);
          var newHead = skipAtomic(doc, range2.head, old && old.head, bias, mayClear);
          if (out || newAnchor != range2.anchor || newHead != range2.head) {
            if (!out) {
              out = sel.ranges.slice(0, i2);
            }
            out[i2] = new Range(newAnchor, newHead);
          }
        }
        return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel;
      }
      function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
        var line = getLine(doc, pos.line);
        if (line.markedSpans) {
          for (var i2 = 0; i2 < line.markedSpans.length; ++i2) {
            var sp = line.markedSpans[i2], m = sp.marker;
            var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft;
            var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight;
            if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
              if (mayClear) {
                signal(m, "beforeCursorEnter");
                if (m.explicitlyCleared) {
                  if (!line.markedSpans) {
                    break;
                  } else {
                    --i2;
                    continue;
                  }
                }
              }
              if (!m.atomic) {
                continue;
              }
              if (oldPos) {
                var near = m.find(dir < 0 ? 1 : -1), diff = void 0;
                if (dir < 0 ? preventCursorRight : preventCursorLeft) {
                  near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
                }
                if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) {
                  return skipAtomicInner(doc, near, pos, dir, mayClear);
                }
              }
              var far = m.find(dir < 0 ? -1 : 1);
              if (dir < 0 ? preventCursorLeft : preventCursorRight) {
                far = movePos(doc, far, dir, far.line == pos.line ? line : null);
              }
              return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
            }
          }
        }
        return pos;
      }
      function skipAtomic(doc, pos, oldPos, bias, mayClear) {
        var dir = bias || 1;
        var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true);
        if (!found) {
          doc.cantEdit = true;
          return Pos(doc.first, 0);
        }
        return found;
      }
      function movePos(doc, pos, dir, line) {
        if (dir < 0 && pos.ch == 0) {
          if (pos.line > doc.first) {
            return clipPos(doc, Pos(pos.line - 1));
          } else {
            return null;
          }
        } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
          if (pos.line < doc.first + doc.size - 1) {
            return Pos(pos.line + 1, 0);
          } else {
            return null;
          }
        } else {
          return new Pos(pos.line, pos.ch + dir);
        }
      }
      function selectAll(cm) {
        cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
      }
      function filterChange(doc, change, update2) {
        var obj = {
          canceled: false,
          from: change.from,
          to: change.to,
          text: change.text,
          origin: change.origin,
          cancel: function() {
            return obj.canceled = true;
          }
        };
        if (update2) {
          obj.update = function(from, to, text2, origin) {
            if (from) {
              obj.from = clipPos(doc, from);
            }
            if (to) {
              obj.to = clipPos(doc, to);
            }
            if (text2) {
              obj.text = text2;
            }
            if (origin !== void 0) {
              obj.origin = origin;
            }
          };
        }
        signal(doc, "beforeChange", doc, obj);
        if (doc.cm) {
          signal(doc.cm, "beforeChange", doc.cm, obj);
        }
        if (obj.canceled) {
          if (doc.cm) {
            doc.cm.curOp.updateInput = 2;
          }
          return null;
        }
        return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
      }
      function makeChange(doc, change, ignoreReadOnly) {
        if (doc.cm) {
          if (!doc.cm.curOp) {
            return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
          }
          if (doc.cm.state.suppressEdits) {
            return;
          }
        }
        if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
          change = filterChange(doc, change, true);
          if (!change) {
            return;
          }
        }
        var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
        if (split) {
          for (var i2 = split.length - 1; i2 >= 0; --i2) {
            makeChangeInner(doc, {from: split[i2].from, to: split[i2].to, text: i2 ? [""] : change.text, origin: change.origin});
          }
        } else {
          makeChangeInner(doc, change);
        }
      }
      function makeChangeInner(doc, change) {
        if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) {
          return;
        }
        var selAfter = computeSelAfterChange(doc, change);
        addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
        makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
        var rebased = [];
        linkedDocs(doc, function(doc2, sharedHist) {
          if (!sharedHist && indexOf(rebased, doc2.history) == -1) {
            rebaseHist(doc2.history, change);
            rebased.push(doc2.history);
          }
          makeChangeSingleDoc(doc2, change, null, stretchSpansOverChange(doc2, change));
        });
      }
      function makeChangeFromHistory(doc, type, allowSelectionOnly) {
        var suppress = doc.cm && doc.cm.state.suppressEdits;
        if (suppress && !allowSelectionOnly) {
          return;
        }
        var hist = doc.history, event, selAfter = doc.sel;
        var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
        var i2 = 0;
        for (; i2 < source.length; i2++) {
          event = source[i2];
          if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {
            break;
          }
        }
        if (i2 == source.length) {
          return;
        }
        hist.lastOrigin = hist.lastSelOrigin = null;
        for (; ; ) {
          event = source.pop();
          if (event.ranges) {
            pushSelectionToHistory(event, dest);
            if (allowSelectionOnly && !event.equals(doc.sel)) {
              setSelection(doc, event, {clearRedo: false});
              return;
            }
            selAfter = event;
          } else if (suppress) {
            source.push(event);
            return;
          } else {
            break;
          }
        }
        var antiChanges = [];
        pushSelectionToHistory(selAfter, dest);
        dest.push({changes: antiChanges, generation: hist.generation});
        hist.generation = event.generation || ++hist.maxGeneration;
        var filter2 = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
        var loop = function(i3) {
          var change = event.changes[i3];
          change.origin = type;
          if (filter2 && !filterChange(doc, change, false)) {
            source.length = 0;
            return {};
          }
          antiChanges.push(historyChangeFromChange(doc, change));
          var after = i3 ? computeSelAfterChange(doc, change) : lst(source);
          makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
          if (!i3 && doc.cm) {
            doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
          }
          var rebased = [];
          linkedDocs(doc, function(doc2, sharedHist) {
            if (!sharedHist && indexOf(rebased, doc2.history) == -1) {
              rebaseHist(doc2.history, change);
              rebased.push(doc2.history);
            }
            makeChangeSingleDoc(doc2, change, null, mergeOldSpans(doc2, change));
          });
        };
        for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) {
          var returned = loop(i$12);
          if (returned)
            return returned.v;
        }
      }
      function shiftDoc(doc, distance) {
        if (distance == 0) {
          return;
        }
        doc.first += distance;
        doc.sel = new Selection2(map2(doc.sel.ranges, function(range2) {
          return new Range(Pos(range2.anchor.line + distance, range2.anchor.ch), Pos(range2.head.line + distance, range2.head.ch));
        }), doc.sel.primIndex);
        if (doc.cm) {
          regChange(doc.cm, doc.first, doc.first - distance, distance);
          for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {
            regLineChange(doc.cm, l, "gutter");
          }
        }
      }
      function makeChangeSingleDoc(doc, change, selAfter, spans) {
        if (doc.cm && !doc.cm.curOp) {
          return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
        }
        if (change.to.line < doc.first) {
          shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
          return;
        }
        if (change.from.line > doc.lastLine()) {
          return;
        }
        if (change.from.line < doc.first) {
          var shift = change.text.length - 1 - (doc.first - change.from.line);
          shiftDoc(doc, shift);
          change = {
            from: Pos(doc.first, 0),
            to: Pos(change.to.line + shift, change.to.ch),
            text: [lst(change.text)],
            origin: change.origin
          };
        }
        var last = doc.lastLine();
        if (change.to.line > last) {
          change = {
            from: change.from,
            to: Pos(last, getLine(doc, last).text.length),
            text: [change.text[0]],
            origin: change.origin
          };
        }
        change.removed = getBetween(doc, change.from, change.to);
        if (!selAfter) {
          selAfter = computeSelAfterChange(doc, change);
        }
        if (doc.cm) {
          makeChangeSingleDocInEditor(doc.cm, change, spans);
        } else {
          updateDoc(doc, change, spans);
        }
        setSelectionNoUndo(doc, selAfter, sel_dontScroll);
        if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) {
          doc.cantEdit = false;
        }
      }
      function makeChangeSingleDocInEditor(cm, change, spans) {
        var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
        var recomputeMaxLength = false, checkWidthStart = from.line;
        if (!cm.options.lineWrapping) {
          checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
          doc.iter(checkWidthStart, to.line + 1, function(line) {
            if (line == display.maxLine) {
              recomputeMaxLength = true;
              return true;
            }
          });
        }
        if (doc.sel.contains(change.from, change.to) > -1) {
          signalCursorActivity(cm);
        }
        updateDoc(doc, change, spans, estimateHeight(cm));
        if (!cm.options.lineWrapping) {
          doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
            var len = lineLength(line);
            if (len > display.maxLineLength) {
              display.maxLine = line;
              display.maxLineLength = len;
              display.maxLineChanged = true;
              recomputeMaxLength = false;
            }
          });
          if (recomputeMaxLength) {
            cm.curOp.updateMaxLine = true;
          }
        }
        retreatFrontier(doc, from.line);
        startWorker(cm, 400);
        var lendiff = change.text.length - (to.line - from.line) - 1;
        if (change.full) {
          regChange(cm);
        } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {
          regLineChange(cm, from.line, "text");
        } else {
          regChange(cm, from.line, to.line + 1, lendiff);
        }
        var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
        if (changeHandler || changesHandler) {
          var obj = {
            from,
            to,
            text: change.text,
            removed: change.removed,
            origin: change.origin
          };
          if (changeHandler) {
            signalLater(cm, "change", cm, obj);
          }
          if (changesHandler) {
            (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
          }
        }
        cm.display.selForContextMenu = null;
      }
      function replaceRange(doc, code, from, to, origin) {
        var assign2;
        if (!to) {
          to = from;
        }
        if (cmp(to, from) < 0) {
          assign2 = [to, from], from = assign2[0], to = assign2[1];
        }
        if (typeof code == "string") {
          code = doc.splitLines(code);
        }
        makeChange(doc, {from, to, text: code, origin});
      }
      function rebaseHistSelSingle(pos, from, to, diff) {
        if (to < pos.line) {
          pos.line += diff;
        } else if (from < pos.line) {
          pos.line = from;
          pos.ch = 0;
        }
      }
      function rebaseHistArray(array2, from, to, diff) {
        for (var i2 = 0; i2 < array2.length; ++i2) {
          var sub = array2[i2], ok = true;
          if (sub.ranges) {
            if (!sub.copied) {
              sub = array2[i2] = sub.deepCopy();
              sub.copied = true;
            }
            for (var j = 0; j < sub.ranges.length; j++) {
              rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
              rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
            }
            continue;
          }
          for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
            var cur = sub.changes[j$1];
            if (to < cur.from.line) {
              cur.from = Pos(cur.from.line + diff, cur.from.ch);
              cur.to = Pos(cur.to.line + diff, cur.to.ch);
            } else if (from <= cur.to.line) {
              ok = false;
              break;
            }
          }
          if (!ok) {
            array2.splice(0, i2 + 1);
            i2 = 0;
          }
        }
      }
      function rebaseHist(hist, change) {
        var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
        rebaseHistArray(hist.done, from, to, diff);
        rebaseHistArray(hist.undone, from, to, diff);
      }
      function changeLine(doc, handle, changeType, op) {
        var no = handle, line = handle;
        if (typeof handle == "number") {
          line = getLine(doc, clipLine(doc, handle));
        } else {
          no = lineNo(handle);
        }
        if (no == null) {
          return null;
        }
        if (op(line, no) && doc.cm) {
          regLineChange(doc.cm, no, changeType);
        }
        return line;
      }
      function LeafChunk(lines) {
        this.lines = lines;
        this.parent = null;
        var height4 = 0;
        for (var i2 = 0; i2 < lines.length; ++i2) {
          lines[i2].parent = this;
          height4 += lines[i2].height;
        }
        this.height = height4;
      }
      LeafChunk.prototype = {
        chunkSize: function() {
          return this.lines.length;
        },
        removeInner: function(at, n) {
          for (var i2 = at, e = at + n; i2 < e; ++i2) {
            var line = this.lines[i2];
            this.height -= line.height;
            cleanUpLine(line);
            signalLater(line, "delete");
          }
          this.lines.splice(at, n);
        },
        collapse: function(lines) {
          lines.push.apply(lines, this.lines);
        },
        insertInner: function(at, lines, height4) {
          this.height += height4;
          this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
          for (var i2 = 0; i2 < lines.length; ++i2) {
            lines[i2].parent = this;
          }
        },
        iterN: function(at, n, op) {
          for (var e = at + n; at < e; ++at) {
            if (op(this.lines[at])) {
              return true;
            }
          }
        }
      };
      function BranchChunk(children3) {
        this.children = children3;
        var size = 0, height4 = 0;
        for (var i2 = 0; i2 < children3.length; ++i2) {
          var ch = children3[i2];
          size += ch.chunkSize();
          height4 += ch.height;
          ch.parent = this;
        }
        this.size = size;
        this.height = height4;
        this.parent = null;
      }
      BranchChunk.prototype = {
        chunkSize: function() {
          return this.size;
        },
        removeInner: function(at, n) {
          this.size -= n;
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            var child = this.children[i2], sz = child.chunkSize();
            if (at < sz) {
              var rm = Math.min(n, sz - at), oldHeight = child.height;
              child.removeInner(at, rm);
              this.height -= oldHeight - child.height;
              if (sz == rm) {
                this.children.splice(i2--, 1);
                child.parent = null;
              }
              if ((n -= rm) == 0) {
                break;
              }
              at = 0;
            } else {
              at -= sz;
            }
          }
          if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
            var lines = [];
            this.collapse(lines);
            this.children = [new LeafChunk(lines)];
            this.children[0].parent = this;
          }
        },
        collapse: function(lines) {
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            this.children[i2].collapse(lines);
          }
        },
        insertInner: function(at, lines, height4) {
          this.size += lines.length;
          this.height += height4;
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            var child = this.children[i2], sz = child.chunkSize();
            if (at <= sz) {
              child.insertInner(at, lines, height4);
              if (child.lines && child.lines.length > 50) {
                var remaining = child.lines.length % 25 + 25;
                for (var pos = remaining; pos < child.lines.length; ) {
                  var leaf2 = new LeafChunk(child.lines.slice(pos, pos += 25));
                  child.height -= leaf2.height;
                  this.children.splice(++i2, 0, leaf2);
                  leaf2.parent = this;
                }
                child.lines = child.lines.slice(0, remaining);
                this.maybeSpill();
              }
              break;
            }
            at -= sz;
          }
        },
        maybeSpill: function() {
          if (this.children.length <= 10) {
            return;
          }
          var me = this;
          do {
            var spilled = me.children.splice(me.children.length - 5, 5);
            var sibling = new BranchChunk(spilled);
            if (!me.parent) {
              var copy2 = new BranchChunk(me.children);
              copy2.parent = me;
              me.children = [copy2, sibling];
              me = copy2;
            } else {
              me.size -= sibling.size;
              me.height -= sibling.height;
              var myIndex = indexOf(me.parent.children, me);
              me.parent.children.splice(myIndex + 1, 0, sibling);
            }
            sibling.parent = me.parent;
          } while (me.children.length > 10);
          me.parent.maybeSpill();
        },
        iterN: function(at, n, op) {
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            var child = this.children[i2], sz = child.chunkSize();
            if (at < sz) {
              var used = Math.min(n, sz - at);
              if (child.iterN(at, used, op)) {
                return true;
              }
              if ((n -= used) == 0) {
                break;
              }
              at = 0;
            } else {
              at -= sz;
            }
          }
        }
      };
      var LineWidget = function(doc, node, options) {
        if (options) {
          for (var opt in options) {
            if (options.hasOwnProperty(opt)) {
              this[opt] = options[opt];
            }
          }
        }
        this.doc = doc;
        this.node = node;
      };
      LineWidget.prototype.clear = function() {
        var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
        if (no == null || !ws) {
          return;
        }
        for (var i2 = 0; i2 < ws.length; ++i2) {
          if (ws[i2] == this) {
            ws.splice(i2--, 1);
          }
        }
        if (!ws.length) {
          line.widgets = null;
        }
        var height4 = widgetHeight(this);
        updateLineHeight(line, Math.max(0, line.height - height4));
        if (cm) {
          runInOp(cm, function() {
            adjustScrollWhenAboveVisible(cm, line, -height4);
            regLineChange(cm, no, "widget");
          });
          signalLater(cm, "lineWidgetCleared", cm, this, no);
        }
      };
      LineWidget.prototype.changed = function() {
        var this$1 = this;
        var oldH = this.height, cm = this.doc.cm, line = this.line;
        this.height = null;
        var diff = widgetHeight(this) - oldH;
        if (!diff) {
          return;
        }
        if (!lineIsHidden(this.doc, line)) {
          updateLineHeight(line, line.height + diff);
        }
        if (cm) {
          runInOp(cm, function() {
            cm.curOp.forceUpdate = true;
            adjustScrollWhenAboveVisible(cm, line, diff);
            signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
          });
        }
      };
      eventMixin(LineWidget);
      function adjustScrollWhenAboveVisible(cm, line, diff) {
        if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) {
          addToScrollTop(cm, diff);
        }
      }
      function addLineWidget(doc, handle, node, options) {
        var widget = new LineWidget(doc, node, options);
        var cm = doc.cm;
        if (cm && widget.noHScroll) {
          cm.display.alignWidgets = true;
        }
        changeLine(doc, handle, "widget", function(line) {
          var widgets = line.widgets || (line.widgets = []);
          if (widget.insertAt == null) {
            widgets.push(widget);
          } else {
            widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget);
          }
          widget.line = line;
          if (cm && !lineIsHidden(doc, line)) {
            var aboveVisible = heightAtLine(line) < doc.scrollTop;
            updateLineHeight(line, line.height + widgetHeight(widget));
            if (aboveVisible) {
              addToScrollTop(cm, widget.height);
            }
            cm.curOp.forceUpdate = true;
          }
          return true;
        });
        if (cm) {
          signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
        }
        return widget;
      }
      var nextMarkerId = 0;
      var TextMarker = function(doc, type) {
        this.lines = [];
        this.type = type;
        this.doc = doc;
        this.id = ++nextMarkerId;
      };
      TextMarker.prototype.clear = function() {
        if (this.explicitlyCleared) {
          return;
        }
        var cm = this.doc.cm, withOp = cm && !cm.curOp;
        if (withOp) {
          startOperation(cm);
        }
        if (hasHandler(this, "clear")) {
          var found = this.find();
          if (found) {
            signalLater(this, "clear", found.from, found.to);
          }
        }
        var min3 = null, max3 = null;
        for (var i2 = 0; i2 < this.lines.length; ++i2) {
          var line = this.lines[i2];
          var span = getMarkedSpanFor(line.markedSpans, this);
          if (cm && !this.collapsed) {
            regLineChange(cm, lineNo(line), "text");
          } else if (cm) {
            if (span.to != null) {
              max3 = lineNo(line);
            }
            if (span.from != null) {
              min3 = lineNo(line);
            }
          }
          line.markedSpans = removeMarkedSpan(line.markedSpans, span);
          if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {
            updateLineHeight(line, textHeight(cm.display));
          }
        }
        if (cm && this.collapsed && !cm.options.lineWrapping) {
          for (var i$12 = 0; i$12 < this.lines.length; ++i$12) {
            var visual = visualLine(this.lines[i$12]), len = lineLength(visual);
            if (len > cm.display.maxLineLength) {
              cm.display.maxLine = visual;
              cm.display.maxLineLength = len;
              cm.display.maxLineChanged = true;
            }
          }
        }
        if (min3 != null && cm && this.collapsed) {
          regChange(cm, min3, max3 + 1);
        }
        this.lines.length = 0;
        this.explicitlyCleared = true;
        if (this.atomic && this.doc.cantEdit) {
          this.doc.cantEdit = false;
          if (cm) {
            reCheckSelection(cm.doc);
          }
        }
        if (cm) {
          signalLater(cm, "markerCleared", cm, this, min3, max3);
        }
        if (withOp) {
          endOperation(cm);
        }
        if (this.parent) {
          this.parent.clear();
        }
      };
      TextMarker.prototype.find = function(side, lineObj) {
        if (side == null && this.type == "bookmark") {
          side = 1;
        }
        var from, to;
        for (var i2 = 0; i2 < this.lines.length; ++i2) {
          var line = this.lines[i2];
          var span = getMarkedSpanFor(line.markedSpans, this);
          if (span.from != null) {
            from = Pos(lineObj ? line : lineNo(line), span.from);
            if (side == -1) {
              return from;
            }
          }
          if (span.to != null) {
            to = Pos(lineObj ? line : lineNo(line), span.to);
            if (side == 1) {
              return to;
            }
          }
        }
        return from && {from, to};
      };
      TextMarker.prototype.changed = function() {
        var this$1 = this;
        var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
        if (!pos || !cm) {
          return;
        }
        runInOp(cm, function() {
          var line = pos.line, lineN = lineNo(pos.line);
          var view = findViewForLine(cm, lineN);
          if (view) {
            clearLineMeasurementCacheFor(view);
            cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
          }
          cm.curOp.updateMaxLine = true;
          if (!lineIsHidden(widget.doc, line) && widget.height != null) {
            var oldHeight = widget.height;
            widget.height = null;
            var dHeight = widgetHeight(widget) - oldHeight;
            if (dHeight) {
              updateLineHeight(line, line.height + dHeight);
            }
          }
          signalLater(cm, "markerChanged", cm, this$1);
        });
      };
      TextMarker.prototype.attachLine = function(line) {
        if (!this.lines.length && this.doc.cm) {
          var op = this.doc.cm.curOp;
          if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {
            (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
          }
        }
        this.lines.push(line);
      };
      TextMarker.prototype.detachLine = function(line) {
        this.lines.splice(indexOf(this.lines, line), 1);
        if (!this.lines.length && this.doc.cm) {
          var op = this.doc.cm.curOp;
          (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
        }
      };
      eventMixin(TextMarker);
      function markText(doc, from, to, options, type) {
        if (options && options.shared) {
          return markTextShared(doc, from, to, options, type);
        }
        if (doc.cm && !doc.cm.curOp) {
          return operation(doc.cm, markText)(doc, from, to, options, type);
        }
        var marker = new TextMarker(doc, type), diff = cmp(from, to);
        if (options) {
          copyObj(options, marker, false);
        }
        if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {
          return marker;
        }
        if (marker.replacedWith) {
          marker.collapsed = true;
          marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
          if (!options.handleMouseEvents) {
            marker.widgetNode.setAttribute("cm-ignore-events", "true");
          }
          if (options.insertLeft) {
            marker.widgetNode.insertLeft = true;
          }
        }
        if (marker.collapsed) {
          if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) {
            throw new Error("Inserting collapsed marker partially overlapping an existing one");
          }
          seeCollapsedSpans();
        }
        if (marker.addToHistory) {
          addChangeToHistory(doc, {from, to, origin: "markText"}, doc.sel, NaN);
        }
        var curLine = from.line, cm = doc.cm, updateMaxLine;
        doc.iter(curLine, to.line + 1, function(line) {
          if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {
            updateMaxLine = true;
          }
          if (marker.collapsed && curLine != from.line) {
            updateLineHeight(line, 0);
          }
          addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null));
          ++curLine;
        });
        if (marker.collapsed) {
          doc.iter(from.line, to.line + 1, function(line) {
            if (lineIsHidden(doc, line)) {
              updateLineHeight(line, 0);
            }
          });
        }
        if (marker.clearOnEnter) {
          on(marker, "beforeCursorEnter", function() {
            return marker.clear();
          });
        }
        if (marker.readOnly) {
          seeReadOnlySpans();
          if (doc.history.done.length || doc.history.undone.length) {
            doc.clearHistory();
          }
        }
        if (marker.collapsed) {
          marker.id = ++nextMarkerId;
          marker.atomic = true;
        }
        if (cm) {
          if (updateMaxLine) {
            cm.curOp.updateMaxLine = true;
          }
          if (marker.collapsed) {
            regChange(cm, from.line, to.line + 1);
          } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) {
            for (var i2 = from.line; i2 <= to.line; i2++) {
              regLineChange(cm, i2, "text");
            }
          }
          if (marker.atomic) {
            reCheckSelection(cm.doc);
          }
          signalLater(cm, "markerAdded", cm, marker);
        }
        return marker;
      }
      var SharedTextMarker = function(markers, primary) {
        this.markers = markers;
        this.primary = primary;
        for (var i2 = 0; i2 < markers.length; ++i2) {
          markers[i2].parent = this;
        }
      };
      SharedTextMarker.prototype.clear = function() {
        if (this.explicitlyCleared) {
          return;
        }
        this.explicitlyCleared = true;
        for (var i2 = 0; i2 < this.markers.length; ++i2) {
          this.markers[i2].clear();
        }
        signalLater(this, "clear");
      };
      SharedTextMarker.prototype.find = function(side, lineObj) {
        return this.primary.find(side, lineObj);
      };
      eventMixin(SharedTextMarker);
      function markTextShared(doc, from, to, options, type) {
        options = copyObj(options);
        options.shared = false;
        var markers = [markText(doc, from, to, options, type)], primary = markers[0];
        var widget = options.widgetNode;
        linkedDocs(doc, function(doc2) {
          if (widget) {
            options.widgetNode = widget.cloneNode(true);
          }
          markers.push(markText(doc2, clipPos(doc2, from), clipPos(doc2, to), options, type));
          for (var i2 = 0; i2 < doc2.linked.length; ++i2) {
            if (doc2.linked[i2].isParent) {
              return;
            }
          }
          primary = lst(markers);
        });
        return new SharedTextMarker(markers, primary);
      }
      function findSharedMarkers(doc) {
        return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function(m) {
          return m.parent;
        });
      }
      function copySharedMarkers(doc, markers) {
        for (var i2 = 0; i2 < markers.length; i2++) {
          var marker = markers[i2], pos = marker.find();
          var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
          if (cmp(mFrom, mTo)) {
            var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
            marker.markers.push(subMark);
            subMark.parent = marker;
          }
        }
      }
      function detachSharedMarkers(markers) {
        var loop = function(i3) {
          var marker = markers[i3], linked = [marker.primary.doc];
          linkedDocs(marker.primary.doc, function(d) {
            return linked.push(d);
          });
          for (var j = 0; j < marker.markers.length; j++) {
            var subMarker = marker.markers[j];
            if (indexOf(linked, subMarker.doc) == -1) {
              subMarker.parent = null;
              marker.markers.splice(j--, 1);
            }
          }
        };
        for (var i2 = 0; i2 < markers.length; i2++)
          loop(i2);
      }
      var nextDocId = 0;
      var Doc = function(text2, mode, firstLine, lineSep, direction) {
        if (!(this instanceof Doc)) {
          return new Doc(text2, mode, firstLine, lineSep, direction);
        }
        if (firstLine == null) {
          firstLine = 0;
        }
        BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
        this.first = firstLine;
        this.scrollTop = this.scrollLeft = 0;
        this.cantEdit = false;
        this.cleanGeneration = 1;
        this.modeFrontier = this.highlightFrontier = firstLine;
        var start = Pos(firstLine, 0);
        this.sel = simpleSelection(start);
        this.history = new History(null);
        this.id = ++nextDocId;
        this.modeOption = mode;
        this.lineSep = lineSep;
        this.direction = direction == "rtl" ? "rtl" : "ltr";
        this.extend = false;
        if (typeof text2 == "string") {
          text2 = this.splitLines(text2);
        }
        updateDoc(this, {from: start, to: start, text: text2});
        setSelection(this, simpleSelection(start), sel_dontScroll);
      };
      Doc.prototype = createObj(BranchChunk.prototype, {
        constructor: Doc,
        iter: function(from, to, op) {
          if (op) {
            this.iterN(from - this.first, to - from, op);
          } else {
            this.iterN(this.first, this.first + this.size, from);
          }
        },
        insert: function(at, lines) {
          var height4 = 0;
          for (var i2 = 0; i2 < lines.length; ++i2) {
            height4 += lines[i2].height;
          }
          this.insertInner(at - this.first, lines, height4);
        },
        remove: function(at, n) {
          this.removeInner(at - this.first, n);
        },
        getValue: function(lineSep) {
          var lines = getLines(this, this.first, this.first + this.size);
          if (lineSep === false) {
            return lines;
          }
          return lines.join(lineSep || this.lineSeparator());
        },
        setValue: docMethodOp(function(code) {
          var top2 = Pos(this.first, 0), last = this.first + this.size - 1;
          makeChange(this, {
            from: top2,
            to: Pos(last, getLine(this, last).text.length),
            text: this.splitLines(code),
            origin: "setValue",
            full: true
          }, true);
          if (this.cm) {
            scrollToCoords(this.cm, 0, 0);
          }
          setSelection(this, simpleSelection(top2), sel_dontScroll);
        }),
        replaceRange: function(code, from, to, origin) {
          from = clipPos(this, from);
          to = to ? clipPos(this, to) : from;
          replaceRange(this, code, from, to, origin);
        },
        getRange: function(from, to, lineSep) {
          var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
          if (lineSep === false) {
            return lines;
          }
          return lines.join(lineSep || this.lineSeparator());
        },
        getLine: function(line) {
          var l = this.getLineHandle(line);
          return l && l.text;
        },
        getLineHandle: function(line) {
          if (isLine(this, line)) {
            return getLine(this, line);
          }
        },
        getLineNumber: function(line) {
          return lineNo(line);
        },
        getLineHandleVisualStart: function(line) {
          if (typeof line == "number") {
            line = getLine(this, line);
          }
          return visualLine(line);
        },
        lineCount: function() {
          return this.size;
        },
        firstLine: function() {
          return this.first;
        },
        lastLine: function() {
          return this.first + this.size - 1;
        },
        clipPos: function(pos) {
          return clipPos(this, pos);
        },
        getCursor: function(start) {
          var range2 = this.sel.primary(), pos;
          if (start == null || start == "head") {
            pos = range2.head;
          } else if (start == "anchor") {
            pos = range2.anchor;
          } else if (start == "end" || start == "to" || start === false) {
            pos = range2.to();
          } else {
            pos = range2.from();
          }
          return pos;
        },
        listSelections: function() {
          return this.sel.ranges;
        },
        somethingSelected: function() {
          return this.sel.somethingSelected();
        },
        setCursor: docMethodOp(function(line, ch, options) {
          setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
        }),
        setSelection: docMethodOp(function(anchor, head, options) {
          setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
        }),
        extendSelection: docMethodOp(function(head, other, options) {
          extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
        }),
        extendSelections: docMethodOp(function(heads, options) {
          extendSelections(this, clipPosArray(this, heads), options);
        }),
        extendSelectionsBy: docMethodOp(function(f, options) {
          var heads = map2(this.sel.ranges, f);
          extendSelections(this, clipPosArray(this, heads), options);
        }),
        setSelections: docMethodOp(function(ranges, primary, options) {
          if (!ranges.length) {
            return;
          }
          var out = [];
          for (var i2 = 0; i2 < ranges.length; i2++) {
            out[i2] = new Range(clipPos(this, ranges[i2].anchor), clipPos(this, ranges[i2].head));
          }
          if (primary == null) {
            primary = Math.min(ranges.length - 1, this.sel.primIndex);
          }
          setSelection(this, normalizeSelection(this.cm, out, primary), options);
        }),
        addSelection: docMethodOp(function(anchor, head, options) {
          var ranges = this.sel.ranges.slice(0);
          ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
          setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
        }),
        getSelection: function(lineSep) {
          var ranges = this.sel.ranges, lines;
          for (var i2 = 0; i2 < ranges.length; i2++) {
            var sel = getBetween(this, ranges[i2].from(), ranges[i2].to());
            lines = lines ? lines.concat(sel) : sel;
          }
          if (lineSep === false) {
            return lines;
          } else {
            return lines.join(lineSep || this.lineSeparator());
          }
        },
        getSelections: function(lineSep) {
          var parts = [], ranges = this.sel.ranges;
          for (var i2 = 0; i2 < ranges.length; i2++) {
            var sel = getBetween(this, ranges[i2].from(), ranges[i2].to());
            if (lineSep !== false) {
              sel = sel.join(lineSep || this.lineSeparator());
            }
            parts[i2] = sel;
          }
          return parts;
        },
        replaceSelection: function(code, collapse, origin) {
          var dup = [];
          for (var i2 = 0; i2 < this.sel.ranges.length; i2++) {
            dup[i2] = code;
          }
          this.replaceSelections(dup, collapse, origin || "+input");
        },
        replaceSelections: docMethodOp(function(code, collapse, origin) {
          var changes = [], sel = this.sel;
          for (var i2 = 0; i2 < sel.ranges.length; i2++) {
            var range2 = sel.ranges[i2];
            changes[i2] = {from: range2.from(), to: range2.to(), text: this.splitLines(code[i2]), origin};
          }
          var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
          for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) {
            makeChange(this, changes[i$12]);
          }
          if (newSel) {
            setSelectionReplaceHistory(this, newSel);
          } else if (this.cm) {
            ensureCursorVisible(this.cm);
          }
        }),
        undo: docMethodOp(function() {
          makeChangeFromHistory(this, "undo");
        }),
        redo: docMethodOp(function() {
          makeChangeFromHistory(this, "redo");
        }),
        undoSelection: docMethodOp(function() {
          makeChangeFromHistory(this, "undo", true);
        }),
        redoSelection: docMethodOp(function() {
          makeChangeFromHistory(this, "redo", true);
        }),
        setExtending: function(val) {
          this.extend = val;
        },
        getExtending: function() {
          return this.extend;
        },
        historySize: function() {
          var hist = this.history, done = 0, undone = 0;
          for (var i2 = 0; i2 < hist.done.length; i2++) {
            if (!hist.done[i2].ranges) {
              ++done;
            }
          }
          for (var i$12 = 0; i$12 < hist.undone.length; i$12++) {
            if (!hist.undone[i$12].ranges) {
              ++undone;
            }
          }
          return {undo: done, redo: undone};
        },
        clearHistory: function() {
          var this$1 = this;
          this.history = new History(this.history.maxGeneration);
          linkedDocs(this, function(doc) {
            return doc.history = this$1.history;
          }, true);
        },
        markClean: function() {
          this.cleanGeneration = this.changeGeneration(true);
        },
        changeGeneration: function(forceSplit) {
          if (forceSplit) {
            this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
          }
          return this.history.generation;
        },
        isClean: function(gen) {
          return this.history.generation == (gen || this.cleanGeneration);
        },
        getHistory: function() {
          return {
            done: copyHistoryArray(this.history.done),
            undone: copyHistoryArray(this.history.undone)
          };
        },
        setHistory: function(histData) {
          var hist = this.history = new History(this.history.maxGeneration);
          hist.done = copyHistoryArray(histData.done.slice(0), null, true);
          hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
        },
        setGutterMarker: docMethodOp(function(line, gutterID, value) {
          return changeLine(this, line, "gutter", function(line2) {
            var markers = line2.gutterMarkers || (line2.gutterMarkers = {});
            markers[gutterID] = value;
            if (!value && isEmpty(markers)) {
              line2.gutterMarkers = null;
            }
            return true;
          });
        }),
        clearGutter: docMethodOp(function(gutterID) {
          var this$1 = this;
          this.iter(function(line) {
            if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
              changeLine(this$1, line, "gutter", function() {
                line.gutterMarkers[gutterID] = null;
                if (isEmpty(line.gutterMarkers)) {
                  line.gutterMarkers = null;
                }
                return true;
              });
            }
          });
        }),
        lineInfo: function(line) {
          var n;
          if (typeof line == "number") {
            if (!isLine(this, line)) {
              return null;
            }
            n = line;
            line = getLine(this, line);
            if (!line) {
              return null;
            }
          } else {
            n = lineNo(line);
            if (n == null) {
              return null;
            }
          }
          return {
            line: n,
            handle: line,
            text: line.text,
            gutterMarkers: line.gutterMarkers,
            textClass: line.textClass,
            bgClass: line.bgClass,
            wrapClass: line.wrapClass,
            widgets: line.widgets
          };
        },
        addLineClass: docMethodOp(function(handle, where, cls) {
          return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
            var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass";
            if (!line[prop2]) {
              line[prop2] = cls;
            } else if (classTest(cls).test(line[prop2])) {
              return false;
            } else {
              line[prop2] += " " + cls;
            }
            return true;
          });
        }),
        removeLineClass: docMethodOp(function(handle, where, cls) {
          return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
            var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass";
            var cur = line[prop2];
            if (!cur) {
              return false;
            } else if (cls == null) {
              line[prop2] = null;
            } else {
              var found = cur.match(classTest(cls));
              if (!found) {
                return false;
              }
              var end = found.index + found[0].length;
              line[prop2] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
            }
            return true;
          });
        }),
        addLineWidget: docMethodOp(function(handle, node, options) {
          return addLineWidget(this, handle, node, options);
        }),
        removeLineWidget: function(widget) {
          widget.clear();
        },
        markText: function(from, to, options) {
          return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
        },
        setBookmark: function(pos, options) {
          var realOpts = {
            replacedWith: options && (options.nodeType == null ? options.widget : options),
            insertLeft: options && options.insertLeft,
            clearWhenEmpty: false,
            shared: options && options.shared,
            handleMouseEvents: options && options.handleMouseEvents
          };
          pos = clipPos(this, pos);
          return markText(this, pos, pos, realOpts, "bookmark");
        },
        findMarksAt: function(pos) {
          pos = clipPos(this, pos);
          var markers = [], spans = getLine(this, pos.line).markedSpans;
          if (spans) {
            for (var i2 = 0; i2 < spans.length; ++i2) {
              var span = spans[i2];
              if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) {
                markers.push(span.marker.parent || span.marker);
              }
            }
          }
          return markers;
        },
        findMarks: function(from, to, filter2) {
          from = clipPos(this, from);
          to = clipPos(this, to);
          var found = [], lineNo2 = from.line;
          this.iter(from.line, to.line + 1, function(line) {
            var spans = line.markedSpans;
            if (spans) {
              for (var i2 = 0; i2 < spans.length; i2++) {
                var span = spans[i2];
                if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter2 || filter2(span.marker))) {
                  found.push(span.marker.parent || span.marker);
                }
              }
            }
            ++lineNo2;
          });
          return found;
        },
        getAllMarks: function() {
          var markers = [];
          this.iter(function(line) {
            var sps = line.markedSpans;
            if (sps) {
              for (var i2 = 0; i2 < sps.length; ++i2) {
                if (sps[i2].from != null) {
                  markers.push(sps[i2].marker);
                }
              }
            }
          });
          return markers;
        },
        posFromIndex: function(off2) {
          var ch, lineNo2 = this.first, sepSize = this.lineSeparator().length;
          this.iter(function(line) {
            var sz = line.text.length + sepSize;
            if (sz > off2) {
              ch = off2;
              return true;
            }
            off2 -= sz;
            ++lineNo2;
          });
          return clipPos(this, Pos(lineNo2, ch));
        },
        indexFromPos: function(coords) {
          coords = clipPos(this, coords);
          var index = coords.ch;
          if (coords.line < this.first || coords.ch < 0) {
            return 0;
          }
          var sepSize = this.lineSeparator().length;
          this.iter(this.first, coords.line, function(line) {
            index += line.text.length + sepSize;
          });
          return index;
        },
        copy: function(copyHistory) {
          var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction);
          doc.scrollTop = this.scrollTop;
          doc.scrollLeft = this.scrollLeft;
          doc.sel = this.sel;
          doc.extend = false;
          if (copyHistory) {
            doc.history.undoDepth = this.history.undoDepth;
            doc.setHistory(this.getHistory());
          }
          return doc;
        },
        linkedDoc: function(options) {
          if (!options) {
            options = {};
          }
          var from = this.first, to = this.first + this.size;
          if (options.from != null && options.from > from) {
            from = options.from;
          }
          if (options.to != null && options.to < to) {
            to = options.to;
          }
          var copy2 = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
          if (options.sharedHist) {
            copy2.history = this.history;
          }
          (this.linked || (this.linked = [])).push({doc: copy2, sharedHist: options.sharedHist});
          copy2.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
          copySharedMarkers(copy2, findSharedMarkers(this));
          return copy2;
        },
        unlinkDoc: function(other) {
          if (other instanceof CodeMirror10) {
            other = other.doc;
          }
          if (this.linked) {
            for (var i2 = 0; i2 < this.linked.length; ++i2) {
              var link = this.linked[i2];
              if (link.doc != other) {
                continue;
              }
              this.linked.splice(i2, 1);
              other.unlinkDoc(this);
              detachSharedMarkers(findSharedMarkers(this));
              break;
            }
          }
          if (other.history == this.history) {
            var splitIds = [other.id];
            linkedDocs(other, function(doc) {
              return splitIds.push(doc.id);
            }, true);
            other.history = new History(null);
            other.history.done = copyHistoryArray(this.history.done, splitIds);
            other.history.undone = copyHistoryArray(this.history.undone, splitIds);
          }
        },
        iterLinkedDocs: function(f) {
          linkedDocs(this, f);
        },
        getMode: function() {
          return this.mode;
        },
        getEditor: function() {
          return this.cm;
        },
        splitLines: function(str) {
          if (this.lineSep) {
            return str.split(this.lineSep);
          }
          return splitLinesAuto(str);
        },
        lineSeparator: function() {
          return this.lineSep || "\n";
        },
        setDirection: docMethodOp(function(dir) {
          if (dir != "rtl") {
            dir = "ltr";
          }
          if (dir == this.direction) {
            return;
          }
          this.direction = dir;
          this.iter(function(line) {
            return line.order = null;
          });
          if (this.cm) {
            directionChanged(this.cm);
          }
        })
      });
      Doc.prototype.eachLine = Doc.prototype.iter;
      var lastDrop = 0;
      function onDrop(e) {
        var cm = this;
        clearDragCursor(cm);
        if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
          return;
        }
        e_preventDefault(e);
        if (ie) {
          lastDrop = +new Date();
        }
        var pos = posFromMouse(cm, e, true), files2 = e.dataTransfer.files;
        if (!pos || cm.isReadOnly()) {
          return;
        }
        if (files2 && files2.length && window.FileReader && window.File) {
          var n = files2.length, text2 = Array(n), read = 0;
          var markAsReadAndPasteIfAllFilesAreRead = function() {
            if (++read == n) {
              operation(cm, function() {
                pos = clipPos(cm.doc, pos);
                var change = {
                  from: pos,
                  to: pos,
                  text: cm.doc.splitLines(text2.filter(function(t) {
                    return t != null;
                  }).join(cm.doc.lineSeparator())),
                  origin: "paste"
                };
                makeChange(cm.doc, change);
                setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
              })();
            }
          };
          var readTextFromFile = function(file, i3) {
            if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
              markAsReadAndPasteIfAllFilesAreRead();
              return;
            }
            var reader = new FileReader();
            reader.onerror = function() {
              return markAsReadAndPasteIfAllFilesAreRead();
            };
            reader.onload = function() {
              var content = reader.result;
              if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
                markAsReadAndPasteIfAllFilesAreRead();
                return;
              }
              text2[i3] = content;
              markAsReadAndPasteIfAllFilesAreRead();
            };
            reader.readAsText(file);
          };
          for (var i2 = 0; i2 < files2.length; i2++) {
            readTextFromFile(files2[i2], i2);
          }
        } else {
          if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
            cm.state.draggingText(e);
            setTimeout(function() {
              return cm.display.input.focus();
            }, 20);
            return;
          }
          try {
            var text$1 = e.dataTransfer.getData("Text");
            if (text$1) {
              var selected;
              if (cm.state.draggingText && !cm.state.draggingText.copy) {
                selected = cm.listSelections();
              }
              setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
              if (selected) {
                for (var i$12 = 0; i$12 < selected.length; ++i$12) {
                  replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag");
                }
              }
              cm.replaceSelection(text$1, "around", "paste");
              cm.display.input.focus();
            }
          } catch (e$1) {
          }
        }
      }
      function onDragStart(cm, e) {
        if (ie && (!cm.state.draggingText || +new Date() - lastDrop < 100)) {
          e_stop(e);
          return;
        }
        if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
          return;
        }
        e.dataTransfer.setData("Text", cm.getSelection());
        e.dataTransfer.effectAllowed = "copyMove";
        if (e.dataTransfer.setDragImage && !safari) {
          var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
          img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
          if (presto) {
            img.width = img.height = 1;
            cm.display.wrapper.appendChild(img);
            img._top = img.offsetTop;
          }
          e.dataTransfer.setDragImage(img, 0, 0);
          if (presto) {
            img.parentNode.removeChild(img);
          }
        }
      }
      function onDragOver(cm, e) {
        var pos = posFromMouse(cm, e);
        if (!pos) {
          return;
        }
        var frag = document.createDocumentFragment();
        drawSelectionCursor(cm, pos, frag);
        if (!cm.display.dragCursor) {
          cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
          cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
        }
        removeChildrenAndAdd(cm.display.dragCursor, frag);
      }
      function clearDragCursor(cm) {
        if (cm.display.dragCursor) {
          cm.display.lineSpace.removeChild(cm.display.dragCursor);
          cm.display.dragCursor = null;
        }
      }
      function forEachCodeMirror(f) {
        if (!document.getElementsByClassName) {
          return;
        }
        var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
        for (var i2 = 0; i2 < byClass.length; i2++) {
          var cm = byClass[i2].CodeMirror;
          if (cm) {
            editors.push(cm);
          }
        }
        if (editors.length) {
          editors[0].operation(function() {
            for (var i3 = 0; i3 < editors.length; i3++) {
              f(editors[i3]);
            }
          });
        }
      }
      var globalsRegistered = false;
      function ensureGlobalHandlers() {
        if (globalsRegistered) {
          return;
        }
        registerGlobalHandlers();
        globalsRegistered = true;
      }
      function registerGlobalHandlers() {
        var resizeTimer;
        on(window, "resize", function() {
          if (resizeTimer == null) {
            resizeTimer = setTimeout(function() {
              resizeTimer = null;
              forEachCodeMirror(onResize);
            }, 100);
          }
        });
        on(window, "blur", function() {
          return forEachCodeMirror(onBlur);
        });
      }
      function onResize(cm) {
        var d = cm.display;
        d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
        d.scrollbarsClipped = false;
        cm.setSize();
      }
      var keyNames = {
        3: "Pause",
        8: "Backspace",
        9: "Tab",
        13: "Enter",
        16: "Shift",
        17: "Ctrl",
        18: "Alt",
        19: "Pause",
        20: "CapsLock",
        27: "Esc",
        32: "Space",
        33: "PageUp",
        34: "PageDown",
        35: "End",
        36: "Home",
        37: "Left",
        38: "Up",
        39: "Right",
        40: "Down",
        44: "PrintScrn",
        45: "Insert",
        46: "Delete",
        59: ";",
        61: "=",
        91: "Mod",
        92: "Mod",
        93: "Mod",
        106: "*",
        107: "=",
        109: "-",
        110: ".",
        111: "/",
        145: "ScrollLock",
        173: "-",
        186: ";",
        187: "=",
        188: ",",
        189: "-",
        190: ".",
        191: "/",
        192: "`",
        219: "[",
        220: "\\",
        221: "]",
        222: "'",
        224: "Mod",
        63232: "Up",
        63233: "Down",
        63234: "Left",
        63235: "Right",
        63272: "Delete",
        63273: "Home",
        63275: "End",
        63276: "PageUp",
        63277: "PageDown",
        63302: "Insert"
      };
      for (var i = 0; i < 10; i++) {
        keyNames[i + 48] = keyNames[i + 96] = String(i);
      }
      for (var i$1 = 65; i$1 <= 90; i$1++) {
        keyNames[i$1] = String.fromCharCode(i$1);
      }
      for (var i$2 = 1; i$2 <= 12; i$2++) {
        keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2;
      }
      var keyMap = {};
      keyMap.basic = {
        Left: "goCharLeft",
        Right: "goCharRight",
        Up: "goLineUp",
        Down: "goLineDown",
        End: "goLineEnd",
        Home: "goLineStartSmart",
        PageUp: "goPageUp",
        PageDown: "goPageDown",
        Delete: "delCharAfter",
        Backspace: "delCharBefore",
        "Shift-Backspace": "delCharBefore",
        Tab: "defaultTab",
        "Shift-Tab": "indentAuto",
        Enter: "newlineAndIndent",
        Insert: "toggleOverwrite",
        Esc: "singleSelection"
      };
      keyMap.pcDefault = {
        "Ctrl-A": "selectAll",
        "Ctrl-D": "deleteLine",
        "Ctrl-Z": "undo",
        "Shift-Ctrl-Z": "redo",
        "Ctrl-Y": "redo",
        "Ctrl-Home": "goDocStart",
        "Ctrl-End": "goDocEnd",
        "Ctrl-Up": "goLineUp",
        "Ctrl-Down": "goLineDown",
        "Ctrl-Left": "goGroupLeft",
        "Ctrl-Right": "goGroupRight",
        "Alt-Left": "goLineStart",
        "Alt-Right": "goLineEnd",
        "Ctrl-Backspace": "delGroupBefore",
        "Ctrl-Delete": "delGroupAfter",
        "Ctrl-S": "save",
        "Ctrl-F": "find",
        "Ctrl-G": "findNext",
        "Shift-Ctrl-G": "findPrev",
        "Shift-Ctrl-F": "replace",
        "Shift-Ctrl-R": "replaceAll",
        "Ctrl-[": "indentLess",
        "Ctrl-]": "indentMore",
        "Ctrl-U": "undoSelection",
        "Shift-Ctrl-U": "redoSelection",
        "Alt-U": "redoSelection",
        fallthrough: "basic"
      };
      keyMap.emacsy = {
        "Ctrl-F": "goCharRight",
        "Ctrl-B": "goCharLeft",
        "Ctrl-P": "goLineUp",
        "Ctrl-N": "goLineDown",
        "Alt-F": "goWordRight",
        "Alt-B": "goWordLeft",
        "Ctrl-A": "goLineStart",
        "Ctrl-E": "goLineEnd",
        "Ctrl-V": "goPageDown",
        "Shift-Ctrl-V": "goPageUp",
        "Ctrl-D": "delCharAfter",
        "Ctrl-H": "delCharBefore",
        "Alt-D": "delWordAfter",
        "Alt-Backspace": "delWordBefore",
        "Ctrl-K": "killLine",
        "Ctrl-T": "transposeChars",
        "Ctrl-O": "openLine"
      };
      keyMap.macDefault = {
        "Cmd-A": "selectAll",
        "Cmd-D": "deleteLine",
        "Cmd-Z": "undo",
        "Shift-Cmd-Z": "redo",
        "Cmd-Y": "redo",
        "Cmd-Home": "goDocStart",
        "Cmd-Up": "goDocStart",
        "Cmd-End": "goDocEnd",
        "Cmd-Down": "goDocEnd",
        "Alt-Left": "goGroupLeft",
        "Alt-Right": "goGroupRight",
        "Cmd-Left": "goLineLeft",
        "Cmd-Right": "goLineRight",
        "Alt-Backspace": "delGroupBefore",
        "Ctrl-Alt-Backspace": "delGroupAfter",
        "Alt-Delete": "delGroupAfter",
        "Cmd-S": "save",
        "Cmd-F": "find",
        "Cmd-G": "findNext",
        "Shift-Cmd-G": "findPrev",
        "Cmd-Alt-F": "replace",
        "Shift-Cmd-Alt-F": "replaceAll",
        "Cmd-[": "indentLess",
        "Cmd-]": "indentMore",
        "Cmd-Backspace": "delWrappedLineLeft",
        "Cmd-Delete": "delWrappedLineRight",
        "Cmd-U": "undoSelection",
        "Shift-Cmd-U": "redoSelection",
        "Ctrl-Up": "goDocStart",
        "Ctrl-Down": "goDocEnd",
        fallthrough: ["basic", "emacsy"]
      };
      keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
      function normalizeKeyName(name) {
        var parts = name.split(/-(?!$)/);
        name = parts[parts.length - 1];
        var alt, ctrl, shift, cmd;
        for (var i2 = 0; i2 < parts.length - 1; i2++) {
          var mod = parts[i2];
          if (/^(cmd|meta|m)$/i.test(mod)) {
            cmd = true;
          } else if (/^a(lt)?$/i.test(mod)) {
            alt = true;
          } else if (/^(c|ctrl|control)$/i.test(mod)) {
            ctrl = true;
          } else if (/^s(hift)?$/i.test(mod)) {
            shift = true;
          } else {
            throw new Error("Unrecognized modifier name: " + mod);
          }
        }
        if (alt) {
          name = "Alt-" + name;
        }
        if (ctrl) {
          name = "Ctrl-" + name;
        }
        if (cmd) {
          name = "Cmd-" + name;
        }
        if (shift) {
          name = "Shift-" + name;
        }
        return name;
      }
      function normalizeKeyMap(keymap) {
        var copy2 = {};
        for (var keyname in keymap) {
          if (keymap.hasOwnProperty(keyname)) {
            var value = keymap[keyname];
            if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) {
              continue;
            }
            if (value == "...") {
              delete keymap[keyname];
              continue;
            }
            var keys = map2(keyname.split(" "), normalizeKeyName);
            for (var i2 = 0; i2 < keys.length; i2++) {
              var val = void 0, name = void 0;
              if (i2 == keys.length - 1) {
                name = keys.join(" ");
                val = value;
              } else {
                name = keys.slice(0, i2 + 1).join(" ");
                val = "...";
              }
              var prev = copy2[name];
              if (!prev) {
                copy2[name] = val;
              } else if (prev != val) {
                throw new Error("Inconsistent bindings for " + name);
              }
            }
            delete keymap[keyname];
          }
        }
        for (var prop2 in copy2) {
          keymap[prop2] = copy2[prop2];
        }
        return keymap;
      }
      function lookupKey(key, map3, handle, context) {
        map3 = getKeyMap(map3);
        var found = map3.call ? map3.call(key, context) : map3[key];
        if (found === false) {
          return "nothing";
        }
        if (found === "...") {
          return "multi";
        }
        if (found != null && handle(found)) {
          return "handled";
        }
        if (map3.fallthrough) {
          if (Object.prototype.toString.call(map3.fallthrough) != "[object Array]") {
            return lookupKey(key, map3.fallthrough, handle, context);
          }
          for (var i2 = 0; i2 < map3.fallthrough.length; i2++) {
            var result = lookupKey(key, map3.fallthrough[i2], handle, context);
            if (result) {
              return result;
            }
          }
        }
      }
      function isModifierKey(value) {
        var name = typeof value == "string" ? value : keyNames[value.keyCode];
        return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
      }
      function addModifierNames(name, event, noShift) {
        var base = name;
        if (event.altKey && base != "Alt") {
          name = "Alt-" + name;
        }
        if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") {
          name = "Ctrl-" + name;
        }
        if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") {
          name = "Cmd-" + name;
        }
        if (!noShift && event.shiftKey && base != "Shift") {
          name = "Shift-" + name;
        }
        return name;
      }
      function keyName(event, noShift) {
        if (presto && event.keyCode == 34 && event["char"]) {
          return false;
        }
        var name = keyNames[event.keyCode];
        if (name == null || event.altGraphKey) {
          return false;
        }
        if (event.keyCode == 3 && event.code) {
          name = event.code;
        }
        return addModifierNames(name, event, noShift);
      }
      function getKeyMap(val) {
        return typeof val == "string" ? keyMap[val] : val;
      }
      function deleteNearSelection(cm, compute) {
        var ranges = cm.doc.sel.ranges, kill = [];
        for (var i2 = 0; i2 < ranges.length; i2++) {
          var toKill = compute(ranges[i2]);
          while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
            var replaced = kill.pop();
            if (cmp(replaced.from, toKill.from) < 0) {
              toKill.from = replaced.from;
              break;
            }
          }
          kill.push(toKill);
        }
        runInOp(cm, function() {
          for (var i3 = kill.length - 1; i3 >= 0; i3--) {
            replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete");
          }
          ensureCursorVisible(cm);
        });
      }
      function moveCharLogically(line, ch, dir) {
        var target = skipExtendingChars(line.text, ch + dir, dir);
        return target < 0 || target > line.text.length ? null : target;
      }
      function moveLogically(line, start, dir) {
        var ch = moveCharLogically(line, start.ch, dir);
        return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before");
      }
      function endOfLine(visually, cm, lineObj, lineNo2, dir) {
        if (visually) {
          if (cm.doc.direction == "rtl") {
            dir = -dir;
          }
          var order = getOrder(lineObj, cm.doc.direction);
          if (order) {
            var part = dir < 0 ? lst(order) : order[0];
            var moveInStorageOrder = dir < 0 == (part.level == 1);
            var sticky = moveInStorageOrder ? "after" : "before";
            var ch;
            if (part.level > 0 || cm.doc.direction == "rtl") {
              var prep = prepareMeasureForLine(cm, lineObj);
              ch = dir < 0 ? lineObj.text.length - 1 : 0;
              var targetTop = measureCharPrepared(cm, prep, ch).top;
              ch = findFirst(function(ch2) {
                return measureCharPrepared(cm, prep, ch2).top == targetTop;
              }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch);
              if (sticky == "before") {
                ch = moveCharLogically(lineObj, ch, 1);
              }
            } else {
              ch = dir < 0 ? part.to : part.from;
            }
            return new Pos(lineNo2, ch, sticky);
          }
        }
        return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after");
      }
      function moveVisually(cm, line, start, dir) {
        var bidi = getOrder(line, cm.doc.direction);
        if (!bidi) {
          return moveLogically(line, start, dir);
        }
        if (start.ch >= line.text.length) {
          start.ch = line.text.length;
          start.sticky = "before";
        } else if (start.ch <= 0) {
          start.ch = 0;
          start.sticky = "after";
        }
        var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
        if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
          return moveLogically(line, start, dir);
        }
        var mv = function(pos, dir2) {
          return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2);
        };
        var prep;
        var getWrappedLineExtent = function(ch2) {
          if (!cm.options.lineWrapping) {
            return {begin: 0, end: line.text.length};
          }
          prep = prep || prepareMeasureForLine(cm, line);
          return wrappedLineExtentChar(cm, line, prep, ch2);
        };
        var wrappedLineExtent2 = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
        if (cm.doc.direction == "rtl" || part.level == 1) {
          var moveInStorageOrder = part.level == 1 == dir < 0;
          var ch = mv(start, moveInStorageOrder ? 1 : -1);
          if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) {
            var sticky = moveInStorageOrder ? "before" : "after";
            return new Pos(start.line, ch, sticky);
          }
        }
        var searchInVisualLine = function(partPos2, dir2, wrappedLineExtent3) {
          var getRes = function(ch3, moveInStorageOrder3) {
            return moveInStorageOrder3 ? new Pos(start.line, mv(ch3, 1), "before") : new Pos(start.line, ch3, "after");
          };
          for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) {
            var part2 = bidi[partPos2];
            var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1);
            var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1);
            if (part2.from <= ch2 && ch2 < part2.to) {
              return getRes(ch2, moveInStorageOrder2);
            }
            ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1);
            if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) {
              return getRes(ch2, moveInStorageOrder2);
            }
          }
        };
        var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2);
        if (res) {
          return res;
        }
        var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1);
        if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
          res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
          if (res) {
            return res;
          }
        }
        return null;
      }
      var commands2 = {
        selectAll,
        singleSelection: function(cm) {
          return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
        },
        killLine: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            if (range2.empty()) {
              var len = getLine(cm.doc, range2.head.line).text.length;
              if (range2.head.ch == len && range2.head.line < cm.lastLine()) {
                return {from: range2.head, to: Pos(range2.head.line + 1, 0)};
              } else {
                return {from: range2.head, to: Pos(range2.head.line, len)};
              }
            } else {
              return {from: range2.from(), to: range2.to()};
            }
          });
        },
        deleteLine: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            return {
              from: Pos(range2.from().line, 0),
              to: clipPos(cm.doc, Pos(range2.to().line + 1, 0))
            };
          });
        },
        delLineLeft: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            return {
              from: Pos(range2.from().line, 0),
              to: range2.from()
            };
          });
        },
        delWrappedLineLeft: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            var top2 = cm.charCoords(range2.head, "div").top + 5;
            var leftPos = cm.coordsChar({left: 0, top: top2}, "div");
            return {from: leftPos, to: range2.from()};
          });
        },
        delWrappedLineRight: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            var top2 = cm.charCoords(range2.head, "div").top + 5;
            var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top2}, "div");
            return {from: range2.from(), to: rightPos};
          });
        },
        undo: function(cm) {
          return cm.undo();
        },
        redo: function(cm) {
          return cm.redo();
        },
        undoSelection: function(cm) {
          return cm.undoSelection();
        },
        redoSelection: function(cm) {
          return cm.redoSelection();
        },
        goDocStart: function(cm) {
          return cm.extendSelection(Pos(cm.firstLine(), 0));
        },
        goDocEnd: function(cm) {
          return cm.extendSelection(Pos(cm.lastLine()));
        },
        goLineStart: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            return lineStart(cm, range2.head.line);
          }, {origin: "+move", bias: 1});
        },
        goLineStartSmart: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            return lineStartSmart(cm, range2.head);
          }, {origin: "+move", bias: 1});
        },
        goLineEnd: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            return lineEnd(cm, range2.head.line);
          }, {origin: "+move", bias: -1});
        },
        goLineRight: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            var top2 = cm.cursorCoords(range2.head, "div").top + 5;
            return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top2}, "div");
          }, sel_move);
        },
        goLineLeft: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            var top2 = cm.cursorCoords(range2.head, "div").top + 5;
            return cm.coordsChar({left: 0, top: top2}, "div");
          }, sel_move);
        },
        goLineLeftSmart: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            var top2 = cm.cursorCoords(range2.head, "div").top + 5;
            var pos = cm.coordsChar({left: 0, top: top2}, "div");
            if (pos.ch < cm.getLine(pos.line).search(/\S/)) {
              return lineStartSmart(cm, range2.head);
            }
            return pos;
          }, sel_move);
        },
        goLineUp: function(cm) {
          return cm.moveV(-1, "line");
        },
        goLineDown: function(cm) {
          return cm.moveV(1, "line");
        },
        goPageUp: function(cm) {
          return cm.moveV(-1, "page");
        },
        goPageDown: function(cm) {
          return cm.moveV(1, "page");
        },
        goCharLeft: function(cm) {
          return cm.moveH(-1, "char");
        },
        goCharRight: function(cm) {
          return cm.moveH(1, "char");
        },
        goColumnLeft: function(cm) {
          return cm.moveH(-1, "column");
        },
        goColumnRight: function(cm) {
          return cm.moveH(1, "column");
        },
        goWordLeft: function(cm) {
          return cm.moveH(-1, "word");
        },
        goGroupRight: function(cm) {
          return cm.moveH(1, "group");
        },
        goGroupLeft: function(cm) {
          return cm.moveH(-1, "group");
        },
        goWordRight: function(cm) {
          return cm.moveH(1, "word");
        },
        delCharBefore: function(cm) {
          return cm.deleteH(-1, "codepoint");
        },
        delCharAfter: function(cm) {
          return cm.deleteH(1, "char");
        },
        delWordBefore: function(cm) {
          return cm.deleteH(-1, "word");
        },
        delWordAfter: function(cm) {
          return cm.deleteH(1, "word");
        },
        delGroupBefore: function(cm) {
          return cm.deleteH(-1, "group");
        },
        delGroupAfter: function(cm) {
          return cm.deleteH(1, "group");
        },
        indentAuto: function(cm) {
          return cm.indentSelection("smart");
        },
        indentMore: function(cm) {
          return cm.indentSelection("add");
        },
        indentLess: function(cm) {
          return cm.indentSelection("subtract");
        },
        insertTab: function(cm) {
          return cm.replaceSelection("	");
        },
        insertSoftTab: function(cm) {
          var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
          for (var i2 = 0; i2 < ranges.length; i2++) {
            var pos = ranges[i2].from();
            var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
            spaces.push(spaceStr(tabSize - col % tabSize));
          }
          cm.replaceSelections(spaces);
        },
        defaultTab: function(cm) {
          if (cm.somethingSelected()) {
            cm.indentSelection("add");
          } else {
            cm.execCommand("insertTab");
          }
        },
        transposeChars: function(cm) {
          return runInOp(cm, function() {
            var ranges = cm.listSelections(), newSel = [];
            for (var i2 = 0; i2 < ranges.length; i2++) {
              if (!ranges[i2].empty()) {
                continue;
              }
              var cur = ranges[i2].head, line = getLine(cm.doc, cur.line).text;
              if (line) {
                if (cur.ch == line.length) {
                  cur = new Pos(cur.line, cur.ch - 1);
                }
                if (cur.ch > 0) {
                  cur = new Pos(cur.line, cur.ch + 1);
                  cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose");
                } else if (cur.line > cm.doc.first) {
                  var prev = getLine(cm.doc, cur.line - 1).text;
                  if (prev) {
                    cur = new Pos(cur.line, 1);
                    cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
                  }
                }
              }
              newSel.push(new Range(cur, cur));
            }
            cm.setSelections(newSel);
          });
        },
        newlineAndIndent: function(cm) {
          return runInOp(cm, function() {
            var sels = cm.listSelections();
            for (var i2 = sels.length - 1; i2 >= 0; i2--) {
              cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input");
            }
            sels = cm.listSelections();
            for (var i$12 = 0; i$12 < sels.length; i$12++) {
              cm.indentLine(sels[i$12].from().line, null, true);
            }
            ensureCursorVisible(cm);
          });
        },
        openLine: function(cm) {
          return cm.replaceSelection("\n", "start");
        },
        toggleOverwrite: function(cm) {
          return cm.toggleOverwrite();
        }
      };
      function lineStart(cm, lineN) {
        var line = getLine(cm.doc, lineN);
        var visual = visualLine(line);
        if (visual != line) {
          lineN = lineNo(visual);
        }
        return endOfLine(true, cm, visual, lineN, 1);
      }
      function lineEnd(cm, lineN) {
        var line = getLine(cm.doc, lineN);
        var visual = visualLineEnd(line);
        if (visual != line) {
          lineN = lineNo(visual);
        }
        return endOfLine(true, cm, line, lineN, -1);
      }
      function lineStartSmart(cm, pos) {
        var start = lineStart(cm, pos.line);
        var line = getLine(cm.doc, start.line);
        var order = getOrder(line, cm.doc.direction);
        if (!order || order[0].level == 0) {
          var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
          var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
          return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky);
        }
        return start;
      }
      function doHandleBinding(cm, bound, dropShift) {
        if (typeof bound == "string") {
          bound = commands2[bound];
          if (!bound) {
            return false;
          }
        }
        cm.display.input.ensurePolled();
        var prevShift = cm.display.shift, done = false;
        try {
          if (cm.isReadOnly()) {
            cm.state.suppressEdits = true;
          }
          if (dropShift) {
            cm.display.shift = false;
          }
          done = bound(cm) != Pass;
        } finally {
          cm.display.shift = prevShift;
          cm.state.suppressEdits = false;
        }
        return done;
      }
      function lookupKeyForEditor(cm, name, handle) {
        for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) {
          var result = lookupKey(name, cm.state.keyMaps[i2], handle, cm);
          if (result) {
            return result;
          }
        }
        return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm);
      }
      var stopSeq = new Delayed();
      function dispatchKey(cm, name, e, handle) {
        var seq = cm.state.keySeq;
        if (seq) {
          if (isModifierKey(name)) {
            return "handled";
          }
          if (/\'$/.test(name)) {
            cm.state.keySeq = null;
          } else {
            stopSeq.set(50, function() {
              if (cm.state.keySeq == seq) {
                cm.state.keySeq = null;
                cm.display.input.reset();
              }
            });
          }
          if (dispatchKeyInner(cm, seq + " " + name, e, handle)) {
            return true;
          }
        }
        return dispatchKeyInner(cm, name, e, handle);
      }
      function dispatchKeyInner(cm, name, e, handle) {
        var result = lookupKeyForEditor(cm, name, handle);
        if (result == "multi") {
          cm.state.keySeq = name;
        }
        if (result == "handled") {
          signalLater(cm, "keyHandled", cm, name, e);
        }
        if (result == "handled" || result == "multi") {
          e_preventDefault(e);
          restartBlink(cm);
        }
        return !!result;
      }
      function handleKeyBinding(cm, e) {
        var name = keyName(e, true);
        if (!name) {
          return false;
        }
        if (e.shiftKey && !cm.state.keySeq) {
          return dispatchKey(cm, "Shift-" + name, e, function(b) {
            return doHandleBinding(cm, b, true);
          }) || dispatchKey(cm, name, e, function(b) {
            if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) {
              return doHandleBinding(cm, b);
            }
          });
        } else {
          return dispatchKey(cm, name, e, function(b) {
            return doHandleBinding(cm, b);
          });
        }
      }
      function handleCharBinding(cm, e, ch) {
        return dispatchKey(cm, "'" + ch + "'", e, function(b) {
          return doHandleBinding(cm, b, true);
        });
      }
      var lastStoppedKey = null;
      function onKeyDown(e) {
        var cm = this;
        if (e.target && e.target != cm.display.input.getField()) {
          return;
        }
        cm.curOp.focus = activeElt();
        if (signalDOMEvent(cm, e)) {
          return;
        }
        if (ie && ie_version < 11 && e.keyCode == 27) {
          e.returnValue = false;
        }
        var code = e.keyCode;
        cm.display.shift = code == 16 || e.shiftKey;
        var handled = handleKeyBinding(cm, e);
        if (presto) {
          lastStoppedKey = handled ? code : null;
          if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {
            cm.replaceSelection("", null, "cut");
          }
        }
        if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) {
          document.execCommand("cut");
        }
        if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {
          showCrossHair(cm);
        }
      }
      function showCrossHair(cm) {
        var lineDiv = cm.display.lineDiv;
        addClass(lineDiv, "CodeMirror-crosshair");
        function up(e) {
          if (e.keyCode == 18 || !e.altKey) {
            rmClass(lineDiv, "CodeMirror-crosshair");
            off(document, "keyup", up);
            off(document, "mouseover", up);
          }
        }
        on(document, "keyup", up);
        on(document, "mouseover", up);
      }
      function onKeyUp(e) {
        if (e.keyCode == 16) {
          this.doc.sel.shift = false;
        }
        signalDOMEvent(this, e);
      }
      function onKeyPress(e) {
        var cm = this;
        if (e.target && e.target != cm.display.input.getField()) {
          return;
        }
        if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) {
          return;
        }
        var keyCode = e.keyCode, charCode = e.charCode;
        if (presto && keyCode == lastStoppedKey) {
          lastStoppedKey = null;
          e_preventDefault(e);
          return;
        }
        if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) {
          return;
        }
        var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
        if (ch == "\b") {
          return;
        }
        if (handleCharBinding(cm, e, ch)) {
          return;
        }
        cm.display.input.onKeyPress(e);
      }
      var DOUBLECLICK_DELAY = 400;
      var PastClick = function(time, pos, button) {
        this.time = time;
        this.pos = pos;
        this.button = button;
      };
      PastClick.prototype.compare = function(time, pos, button) {
        return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button;
      };
      var lastClick, lastDoubleClick;
      function clickRepeat(pos, button) {
        var now = +new Date();
        if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
          lastClick = lastDoubleClick = null;
          return "triple";
        } else if (lastClick && lastClick.compare(now, pos, button)) {
          lastDoubleClick = new PastClick(now, pos, button);
          lastClick = null;
          return "double";
        } else {
          lastClick = new PastClick(now, pos, button);
          lastDoubleClick = null;
          return "single";
        }
      }
      function onMouseDown(e) {
        var cm = this, display = cm.display;
        if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) {
          return;
        }
        display.input.ensurePolled();
        display.shift = e.shiftKey;
        if (eventInWidget(display, e)) {
          if (!webkit) {
            display.scroller.draggable = false;
            setTimeout(function() {
              return display.scroller.draggable = true;
            }, 100);
          }
          return;
        }
        if (clickInGutter(cm, e)) {
          return;
        }
        var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
        window.focus();
        if (button == 1 && cm.state.selectingText) {
          cm.state.selectingText(e);
        }
        if (pos && handleMappedButton(cm, button, pos, repeat, e)) {
          return;
        }
        if (button == 1) {
          if (pos) {
            leftButtonDown(cm, pos, repeat, e);
          } else if (e_target(e) == display.scroller) {
            e_preventDefault(e);
          }
        } else if (button == 2) {
          if (pos) {
            extendSelection(cm.doc, pos);
          }
          setTimeout(function() {
            return display.input.focus();
          }, 20);
        } else if (button == 3) {
          if (captureRightClick) {
            cm.display.input.onContextMenu(e);
          } else {
            delayBlurEvent(cm);
          }
        }
      }
      function handleMappedButton(cm, button, pos, repeat, event) {
        var name = "Click";
        if (repeat == "double") {
          name = "Double" + name;
        } else if (repeat == "triple") {
          name = "Triple" + name;
        }
        name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
        return dispatchKey(cm, addModifierNames(name, event), event, function(bound) {
          if (typeof bound == "string") {
            bound = commands2[bound];
          }
          if (!bound) {
            return false;
          }
          var done = false;
          try {
            if (cm.isReadOnly()) {
              cm.state.suppressEdits = true;
            }
            done = bound(cm, pos) != Pass;
          } finally {
            cm.state.suppressEdits = false;
          }
          return done;
        });
      }
      function configureMouse(cm, repeat, event) {
        var option = cm.getOption("configureMouse");
        var value = option ? option(cm, repeat, event) : {};
        if (value.unit == null) {
          var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
          value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
        }
        if (value.extend == null || cm.doc.extend) {
          value.extend = cm.doc.extend || event.shiftKey;
        }
        if (value.addNew == null) {
          value.addNew = mac ? event.metaKey : event.ctrlKey;
        }
        if (value.moveOnDrag == null) {
          value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey);
        }
        return value;
      }
      function leftButtonDown(cm, pos, repeat, event) {
        if (ie) {
          setTimeout(bind2(ensureFocus, cm), 0);
        } else {
          cm.curOp.focus = activeElt();
        }
        var behavior = configureMouse(cm, repeat, event);
        var sel = cm.doc.sel, contained;
        if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) {
          leftButtonStartDrag(cm, event, pos, behavior);
        } else {
          leftButtonSelect(cm, event, pos, behavior);
        }
      }
      function leftButtonStartDrag(cm, event, pos, behavior) {
        var display = cm.display, moved = false;
        var dragEnd = operation(cm, function(e) {
          if (webkit) {
            display.scroller.draggable = false;
          }
          cm.state.draggingText = false;
          if (cm.state.delayingBlurEvent) {
            if (cm.hasFocus()) {
              cm.state.delayingBlurEvent = false;
            } else {
              delayBlurEvent(cm);
            }
          }
          off(display.wrapper.ownerDocument, "mouseup", dragEnd);
          off(display.wrapper.ownerDocument, "mousemove", mouseMove);
          off(display.scroller, "dragstart", dragStart);
          off(display.scroller, "drop", dragEnd);
          if (!moved) {
            e_preventDefault(e);
            if (!behavior.addNew) {
              extendSelection(cm.doc, pos, null, null, behavior.extend);
            }
            if (webkit && !safari || ie && ie_version == 9) {
              setTimeout(function() {
                display.wrapper.ownerDocument.body.focus({preventScroll: true});
                display.input.focus();
              }, 20);
            } else {
              display.input.focus();
            }
          }
        });
        var mouseMove = function(e22) {
          moved = moved || Math.abs(event.clientX - e22.clientX) + Math.abs(event.clientY - e22.clientY) >= 10;
        };
        var dragStart = function() {
          return moved = true;
        };
        if (webkit) {
          display.scroller.draggable = true;
        }
        cm.state.draggingText = dragEnd;
        dragEnd.copy = !behavior.moveOnDrag;
        on(display.wrapper.ownerDocument, "mouseup", dragEnd);
        on(display.wrapper.ownerDocument, "mousemove", mouseMove);
        on(display.scroller, "dragstart", dragStart);
        on(display.scroller, "drop", dragEnd);
        cm.state.delayingBlurEvent = true;
        setTimeout(function() {
          return display.input.focus();
        }, 20);
        if (display.scroller.dragDrop) {
          display.scroller.dragDrop();
        }
      }
      function rangeForUnit(cm, pos, unit2) {
        if (unit2 == "char") {
          return new Range(pos, pos);
        }
        if (unit2 == "word") {
          return cm.findWordAt(pos);
        }
        if (unit2 == "line") {
          return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
        }
        var result = unit2(cm, pos);
        return new Range(result.from, result.to);
      }
      function leftButtonSelect(cm, event, start, behavior) {
        if (ie) {
          delayBlurEvent(cm);
        }
        var display = cm.display, doc = cm.doc;
        e_preventDefault(event);
        var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
        if (behavior.addNew && !behavior.extend) {
          ourIndex = doc.sel.contains(start);
          if (ourIndex > -1) {
            ourRange = ranges[ourIndex];
          } else {
            ourRange = new Range(start, start);
          }
        } else {
          ourRange = doc.sel.primary();
          ourIndex = doc.sel.primIndex;
        }
        if (behavior.unit == "rectangle") {
          if (!behavior.addNew) {
            ourRange = new Range(start, start);
          }
          start = posFromMouse(cm, event, true, true);
          ourIndex = -1;
        } else {
          var range2 = rangeForUnit(cm, start, behavior.unit);
          if (behavior.extend) {
            ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend);
          } else {
            ourRange = range2;
          }
        }
        if (!behavior.addNew) {
          ourIndex = 0;
          setSelection(doc, new Selection2([ourRange], 0), sel_mouse);
          startSel = doc.sel;
        } else if (ourIndex == -1) {
          ourIndex = ranges.length;
          setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"});
        } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
          setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {scroll: false, origin: "*mouse"});
          startSel = doc.sel;
        } else {
          replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
        }
        var lastPos = start;
        function extendTo(pos) {
          if (cmp(lastPos, pos) == 0) {
            return;
          }
          lastPos = pos;
          if (behavior.unit == "rectangle") {
            var ranges2 = [], tabSize = cm.options.tabSize;
            var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
            var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
            var left2 = Math.min(startCol, posCol), right2 = Math.max(startCol, posCol);
            for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) {
              var text2 = getLine(doc, line).text, leftPos = findColumn(text2, left2, tabSize);
              if (left2 == right2) {
                ranges2.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
              } else if (text2.length > leftPos) {
                ranges2.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text2, right2, tabSize))));
              }
            }
            if (!ranges2.length) {
              ranges2.push(new Range(start, start));
            }
            setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex), {origin: "*mouse", scroll: false});
            cm.scrollIntoView(pos);
          } else {
            var oldRange = ourRange;
            var range3 = rangeForUnit(cm, pos, behavior.unit);
            var anchor = oldRange.anchor, head;
            if (cmp(range3.anchor, anchor) > 0) {
              head = range3.head;
              anchor = minPos(oldRange.from(), range3.anchor);
            } else {
              head = range3.anchor;
              anchor = maxPos(oldRange.to(), range3.head);
            }
            var ranges$1 = startSel.ranges.slice(0);
            ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
            setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
          }
        }
        var editorSize = display.wrapper.getBoundingClientRect();
        var counter = 0;
        function extend2(e) {
          var curCount = ++counter;
          var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
          if (!cur) {
            return;
          }
          if (cmp(cur, lastPos) != 0) {
            cm.curOp.focus = activeElt();
            extendTo(cur);
            var visible = visibleLines(display, doc);
            if (cur.line >= visible.to || cur.line < visible.from) {
              setTimeout(operation(cm, function() {
                if (counter == curCount) {
                  extend2(e);
                }
              }), 150);
            }
          } else {
            var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
            if (outside) {
              setTimeout(operation(cm, function() {
                if (counter != curCount) {
                  return;
                }
                display.scroller.scrollTop += outside;
                extend2(e);
              }), 50);
            }
          }
        }
        function done(e) {
          cm.state.selectingText = false;
          counter = Infinity;
          if (e) {
            e_preventDefault(e);
            display.input.focus();
          }
          off(display.wrapper.ownerDocument, "mousemove", move);
          off(display.wrapper.ownerDocument, "mouseup", up);
          doc.history.lastSelOrigin = null;
        }
        var move = operation(cm, function(e) {
          if (e.buttons === 0 || !e_button(e)) {
            done(e);
          } else {
            extend2(e);
          }
        });
        var up = operation(cm, done);
        cm.state.selectingText = up;
        on(display.wrapper.ownerDocument, "mousemove", move);
        on(display.wrapper.ownerDocument, "mouseup", up);
      }
      function bidiSimplify(cm, range2) {
        var anchor = range2.anchor;
        var head = range2.head;
        var anchorLine = getLine(cm.doc, anchor.line);
        if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) {
          return range2;
        }
        var order = getOrder(anchorLine);
        if (!order) {
          return range2;
        }
        var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
        if (part.from != anchor.ch && part.to != anchor.ch) {
          return range2;
        }
        var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1);
        if (boundary == 0 || boundary == order.length) {
          return range2;
        }
        var leftSide;
        if (head.line != anchor.line) {
          leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
        } else {
          var headIndex = getBidiPartAt(order, head.ch, head.sticky);
          var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
          if (headIndex == boundary - 1 || headIndex == boundary) {
            leftSide = dir < 0;
          } else {
            leftSide = dir > 0;
          }
        }
        var usePart = order[boundary + (leftSide ? -1 : 0)];
        var from = leftSide == (usePart.level == 1);
        var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
        return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range(new Pos(anchor.line, ch, sticky), head);
      }
      function gutterEvent(cm, e, type, prevent) {
        var mX, mY;
        if (e.touches) {
          mX = e.touches[0].clientX;
          mY = e.touches[0].clientY;
        } else {
          try {
            mX = e.clientX;
            mY = e.clientY;
          } catch (e$1) {
            return false;
          }
        }
        if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) {
          return false;
        }
        if (prevent) {
          e_preventDefault(e);
        }
        var display = cm.display;
        var lineBox = display.lineDiv.getBoundingClientRect();
        if (mY > lineBox.bottom || !hasHandler(cm, type)) {
          return e_defaultPrevented(e);
        }
        mY -= lineBox.top - display.viewOffset;
        for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) {
          var g = display.gutters.childNodes[i2];
          if (g && g.getBoundingClientRect().right >= mX) {
            var line = lineAtHeight(cm.doc, mY);
            var gutter = cm.display.gutterSpecs[i2];
            signal(cm, type, cm, line, gutter.className, e);
            return e_defaultPrevented(e);
          }
        }
      }
      function clickInGutter(cm, e) {
        return gutterEvent(cm, e, "gutterClick", true);
      }
      function onContextMenu(cm, e) {
        if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) {
          return;
        }
        if (signalDOMEvent(cm, e, "contextmenu")) {
          return;
        }
        if (!captureRightClick) {
          cm.display.input.onContextMenu(e);
        }
      }
      function contextMenuInGutter(cm, e) {
        if (!hasHandler(cm, "gutterContextMenu")) {
          return false;
        }
        return gutterEvent(cm, e, "gutterContextMenu", false);
      }
      function themeChanged(cm) {
        cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
        clearCaches(cm);
      }
      var Init = {toString: function() {
        return "CodeMirror.Init";
      }};
      var defaults = {};
      var optionHandlers = {};
      function defineOptions(CodeMirror11) {
        var optionHandlers2 = CodeMirror11.optionHandlers;
        function option(name, deflt, handle, notOnInit) {
          CodeMirror11.defaults[name] = deflt;
          if (handle) {
            optionHandlers2[name] = notOnInit ? function(cm, val, old) {
              if (old != Init) {
                handle(cm, val, old);
              }
            } : handle;
          }
        }
        CodeMirror11.defineOption = option;
        CodeMirror11.Init = Init;
        option("value", "", function(cm, val) {
          return cm.setValue(val);
        }, true);
        option("mode", null, function(cm, val) {
          cm.doc.modeOption = val;
          loadMode(cm);
        }, true);
        option("indentUnit", 2, loadMode, true);
        option("indentWithTabs", false);
        option("smartIndent", true);
        option("tabSize", 4, function(cm) {
          resetModeState(cm);
          clearCaches(cm);
          regChange(cm);
        }, true);
        option("lineSeparator", null, function(cm, val) {
          cm.doc.lineSep = val;
          if (!val) {
            return;
          }
          var newBreaks = [], lineNo2 = cm.doc.first;
          cm.doc.iter(function(line) {
            for (var pos = 0; ; ) {
              var found = line.text.indexOf(val, pos);
              if (found == -1) {
                break;
              }
              pos = found + val.length;
              newBreaks.push(Pos(lineNo2, found));
            }
            lineNo2++;
          });
          for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) {
            replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length));
          }
        });
        option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function(cm, val, old) {
          cm.state.specialChars = new RegExp(val.source + (val.test("	") ? "" : "|	"), "g");
          if (old != Init) {
            cm.refresh();
          }
        });
        option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {
          return cm.refresh();
        }, true);
        option("electricChars", true);
        option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
          throw new Error("inputStyle can not (yet) be changed in a running editor");
        }, true);
        option("spellcheck", false, function(cm, val) {
          return cm.getInputField().spellcheck = val;
        }, true);
        option("autocorrect", false, function(cm, val) {
          return cm.getInputField().autocorrect = val;
        }, true);
        option("autocapitalize", false, function(cm, val) {
          return cm.getInputField().autocapitalize = val;
        }, true);
        option("rtlMoveVisually", !windows);
        option("wholeLineUpdateBefore", true);
        option("theme", "default", function(cm) {
          themeChanged(cm);
          updateGutters(cm);
        }, true);
        option("keyMap", "default", function(cm, val, old) {
          var next = getKeyMap(val);
          var prev = old != Init && getKeyMap(old);
          if (prev && prev.detach) {
            prev.detach(cm, next);
          }
          if (next.attach) {
            next.attach(cm, prev || null);
          }
        });
        option("extraKeys", null);
        option("configureMouse", null);
        option("lineWrapping", false, wrappingChanged, true);
        option("gutters", [], function(cm, val) {
          cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
          updateGutters(cm);
        }, true);
        option("fixedGutter", true, function(cm, val) {
          cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
          cm.refresh();
        }, true);
        option("coverGutterNextToScrollbar", false, function(cm) {
          return updateScrollbars(cm);
        }, true);
        option("scrollbarStyle", "native", function(cm) {
          initScrollbars(cm);
          updateScrollbars(cm);
          cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
          cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
        }, true);
        option("lineNumbers", false, function(cm, val) {
          cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
          updateGutters(cm);
        }, true);
        option("firstLineNumber", 1, updateGutters, true);
        option("lineNumberFormatter", function(integer) {
          return integer;
        }, updateGutters, true);
        option("showCursorWhenSelecting", false, updateSelection, true);
        option("resetSelectionOnContextMenu", true);
        option("lineWiseCopyCut", true);
        option("pasteLinesPerSelection", true);
        option("selectionsMayTouch", false);
        option("readOnly", false, function(cm, val) {
          if (val == "nocursor") {
            onBlur(cm);
            cm.display.input.blur();
          }
          cm.display.input.readOnlyChanged(val);
        });
        option("screenReaderLabel", null, function(cm, val) {
          val = val === "" ? null : val;
          cm.display.input.screenReaderLabelChanged(val);
        });
        option("disableInput", false, function(cm, val) {
          if (!val) {
            cm.display.input.reset();
          }
        }, true);
        option("dragDrop", true, dragDropChanged);
        option("allowDropFileTypes", null);
        option("cursorBlinkRate", 530);
        option("cursorScrollMargin", 0);
        option("cursorHeight", 1, updateSelection, true);
        option("singleCursorHeightPerLine", true, updateSelection, true);
        option("workTime", 100);
        option("workDelay", 100);
        option("flattenSpans", true, resetModeState, true);
        option("addModeClass", false, resetModeState, true);
        option("pollInterval", 100);
        option("undoDepth", 200, function(cm, val) {
          return cm.doc.history.undoDepth = val;
        });
        option("historyEventDelay", 1250);
        option("viewportMargin", 10, function(cm) {
          return cm.refresh();
        }, true);
        option("maxHighlightLength", 1e4, resetModeState, true);
        option("moveInputWithCursor", true, function(cm, val) {
          if (!val) {
            cm.display.input.resetPosition();
          }
        });
        option("tabindex", null, function(cm, val) {
          return cm.display.input.getField().tabIndex = val || "";
        });
        option("autofocus", null);
        option("direction", "ltr", function(cm, val) {
          return cm.doc.setDirection(val);
        }, true);
        option("phrases", null);
      }
      function dragDropChanged(cm, value, old) {
        var wasOn = old && old != Init;
        if (!value != !wasOn) {
          var funcs = cm.display.dragFunctions;
          var toggle = value ? on : off;
          toggle(cm.display.scroller, "dragstart", funcs.start);
          toggle(cm.display.scroller, "dragenter", funcs.enter);
          toggle(cm.display.scroller, "dragover", funcs.over);
          toggle(cm.display.scroller, "dragleave", funcs.leave);
          toggle(cm.display.scroller, "drop", funcs.drop);
        }
      }
      function wrappingChanged(cm) {
        if (cm.options.lineWrapping) {
          addClass(cm.display.wrapper, "CodeMirror-wrap");
          cm.display.sizer.style.minWidth = "";
          cm.display.sizerWidth = null;
        } else {
          rmClass(cm.display.wrapper, "CodeMirror-wrap");
          findMaxLine(cm);
        }
        estimateLineHeights(cm);
        regChange(cm);
        clearCaches(cm);
        setTimeout(function() {
          return updateScrollbars(cm);
        }, 100);
      }
      function CodeMirror10(place, options) {
        var this$1 = this;
        if (!(this instanceof CodeMirror10)) {
          return new CodeMirror10(place, options);
        }
        this.options = options = options ? copyObj(options) : {};
        copyObj(defaults, options, false);
        var doc = options.value;
        if (typeof doc == "string") {
          doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction);
        } else if (options.mode) {
          doc.modeOption = options.mode;
        }
        this.doc = doc;
        var input = new CodeMirror10.inputStyles[options.inputStyle](this);
        var display = this.display = new Display(place, doc, input, options);
        display.wrapper.CodeMirror = this;
        themeChanged(this);
        if (options.lineWrapping) {
          this.display.wrapper.className += " CodeMirror-wrap";
        }
        initScrollbars(this);
        this.state = {
          keyMaps: [],
          overlays: [],
          modeGen: 0,
          overwrite: false,
          delayingBlurEvent: false,
          focused: false,
          suppressEdits: false,
          pasteIncoming: -1,
          cutIncoming: -1,
          selectingText: false,
          draggingText: false,
          highlight: new Delayed(),
          keySeq: null,
          specialChars: null
        };
        if (options.autofocus && !mobile) {
          display.input.focus();
        }
        if (ie && ie_version < 11) {
          setTimeout(function() {
            return this$1.display.input.reset(true);
          }, 20);
        }
        registerEventHandlers(this);
        ensureGlobalHandlers();
        startOperation(this);
        this.curOp.forceUpdate = true;
        attachDoc(this, doc);
        if (options.autofocus && !mobile || this.hasFocus()) {
          setTimeout(function() {
            if (this$1.hasFocus() && !this$1.state.focused) {
              onFocus(this$1);
            }
          }, 20);
        } else {
          onBlur(this);
        }
        for (var opt in optionHandlers) {
          if (optionHandlers.hasOwnProperty(opt)) {
            optionHandlers[opt](this, options[opt], Init);
          }
        }
        maybeUpdateLineNumberWidth(this);
        if (options.finishInit) {
          options.finishInit(this);
        }
        for (var i2 = 0; i2 < initHooks.length; ++i2) {
          initHooks[i2](this);
        }
        endOperation(this);
        if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {
          display.lineDiv.style.textRendering = "auto";
        }
      }
      CodeMirror10.defaults = defaults;
      CodeMirror10.optionHandlers = optionHandlers;
      function registerEventHandlers(cm) {
        var d = cm.display;
        on(d.scroller, "mousedown", operation(cm, onMouseDown));
        if (ie && ie_version < 11) {
          on(d.scroller, "dblclick", operation(cm, function(e) {
            if (signalDOMEvent(cm, e)) {
              return;
            }
            var pos = posFromMouse(cm, e);
            if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) {
              return;
            }
            e_preventDefault(e);
            var word = cm.findWordAt(pos);
            extendSelection(cm.doc, word.anchor, word.head);
          }));
        } else {
          on(d.scroller, "dblclick", function(e) {
            return signalDOMEvent(cm, e) || e_preventDefault(e);
          });
        }
        on(d.scroller, "contextmenu", function(e) {
          return onContextMenu(cm, e);
        });
        on(d.input.getField(), "contextmenu", function(e) {
          if (!d.scroller.contains(e.target)) {
            onContextMenu(cm, e);
          }
        });
        var touchFinished, prevTouch = {end: 0};
        function finishTouch() {
          if (d.activeTouch) {
            touchFinished = setTimeout(function() {
              return d.activeTouch = null;
            }, 1e3);
            prevTouch = d.activeTouch;
            prevTouch.end = +new Date();
          }
        }
        function isMouseLikeTouchEvent(e) {
          if (e.touches.length != 1) {
            return false;
          }
          var touch = e.touches[0];
          return touch.radiusX <= 1 && touch.radiusY <= 1;
        }
        function farAway(touch, other) {
          if (other.left == null) {
            return true;
          }
          var dx = other.left - touch.left, dy = other.top - touch.top;
          return dx * dx + dy * dy > 20 * 20;
        }
        on(d.scroller, "touchstart", function(e) {
          if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
            d.input.ensurePolled();
            clearTimeout(touchFinished);
            var now = +new Date();
            d.activeTouch = {
              start: now,
              moved: false,
              prev: now - prevTouch.end <= 300 ? prevTouch : null
            };
            if (e.touches.length == 1) {
              d.activeTouch.left = e.touches[0].pageX;
              d.activeTouch.top = e.touches[0].pageY;
            }
          }
        });
        on(d.scroller, "touchmove", function() {
          if (d.activeTouch) {
            d.activeTouch.moved = true;
          }
        });
        on(d.scroller, "touchend", function(e) {
          var touch = d.activeTouch;
          if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date() - touch.start < 300) {
            var pos = cm.coordsChar(d.activeTouch, "page"), range2;
            if (!touch.prev || farAway(touch, touch.prev)) {
              range2 = new Range(pos, pos);
            } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) {
              range2 = cm.findWordAt(pos);
            } else {
              range2 = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
            }
            cm.setSelection(range2.anchor, range2.head);
            cm.focus();
            e_preventDefault(e);
          }
          finishTouch();
        });
        on(d.scroller, "touchcancel", finishTouch);
        on(d.scroller, "scroll", function() {
          if (d.scroller.clientHeight) {
            updateScrollTop(cm, d.scroller.scrollTop);
            setScrollLeft(cm, d.scroller.scrollLeft, true);
            signal(cm, "scroll", cm);
          }
        });
        on(d.scroller, "mousewheel", function(e) {
          return onScrollWheel(cm, e);
        });
        on(d.scroller, "DOMMouseScroll", function(e) {
          return onScrollWheel(cm, e);
        });
        on(d.wrapper, "scroll", function() {
          return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0;
        });
        d.dragFunctions = {
          enter: function(e) {
            if (!signalDOMEvent(cm, e)) {
              e_stop(e);
            }
          },
          over: function(e) {
            if (!signalDOMEvent(cm, e)) {
              onDragOver(cm, e);
              e_stop(e);
            }
          },
          start: function(e) {
            return onDragStart(cm, e);
          },
          drop: operation(cm, onDrop),
          leave: function(e) {
            if (!signalDOMEvent(cm, e)) {
              clearDragCursor(cm);
            }
          }
        };
        var inp = d.input.getField();
        on(inp, "keyup", function(e) {
          return onKeyUp.call(cm, e);
        });
        on(inp, "keydown", operation(cm, onKeyDown));
        on(inp, "keypress", operation(cm, onKeyPress));
        on(inp, "focus", function(e) {
          return onFocus(cm, e);
        });
        on(inp, "blur", function(e) {
          return onBlur(cm, e);
        });
      }
      var initHooks = [];
      CodeMirror10.defineInitHook = function(f) {
        return initHooks.push(f);
      };
      function indentLine(cm, n, how, aggressive) {
        var doc = cm.doc, state;
        if (how == null) {
          how = "add";
        }
        if (how == "smart") {
          if (!doc.mode.indent) {
            how = "prev";
          } else {
            state = getContextBefore(cm, n).state;
          }
        }
        var tabSize = cm.options.tabSize;
        var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
        if (line.stateAfter) {
          line.stateAfter = null;
        }
        var curSpaceString = line.text.match(/^\s*/)[0], indentation;
        if (!aggressive && !/\S/.test(line.text)) {
          indentation = 0;
          how = "not";
        } else if (how == "smart") {
          indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
          if (indentation == Pass || indentation > 150) {
            if (!aggressive) {
              return;
            }
            how = "prev";
          }
        }
        if (how == "prev") {
          if (n > doc.first) {
            indentation = countColumn(getLine(doc, n - 1).text, null, tabSize);
          } else {
            indentation = 0;
          }
        } else if (how == "add") {
          indentation = curSpace + cm.options.indentUnit;
        } else if (how == "subtract") {
          indentation = curSpace - cm.options.indentUnit;
        } else if (typeof how == "number") {
          indentation = curSpace + how;
        }
        indentation = Math.max(0, indentation);
        var indentString = "", pos = 0;
        if (cm.options.indentWithTabs) {
          for (var i2 = Math.floor(indentation / tabSize); i2; --i2) {
            pos += tabSize;
            indentString += "	";
          }
        }
        if (pos < indentation) {
          indentString += spaceStr(indentation - pos);
        }
        if (indentString != curSpaceString) {
          replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
          line.stateAfter = null;
          return true;
        } else {
          for (var i$12 = 0; i$12 < doc.sel.ranges.length; i$12++) {
            var range2 = doc.sel.ranges[i$12];
            if (range2.head.line == n && range2.head.ch < curSpaceString.length) {
              var pos$1 = Pos(n, curSpaceString.length);
              replaceOneSelection(doc, i$12, new Range(pos$1, pos$1));
              break;
            }
          }
        }
      }
      var lastCopied = null;
      function setLastCopied(newLastCopied) {
        lastCopied = newLastCopied;
      }
      function applyTextInput(cm, inserted, deleted, sel, origin) {
        var doc = cm.doc;
        cm.display.shift = false;
        if (!sel) {
          sel = doc.sel;
        }
        var recent = +new Date() - 200;
        var paste = origin == "paste" || cm.state.pasteIncoming > recent;
        var textLines = splitLinesAuto(inserted), multiPaste = null;
        if (paste && sel.ranges.length > 1) {
          if (lastCopied && lastCopied.text.join("\n") == inserted) {
            if (sel.ranges.length % lastCopied.text.length == 0) {
              multiPaste = [];
              for (var i2 = 0; i2 < lastCopied.text.length; i2++) {
                multiPaste.push(doc.splitLines(lastCopied.text[i2]));
              }
            }
          } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
            multiPaste = map2(textLines, function(l) {
              return [l];
            });
          }
        }
        var updateInput = cm.curOp.updateInput;
        for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) {
          var range2 = sel.ranges[i$12];
          var from = range2.from(), to = range2.to();
          if (range2.empty()) {
            if (deleted && deleted > 0) {
              from = Pos(from.line, from.ch - deleted);
            } else if (cm.state.overwrite && !paste) {
              to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
            } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) {
              from = to = Pos(from.line, 0);
            }
          }
          var changeEvent = {
            from,
            to,
            text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines,
            origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")
          };
          makeChange(cm.doc, changeEvent);
          signalLater(cm, "inputRead", cm, changeEvent);
        }
        if (inserted && !paste) {
          triggerElectric(cm, inserted);
        }
        ensureCursorVisible(cm);
        if (cm.curOp.updateInput < 2) {
          cm.curOp.updateInput = updateInput;
        }
        cm.curOp.typing = true;
        cm.state.pasteIncoming = cm.state.cutIncoming = -1;
      }
      function handlePaste(e, cm) {
        var pasted = e.clipboardData && e.clipboardData.getData("Text");
        if (pasted) {
          e.preventDefault();
          if (!cm.isReadOnly() && !cm.options.disableInput) {
            runInOp(cm, function() {
              return applyTextInput(cm, pasted, 0, null, "paste");
            });
          }
          return true;
        }
      }
      function triggerElectric(cm, inserted) {
        if (!cm.options.electricChars || !cm.options.smartIndent) {
          return;
        }
        var sel = cm.doc.sel;
        for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) {
          var range2 = sel.ranges[i2];
          if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) {
            continue;
          }
          var mode = cm.getModeAt(range2.head);
          var indented = false;
          if (mode.electricChars) {
            for (var j = 0; j < mode.electricChars.length; j++) {
              if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
                indented = indentLine(cm, range2.head.line, "smart");
                break;
              }
            }
          } else if (mode.electricInput) {
            if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) {
              indented = indentLine(cm, range2.head.line, "smart");
            }
          }
          if (indented) {
            signalLater(cm, "electricInput", cm, range2.head.line);
          }
        }
      }
      function copyableRanges(cm) {
        var text2 = [], ranges = [];
        for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) {
          var line = cm.doc.sel.ranges[i2].head.line;
          var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
          ranges.push(lineRange);
          text2.push(cm.getRange(lineRange.anchor, lineRange.head));
        }
        return {text: text2, ranges};
      }
      function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
        field.setAttribute("autocorrect", autocorrect ? "" : "off");
        field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
        field.setAttribute("spellcheck", !!spellcheck);
      }
      function hiddenTextarea() {
        var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
        var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
        if (webkit) {
          te.style.width = "1000px";
        } else {
          te.setAttribute("wrap", "off");
        }
        if (ios) {
          te.style.border = "1px solid black";
        }
        disableBrowserMagic(te);
        return div;
      }
      function addEditorMethods(CodeMirror11) {
        var optionHandlers2 = CodeMirror11.optionHandlers;
        var helpers = CodeMirror11.helpers = {};
        CodeMirror11.prototype = {
          constructor: CodeMirror11,
          focus: function() {
            window.focus();
            this.display.input.focus();
          },
          setOption: function(option, value) {
            var options = this.options, old = options[option];
            if (options[option] == value && option != "mode") {
              return;
            }
            options[option] = value;
            if (optionHandlers2.hasOwnProperty(option)) {
              operation(this, optionHandlers2[option])(this, value, old);
            }
            signal(this, "optionChange", this, option);
          },
          getOption: function(option) {
            return this.options[option];
          },
          getDoc: function() {
            return this.doc;
          },
          addKeyMap: function(map3, bottom2) {
            this.state.keyMaps[bottom2 ? "push" : "unshift"](getKeyMap(map3));
          },
          removeKeyMap: function(map3) {
            var maps = this.state.keyMaps;
            for (var i2 = 0; i2 < maps.length; ++i2) {
              if (maps[i2] == map3 || maps[i2].name == map3) {
                maps.splice(i2, 1);
                return true;
              }
            }
          },
          addOverlay: methodOp(function(spec, options) {
            var mode = spec.token ? spec : CodeMirror11.getMode(this.options, spec);
            if (mode.startState) {
              throw new Error("Overlays may not be stateful.");
            }
            insertSorted(this.state.overlays, {
              mode,
              modeSpec: spec,
              opaque: options && options.opaque,
              priority: options && options.priority || 0
            }, function(overlay) {
              return overlay.priority;
            });
            this.state.modeGen++;
            regChange(this);
          }),
          removeOverlay: methodOp(function(spec) {
            var overlays = this.state.overlays;
            for (var i2 = 0; i2 < overlays.length; ++i2) {
              var cur = overlays[i2].modeSpec;
              if (cur == spec || typeof spec == "string" && cur.name == spec) {
                overlays.splice(i2, 1);
                this.state.modeGen++;
                regChange(this);
                return;
              }
            }
          }),
          indentLine: methodOp(function(n, dir, aggressive) {
            if (typeof dir != "string" && typeof dir != "number") {
              if (dir == null) {
                dir = this.options.smartIndent ? "smart" : "prev";
              } else {
                dir = dir ? "add" : "subtract";
              }
            }
            if (isLine(this.doc, n)) {
              indentLine(this, n, dir, aggressive);
            }
          }),
          indentSelection: methodOp(function(how) {
            var ranges = this.doc.sel.ranges, end = -1;
            for (var i2 = 0; i2 < ranges.length; i2++) {
              var range2 = ranges[i2];
              if (!range2.empty()) {
                var from = range2.from(), to = range2.to();
                var start = Math.max(end, from.line);
                end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
                for (var j = start; j < end; ++j) {
                  indentLine(this, j, how);
                }
                var newRanges = this.doc.sel.ranges;
                if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) {
                  replaceOneSelection(this.doc, i2, new Range(from, newRanges[i2].to()), sel_dontScroll);
                }
              } else if (range2.head.line > end) {
                indentLine(this, range2.head.line, how, true);
                end = range2.head.line;
                if (i2 == this.doc.sel.primIndex) {
                  ensureCursorVisible(this);
                }
              }
            }
          }),
          getTokenAt: function(pos, precise) {
            return takeToken(this, pos, precise);
          },
          getLineTokens: function(line, precise) {
            return takeToken(this, Pos(line), precise, true);
          },
          getTokenTypeAt: function(pos) {
            pos = clipPos(this.doc, pos);
            var styles = getLineStyles(this, getLine(this.doc, pos.line));
            var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
            var type;
            if (ch == 0) {
              type = styles[2];
            } else {
              for (; ; ) {
                var mid = before + after >> 1;
                if ((mid ? styles[mid * 2 - 1] : 0) >= ch) {
                  after = mid;
                } else if (styles[mid * 2 + 1] < ch) {
                  before = mid + 1;
                } else {
                  type = styles[mid * 2 + 2];
                  break;
                }
              }
            }
            var cut = type ? type.indexOf("overlay ") : -1;
            return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
          },
          getModeAt: function(pos) {
            var mode = this.doc.mode;
            if (!mode.innerMode) {
              return mode;
            }
            return CodeMirror11.innerMode(mode, this.getTokenAt(pos).state).mode;
          },
          getHelper: function(pos, type) {
            return this.getHelpers(pos, type)[0];
          },
          getHelpers: function(pos, type) {
            var found = [];
            if (!helpers.hasOwnProperty(type)) {
              return found;
            }
            var help = helpers[type], mode = this.getModeAt(pos);
            if (typeof mode[type] == "string") {
              if (help[mode[type]]) {
                found.push(help[mode[type]]);
              }
            } else if (mode[type]) {
              for (var i2 = 0; i2 < mode[type].length; i2++) {
                var val = help[mode[type][i2]];
                if (val) {
                  found.push(val);
                }
              }
            } else if (mode.helperType && help[mode.helperType]) {
              found.push(help[mode.helperType]);
            } else if (help[mode.name]) {
              found.push(help[mode.name]);
            }
            for (var i$12 = 0; i$12 < help._global.length; i$12++) {
              var cur = help._global[i$12];
              if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {
                found.push(cur.val);
              }
            }
            return found;
          },
          getStateAfter: function(line, precise) {
            var doc = this.doc;
            line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line);
            return getContextBefore(this, line + 1, precise).state;
          },
          cursorCoords: function(start, mode) {
            var pos, range2 = this.doc.sel.primary();
            if (start == null) {
              pos = range2.head;
            } else if (typeof start == "object") {
              pos = clipPos(this.doc, start);
            } else {
              pos = start ? range2.from() : range2.to();
            }
            return cursorCoords(this, pos, mode || "page");
          },
          charCoords: function(pos, mode) {
            return charCoords(this, clipPos(this.doc, pos), mode || "page");
          },
          coordsChar: function(coords, mode) {
            coords = fromCoordSystem(this, coords, mode || "page");
            return coordsChar(this, coords.left, coords.top);
          },
          lineAtHeight: function(height4, mode) {
            height4 = fromCoordSystem(this, {top: height4, left: 0}, mode || "page").top;
            return lineAtHeight(this.doc, height4 + this.display.viewOffset);
          },
          heightAtLine: function(line, mode, includeWidgets) {
            var end = false, lineObj;
            if (typeof line == "number") {
              var last = this.doc.first + this.doc.size - 1;
              if (line < this.doc.first) {
                line = this.doc.first;
              } else if (line > last) {
                line = last;
                end = true;
              }
              lineObj = getLine(this.doc, line);
            } else {
              lineObj = line;
            }
            return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0);
          },
          defaultTextHeight: function() {
            return textHeight(this.display);
          },
          defaultCharWidth: function() {
            return charWidth(this.display);
          },
          getViewport: function() {
            return {from: this.display.viewFrom, to: this.display.viewTo};
          },
          addWidget: function(pos, node, scroll, vert, horiz) {
            var display = this.display;
            pos = cursorCoords(this, clipPos(this.doc, pos));
            var top2 = pos.bottom, left2 = pos.left;
            node.style.position = "absolute";
            node.setAttribute("cm-ignore-events", "true");
            this.display.input.setUneditable(node);
            display.sizer.appendChild(node);
            if (vert == "over") {
              top2 = pos.top;
            } else if (vert == "above" || vert == "near") {
              var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
              if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {
                top2 = pos.top - node.offsetHeight;
              } else if (pos.bottom + node.offsetHeight <= vspace) {
                top2 = pos.bottom;
              }
              if (left2 + node.offsetWidth > hspace) {
                left2 = hspace - node.offsetWidth;
              }
            }
            node.style.top = top2 + "px";
            node.style.left = node.style.right = "";
            if (horiz == "right") {
              left2 = display.sizer.clientWidth - node.offsetWidth;
              node.style.right = "0px";
            } else {
              if (horiz == "left") {
                left2 = 0;
              } else if (horiz == "middle") {
                left2 = (display.sizer.clientWidth - node.offsetWidth) / 2;
              }
              node.style.left = left2 + "px";
            }
            if (scroll) {
              scrollIntoView(this, {left: left2, top: top2, right: left2 + node.offsetWidth, bottom: top2 + node.offsetHeight});
            }
          },
          triggerOnKeyDown: methodOp(onKeyDown),
          triggerOnKeyPress: methodOp(onKeyPress),
          triggerOnKeyUp: onKeyUp,
          triggerOnMouseDown: methodOp(onMouseDown),
          execCommand: function(cmd) {
            if (commands2.hasOwnProperty(cmd)) {
              return commands2[cmd].call(null, this);
            }
          },
          triggerElectric: methodOp(function(text2) {
            triggerElectric(this, text2);
          }),
          findPosH: function(from, amount, unit2, visually) {
            var dir = 1;
            if (amount < 0) {
              dir = -1;
              amount = -amount;
            }
            var cur = clipPos(this.doc, from);
            for (var i2 = 0; i2 < amount; ++i2) {
              cur = findPosH(this.doc, cur, dir, unit2, visually);
              if (cur.hitSide) {
                break;
              }
            }
            return cur;
          },
          moveH: methodOp(function(dir, unit2) {
            var this$1 = this;
            this.extendSelectionsBy(function(range2) {
              if (this$1.display.shift || this$1.doc.extend || range2.empty()) {
                return findPosH(this$1.doc, range2.head, dir, unit2, this$1.options.rtlMoveVisually);
              } else {
                return dir < 0 ? range2.from() : range2.to();
              }
            }, sel_move);
          }),
          deleteH: methodOp(function(dir, unit2) {
            var sel = this.doc.sel, doc = this.doc;
            if (sel.somethingSelected()) {
              doc.replaceSelection("", null, "+delete");
            } else {
              deleteNearSelection(this, function(range2) {
                var other = findPosH(doc, range2.head, dir, unit2, false);
                return dir < 0 ? {from: other, to: range2.head} : {from: range2.head, to: other};
              });
            }
          }),
          findPosV: function(from, amount, unit2, goalColumn) {
            var dir = 1, x2 = goalColumn;
            if (amount < 0) {
              dir = -1;
              amount = -amount;
            }
            var cur = clipPos(this.doc, from);
            for (var i2 = 0; i2 < amount; ++i2) {
              var coords = cursorCoords(this, cur, "div");
              if (x2 == null) {
                x2 = coords.left;
              } else {
                coords.left = x2;
              }
              cur = findPosV(this, coords, dir, unit2);
              if (cur.hitSide) {
                break;
              }
            }
            return cur;
          },
          moveV: methodOp(function(dir, unit2) {
            var this$1 = this;
            var doc = this.doc, goals = [];
            var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
            doc.extendSelectionsBy(function(range2) {
              if (collapse) {
                return dir < 0 ? range2.from() : range2.to();
              }
              var headPos = cursorCoords(this$1, range2.head, "div");
              if (range2.goalColumn != null) {
                headPos.left = range2.goalColumn;
              }
              goals.push(headPos.left);
              var pos = findPosV(this$1, headPos, dir, unit2);
              if (unit2 == "page" && range2 == doc.sel.primary()) {
                addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top);
              }
              return pos;
            }, sel_move);
            if (goals.length) {
              for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) {
                doc.sel.ranges[i2].goalColumn = goals[i2];
              }
            }
          }),
          findWordAt: function(pos) {
            var doc = this.doc, line = getLine(doc, pos.line).text;
            var start = pos.ch, end = pos.ch;
            if (line) {
              var helper = this.getHelper(pos, "wordChars");
              if ((pos.sticky == "before" || end == line.length) && start) {
                --start;
              } else {
                ++end;
              }
              var startChar = line.charAt(start);
              var check = isWordChar(startChar, helper) ? function(ch) {
                return isWordChar(ch, helper);
              } : /\s/.test(startChar) ? function(ch) {
                return /\s/.test(ch);
              } : function(ch) {
                return !/\s/.test(ch) && !isWordChar(ch);
              };
              while (start > 0 && check(line.charAt(start - 1))) {
                --start;
              }
              while (end < line.length && check(line.charAt(end))) {
                ++end;
              }
            }
            return new Range(Pos(pos.line, start), Pos(pos.line, end));
          },
          toggleOverwrite: function(value) {
            if (value != null && value == this.state.overwrite) {
              return;
            }
            if (this.state.overwrite = !this.state.overwrite) {
              addClass(this.display.cursorDiv, "CodeMirror-overwrite");
            } else {
              rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
            }
            signal(this, "overwriteToggle", this, this.state.overwrite);
          },
          hasFocus: function() {
            return this.display.input.getField() == activeElt();
          },
          isReadOnly: function() {
            return !!(this.options.readOnly || this.doc.cantEdit);
          },
          scrollTo: methodOp(function(x2, y2) {
            scrollToCoords(this, x2, y2);
          }),
          getScrollInfo: function() {
            var scroller = this.display.scroller;
            return {
              left: scroller.scrollLeft,
              top: scroller.scrollTop,
              height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
              width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
              clientHeight: displayHeight(this),
              clientWidth: displayWidth(this)
            };
          },
          scrollIntoView: methodOp(function(range2, margin) {
            if (range2 == null) {
              range2 = {from: this.doc.sel.primary().head, to: null};
              if (margin == null) {
                margin = this.options.cursorScrollMargin;
              }
            } else if (typeof range2 == "number") {
              range2 = {from: Pos(range2, 0), to: null};
            } else if (range2.from == null) {
              range2 = {from: range2, to: null};
            }
            if (!range2.to) {
              range2.to = range2.from;
            }
            range2.margin = margin || 0;
            if (range2.from.line != null) {
              scrollToRange(this, range2);
            } else {
              scrollToCoordsRange(this, range2.from, range2.to, range2.margin);
            }
          }),
          setSize: methodOp(function(width, height4) {
            var this$1 = this;
            var interpret = function(val) {
              return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
            };
            if (width != null) {
              this.display.wrapper.style.width = interpret(width);
            }
            if (height4 != null) {
              this.display.wrapper.style.height = interpret(height4);
            }
            if (this.options.lineWrapping) {
              clearLineMeasurementCache(this);
            }
            var lineNo2 = this.display.viewFrom;
            this.doc.iter(lineNo2, this.display.viewTo, function(line) {
              if (line.widgets) {
                for (var i2 = 0; i2 < line.widgets.length; i2++) {
                  if (line.widgets[i2].noHScroll) {
                    regLineChange(this$1, lineNo2, "widget");
                    break;
                  }
                }
              }
              ++lineNo2;
            });
            this.curOp.forceUpdate = true;
            signal(this, "refresh", this);
          }),
          operation: function(f) {
            return runInOp(this, f);
          },
          startOperation: function() {
            return startOperation(this);
          },
          endOperation: function() {
            return endOperation(this);
          },
          refresh: methodOp(function() {
            var oldHeight = this.display.cachedTextHeight;
            regChange(this);
            this.curOp.forceUpdate = true;
            clearCaches(this);
            scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
            updateGutterSpace(this.display);
            if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) {
              estimateLineHeights(this);
            }
            signal(this, "refresh", this);
          }),
          swapDoc: methodOp(function(doc) {
            var old = this.doc;
            old.cm = null;
            if (this.state.selectingText) {
              this.state.selectingText();
            }
            attachDoc(this, doc);
            clearCaches(this);
            this.display.input.reset();
            scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
            this.curOp.forceScroll = true;
            signalLater(this, "swapDoc", this, old);
            return old;
          }),
          phrase: function(phraseText) {
            var phrases = this.options.phrases;
            return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText;
          },
          getInputField: function() {
            return this.display.input.getField();
          },
          getWrapperElement: function() {
            return this.display.wrapper;
          },
          getScrollerElement: function() {
            return this.display.scroller;
          },
          getGutterElement: function() {
            return this.display.gutters;
          }
        };
        eventMixin(CodeMirror11);
        CodeMirror11.registerHelper = function(type, name, value) {
          if (!helpers.hasOwnProperty(type)) {
            helpers[type] = CodeMirror11[type] = {_global: []};
          }
          helpers[type][name] = value;
        };
        CodeMirror11.registerGlobalHelper = function(type, name, predicate, value) {
          CodeMirror11.registerHelper(type, name, value);
          helpers[type]._global.push({pred: predicate, val: value});
        };
      }
      function findPosH(doc, pos, dir, unit2, visually) {
        var oldPos = pos;
        var origDir = dir;
        var lineObj = getLine(doc, pos.line);
        var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
        function findNextLine() {
          var l = pos.line + lineDir;
          if (l < doc.first || l >= doc.first + doc.size) {
            return false;
          }
          pos = new Pos(l, pos.ch, pos.sticky);
          return lineObj = getLine(doc, l);
        }
        function moveOnce(boundToLine) {
          var next;
          if (unit2 == "codepoint") {
            var ch = lineObj.text.charCodeAt(pos.ch + (unit2 > 0 ? 0 : -1));
            if (isNaN(ch)) {
              next = null;
            } else {
              var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343;
              next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
            }
          } else if (visually) {
            next = moveVisually(doc.cm, lineObj, pos, dir);
          } else {
            next = moveLogically(lineObj, pos, dir);
          }
          if (next == null) {
            if (!boundToLine && findNextLine()) {
              pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir);
            } else {
              return false;
            }
          } else {
            pos = next;
          }
          return true;
        }
        if (unit2 == "char" || unit2 == "codepoint") {
          moveOnce();
        } else if (unit2 == "column") {
          moveOnce(true);
        } else if (unit2 == "word" || unit2 == "group") {
          var sawType = null, group = unit2 == "group";
          var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
          for (var first = true; ; first = false) {
            if (dir < 0 && !moveOnce(!first)) {
              break;
            }
            var cur = lineObj.text.charAt(pos.ch) || "\n";
            var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p";
            if (group && !first && !type) {
              type = "s";
            }
            if (sawType && sawType != type) {
              if (dir < 0) {
                dir = 1;
                moveOnce();
                pos.sticky = "after";
              }
              break;
            }
            if (type) {
              sawType = type;
            }
            if (dir > 0 && !moveOnce(!first)) {
              break;
            }
          }
        }
        var result = skipAtomic(doc, pos, oldPos, origDir, true);
        if (equalCursorPos(oldPos, result)) {
          result.hitSide = true;
        }
        return result;
      }
      function findPosV(cm, pos, dir, unit2) {
        var doc = cm.doc, x2 = pos.left, y2;
        if (unit2 == "page") {
          var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
          var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3);
          y2 = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
        } else if (unit2 == "line") {
          y2 = dir > 0 ? pos.bottom + 3 : pos.top - 3;
        }
        var target;
        for (; ; ) {
          target = coordsChar(cm, x2, y2);
          if (!target.outside) {
            break;
          }
          if (dir < 0 ? y2 <= 0 : y2 >= doc.height) {
            target.hitSide = true;
            break;
          }
          y2 += dir * 5;
        }
        return target;
      }
      var ContentEditableInput = function(cm) {
        this.cm = cm;
        this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
        this.polling = new Delayed();
        this.composing = null;
        this.gracePeriod = false;
        this.readDOMTimeout = null;
      };
      ContentEditableInput.prototype.init = function(display) {
        var this$1 = this;
        var input = this, cm = input.cm;
        var div = input.div = display.lineDiv;
        disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
        function belongsToInput(e) {
          for (var t = e.target; t; t = t.parentNode) {
            if (t == div) {
              return true;
            }
            if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) {
              break;
            }
          }
          return false;
        }
        on(div, "paste", function(e) {
          if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) {
            return;
          }
          if (ie_version <= 11) {
            setTimeout(operation(cm, function() {
              return this$1.updateFromDOM();
            }), 20);
          }
        });
        on(div, "compositionstart", function(e) {
          this$1.composing = {data: e.data, done: false};
        });
        on(div, "compositionupdate", function(e) {
          if (!this$1.composing) {
            this$1.composing = {data: e.data, done: false};
          }
        });
        on(div, "compositionend", function(e) {
          if (this$1.composing) {
            if (e.data != this$1.composing.data) {
              this$1.readFromDOMSoon();
            }
            this$1.composing.done = true;
          }
        });
        on(div, "touchstart", function() {
          return input.forceCompositionEnd();
        });
        on(div, "input", function() {
          if (!this$1.composing) {
            this$1.readFromDOMSoon();
          }
        });
        function onCopyCut(e) {
          if (!belongsToInput(e) || signalDOMEvent(cm, e)) {
            return;
          }
          if (cm.somethingSelected()) {
            setLastCopied({lineWise: false, text: cm.getSelections()});
            if (e.type == "cut") {
              cm.replaceSelection("", null, "cut");
            }
          } else if (!cm.options.lineWiseCopyCut) {
            return;
          } else {
            var ranges = copyableRanges(cm);
            setLastCopied({lineWise: true, text: ranges.text});
            if (e.type == "cut") {
              cm.operation(function() {
                cm.setSelections(ranges.ranges, 0, sel_dontScroll);
                cm.replaceSelection("", null, "cut");
              });
            }
          }
          if (e.clipboardData) {
            e.clipboardData.clearData();
            var content = lastCopied.text.join("\n");
            e.clipboardData.setData("Text", content);
            if (e.clipboardData.getData("Text") == content) {
              e.preventDefault();
              return;
            }
          }
          var kludge = hiddenTextarea(), te = kludge.firstChild;
          cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
          te.value = lastCopied.text.join("\n");
          var hadFocus = document.activeElement;
          selectInput(te);
          setTimeout(function() {
            cm.display.lineSpace.removeChild(kludge);
            hadFocus.focus();
            if (hadFocus == div) {
              input.showPrimarySelection();
            }
          }, 50);
        }
        on(div, "copy", onCopyCut);
        on(div, "cut", onCopyCut);
      };
      ContentEditableInput.prototype.screenReaderLabelChanged = function(label) {
        if (label) {
          this.div.setAttribute("aria-label", label);
        } else {
          this.div.removeAttribute("aria-label");
        }
      };
      ContentEditableInput.prototype.prepareSelection = function() {
        var result = prepareSelection(this.cm, false);
        result.focus = document.activeElement == this.div;
        return result;
      };
      ContentEditableInput.prototype.showSelection = function(info, takeFocus) {
        if (!info || !this.cm.display.view.length) {
          return;
        }
        if (info.focus || takeFocus) {
          this.showPrimarySelection();
        }
        this.showMultipleSelections(info);
      };
      ContentEditableInput.prototype.getSelection = function() {
        return this.cm.display.wrapper.ownerDocument.getSelection();
      };
      ContentEditableInput.prototype.showPrimarySelection = function() {
        var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
        var from = prim.from(), to = prim.to();
        if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
          sel.removeAllRanges();
          return;
        }
        var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
        var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
        if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) {
          return;
        }
        var view = cm.display.view;
        var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || {node: view[0].measure.map[2], offset: 0};
        var end = to.line < cm.display.viewTo && posToDOM(cm, to);
        if (!end) {
          var measure = view[view.length - 1].measure;
          var map3 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
          end = {node: map3[map3.length - 1], offset: map3[map3.length - 2] - map3[map3.length - 3]};
        }
        if (!start || !end) {
          sel.removeAllRanges();
          return;
        }
        var old = sel.rangeCount && sel.getRangeAt(0), rng;
        try {
          rng = range(start.node, start.offset, end.offset, end.node);
        } catch (e) {
        }
        if (rng) {
          if (!gecko && cm.state.focused) {
            sel.collapse(start.node, start.offset);
            if (!rng.collapsed) {
              sel.removeAllRanges();
              sel.addRange(rng);
            }
          } else {
            sel.removeAllRanges();
            sel.addRange(rng);
          }
          if (old && sel.anchorNode == null) {
            sel.addRange(old);
          } else if (gecko) {
            this.startGracePeriod();
          }
        }
        this.rememberSelection();
      };
      ContentEditableInput.prototype.startGracePeriod = function() {
        var this$1 = this;
        clearTimeout(this.gracePeriod);
        this.gracePeriod = setTimeout(function() {
          this$1.gracePeriod = false;
          if (this$1.selectionChanged()) {
            this$1.cm.operation(function() {
              return this$1.cm.curOp.selectionChanged = true;
            });
          }
        }, 20);
      };
      ContentEditableInput.prototype.showMultipleSelections = function(info) {
        removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
        removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
      };
      ContentEditableInput.prototype.rememberSelection = function() {
        var sel = this.getSelection();
        this.lastAnchorNode = sel.anchorNode;
        this.lastAnchorOffset = sel.anchorOffset;
        this.lastFocusNode = sel.focusNode;
        this.lastFocusOffset = sel.focusOffset;
      };
      ContentEditableInput.prototype.selectionInEditor = function() {
        var sel = this.getSelection();
        if (!sel.rangeCount) {
          return false;
        }
        var node = sel.getRangeAt(0).commonAncestorContainer;
        return contains(this.div, node);
      };
      ContentEditableInput.prototype.focus = function() {
        if (this.cm.options.readOnly != "nocursor") {
          if (!this.selectionInEditor() || document.activeElement != this.div) {
            this.showSelection(this.prepareSelection(), true);
          }
          this.div.focus();
        }
      };
      ContentEditableInput.prototype.blur = function() {
        this.div.blur();
      };
      ContentEditableInput.prototype.getField = function() {
        return this.div;
      };
      ContentEditableInput.prototype.supportsTouch = function() {
        return true;
      };
      ContentEditableInput.prototype.receivedFocus = function() {
        var input = this;
        if (this.selectionInEditor()) {
          this.pollSelection();
        } else {
          runInOp(this.cm, function() {
            return input.cm.curOp.selectionChanged = true;
          });
        }
        function poll() {
          if (input.cm.state.focused) {
            input.pollSelection();
            input.polling.set(input.cm.options.pollInterval, poll);
          }
        }
        this.polling.set(this.cm.options.pollInterval, poll);
      };
      ContentEditableInput.prototype.selectionChanged = function() {
        var sel = this.getSelection();
        return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
      };
      ContentEditableInput.prototype.pollSelection = function() {
        if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) {
          return;
        }
        var sel = this.getSelection(), cm = this.cm;
        if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
          this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
          this.blur();
          this.focus();
          return;
        }
        if (this.composing) {
          return;
        }
        this.rememberSelection();
        var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
        var head = domToPos(cm, sel.focusNode, sel.focusOffset);
        if (anchor && head) {
          runInOp(cm, function() {
            setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
            if (anchor.bad || head.bad) {
              cm.curOp.selectionChanged = true;
            }
          });
        }
      };
      ContentEditableInput.prototype.pollContent = function() {
        if (this.readDOMTimeout != null) {
          clearTimeout(this.readDOMTimeout);
          this.readDOMTimeout = null;
        }
        var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
        var from = sel.from(), to = sel.to();
        if (from.ch == 0 && from.line > cm.firstLine()) {
          from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length);
        }
        if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) {
          to = Pos(to.line + 1, 0);
        }
        if (from.line < display.viewFrom || to.line > display.viewTo - 1) {
          return false;
        }
        var fromIndex, fromLine, fromNode;
        if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
          fromLine = lineNo(display.view[0].line);
          fromNode = display.view[0].node;
        } else {
          fromLine = lineNo(display.view[fromIndex].line);
          fromNode = display.view[fromIndex - 1].node.nextSibling;
        }
        var toIndex = findViewIndex(cm, to.line);
        var toLine, toNode;
        if (toIndex == display.view.length - 1) {
          toLine = display.viewTo - 1;
          toNode = display.lineDiv.lastChild;
        } else {
          toLine = lineNo(display.view[toIndex + 1].line) - 1;
          toNode = display.view[toIndex + 1].node.previousSibling;
        }
        if (!fromNode) {
          return false;
        }
        var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
        var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
        while (newText.length > 1 && oldText.length > 1) {
          if (lst(newText) == lst(oldText)) {
            newText.pop();
            oldText.pop();
            toLine--;
          } else if (newText[0] == oldText[0]) {
            newText.shift();
            oldText.shift();
            fromLine++;
          } else {
            break;
          }
        }
        var cutFront = 0, cutEnd = 0;
        var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
        while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {
          ++cutFront;
        }
        var newBot = lst(newText), oldBot = lst(oldText);
        var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0));
        while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
          ++cutEnd;
        }
        if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
          while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
            cutFront--;
            cutEnd++;
          }
        }
        newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
        newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
        var chFrom = Pos(fromLine, cutFront);
        var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
        if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
          replaceRange(cm.doc, newText, chFrom, chTo, "+input");
          return true;
        }
      };
      ContentEditableInput.prototype.ensurePolled = function() {
        this.forceCompositionEnd();
      };
      ContentEditableInput.prototype.reset = function() {
        this.forceCompositionEnd();
      };
      ContentEditableInput.prototype.forceCompositionEnd = function() {
        if (!this.composing) {
          return;
        }
        clearTimeout(this.readDOMTimeout);
        this.composing = null;
        this.updateFromDOM();
        this.div.blur();
        this.div.focus();
      };
      ContentEditableInput.prototype.readFromDOMSoon = function() {
        var this$1 = this;
        if (this.readDOMTimeout != null) {
          return;
        }
        this.readDOMTimeout = setTimeout(function() {
          this$1.readDOMTimeout = null;
          if (this$1.composing) {
            if (this$1.composing.done) {
              this$1.composing = null;
            } else {
              return;
            }
          }
          this$1.updateFromDOM();
        }, 80);
      };
      ContentEditableInput.prototype.updateFromDOM = function() {
        var this$1 = this;
        if (this.cm.isReadOnly() || !this.pollContent()) {
          runInOp(this.cm, function() {
            return regChange(this$1.cm);
          });
        }
      };
      ContentEditableInput.prototype.setUneditable = function(node) {
        node.contentEditable = "false";
      };
      ContentEditableInput.prototype.onKeyPress = function(e) {
        if (e.charCode == 0 || this.composing) {
          return;
        }
        e.preventDefault();
        if (!this.cm.isReadOnly()) {
          operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
        }
      };
      ContentEditableInput.prototype.readOnlyChanged = function(val) {
        this.div.contentEditable = String(val != "nocursor");
      };
      ContentEditableInput.prototype.onContextMenu = function() {
      };
      ContentEditableInput.prototype.resetPosition = function() {
      };
      ContentEditableInput.prototype.needsContentAttribute = true;
      function posToDOM(cm, pos) {
        var view = findViewForLine(cm, pos.line);
        if (!view || view.hidden) {
          return null;
        }
        var line = getLine(cm.doc, pos.line);
        var info = mapFromLineView(view, line, pos.line);
        var order = getOrder(line, cm.doc.direction), side = "left";
        if (order) {
          var partPos = getBidiPartAt(order, pos.ch);
          side = partPos % 2 ? "right" : "left";
        }
        var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
        result.offset = result.collapse == "right" ? result.end : result.start;
        return result;
      }
      function isInGutter(node) {
        for (var scan = node; scan; scan = scan.parentNode) {
          if (/CodeMirror-gutter-wrapper/.test(scan.className)) {
            return true;
          }
        }
        return false;
      }
      function badPos(pos, bad) {
        if (bad) {
          pos.bad = true;
        }
        return pos;
      }
      function domTextBetween(cm, from, to, fromLine, toLine) {
        var text2 = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
        function recognizeMarker(id) {
          return function(marker) {
            return marker.id == id;
          };
        }
        function close() {
          if (closing) {
            text2 += lineSep;
            if (extraLinebreak) {
              text2 += lineSep;
            }
            closing = extraLinebreak = false;
          }
        }
        function addText(str) {
          if (str) {
            close();
            text2 += str;
          }
        }
        function walk(node) {
          if (node.nodeType == 1) {
            var cmText = node.getAttribute("cm-text");
            if (cmText) {
              addText(cmText);
              return;
            }
            var markerID = node.getAttribute("cm-marker"), range2;
            if (markerID) {
              var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
              if (found.length && (range2 = found[0].find(0))) {
                addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep));
              }
              return;
            }
            if (node.getAttribute("contenteditable") == "false") {
              return;
            }
            var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
            if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) {
              return;
            }
            if (isBlock) {
              close();
            }
            for (var i2 = 0; i2 < node.childNodes.length; i2++) {
              walk(node.childNodes[i2]);
            }
            if (/^(pre|p)$/i.test(node.nodeName)) {
              extraLinebreak = true;
            }
            if (isBlock) {
              closing = true;
            }
          } else if (node.nodeType == 3) {
            addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
          }
        }
        for (; ; ) {
          walk(from);
          if (from == to) {
            break;
          }
          from = from.nextSibling;
          extraLinebreak = false;
        }
        return text2;
      }
      function domToPos(cm, node, offset) {
        var lineNode;
        if (node == cm.display.lineDiv) {
          lineNode = cm.display.lineDiv.childNodes[offset];
          if (!lineNode) {
            return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
          }
          node = null;
          offset = 0;
        } else {
          for (lineNode = node; ; lineNode = lineNode.parentNode) {
            if (!lineNode || lineNode == cm.display.lineDiv) {
              return null;
            }
            if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) {
              break;
            }
          }
        }
        for (var i2 = 0; i2 < cm.display.view.length; i2++) {
          var lineView = cm.display.view[i2];
          if (lineView.node == lineNode) {
            return locateNodeInLineView(lineView, node, offset);
          }
        }
      }
      function locateNodeInLineView(lineView, node, offset) {
        var wrapper = lineView.text.firstChild, bad = false;
        if (!node || !contains(wrapper, node)) {
          return badPos(Pos(lineNo(lineView.line), 0), true);
        }
        if (node == wrapper) {
          bad = true;
          node = wrapper.childNodes[offset];
          offset = 0;
          if (!node) {
            var line = lineView.rest ? lst(lineView.rest) : lineView.line;
            return badPos(Pos(lineNo(line), line.text.length), bad);
          }
        }
        var textNode = node.nodeType == 3 ? node : null, topNode = node;
        if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
          textNode = node.firstChild;
          if (offset) {
            offset = textNode.nodeValue.length;
          }
        }
        while (topNode.parentNode != wrapper) {
          topNode = topNode.parentNode;
        }
        var measure = lineView.measure, maps = measure.maps;
        function find2(textNode2, topNode2, offset2) {
          for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) {
            var map3 = i2 < 0 ? measure.map : maps[i2];
            for (var j = 0; j < map3.length; j += 3) {
              var curNode = map3[j + 2];
              if (curNode == textNode2 || curNode == topNode2) {
                var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]);
                var ch = map3[j] + offset2;
                if (offset2 < 0 || curNode != textNode2) {
                  ch = map3[j + (offset2 ? 1 : 0)];
                }
                return Pos(line2, ch);
              }
            }
          }
        }
        var found = find2(textNode, topNode, offset);
        if (found) {
          return badPos(found, bad);
        }
        for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
          found = find2(after, after.firstChild, 0);
          if (found) {
            return badPos(Pos(found.line, found.ch - dist), bad);
          } else {
            dist += after.textContent.length;
          }
        }
        for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
          found = find2(before, before.firstChild, -1);
          if (found) {
            return badPos(Pos(found.line, found.ch + dist$1), bad);
          } else {
            dist$1 += before.textContent.length;
          }
        }
      }
      var TextareaInput = function(cm) {
        this.cm = cm;
        this.prevInput = "";
        this.pollingFast = false;
        this.polling = new Delayed();
        this.hasSelection = false;
        this.composing = null;
      };
      TextareaInput.prototype.init = function(display) {
        var this$1 = this;
        var input = this, cm = this.cm;
        this.createField(display);
        var te = this.textarea;
        display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
        if (ios) {
          te.style.width = "0px";
        }
        on(te, "input", function() {
          if (ie && ie_version >= 9 && this$1.hasSelection) {
            this$1.hasSelection = null;
          }
          input.poll();
        });
        on(te, "paste", function(e) {
          if (signalDOMEvent(cm, e) || handlePaste(e, cm)) {
            return;
          }
          cm.state.pasteIncoming = +new Date();
          input.fastPoll();
        });
        function prepareCopyCut(e) {
          if (signalDOMEvent(cm, e)) {
            return;
          }
          if (cm.somethingSelected()) {
            setLastCopied({lineWise: false, text: cm.getSelections()});
          } else if (!cm.options.lineWiseCopyCut) {
            return;
          } else {
            var ranges = copyableRanges(cm);
            setLastCopied({lineWise: true, text: ranges.text});
            if (e.type == "cut") {
              cm.setSelections(ranges.ranges, null, sel_dontScroll);
            } else {
              input.prevInput = "";
              te.value = ranges.text.join("\n");
              selectInput(te);
            }
          }
          if (e.type == "cut") {
            cm.state.cutIncoming = +new Date();
          }
        }
        on(te, "cut", prepareCopyCut);
        on(te, "copy", prepareCopyCut);
        on(display.scroller, "paste", function(e) {
          if (eventInWidget(display, e) || signalDOMEvent(cm, e)) {
            return;
          }
          if (!te.dispatchEvent) {
            cm.state.pasteIncoming = +new Date();
            input.focus();
            return;
          }
          var event = new Event("paste");
          event.clipboardData = e.clipboardData;
          te.dispatchEvent(event);
        });
        on(display.lineSpace, "selectstart", function(e) {
          if (!eventInWidget(display, e)) {
            e_preventDefault(e);
          }
        });
        on(te, "compositionstart", function() {
          var start = cm.getCursor("from");
          if (input.composing) {
            input.composing.range.clear();
          }
          input.composing = {
            start,
            range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
          };
        });
        on(te, "compositionend", function() {
          if (input.composing) {
            input.poll();
            input.composing.range.clear();
            input.composing = null;
          }
        });
      };
      TextareaInput.prototype.createField = function(_display) {
        this.wrapper = hiddenTextarea();
        this.textarea = this.wrapper.firstChild;
      };
      TextareaInput.prototype.screenReaderLabelChanged = function(label) {
        if (label) {
          this.textarea.setAttribute("aria-label", label);
        } else {
          this.textarea.removeAttribute("aria-label");
        }
      };
      TextareaInput.prototype.prepareSelection = function() {
        var cm = this.cm, display = cm.display, doc = cm.doc;
        var result = prepareSelection(cm);
        if (cm.options.moveInputWithCursor) {
          var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
          var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
          result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top));
          result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left));
        }
        return result;
      };
      TextareaInput.prototype.showSelection = function(drawn) {
        var cm = this.cm, display = cm.display;
        removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
        removeChildrenAndAdd(display.selectionDiv, drawn.selection);
        if (drawn.teTop != null) {
          this.wrapper.style.top = drawn.teTop + "px";
          this.wrapper.style.left = drawn.teLeft + "px";
        }
      };
      TextareaInput.prototype.reset = function(typing) {
        if (this.contextMenuPending || this.composing) {
          return;
        }
        var cm = this.cm;
        if (cm.somethingSelected()) {
          this.prevInput = "";
          var content = cm.getSelection();
          this.textarea.value = content;
          if (cm.state.focused) {
            selectInput(this.textarea);
          }
          if (ie && ie_version >= 9) {
            this.hasSelection = content;
          }
        } else if (!typing) {
          this.prevInput = this.textarea.value = "";
          if (ie && ie_version >= 9) {
            this.hasSelection = null;
          }
        }
      };
      TextareaInput.prototype.getField = function() {
        return this.textarea;
      };
      TextareaInput.prototype.supportsTouch = function() {
        return false;
      };
      TextareaInput.prototype.focus = function() {
        if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
          try {
            this.textarea.focus();
          } catch (e) {
          }
        }
      };
      TextareaInput.prototype.blur = function() {
        this.textarea.blur();
      };
      TextareaInput.prototype.resetPosition = function() {
        this.wrapper.style.top = this.wrapper.style.left = 0;
      };
      TextareaInput.prototype.receivedFocus = function() {
        this.slowPoll();
      };
      TextareaInput.prototype.slowPoll = function() {
        var this$1 = this;
        if (this.pollingFast) {
          return;
        }
        this.polling.set(this.cm.options.pollInterval, function() {
          this$1.poll();
          if (this$1.cm.state.focused) {
            this$1.slowPoll();
          }
        });
      };
      TextareaInput.prototype.fastPoll = function() {
        var missed = false, input = this;
        input.pollingFast = true;
        function p() {
          var changed = input.poll();
          if (!changed && !missed) {
            missed = true;
            input.polling.set(60, p);
          } else {
            input.pollingFast = false;
            input.slowPoll();
          }
        }
        input.polling.set(20, p);
      };
      TextareaInput.prototype.poll = function() {
        var this$1 = this;
        var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
        if (this.contextMenuPending || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) {
          return false;
        }
        var text2 = input.value;
        if (text2 == prevInput && !cm.somethingSelected()) {
          return false;
        }
        if (ie && ie_version >= 9 && this.hasSelection === text2 || mac && /[\uf700-\uf7ff]/.test(text2)) {
          cm.display.input.reset();
          return false;
        }
        if (cm.doc.sel == cm.display.selForContextMenu) {
          var first = text2.charCodeAt(0);
          if (first == 8203 && !prevInput) {
            prevInput = "\u200B";
          }
          if (first == 8666) {
            this.reset();
            return this.cm.execCommand("undo");
          }
        }
        var same = 0, l = Math.min(prevInput.length, text2.length);
        while (same < l && prevInput.charCodeAt(same) == text2.charCodeAt(same)) {
          ++same;
        }
        runInOp(cm, function() {
          applyTextInput(cm, text2.slice(same), prevInput.length - same, null, this$1.composing ? "*compose" : null);
          if (text2.length > 1e3 || text2.indexOf("\n") > -1) {
            input.value = this$1.prevInput = "";
          } else {
            this$1.prevInput = text2;
          }
          if (this$1.composing) {
            this$1.composing.range.clear();
            this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), {className: "CodeMirror-composing"});
          }
        });
        return true;
      };
      TextareaInput.prototype.ensurePolled = function() {
        if (this.pollingFast && this.poll()) {
          this.pollingFast = false;
        }
      };
      TextareaInput.prototype.onKeyPress = function() {
        if (ie && ie_version >= 9) {
          this.hasSelection = null;
        }
        this.fastPoll();
      };
      TextareaInput.prototype.onContextMenu = function(e) {
        var input = this, cm = input.cm, display = cm.display, te = input.textarea;
        if (input.contextMenuPending) {
          input.contextMenuPending();
        }
        var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
        if (!pos || presto) {
          return;
        }
        var reset = cm.options.resetSelectionOnContextMenu;
        if (reset && cm.doc.sel.contains(pos) == -1) {
          operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
        }
        var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
        var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
        input.wrapper.style.cssText = "position: static";
        te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
        var oldScrollY;
        if (webkit) {
          oldScrollY = window.scrollY;
        }
        display.input.focus();
        if (webkit) {
          window.scrollTo(null, oldScrollY);
        }
        display.input.reset();
        if (!cm.somethingSelected()) {
          te.value = input.prevInput = " ";
        }
        input.contextMenuPending = rehide;
        display.selForContextMenu = cm.doc.sel;
        clearTimeout(display.detectingSelectAll);
        function prepareSelectAllHack() {
          if (te.selectionStart != null) {
            var selected = cm.somethingSelected();
            var extval = "\u200B" + (selected ? te.value : "");
            te.value = "\u21DA";
            te.value = extval;
            input.prevInput = selected ? "" : "\u200B";
            te.selectionStart = 1;
            te.selectionEnd = extval.length;
            display.selForContextMenu = cm.doc.sel;
          }
        }
        function rehide() {
          if (input.contextMenuPending != rehide) {
            return;
          }
          input.contextMenuPending = false;
          input.wrapper.style.cssText = oldWrapperCSS;
          te.style.cssText = oldCSS;
          if (ie && ie_version < 9) {
            display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
          }
          if (te.selectionStart != null) {
            if (!ie || ie && ie_version < 9) {
              prepareSelectAllHack();
            }
            var i2 = 0, poll = function() {
              if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200B") {
                operation(cm, selectAll)(cm);
              } else if (i2++ < 10) {
                display.detectingSelectAll = setTimeout(poll, 500);
              } else {
                display.selForContextMenu = null;
                display.input.reset();
              }
            };
            display.detectingSelectAll = setTimeout(poll, 200);
          }
        }
        if (ie && ie_version >= 9) {
          prepareSelectAllHack();
        }
        if (captureRightClick) {
          e_stop(e);
          var mouseup = function() {
            off(window, "mouseup", mouseup);
            setTimeout(rehide, 20);
          };
          on(window, "mouseup", mouseup);
        } else {
          setTimeout(rehide, 50);
        }
      };
      TextareaInput.prototype.readOnlyChanged = function(val) {
        if (!val) {
          this.reset();
        }
        this.textarea.disabled = val == "nocursor";
        this.textarea.readOnly = !!val;
      };
      TextareaInput.prototype.setUneditable = function() {
      };
      TextareaInput.prototype.needsContentAttribute = false;
      function fromTextArea(textarea, options) {
        options = options ? copyObj(options) : {};
        options.value = textarea.value;
        if (!options.tabindex && textarea.tabIndex) {
          options.tabindex = textarea.tabIndex;
        }
        if (!options.placeholder && textarea.placeholder) {
          options.placeholder = textarea.placeholder;
        }
        if (options.autofocus == null) {
          var hasFocus = activeElt();
          options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body;
        }
        function save() {
          textarea.value = cm.getValue();
        }
        var realSubmit;
        if (textarea.form) {
          on(textarea.form, "submit", save);
          if (!options.leaveSubmitMethodAlone) {
            var form = textarea.form;
            realSubmit = form.submit;
            try {
              var wrappedSubmit = form.submit = function() {
                save();
                form.submit = realSubmit;
                form.submit();
                form.submit = wrappedSubmit;
              };
            } catch (e) {
            }
          }
        }
        options.finishInit = function(cm2) {
          cm2.save = save;
          cm2.getTextArea = function() {
            return textarea;
          };
          cm2.toTextArea = function() {
            cm2.toTextArea = isNaN;
            save();
            textarea.parentNode.removeChild(cm2.getWrapperElement());
            textarea.style.display = "";
            if (textarea.form) {
              off(textarea.form, "submit", save);
              if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") {
                textarea.form.submit = realSubmit;
              }
            }
          };
        };
        textarea.style.display = "none";
        var cm = CodeMirror10(function(node) {
          return textarea.parentNode.insertBefore(node, textarea.nextSibling);
        }, options);
        return cm;
      }
      function addLegacyProps(CodeMirror11) {
        CodeMirror11.off = off;
        CodeMirror11.on = on;
        CodeMirror11.wheelEventPixels = wheelEventPixels;
        CodeMirror11.Doc = Doc;
        CodeMirror11.splitLines = splitLinesAuto;
        CodeMirror11.countColumn = countColumn;
        CodeMirror11.findColumn = findColumn;
        CodeMirror11.isWordChar = isWordCharBasic;
        CodeMirror11.Pass = Pass;
        CodeMirror11.signal = signal;
        CodeMirror11.Line = Line;
        CodeMirror11.changeEnd = changeEnd;
        CodeMirror11.scrollbarModel = scrollbarModel;
        CodeMirror11.Pos = Pos;
        CodeMirror11.cmpPos = cmp;
        CodeMirror11.modes = modes;
        CodeMirror11.mimeModes = mimeModes;
        CodeMirror11.resolveMode = resolveMode;
        CodeMirror11.getMode = getMode;
        CodeMirror11.modeExtensions = modeExtensions;
        CodeMirror11.extendMode = extendMode;
        CodeMirror11.copyState = copyState;
        CodeMirror11.startState = startState;
        CodeMirror11.innerMode = innerMode;
        CodeMirror11.commands = commands2;
        CodeMirror11.keyMap = keyMap;
        CodeMirror11.keyName = keyName;
        CodeMirror11.isModifierKey = isModifierKey;
        CodeMirror11.lookupKey = lookupKey;
        CodeMirror11.normalizeKeyMap = normalizeKeyMap;
        CodeMirror11.StringStream = StringStream;
        CodeMirror11.SharedTextMarker = SharedTextMarker;
        CodeMirror11.TextMarker = TextMarker;
        CodeMirror11.LineWidget = LineWidget;
        CodeMirror11.e_preventDefault = e_preventDefault;
        CodeMirror11.e_stopPropagation = e_stopPropagation;
        CodeMirror11.e_stop = e_stop;
        CodeMirror11.addClass = addClass;
        CodeMirror11.contains = contains;
        CodeMirror11.rmClass = rmClass;
        CodeMirror11.keyNames = keyNames;
      }
      defineOptions(CodeMirror10);
      addEditorMethods(CodeMirror10);
      var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
      for (var prop in Doc.prototype) {
        if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) {
          CodeMirror10.prototype[prop] = function(method) {
            return function() {
              return method.apply(this.doc, arguments);
            };
          }(Doc.prototype[prop]);
        }
      }
      eventMixin(Doc);
      CodeMirror10.inputStyles = {textarea: TextareaInput, contenteditable: ContentEditableInput};
      CodeMirror10.defineMode = function(name) {
        if (!CodeMirror10.defaults.mode && name != "null") {
          CodeMirror10.defaults.mode = name;
        }
        defineMode.apply(this, arguments);
      };
      CodeMirror10.defineMIME = defineMIME;
      CodeMirror10.defineMode("null", function() {
        return {token: function(stream) {
          return stream.skipToEnd();
        }};
      });
      CodeMirror10.defineMIME("text/plain", "null");
      CodeMirror10.defineExtension = function(name, func) {
        CodeMirror10.prototype[name] = func;
      };
      CodeMirror10.defineDocExtension = function(name, func) {
        Doc.prototype[name] = func;
      };
      CodeMirror10.fromTextArea = fromTextArea;
      addLegacyProps(CodeMirror10);
      CodeMirror10.version = "5.59.1";
      return CodeMirror10;
    });
  });

  // node_modules/codemirror/addon/mode/simple.js
  var require_simple = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      CodeMirror10.defineSimpleMode = function(name, states) {
        CodeMirror10.defineMode(name, function(config) {
          return CodeMirror10.simpleMode(config, states);
        });
      };
      CodeMirror10.simpleMode = function(config, states) {
        ensureState(states, "start");
        var states_ = {}, meta = states.meta || {}, hasIndentation = false;
        for (var state in states)
          if (state != meta && states.hasOwnProperty(state)) {
            var list = states_[state] = [], orig = states[state];
            for (var i = 0; i < orig.length; i++) {
              var data = orig[i];
              list.push(new Rule(data, states));
              if (data.indent || data.dedent)
                hasIndentation = true;
            }
          }
        var mode = {
          startState: function() {
            return {
              state: "start",
              pending: null,
              local: null,
              localState: null,
              indent: hasIndentation ? [] : null
            };
          },
          copyState: function(state2) {
            var s = {
              state: state2.state,
              pending: state2.pending,
              local: state2.local,
              localState: null,
              indent: state2.indent && state2.indent.slice(0)
            };
            if (state2.localState)
              s.localState = CodeMirror10.copyState(state2.local.mode, state2.localState);
            if (state2.stack)
              s.stack = state2.stack.slice(0);
            for (var pers = state2.persistentStates; pers; pers = pers.next)
              s.persistentStates = {
                mode: pers.mode,
                spec: pers.spec,
                state: pers.state == state2.localState ? s.localState : CodeMirror10.copyState(pers.mode, pers.state),
                next: s.persistentStates
              };
            return s;
          },
          token: tokenFunction(states_, config),
          innerMode: function(state2) {
            return state2.local && {mode: state2.local.mode, state: state2.localState};
          },
          indent: indentFunction(states_, meta)
        };
        if (meta) {
          for (var prop in meta)
            if (meta.hasOwnProperty(prop))
              mode[prop] = meta[prop];
        }
        return mode;
      };
      function ensureState(states, name) {
        if (!states.hasOwnProperty(name))
          throw new Error("Undefined state " + name + " in simple mode");
      }
      function toRegex(val, caret) {
        if (!val)
          return /(?:)/;
        var flags = "";
        if (val instanceof RegExp) {
          if (val.ignoreCase)
            flags = "i";
          val = val.source;
        } else {
          val = String(val);
        }
        return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
      }
      function asToken(val) {
        if (!val)
          return null;
        if (val.apply)
          return val;
        if (typeof val == "string")
          return val.replace(/\./g, " ");
        var result = [];
        for (var i = 0; i < val.length; i++)
          result.push(val[i] && val[i].replace(/\./g, " "));
        return result;
      }
      function Rule(data, states) {
        if (data.next || data.push)
          ensureState(states, data.next || data.push);
        this.regex = toRegex(data.regex);
        this.token = asToken(data.token);
        this.data = data;
      }
      function tokenFunction(states, config) {
        return function(stream, state) {
          if (state.pending) {
            var pend = state.pending.shift();
            if (state.pending.length == 0)
              state.pending = null;
            stream.pos += pend.text.length;
            return pend.token;
          }
          if (state.local) {
            if (state.local.end && stream.match(state.local.end)) {
              var tok = state.local.endToken || null;
              state.local = state.localState = null;
              return tok;
            } else {
              var tok = state.local.mode.token(stream, state.localState), m;
              if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
                stream.pos = stream.start + m.index;
              return tok;
            }
          }
          var curState = states[state.state];
          for (var i = 0; i < curState.length; i++) {
            var rule = curState[i];
            var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
            if (matches) {
              if (rule.data.next) {
                state.state = rule.data.next;
              } else if (rule.data.push) {
                (state.stack || (state.stack = [])).push(state.state);
                state.state = rule.data.push;
              } else if (rule.data.pop && state.stack && state.stack.length) {
                state.state = state.stack.pop();
              }
              if (rule.data.mode)
                enterLocalMode(config, state, rule.data.mode, rule.token);
              if (rule.data.indent)
                state.indent.push(stream.indentation() + config.indentUnit);
              if (rule.data.dedent)
                state.indent.pop();
              var token = rule.token;
              if (token && token.apply)
                token = token(matches);
              if (matches.length > 2 && rule.token && typeof rule.token != "string") {
                state.pending = [];
                for (var j = 2; j < matches.length; j++)
                  if (matches[j])
                    state.pending.push({text: matches[j], token: rule.token[j - 1]});
                stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
                return token[0];
              } else if (token && token.join) {
                return token[0];
              } else {
                return token;
              }
            }
          }
          stream.next();
          return null;
        };
      }
      function cmp(a, b) {
        if (a === b)
          return true;
        if (!a || typeof a != "object" || !b || typeof b != "object")
          return false;
        var props = 0;
        for (var prop in a)
          if (a.hasOwnProperty(prop)) {
            if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop]))
              return false;
            props++;
          }
        for (var prop in b)
          if (b.hasOwnProperty(prop))
            props--;
        return props == 0;
      }
      function enterLocalMode(config, state, spec, token) {
        var pers;
        if (spec.persistent) {
          for (var p = state.persistentStates; p && !pers; p = p.next)
            if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode)
              pers = p;
        }
        var mode = pers ? pers.mode : spec.mode || CodeMirror10.getMode(config, spec.spec);
        var lState = pers ? pers.state : CodeMirror10.startState(mode);
        if (spec.persistent && !pers)
          state.persistentStates = {mode, spec: spec.spec, state: lState, next: state.persistentStates};
        state.localState = lState;
        state.local = {
          mode,
          end: spec.end && toRegex(spec.end),
          endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
          endToken: token && token.join ? token[token.length - 1] : token
        };
      }
      function indexOf(val, arr) {
        for (var i = 0; i < arr.length; i++)
          if (arr[i] === val)
            return true;
      }
      function indentFunction(states, meta) {
        return function(state, textAfter, line) {
          if (state.local && state.local.mode.indent)
            return state.local.mode.indent(state.localState, textAfter, line);
          if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
            return CodeMirror10.Pass;
          var pos = state.indent.length - 1, rules = states[state.state];
          scan:
            for (; ; ) {
              for (var i = 0; i < rules.length; i++) {
                var rule = rules[i];
                if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
                  var m = rule.regex.exec(textAfter);
                  if (m && m[0]) {
                    pos--;
                    if (rule.next || rule.push)
                      rules = states[rule.next || rule.push];
                    textAfter = textAfter.slice(m[0].length);
                    continue scan;
                  }
                }
              }
              break;
            }
          return pos < 0 ? 0 : state.indent[pos];
        };
      }
    });
  });

  // node_modules/codemirror/addon/dialog/dialog.js
  var require_dialog = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      function dialogDiv(cm, template, bottom2) {
        var wrap = cm.getWrapperElement();
        var dialog;
        dialog = wrap.appendChild(document.createElement("div"));
        if (bottom2)
          dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
        else
          dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
        if (typeof template == "string") {
          dialog.innerHTML = template;
        } else {
          dialog.appendChild(template);
        }
        CodeMirror10.addClass(wrap, "dialog-opened");
        return dialog;
      }
      function closeNotification(cm, newVal) {
        if (cm.state.currentNotificationClose)
          cm.state.currentNotificationClose();
        cm.state.currentNotificationClose = newVal;
      }
      CodeMirror10.defineExtension("openDialog", function(template, callback, options) {
        if (!options)
          options = {};
        closeNotification(this, null);
        var dialog = dialogDiv(this, template, options.bottom);
        var closed = false, me = this;
        function close(newVal) {
          if (typeof newVal == "string") {
            inp.value = newVal;
          } else {
            if (closed)
              return;
            closed = true;
            CodeMirror10.rmClass(dialog.parentNode, "dialog-opened");
            dialog.parentNode.removeChild(dialog);
            me.focus();
            if (options.onClose)
              options.onClose(dialog);
          }
        }
        var inp = dialog.getElementsByTagName("input")[0], button;
        if (inp) {
          inp.focus();
          if (options.value) {
            inp.value = options.value;
            if (options.selectValueOnOpen !== false) {
              inp.select();
            }
          }
          if (options.onInput)
            CodeMirror10.on(inp, "input", function(e) {
              options.onInput(e, inp.value, close);
            });
          if (options.onKeyUp)
            CodeMirror10.on(inp, "keyup", function(e) {
              options.onKeyUp(e, inp.value, close);
            });
          CodeMirror10.on(inp, "keydown", function(e) {
            if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) {
              return;
            }
            if (e.keyCode == 27 || options.closeOnEnter !== false && e.keyCode == 13) {
              inp.blur();
              CodeMirror10.e_stop(e);
              close();
            }
            if (e.keyCode == 13)
              callback(inp.value, e);
          });
          if (options.closeOnBlur !== false)
            CodeMirror10.on(dialog, "focusout", function(evt) {
              if (evt.relatedTarget !== null)
                close();
            });
        } else if (button = dialog.getElementsByTagName("button")[0]) {
          CodeMirror10.on(button, "click", function() {
            close();
            me.focus();
          });
          if (options.closeOnBlur !== false)
            CodeMirror10.on(button, "blur", close);
          button.focus();
        }
        return close;
      });
      CodeMirror10.defineExtension("openConfirm", function(template, callbacks, options) {
        closeNotification(this, null);
        var dialog = dialogDiv(this, template, options && options.bottom);
        var buttons = dialog.getElementsByTagName("button");
        var closed = false, me = this, blurring = 1;
        function close() {
          if (closed)
            return;
          closed = true;
          CodeMirror10.rmClass(dialog.parentNode, "dialog-opened");
          dialog.parentNode.removeChild(dialog);
          me.focus();
        }
        buttons[0].focus();
        for (var i = 0; i < buttons.length; ++i) {
          var b = buttons[i];
          (function(callback) {
            CodeMirror10.on(b, "click", function(e) {
              CodeMirror10.e_preventDefault(e);
              close();
              if (callback)
                callback(me);
            });
          })(callbacks[i]);
          CodeMirror10.on(b, "blur", function() {
            --blurring;
            setTimeout(function() {
              if (blurring <= 0)
                close();
            }, 200);
          });
          CodeMirror10.on(b, "focus", function() {
            ++blurring;
          });
        }
      });
      CodeMirror10.defineExtension("openNotification", function(template, options) {
        closeNotification(this, close);
        var dialog = dialogDiv(this, template, options && options.bottom);
        var closed = false, doneTimer;
        var duration = options && typeof options.duration !== "undefined" ? options.duration : 5e3;
        function close() {
          if (closed)
            return;
          closed = true;
          clearTimeout(doneTimer);
          CodeMirror10.rmClass(dialog.parentNode, "dialog-opened");
          dialog.parentNode.removeChild(dialog);
        }
        CodeMirror10.on(dialog, "click", function(e) {
          CodeMirror10.e_preventDefault(e);
          close();
        });
        if (duration)
          doneTimer = setTimeout(close, duration);
        return close;
      });
    });
  });

  // node_modules/codemirror/addon/search/searchcursor.js
  var require_searchcursor = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      var Pos = CodeMirror10.Pos;
      function regexpFlags(regexp) {
        var flags = regexp.flags;
        return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : "");
      }
      function ensureFlags(regexp, flags) {
        var current = regexpFlags(regexp), target = current;
        for (var i = 0; i < flags.length; i++)
          if (target.indexOf(flags.charAt(i)) == -1)
            target += flags.charAt(i);
        return current == target ? regexp : new RegExp(regexp.source, target);
      }
      function maybeMultiline(regexp) {
        return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source);
      }
      function searchRegexpForward(doc, regexp, start) {
        regexp = ensureFlags(regexp, "g");
        for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
          regexp.lastIndex = ch;
          var string2 = doc.getLine(line), match = regexp.exec(string2);
          if (match)
            return {
              from: Pos(line, match.index),
              to: Pos(line, match.index + match[0].length),
              match
            };
        }
      }
      function searchRegexpForwardMultiline(doc, regexp, start) {
        if (!maybeMultiline(regexp))
          return searchRegexpForward(doc, regexp, start);
        regexp = ensureFlags(regexp, "gm");
        var string2, chunk = 1;
        for (var line = start.line, last = doc.lastLine(); line <= last; ) {
          for (var i = 0; i < chunk; i++) {
            if (line > last)
              break;
            var curLine = doc.getLine(line++);
            string2 = string2 == null ? curLine : string2 + "\n" + curLine;
          }
          chunk = chunk * 2;
          regexp.lastIndex = start.ch;
          var match = regexp.exec(string2);
          if (match) {
            var before = string2.slice(0, match.index).split("\n"), inside = match[0].split("\n");
            var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length;
            return {
              from: Pos(startLine, startCh),
              to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
              match
            };
          }
        }
      }
      function lastMatchIn(string2, regexp, endMargin) {
        var match, from = 0;
        while (from <= string2.length) {
          regexp.lastIndex = from;
          var newMatch = regexp.exec(string2);
          if (!newMatch)
            break;
          var end = newMatch.index + newMatch[0].length;
          if (end > string2.length - endMargin)
            break;
          if (!match || end > match.index + match[0].length)
            match = newMatch;
          from = newMatch.index + 1;
        }
        return match;
      }
      function searchRegexpBackward(doc, regexp, start) {
        regexp = ensureFlags(regexp, "g");
        for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
          var string2 = doc.getLine(line);
          var match = lastMatchIn(string2, regexp, ch < 0 ? 0 : string2.length - ch);
          if (match)
            return {
              from: Pos(line, match.index),
              to: Pos(line, match.index + match[0].length),
              match
            };
        }
      }
      function searchRegexpBackwardMultiline(doc, regexp, start) {
        if (!maybeMultiline(regexp))
          return searchRegexpBackward(doc, regexp, start);
        regexp = ensureFlags(regexp, "gm");
        var string2, chunkSize = 1, endMargin = doc.getLine(start.line).length - start.ch;
        for (var line = start.line, first = doc.firstLine(); line >= first; ) {
          for (var i = 0; i < chunkSize && line >= first; i++) {
            var curLine = doc.getLine(line--);
            string2 = string2 == null ? curLine : curLine + "\n" + string2;
          }
          chunkSize *= 2;
          var match = lastMatchIn(string2, regexp, endMargin);
          if (match) {
            var before = string2.slice(0, match.index).split("\n"), inside = match[0].split("\n");
            var startLine = line + before.length, startCh = before[before.length - 1].length;
            return {
              from: Pos(startLine, startCh),
              to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
              match
            };
          }
        }
      }
      var doFold, noFold;
      if (String.prototype.normalize) {
        doFold = function(str) {
          return str.normalize("NFD").toLowerCase();
        };
        noFold = function(str) {
          return str.normalize("NFD");
        };
      } else {
        doFold = function(str) {
          return str.toLowerCase();
        };
        noFold = function(str) {
          return str;
        };
      }
      function adjustPos(orig, folded, pos, foldFunc) {
        if (orig.length == folded.length)
          return pos;
        for (var min3 = 0, max3 = pos + Math.max(0, orig.length - folded.length); ; ) {
          if (min3 == max3)
            return min3;
          var mid = min3 + max3 >> 1;
          var len = foldFunc(orig.slice(0, mid)).length;
          if (len == pos)
            return mid;
          else if (len > pos)
            max3 = mid;
          else
            min3 = mid + 1;
        }
      }
      function searchStringForward(doc, query, start, caseFold) {
        if (!query.length)
          return null;
        var fold = caseFold ? doFold : noFold;
        var lines = fold(query).split(/\r|\n\r?/);
        search:
          for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
            var orig = doc.getLine(line).slice(ch), string2 = fold(orig);
            if (lines.length == 1) {
              var found = string2.indexOf(lines[0]);
              if (found == -1)
                continue search;
              var start = adjustPos(orig, string2, found, fold) + ch;
              return {
                from: Pos(line, adjustPos(orig, string2, found, fold) + ch),
                to: Pos(line, adjustPos(orig, string2, found + lines[0].length, fold) + ch)
              };
            } else {
              var cutFrom = string2.length - lines[0].length;
              if (string2.slice(cutFrom) != lines[0])
                continue search;
              for (var i = 1; i < lines.length - 1; i++)
                if (fold(doc.getLine(line + i)) != lines[i])
                  continue search;
              var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1];
              if (endString.slice(0, lastLine.length) != lastLine)
                continue search;
              return {
                from: Pos(line, adjustPos(orig, string2, cutFrom, fold) + ch),
                to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))
              };
            }
          }
      }
      function searchStringBackward(doc, query, start, caseFold) {
        if (!query.length)
          return null;
        var fold = caseFold ? doFold : noFold;
        var lines = fold(query).split(/\r|\n\r?/);
        search:
          for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
            var orig = doc.getLine(line);
            if (ch > -1)
              orig = orig.slice(0, ch);
            var string2 = fold(orig);
            if (lines.length == 1) {
              var found = string2.lastIndexOf(lines[0]);
              if (found == -1)
                continue search;
              return {
                from: Pos(line, adjustPos(orig, string2, found, fold)),
                to: Pos(line, adjustPos(orig, string2, found + lines[0].length, fold))
              };
            } else {
              var lastLine = lines[lines.length - 1];
              if (string2.slice(0, lastLine.length) != lastLine)
                continue search;
              for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)
                if (fold(doc.getLine(start + i)) != lines[i])
                  continue search;
              var top2 = doc.getLine(line + 1 - lines.length), topString = fold(top2);
              if (topString.slice(topString.length - lines[0].length) != lines[0])
                continue search;
              return {
                from: Pos(line + 1 - lines.length, adjustPos(top2, topString, top2.length - lines[0].length, fold)),
                to: Pos(line, adjustPos(orig, string2, lastLine.length, fold))
              };
            }
          }
      }
      function SearchCursor(doc, query, pos, options) {
        this.atOccurrence = false;
        this.doc = doc;
        pos = pos ? doc.clipPos(pos) : Pos(0, 0);
        this.pos = {from: pos, to: pos};
        var caseFold;
        if (typeof options == "object") {
          caseFold = options.caseFold;
        } else {
          caseFold = options;
          options = null;
        }
        if (typeof query == "string") {
          if (caseFold == null)
            caseFold = false;
          this.matches = function(reverse, pos2) {
            return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos2, caseFold);
          };
        } else {
          query = ensureFlags(query, "gm");
          if (!options || options.multiline !== false)
            this.matches = function(reverse, pos2) {
              return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos2);
            };
          else
            this.matches = function(reverse, pos2) {
              return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos2);
            };
        }
      }
      SearchCursor.prototype = {
        findNext: function() {
          return this.find(false);
        },
        findPrevious: function() {
          return this.find(true);
        },
        find: function(reverse) {
          var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to));
          while (result && CodeMirror10.cmpPos(result.from, result.to) == 0) {
            if (reverse) {
              if (result.from.ch)
                result.from = Pos(result.from.line, result.from.ch - 1);
              else if (result.from.line == this.doc.firstLine())
                result = null;
              else
                result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)));
            } else {
              if (result.to.ch < this.doc.getLine(result.to.line).length)
                result.to = Pos(result.to.line, result.to.ch + 1);
              else if (result.to.line == this.doc.lastLine())
                result = null;
              else
                result = this.matches(reverse, Pos(result.to.line + 1, 0));
            }
          }
          if (result) {
            this.pos = result;
            this.atOccurrence = true;
            return this.pos.match || true;
          } else {
            var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0);
            this.pos = {from: end, to: end};
            return this.atOccurrence = false;
          }
        },
        from: function() {
          if (this.atOccurrence)
            return this.pos.from;
        },
        to: function() {
          if (this.atOccurrence)
            return this.pos.to;
        },
        replace: function(newText, origin) {
          if (!this.atOccurrence)
            return;
          var lines = CodeMirror10.splitLines(newText);
          this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
          this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
        }
      };
      CodeMirror10.defineExtension("getSearchCursor", function(query, pos, caseFold) {
        return new SearchCursor(this.doc, query, pos, caseFold);
      });
      CodeMirror10.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
        return new SearchCursor(this, query, pos, caseFold);
      });
      CodeMirror10.defineExtension("selectMatches", function(query, caseFold) {
        var ranges = [];
        var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
        while (cur.findNext()) {
          if (CodeMirror10.cmpPos(cur.to(), this.getCursor("to")) > 0)
            break;
          ranges.push({anchor: cur.from(), head: cur.to()});
        }
        if (ranges.length)
          this.setSelections(ranges, 0);
      });
    });
  });

  // node_modules/codemirror/addon/search/search.js
  var require_search = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror(), require_searchcursor(), require_dialog());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      CodeMirror10.defineOption("search", {bottom: false});
      function searchOverlay(query, caseInsensitive) {
        if (typeof query == "string")
          query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
        else if (!query.global)
          query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
        return {token: function(stream) {
          query.lastIndex = stream.pos;
          var match = query.exec(stream.string);
          if (match && match.index == stream.pos) {
            stream.pos += match[0].length || 1;
            return "searching";
          } else if (match) {
            stream.pos = match.index;
          } else {
            stream.skipToEnd();
          }
        }};
      }
      function SearchState() {
        this.posFrom = this.posTo = this.lastQuery = this.query = null;
        this.overlay = null;
      }
      function getSearchState(cm) {
        return cm.state.search || (cm.state.search = new SearchState());
      }
      function queryCaseInsensitive(query) {
        return typeof query == "string" && query == query.toLowerCase();
      }
      function getSearchCursor(cm, query, pos) {
        return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
      }
      function persistentDialog(cm, text2, deflt, onEnter, onKeyDown) {
        cm.openDialog(text2, onEnter, {
          value: deflt,
          selectValueOnOpen: true,
          closeOnEnter: false,
          onClose: function() {
            clearSearch(cm);
          },
          onKeyDown,
          bottom: cm.options.search.bottom
        });
      }
      function dialog(cm, text2, shortText, deflt, f) {
        if (cm.openDialog)
          cm.openDialog(text2, f, {value: deflt, selectValueOnOpen: true, bottom: cm.options.search.bottom});
        else
          f(prompt(shortText, deflt));
      }
      function confirmDialog(cm, text2, shortText, fs) {
        if (cm.openConfirm)
          cm.openConfirm(text2, fs);
        else if (confirm(shortText))
          fs[0]();
      }
      function parseString(string2) {
        return string2.replace(/\\([nrt\\])/g, function(match, ch) {
          if (ch == "n")
            return "\n";
          if (ch == "r")
            return "\r";
          if (ch == "t")
            return "	";
          if (ch == "\\")
            return "\\";
          return match;
        });
      }
      function parseQuery(query) {
        var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
        if (isRE) {
          try {
            query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i");
          } catch (e) {
          }
        } else {
          query = parseString(query);
        }
        if (typeof query == "string" ? query == "" : query.test(""))
          query = /x^/;
        return query;
      }
      function startSearch(cm, state, query) {
        state.queryText = query;
        state.query = parseQuery(query);
        cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
        state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
        cm.addOverlay(state.overlay);
        if (cm.showMatchesOnScrollbar) {
          if (state.annotate) {
            state.annotate.clear();
            state.annotate = null;
          }
          state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
        }
      }
      function doSearch(cm, rev, persistent, immediate) {
        var state = getSearchState(cm);
        if (state.query)
          return findNext(cm, rev);
        var q = cm.getSelection() || state.lastQuery;
        if (q instanceof RegExp && q.source == "x^")
          q = null;
        if (persistent && cm.openDialog) {
          var hiding = null;
          var searchNext = function(query, event) {
            CodeMirror10.e_stop(event);
            if (!query)
              return;
            if (query != state.queryText) {
              startSearch(cm, state, query);
              state.posFrom = state.posTo = cm.getCursor();
            }
            if (hiding)
              hiding.style.opacity = 1;
            findNext(cm, event.shiftKey, function(_2, to) {
              var dialog2;
              if (to.line < 3 && document.querySelector && (dialog2 = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && dialog2.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
                (hiding = dialog2).style.opacity = 0.4;
            });
          };
          persistentDialog(cm, getQueryDialog(cm), q, searchNext, function(event, query) {
            var keyName = CodeMirror10.keyName(event);
            var extra = cm.getOption("extraKeys"), cmd = extra && extra[keyName] || CodeMirror10.keyMap[cm.getOption("keyMap")][keyName];
            if (cmd == "findNext" || cmd == "findPrev" || cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
              CodeMirror10.e_stop(event);
              startSearch(cm, getSearchState(cm), query);
              cm.execCommand(cmd);
            } else if (cmd == "find" || cmd == "findPersistent") {
              CodeMirror10.e_stop(event);
              searchNext(query, event);
            }
          });
          if (immediate && q) {
            startSearch(cm, state, q);
            findNext(cm, rev);
          }
        } else {
          dialog(cm, getQueryDialog(cm), "Search for:", q, function(query) {
            if (query && !state.query)
              cm.operation(function() {
                startSearch(cm, state, query);
                state.posFrom = state.posTo = cm.getCursor();
                findNext(cm, rev);
              });
          });
        }
      }
      function findNext(cm, rev, callback) {
        cm.operation(function() {
          var state = getSearchState(cm);
          var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
          if (!cursor.find(rev)) {
            cursor = getSearchCursor(cm, state.query, rev ? CodeMirror10.Pos(cm.lastLine()) : CodeMirror10.Pos(cm.firstLine(), 0));
            if (!cursor.find(rev))
              return;
          }
          cm.setSelection(cursor.from(), cursor.to());
          cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
          state.posFrom = cursor.from();
          state.posTo = cursor.to();
          if (callback)
            callback(cursor.from(), cursor.to());
        });
      }
      function clearSearch(cm) {
        cm.operation(function() {
          var state = getSearchState(cm);
          state.lastQuery = state.query;
          if (!state.query)
            return;
          state.query = state.queryText = null;
          cm.removeOverlay(state.overlay);
          if (state.annotate) {
            state.annotate.clear();
            state.annotate = null;
          }
        });
      }
      function getQueryDialog(cm) {
        return '<span class="CodeMirror-search-label">' + cm.phrase("Search:") + '</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use /re/ syntax for regexp search)") + "</span>";
      }
      function getReplaceQueryDialog(cm) {
        return ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use /re/ syntax for regexp search)") + "</span>";
      }
      function getReplacementQueryDialog(cm) {
        return '<span class="CodeMirror-search-label">' + cm.phrase("With:") + '</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
      }
      function getDoReplaceConfirm(cm) {
        return '<span class="CodeMirror-search-label">' + cm.phrase("Replace?") + "</span> <button>" + cm.phrase("Yes") + "</button> <button>" + cm.phrase("No") + "</button> <button>" + cm.phrase("All") + "</button> <button>" + cm.phrase("Stop") + "</button> ";
      }
      function replaceAll(cm, query, text2) {
        cm.operation(function() {
          for (var cursor = getSearchCursor(cm, query); cursor.findNext(); ) {
            if (typeof query != "string") {
              var match = cm.getRange(cursor.from(), cursor.to()).match(query);
              cursor.replace(text2.replace(/\$(\d)/g, function(_2, i) {
                return match[i];
              }));
            } else
              cursor.replace(text2);
          }
        });
      }
      function replace(cm, all) {
        if (cm.getOption("readOnly"))
          return;
        var query = cm.getSelection() || getSearchState(cm).lastQuery;
        var dialogText = '<span class="CodeMirror-search-label">' + (all ? cm.phrase("Replace all:") : cm.phrase("Replace:")) + "</span>";
        dialog(cm, dialogText + getReplaceQueryDialog(cm), dialogText, query, function(query2) {
          if (!query2)
            return;
          query2 = parseQuery(query2);
          dialog(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function(text2) {
            text2 = parseString(text2);
            if (all) {
              replaceAll(cm, query2, text2);
            } else {
              clearSearch(cm);
              var cursor = getSearchCursor(cm, query2, cm.getCursor("from"));
              var advance = function() {
                var start = cursor.from(), match;
                if (!(match = cursor.findNext())) {
                  cursor = getSearchCursor(cm, query2);
                  if (!(match = cursor.findNext()) || start && cursor.from().line == start.line && cursor.from().ch == start.ch)
                    return;
                }
                cm.setSelection(cursor.from(), cursor.to());
                cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
                confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"), [
                  function() {
                    doReplace(match);
                  },
                  advance,
                  function() {
                    replaceAll(cm, query2, text2);
                  }
                ]);
              };
              var doReplace = function(match) {
                cursor.replace(typeof query2 == "string" ? text2 : text2.replace(/\$(\d)/g, function(_2, i) {
                  return match[i];
                }));
                advance();
              };
              advance();
            }
          });
        });
      }
      CodeMirror10.commands.find = function(cm) {
        clearSearch(cm);
        doSearch(cm);
      };
      CodeMirror10.commands.findPersistent = function(cm) {
        clearSearch(cm);
        doSearch(cm, false, true);
      };
      CodeMirror10.commands.findPersistentNext = function(cm) {
        doSearch(cm, false, true, true);
      };
      CodeMirror10.commands.findPersistentPrev = function(cm) {
        doSearch(cm, true, true, true);
      };
      CodeMirror10.commands.findNext = doSearch;
      CodeMirror10.commands.findPrev = function(cm) {
        doSearch(cm, true);
      };
      CodeMirror10.commands.clearSearch = clearSearch;
      CodeMirror10.commands.replace = replace;
      CodeMirror10.commands.replaceAll = function(cm) {
        replace(cm, true);
      };
    });
  });

  // node_modules/codemirror/addon/display/rulers.js
  var require_rulers = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      CodeMirror10.defineOption("rulers", false, function(cm, val) {
        if (cm.state.rulerDiv) {
          cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv);
          cm.state.rulerDiv = null;
          cm.off("refresh", drawRulers);
        }
        if (val && val.length) {
          cm.state.rulerDiv = cm.display.lineSpace.parentElement.insertBefore(document.createElement("div"), cm.display.lineSpace);
          cm.state.rulerDiv.className = "CodeMirror-rulers";
          drawRulers(cm);
          cm.on("refresh", drawRulers);
        }
      });
      function drawRulers(cm) {
        cm.state.rulerDiv.textContent = "";
        var val = cm.getOption("rulers");
        var cw = cm.defaultCharWidth();
        var left2 = cm.charCoords(CodeMirror10.Pos(cm.firstLine(), 0), "div").left;
        cm.state.rulerDiv.style.minHeight = cm.display.scroller.offsetHeight + 30 + "px";
        for (var i = 0; i < val.length; i++) {
          var elt = document.createElement("div");
          elt.className = "CodeMirror-ruler";
          var col, conf = val[i];
          if (typeof conf == "number") {
            col = conf;
          } else {
            col = conf.column;
            if (conf.className)
              elt.className += " " + conf.className;
            if (conf.color)
              elt.style.borderColor = conf.color;
            if (conf.lineStyle)
              elt.style.borderLeftStyle = conf.lineStyle;
            if (conf.width)
              elt.style.borderLeftWidth = conf.width;
          }
          elt.style.left = left2 + col * cw + "px";
          cm.state.rulerDiv.appendChild(elt);
        }
      }
    });
  });

  // node_modules/codemirror/addon/edit/trailingspace.js
  var require_trailingspace = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      CodeMirror10.defineOption("showTrailingSpace", false, function(cm, val, prev) {
        if (prev == CodeMirror10.Init)
          prev = false;
        if (prev && !val)
          cm.removeOverlay("trailingspace");
        else if (!prev && val)
          cm.addOverlay({
            token: function(stream) {
              for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {
              }
              if (i > stream.pos) {
                stream.pos = i;
                return null;
              }
              stream.pos = l;
              return "trailingspace";
            },
            name: "trailingspace"
          });
      });
    });
  });

  // node_modules/codemirror/addon/fold/foldcode.js
  var require_foldcode = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      function doFold(cm, pos, options, force) {
        if (options && options.call) {
          var finder = options;
          options = null;
        } else {
          var finder = getOption(cm, options, "rangeFinder");
        }
        if (typeof pos == "number")
          pos = CodeMirror10.Pos(pos, 0);
        var minSize = getOption(cm, options, "minFoldSize");
        function getRange(allowFolded) {
          var range2 = finder(cm, pos);
          if (!range2 || range2.to.line - range2.from.line < minSize)
            return null;
          var marks = cm.findMarksAt(range2.from);
          for (var i = 0; i < marks.length; ++i) {
            if (marks[i].__isFold && force !== "fold") {
              if (!allowFolded)
                return null;
              range2.cleared = true;
              marks[i].clear();
            }
          }
          return range2;
        }
        var range = getRange(true);
        if (getOption(cm, options, "scanUp"))
          while (!range && pos.line > cm.firstLine()) {
            pos = CodeMirror10.Pos(pos.line - 1, 0);
            range = getRange(false);
          }
        if (!range || range.cleared || force === "unfold")
          return;
        var myWidget = makeWidget(cm, options, range);
        CodeMirror10.on(myWidget, "mousedown", function(e) {
          myRange.clear();
          CodeMirror10.e_preventDefault(e);
        });
        var myRange = cm.markText(range.from, range.to, {
          replacedWith: myWidget,
          clearOnEnter: getOption(cm, options, "clearOnEnter"),
          __isFold: true
        });
        myRange.on("clear", function(from, to) {
          CodeMirror10.signal(cm, "unfold", cm, from, to);
        });
        CodeMirror10.signal(cm, "fold", cm, range.from, range.to);
      }
      function makeWidget(cm, options, range) {
        var widget = getOption(cm, options, "widget");
        if (typeof widget == "function") {
          widget = widget(range.from, range.to);
        }
        if (typeof widget == "string") {
          var text2 = document.createTextNode(widget);
          widget = document.createElement("span");
          widget.appendChild(text2);
          widget.className = "CodeMirror-foldmarker";
        } else if (widget) {
          widget = widget.cloneNode(true);
        }
        return widget;
      }
      CodeMirror10.newFoldFunction = function(rangeFinder, widget) {
        return function(cm, pos) {
          doFold(cm, pos, {rangeFinder, widget});
        };
      };
      CodeMirror10.defineExtension("foldCode", function(pos, options, force) {
        doFold(this, pos, options, force);
      });
      CodeMirror10.defineExtension("isFolded", function(pos) {
        var marks = this.findMarksAt(pos);
        for (var i = 0; i < marks.length; ++i)
          if (marks[i].__isFold)
            return true;
      });
      CodeMirror10.commands.toggleFold = function(cm) {
        cm.foldCode(cm.getCursor());
      };
      CodeMirror10.commands.fold = function(cm) {
        cm.foldCode(cm.getCursor(), null, "fold");
      };
      CodeMirror10.commands.unfold = function(cm) {
        cm.foldCode(cm.getCursor(), null, "unfold");
      };
      CodeMirror10.commands.foldAll = function(cm) {
        cm.operation(function() {
          for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
            cm.foldCode(CodeMirror10.Pos(i, 0), null, "fold");
        });
      };
      CodeMirror10.commands.unfoldAll = function(cm) {
        cm.operation(function() {
          for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
            cm.foldCode(CodeMirror10.Pos(i, 0), null, "unfold");
        });
      };
      CodeMirror10.registerHelper("fold", "combine", function() {
        var funcs = Array.prototype.slice.call(arguments, 0);
        return function(cm, start) {
          for (var i = 0; i < funcs.length; ++i) {
            var found = funcs[i](cm, start);
            if (found)
              return found;
          }
        };
      });
      CodeMirror10.registerHelper("fold", "auto", function(cm, start) {
        var helpers = cm.getHelpers(start, "fold");
        for (var i = 0; i < helpers.length; i++) {
          var cur = helpers[i](cm, start);
          if (cur)
            return cur;
        }
      });
      var defaultOptions = {
        rangeFinder: CodeMirror10.fold.auto,
        widget: "\u2194",
        minFoldSize: 0,
        scanUp: false,
        clearOnEnter: true
      };
      CodeMirror10.defineOption("foldOptions", null);
      function getOption(cm, options, name) {
        if (options && options[name] !== void 0)
          return options[name];
        var editorOptions = cm.options.foldOptions;
        if (editorOptions && editorOptions[name] !== void 0)
          return editorOptions[name];
        return defaultOptions[name];
      }
      CodeMirror10.defineExtension("foldOption", function(options, name) {
        return getOption(this, options, name);
      });
    });
  });

  // node_modules/codemirror/addon/fold/foldgutter.js
  var require_foldgutter = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror(), require_foldcode());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror", "./foldcode"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      CodeMirror10.defineOption("foldGutter", false, function(cm, val, old) {
        if (old && old != CodeMirror10.Init) {
          cm.clearGutter(cm.state.foldGutter.options.gutter);
          cm.state.foldGutter = null;
          cm.off("gutterClick", onGutterClick);
          cm.off("changes", onChange);
          cm.off("viewportChange", onViewportChange);
          cm.off("fold", onFold);
          cm.off("unfold", onFold);
          cm.off("swapDoc", onChange);
        }
        if (val) {
          cm.state.foldGutter = new State(parseOptions(val));
          updateInViewport(cm);
          cm.on("gutterClick", onGutterClick);
          cm.on("changes", onChange);
          cm.on("viewportChange", onViewportChange);
          cm.on("fold", onFold);
          cm.on("unfold", onFold);
          cm.on("swapDoc", onChange);
        }
      });
      var Pos = CodeMirror10.Pos;
      function State(options) {
        this.options = options;
        this.from = this.to = 0;
      }
      function parseOptions(opts) {
        if (opts === true)
          opts = {};
        if (opts.gutter == null)
          opts.gutter = "CodeMirror-foldgutter";
        if (opts.indicatorOpen == null)
          opts.indicatorOpen = "CodeMirror-foldgutter-open";
        if (opts.indicatorFolded == null)
          opts.indicatorFolded = "CodeMirror-foldgutter-folded";
        return opts;
      }
      function isFolded(cm, line) {
        var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0));
        for (var i = 0; i < marks.length; ++i) {
          if (marks[i].__isFold) {
            var fromPos = marks[i].find(-1);
            if (fromPos && fromPos.line === line)
              return marks[i];
          }
        }
      }
      function marker(spec) {
        if (typeof spec == "string") {
          var elt = document.createElement("div");
          elt.className = spec + " CodeMirror-guttermarker-subtle";
          return elt;
        } else {
          return spec.cloneNode(true);
        }
      }
      function updateFoldInfo(cm, from, to) {
        var opts = cm.state.foldGutter.options, cur = from - 1;
        var minSize = cm.foldOption(opts, "minFoldSize");
        var func = cm.foldOption(opts, "rangeFinder");
        var clsFolded = typeof opts.indicatorFolded == "string" && classTest(opts.indicatorFolded);
        var clsOpen = typeof opts.indicatorOpen == "string" && classTest(opts.indicatorOpen);
        cm.eachLine(from, to, function(line) {
          ++cur;
          var mark = null;
          var old = line.gutterMarkers;
          if (old)
            old = old[opts.gutter];
          if (isFolded(cm, cur)) {
            if (clsFolded && old && clsFolded.test(old.className))
              return;
            mark = marker(opts.indicatorFolded);
          } else {
            var pos = Pos(cur, 0);
            var range = func && func(cm, pos);
            if (range && range.to.line - range.from.line >= minSize) {
              if (clsOpen && old && clsOpen.test(old.className))
                return;
              mark = marker(opts.indicatorOpen);
            }
          }
          if (!mark && !old)
            return;
          cm.setGutterMarker(line, opts.gutter, mark);
        });
      }
      function classTest(cls) {
        return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*");
      }
      function updateInViewport(cm) {
        var vp = cm.getViewport(), state = cm.state.foldGutter;
        if (!state)
          return;
        cm.operation(function() {
          updateFoldInfo(cm, vp.from, vp.to);
        });
        state.from = vp.from;
        state.to = vp.to;
      }
      function onGutterClick(cm, line, gutter) {
        var state = cm.state.foldGutter;
        if (!state)
          return;
        var opts = state.options;
        if (gutter != opts.gutter)
          return;
        var folded = isFolded(cm, line);
        if (folded)
          folded.clear();
        else
          cm.foldCode(Pos(line, 0), opts);
      }
      function onChange(cm) {
        var state = cm.state.foldGutter;
        if (!state)
          return;
        var opts = state.options;
        state.from = state.to = 0;
        clearTimeout(state.changeUpdate);
        state.changeUpdate = setTimeout(function() {
          updateInViewport(cm);
        }, opts.foldOnChangeTimeSpan || 600);
      }
      function onViewportChange(cm) {
        var state = cm.state.foldGutter;
        if (!state)
          return;
        var opts = state.options;
        clearTimeout(state.changeUpdate);
        state.changeUpdate = setTimeout(function() {
          var vp = cm.getViewport();
          if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
            updateInViewport(cm);
          } else {
            cm.operation(function() {
              if (vp.from < state.from) {
                updateFoldInfo(cm, vp.from, state.from);
                state.from = vp.from;
              }
              if (vp.to > state.to) {
                updateFoldInfo(cm, state.to, vp.to);
                state.to = vp.to;
              }
            });
          }
        }, opts.updateViewportTimeSpan || 400);
      }
      function onFold(cm, from) {
        var state = cm.state.foldGutter;
        if (!state)
          return;
        var line = from.line;
        if (line >= state.from && line < state.to)
          updateFoldInfo(cm, line, line + 1);
      }
    });
  });

  // node_modules/codemirror/addon/hint/show-hint.js
  var require_show_hint = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      var HINT_ELEMENT_CLASS = "CodeMirror-hint";
      var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
      CodeMirror10.showHint = function(cm, getHints, options) {
        if (!getHints)
          return cm.showHint(options);
        if (options && options.async)
          getHints.async = true;
        var newOpts = {hint: getHints};
        if (options)
          for (var prop in options)
            newOpts[prop] = options[prop];
        return cm.showHint(newOpts);
      };
      CodeMirror10.defineExtension("showHint", function(options) {
        options = parseOptions(this, this.getCursor("start"), options);
        var selections = this.listSelections();
        if (selections.length > 1)
          return;
        if (this.somethingSelected()) {
          if (!options.hint.supportsSelection)
            return;
          for (var i = 0; i < selections.length; i++)
            if (selections[i].head.line != selections[i].anchor.line)
              return;
        }
        if (this.state.completionActive)
          this.state.completionActive.close();
        var completion = this.state.completionActive = new Completion(this, options);
        if (!completion.options.hint)
          return;
        CodeMirror10.signal(this, "startCompletion", this);
        completion.update(true);
      });
      CodeMirror10.defineExtension("closeHint", function() {
        if (this.state.completionActive)
          this.state.completionActive.close();
      });
      function Completion(cm, options) {
        this.cm = cm;
        this.options = options;
        this.widget = null;
        this.debounce = 0;
        this.tick = 0;
        this.startPos = this.cm.getCursor("start");
        this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
        var self3 = this;
        cm.on("cursorActivity", this.activityFunc = function() {
          self3.cursorActivity();
        });
      }
      var requestAnimationFrame2 = window.requestAnimationFrame || function(fn) {
        return setTimeout(fn, 1e3 / 60);
      };
      var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
      Completion.prototype = {
        close: function() {
          if (!this.active())
            return;
          this.cm.state.completionActive = null;
          this.tick = null;
          this.cm.off("cursorActivity", this.activityFunc);
          if (this.widget && this.data)
            CodeMirror10.signal(this.data, "close");
          if (this.widget)
            this.widget.close();
          CodeMirror10.signal(this.cm, "endCompletion", this.cm);
        },
        active: function() {
          return this.cm.state.completionActive == this;
        },
        pick: function(data, i) {
          var completion = data.list[i], self3 = this;
          this.cm.operation(function() {
            if (completion.hint)
              completion.hint(self3.cm, data, completion);
            else
              self3.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete");
            CodeMirror10.signal(data, "pick", completion);
            self3.cm.scrollIntoView();
          });
          if (this.options.closeOnPick) {
            this.close();
          }
        },
        cursorActivity: function() {
          if (this.debounce) {
            cancelAnimationFrame(this.debounce);
            this.debounce = 0;
          }
          var identStart = this.startPos;
          if (this.data) {
            identStart = this.data.from;
          }
          var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
          if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < identStart.ch || this.cm.somethingSelected() || (!pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
            if (this.options.closeOnCursorActivity) {
              this.close();
            }
          } else {
            var self3 = this;
            this.debounce = requestAnimationFrame2(function() {
              self3.update();
            });
            if (this.widget)
              this.widget.disable();
          }
        },
        update: function(first) {
          if (this.tick == null)
            return;
          var self3 = this, myTick = ++this.tick;
          fetchHints(this.options.hint, this.cm, this.options, function(data) {
            if (self3.tick == myTick)
              self3.finishUpdate(data, first);
          });
        },
        finishUpdate: function(data, first) {
          if (this.data)
            CodeMirror10.signal(this.data, "update");
          var picked = this.widget && this.widget.picked || first && this.options.completeSingle;
          if (this.widget)
            this.widget.close();
          this.data = data;
          if (data && data.list.length) {
            if (picked && data.list.length == 1) {
              this.pick(data, 0);
            } else {
              this.widget = new Widget(this, data);
              CodeMirror10.signal(data, "shown");
            }
          }
        }
      };
      function parseOptions(cm, pos, options) {
        var editor = cm.options.hintOptions;
        var out = {};
        for (var prop in defaultOptions)
          out[prop] = defaultOptions[prop];
        if (editor) {
          for (var prop in editor)
            if (editor[prop] !== void 0)
              out[prop] = editor[prop];
        }
        if (options) {
          for (var prop in options)
            if (options[prop] !== void 0)
              out[prop] = options[prop];
        }
        if (out.hint.resolve)
          out.hint = out.hint.resolve(cm, pos);
        return out;
      }
      function getText(completion) {
        if (typeof completion == "string")
          return completion;
        else
          return completion.text;
      }
      function buildKeyMap(completion, handle) {
        var baseMap = {
          Up: function() {
            handle.moveFocus(-1);
          },
          Down: function() {
            handle.moveFocus(1);
          },
          PageUp: function() {
            handle.moveFocus(-handle.menuSize() + 1, true);
          },
          PageDown: function() {
            handle.moveFocus(handle.menuSize() - 1, true);
          },
          Home: function() {
            handle.setFocus(0);
          },
          End: function() {
            handle.setFocus(handle.length - 1);
          },
          Enter: handle.pick,
          Tab: handle.pick,
          Esc: handle.close
        };
        var mac = /Mac/.test(navigator.platform);
        if (mac) {
          baseMap["Ctrl-P"] = function() {
            handle.moveFocus(-1);
          };
          baseMap["Ctrl-N"] = function() {
            handle.moveFocus(1);
          };
        }
        var custom2 = completion.options.customKeys;
        var ourMap = custom2 ? {} : baseMap;
        function addBinding(key2, val) {
          var bound;
          if (typeof val != "string")
            bound = function(cm) {
              return val(cm, handle);
            };
          else if (baseMap.hasOwnProperty(val))
            bound = baseMap[val];
          else
            bound = val;
          ourMap[key2] = bound;
        }
        if (custom2) {
          for (var key in custom2)
            if (custom2.hasOwnProperty(key))
              addBinding(key, custom2[key]);
        }
        var extra = completion.options.extraKeys;
        if (extra) {
          for (var key in extra)
            if (extra.hasOwnProperty(key))
              addBinding(key, extra[key]);
        }
        return ourMap;
      }
      function getHintElement(hintsElement, el) {
        while (el && el != hintsElement) {
          if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement)
            return el;
          el = el.parentNode;
        }
      }
      function Widget(completion, data) {
        this.completion = completion;
        this.data = data;
        this.picked = false;
        var widget = this, cm = completion.cm;
        var ownerDocument = cm.getInputField().ownerDocument;
        var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;
        var hints = this.hints = ownerDocument.createElement("ul");
        var theme = completion.cm.options.theme;
        hints.className = "CodeMirror-hints " + theme;
        this.selectedHint = data.selectedHint || 0;
        var completions = data.list;
        for (var i = 0; i < completions.length; ++i) {
          var elt = hints.appendChild(ownerDocument.createElement("li")), cur = completions[i];
          var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
          if (cur.className != null)
            className = cur.className + " " + className;
          elt.className = className;
          if (cur.render)
            cur.render(elt, data, cur);
          else
            elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));
          elt.hintId = i;
        }
        var container = completion.options.container || ownerDocument.body;
        var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
        var left2 = pos.left, top2 = pos.bottom, below = true;
        var offsetLeft = 0, offsetTop = 0;
        if (container !== ownerDocument.body) {
          var isContainerPositioned = ["absolute", "relative", "fixed"].indexOf(parentWindow.getComputedStyle(container).position) !== -1;
          var offsetParent = isContainerPositioned ? container : container.offsetParent;
          var offsetParentPosition = offsetParent.getBoundingClientRect();
          var bodyPosition = ownerDocument.body.getBoundingClientRect();
          offsetLeft = offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft;
          offsetTop = offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop;
        }
        hints.style.left = left2 - offsetLeft + "px";
        hints.style.top = top2 - offsetTop + "px";
        var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);
        var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);
        container.appendChild(hints);
        var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect();
        var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false;
        var startScroll;
        setTimeout(function() {
          startScroll = cm.getScrollInfo();
        });
        var overlapY = box.bottom - winH;
        if (overlapY > 0) {
          var height4 = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
          if (curTop - height4 > 0) {
            hints.style.top = (top2 = pos.top - height4 - offsetTop) + "px";
            below = false;
          } else if (height4 > winH) {
            hints.style.height = winH - 5 + "px";
            hints.style.top = (top2 = pos.bottom - box.top - offsetTop) + "px";
            var cursor = cm.getCursor();
            if (data.from.ch != cursor.ch) {
              pos = cm.cursorCoords(cursor);
              hints.style.left = (left2 = pos.left - offsetLeft) + "px";
              box = hints.getBoundingClientRect();
            }
          }
        }
        var overlapX = box.right - winW;
        if (overlapX > 0) {
          if (box.right - box.left > winW) {
            hints.style.width = winW - 5 + "px";
            overlapX -= box.right - box.left - winW;
          }
          hints.style.left = (left2 = pos.left - overlapX - offsetLeft) + "px";
        }
        if (scrolls)
          for (var node = hints.firstChild; node; node = node.nextSibling)
            node.style.paddingRight = cm.display.nativeBarWidth + "px";
        cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
          moveFocus: function(n, avoidWrap) {
            widget.changeActive(widget.selectedHint + n, avoidWrap);
          },
          setFocus: function(n) {
            widget.changeActive(n);
          },
          menuSize: function() {
            return widget.screenAmount();
          },
          length: completions.length,
          close: function() {
            completion.close();
          },
          pick: function() {
            widget.pick();
          },
          data
        }));
        if (completion.options.closeOnUnfocus) {
          var closingOnBlur;
          cm.on("blur", this.onBlur = function() {
            closingOnBlur = setTimeout(function() {
              completion.close();
            }, 100);
          });
          cm.on("focus", this.onFocus = function() {
            clearTimeout(closingOnBlur);
          });
        }
        cm.on("scroll", this.onScroll = function() {
          var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
          var newTop = top2 + startScroll.top - curScroll.top;
          var point2 = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
          if (!below)
            point2 += hints.offsetHeight;
          if (point2 <= editor.top || point2 >= editor.bottom)
            return completion.close();
          hints.style.top = newTop + "px";
          hints.style.left = left2 + startScroll.left - curScroll.left + "px";
        });
        CodeMirror10.on(hints, "dblclick", function(e) {
          var t = getHintElement(hints, e.target || e.srcElement);
          if (t && t.hintId != null) {
            widget.changeActive(t.hintId);
            widget.pick();
          }
        });
        CodeMirror10.on(hints, "click", function(e) {
          var t = getHintElement(hints, e.target || e.srcElement);
          if (t && t.hintId != null) {
            widget.changeActive(t.hintId);
            if (completion.options.completeOnSingleClick)
              widget.pick();
          }
        });
        CodeMirror10.on(hints, "mousedown", function() {
          setTimeout(function() {
            cm.focus();
          }, 20);
        });
        var selectedHintRange = this.getSelectedHintRange();
        if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) {
          this.scrollToActive();
        }
        CodeMirror10.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
        return true;
      }
      Widget.prototype = {
        close: function() {
          if (this.completion.widget != this)
            return;
          this.completion.widget = null;
          this.hints.parentNode.removeChild(this.hints);
          this.completion.cm.removeKeyMap(this.keyMap);
          var cm = this.completion.cm;
          if (this.completion.options.closeOnUnfocus) {
            cm.off("blur", this.onBlur);
            cm.off("focus", this.onFocus);
          }
          cm.off("scroll", this.onScroll);
        },
        disable: function() {
          this.completion.cm.removeKeyMap(this.keyMap);
          var widget = this;
          this.keyMap = {Enter: function() {
            widget.picked = true;
          }};
          this.completion.cm.addKeyMap(this.keyMap);
        },
        pick: function() {
          this.completion.pick(this.data, this.selectedHint);
        },
        changeActive: function(i, avoidWrap) {
          if (i >= this.data.list.length)
            i = avoidWrap ? this.data.list.length - 1 : 0;
          else if (i < 0)
            i = avoidWrap ? 0 : this.data.list.length - 1;
          if (this.selectedHint == i)
            return;
          var node = this.hints.childNodes[this.selectedHint];
          if (node)
            node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
          node = this.hints.childNodes[this.selectedHint = i];
          node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
          this.scrollToActive();
          CodeMirror10.signal(this.data, "select", this.data.list[this.selectedHint], node);
        },
        scrollToActive: function() {
          var selectedHintRange = this.getSelectedHintRange();
          var node1 = this.hints.childNodes[selectedHintRange.from];
          var node2 = this.hints.childNodes[selectedHintRange.to];
          var firstNode = this.hints.firstChild;
          if (node1.offsetTop < this.hints.scrollTop)
            this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;
          else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
            this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop;
        },
        screenAmount: function() {
          return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
        },
        getSelectedHintRange: function() {
          var margin = this.completion.options.scrollMargin || 0;
          return {
            from: Math.max(0, this.selectedHint - margin),
            to: Math.min(this.data.list.length - 1, this.selectedHint + margin)
          };
        }
      };
      function applicableHelpers(cm, helpers) {
        if (!cm.somethingSelected())
          return helpers;
        var result = [];
        for (var i = 0; i < helpers.length; i++)
          if (helpers[i].supportsSelection)
            result.push(helpers[i]);
        return result;
      }
      function fetchHints(hint, cm, options, callback) {
        if (hint.async) {
          hint(cm, callback, options);
        } else {
          var result = hint(cm, options);
          if (result && result.then)
            result.then(callback);
          else
            callback(result);
        }
      }
      function resolveAutoHints(cm, pos) {
        var helpers = cm.getHelpers(pos, "hint"), words;
        if (helpers.length) {
          var resolved = function(cm2, callback, options) {
            var app = applicableHelpers(cm2, helpers);
            function run2(i) {
              if (i == app.length)
                return callback(null);
              fetchHints(app[i], cm2, options, function(result) {
                if (result && result.list.length > 0)
                  callback(result);
                else
                  run2(i + 1);
              });
            }
            run2(0);
          };
          resolved.async = true;
          resolved.supportsSelection = true;
          return resolved;
        } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
          return function(cm2) {
            return CodeMirror10.hint.fromList(cm2, {words});
          };
        } else if (CodeMirror10.hint.anyword) {
          return function(cm2, options) {
            return CodeMirror10.hint.anyword(cm2, options);
          };
        } else {
          return function() {
          };
        }
      }
      CodeMirror10.registerHelper("hint", "auto", {
        resolve: resolveAutoHints
      });
      CodeMirror10.registerHelper("hint", "fromList", function(cm, options) {
        var cur = cm.getCursor(), token = cm.getTokenAt(cur);
        var term, from = CodeMirror10.Pos(cur.line, token.start), to = cur;
        if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
          term = token.string.substr(0, cur.ch - token.start);
        } else {
          term = "";
          from = cur;
        }
        var found = [];
        for (var i = 0; i < options.words.length; i++) {
          var word = options.words[i];
          if (word.slice(0, term.length) == term)
            found.push(word);
        }
        if (found.length)
          return {list: found, from, to};
      });
      CodeMirror10.commands.autocomplete = CodeMirror10.showHint;
      var defaultOptions = {
        hint: CodeMirror10.hint.auto,
        completeSingle: true,
        alignWithWord: true,
        closeCharacters: /[\s()\[\]{};:>,]/,
        closeOnCursorActivity: true,
        closeOnPick: true,
        closeOnUnfocus: true,
        completeOnSingleClick: true,
        container: null,
        customKeys: null,
        extraKeys: null,
        paddingForScrollbar: true,
        moveOnOverlap: true
      };
      CodeMirror10.defineOption("hintOptions", null);
    });
  });

  // node_modules/codemirror/addon/comment/comment.js
  var require_comment = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      var noOptions = {};
      var nonWS = /[^\s\u00a0]/;
      var Pos = CodeMirror10.Pos, cmp = CodeMirror10.cmpPos;
      function firstNonWS(str) {
        var found = str.search(nonWS);
        return found == -1 ? 0 : found;
      }
      CodeMirror10.commands.toggleComment = function(cm) {
        cm.toggleComment();
      };
      CodeMirror10.defineExtension("toggleComment", function(options) {
        if (!options)
          options = noOptions;
        var cm = this;
        var minLine = Infinity, ranges = this.listSelections(), mode = null;
        for (var i = ranges.length - 1; i >= 0; i--) {
          var from = ranges[i].from(), to = ranges[i].to();
          if (from.line >= minLine)
            continue;
          if (to.line >= minLine)
            to = Pos(minLine, 0);
          minLine = from.line;
          if (mode == null) {
            if (cm.uncomment(from, to, options))
              mode = "un";
            else {
              cm.lineComment(from, to, options);
              mode = "line";
            }
          } else if (mode == "un") {
            cm.uncomment(from, to, options);
          } else {
            cm.lineComment(from, to, options);
          }
        }
      });
      function probablyInsideString(cm, pos, line) {
        return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line);
      }
      function getMode(cm, pos) {
        var mode = cm.getMode();
        return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos);
      }
      CodeMirror10.defineExtension("lineComment", function(from, to, options) {
        if (!options)
          options = noOptions;
        var self3 = this, mode = getMode(self3, from);
        var firstLine = self3.getLine(from.line);
        if (firstLine == null || probablyInsideString(self3, from, firstLine))
          return;
        var commentString = options.lineComment || mode.lineComment;
        if (!commentString) {
          if (options.blockCommentStart || mode.blockCommentStart) {
            options.fullLines = true;
            self3.blockComment(from, to, options);
          }
          return;
        }
        var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self3.lastLine() + 1);
        var pad2 = options.padding == null ? " " : options.padding;
        var blankLines = options.commentBlankLines || from.line == to.line;
        self3.operation(function() {
          if (options.indent) {
            var baseString = null;
            for (var i = from.line; i < end; ++i) {
              var line = self3.getLine(i);
              var whitespace = line.slice(0, firstNonWS(line));
              if (baseString == null || baseString.length > whitespace.length) {
                baseString = whitespace;
              }
            }
            for (var i = from.line; i < end; ++i) {
              var line = self3.getLine(i), cut = baseString.length;
              if (!blankLines && !nonWS.test(line))
                continue;
              if (line.slice(0, cut) != baseString)
                cut = firstNonWS(line);
              self3.replaceRange(baseString + commentString + pad2, Pos(i, 0), Pos(i, cut));
            }
          } else {
            for (var i = from.line; i < end; ++i) {
              if (blankLines || nonWS.test(self3.getLine(i)))
                self3.replaceRange(commentString + pad2, Pos(i, 0));
            }
          }
        });
      });
      CodeMirror10.defineExtension("blockComment", function(from, to, options) {
        if (!options)
          options = noOptions;
        var self3 = this, mode = getMode(self3, from);
        var startString = options.blockCommentStart || mode.blockCommentStart;
        var endString = options.blockCommentEnd || mode.blockCommentEnd;
        if (!startString || !endString) {
          if ((options.lineComment || mode.lineComment) && options.fullLines != false)
            self3.lineComment(from, to, options);
          return;
        }
        if (/\bcomment\b/.test(self3.getTokenTypeAt(Pos(from.line, 0))))
          return;
        var end = Math.min(to.line, self3.lastLine());
        if (end != from.line && to.ch == 0 && nonWS.test(self3.getLine(end)))
          --end;
        var pad2 = options.padding == null ? " " : options.padding;
        if (from.line > end)
          return;
        self3.operation(function() {
          if (options.fullLines != false) {
            var lastLineHasText = nonWS.test(self3.getLine(end));
            self3.replaceRange(pad2 + endString, Pos(end));
            self3.replaceRange(startString + pad2, Pos(from.line, 0));
            var lead = options.blockCommentLead || mode.blockCommentLead;
            if (lead != null) {
              for (var i = from.line + 1; i <= end; ++i)
                if (i != end || lastLineHasText)
                  self3.replaceRange(lead + pad2, Pos(i, 0));
            }
          } else {
            var atCursor = cmp(self3.getCursor("to"), to) == 0, empty3 = !self3.somethingSelected();
            self3.replaceRange(endString, to);
            if (atCursor)
              self3.setSelection(empty3 ? to : self3.getCursor("from"), to);
            self3.replaceRange(startString, from);
          }
        });
      });
      CodeMirror10.defineExtension("uncomment", function(from, to, options) {
        if (!options)
          options = noOptions;
        var self3 = this, mode = getMode(self3, from);
        var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self3.lastLine()), start = Math.min(from.line, end);
        var lineString = options.lineComment || mode.lineComment, lines = [];
        var pad2 = options.padding == null ? " " : options.padding, didSomething;
        lineComment: {
          if (!lineString)
            break lineComment;
          for (var i = start; i <= end; ++i) {
            var line = self3.getLine(i);
            var found = line.indexOf(lineString);
            if (found > -1 && !/comment/.test(self3.getTokenTypeAt(Pos(i, found + 1))))
              found = -1;
            if (found == -1 && nonWS.test(line))
              break lineComment;
            if (found > -1 && nonWS.test(line.slice(0, found)))
              break lineComment;
            lines.push(line);
          }
          self3.operation(function() {
            for (var i2 = start; i2 <= end; ++i2) {
              var line2 = lines[i2 - start];
              var pos = line2.indexOf(lineString), endPos = pos + lineString.length;
              if (pos < 0)
                continue;
              if (line2.slice(endPos, endPos + pad2.length) == pad2)
                endPos += pad2.length;
              didSomething = true;
              self3.replaceRange("", Pos(i2, pos), Pos(i2, endPos));
            }
          });
          if (didSomething)
            return true;
        }
        var startString = options.blockCommentStart || mode.blockCommentStart;
        var endString = options.blockCommentEnd || mode.blockCommentEnd;
        if (!startString || !endString)
          return false;
        var lead = options.blockCommentLead || mode.blockCommentLead;
        var startLine = self3.getLine(start), open = startLine.indexOf(startString);
        if (open == -1)
          return false;
        var endLine = end == start ? startLine : self3.getLine(end);
        var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
        var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1);
        if (close == -1 || !/comment/.test(self3.getTokenTypeAt(insideStart)) || !/comment/.test(self3.getTokenTypeAt(insideEnd)) || self3.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1)
          return false;
        var lastStart = startLine.lastIndexOf(startString, from.ch);
        var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
        if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch)
          return false;
        firstEnd = endLine.indexOf(endString, to.ch);
        var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
        lastStart = firstEnd == -1 || almostLastStart == -1 ? -1 : to.ch + almostLastStart;
        if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch)
          return false;
        self3.operation(function() {
          self3.replaceRange("", Pos(end, close - (pad2 && endLine.slice(close - pad2.length, close) == pad2 ? pad2.length : 0)), Pos(end, close + endString.length));
          var openEnd = open + startString.length;
          if (pad2 && startLine.slice(openEnd, openEnd + pad2.length) == pad2)
            openEnd += pad2.length;
          self3.replaceRange("", Pos(start, open), Pos(start, openEnd));
          if (lead)
            for (var i2 = start + 1; i2 <= end; ++i2) {
              var line2 = self3.getLine(i2), found2 = line2.indexOf(lead);
              if (found2 == -1 || nonWS.test(line2.slice(0, found2)))
                continue;
              var foundEnd = found2 + lead.length;
              if (pad2 && line2.slice(foundEnd, foundEnd + pad2.length) == pad2)
                foundEnd += pad2.length;
              self3.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd));
            }
        });
        return true;
      });
    });
  });

  // node_modules/codemirror/addon/display/placeholder.js
  var require_placeholder = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      CodeMirror10.defineOption("placeholder", "", function(cm, val, old) {
        var prev = old && old != CodeMirror10.Init;
        if (val && !prev) {
          cm.on("blur", onBlur);
          cm.on("change", onChange);
          cm.on("swapDoc", onChange);
          CodeMirror10.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function() {
            onComposition(cm);
          });
          onChange(cm);
        } else if (!val && prev) {
          cm.off("blur", onBlur);
          cm.off("change", onChange);
          cm.off("swapDoc", onChange);
          CodeMirror10.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose);
          clearPlaceholder(cm);
          var wrapper = cm.getWrapperElement();
          wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
        }
        if (val && !cm.hasFocus())
          onBlur(cm);
      });
      function clearPlaceholder(cm) {
        if (cm.state.placeholder) {
          cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
          cm.state.placeholder = null;
        }
      }
      function setPlaceholder(cm) {
        clearPlaceholder(cm);
        var elt = cm.state.placeholder = document.createElement("pre");
        elt.style.cssText = "height: 0; overflow: visible";
        elt.style.direction = cm.getOption("direction");
        elt.className = "CodeMirror-placeholder CodeMirror-line-like";
        var placeHolder = cm.getOption("placeholder");
        if (typeof placeHolder == "string")
          placeHolder = document.createTextNode(placeHolder);
        elt.appendChild(placeHolder);
        cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
      }
      function onComposition(cm) {
        setTimeout(function() {
          var empty3 = false;
          if (cm.lineCount() == 1) {
            var input = cm.getInputField();
            empty3 = input.nodeName == "TEXTAREA" ? !cm.getLine(0).length : !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent);
          }
          if (empty3)
            setPlaceholder(cm);
          else
            clearPlaceholder(cm);
        }, 20);
      }
      function onBlur(cm) {
        if (isEmpty(cm))
          setPlaceholder(cm);
      }
      function onChange(cm) {
        var wrapper = cm.getWrapperElement(), empty3 = isEmpty(cm);
        wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty3 ? " CodeMirror-empty" : "");
        if (empty3)
          setPlaceholder(cm);
        else
          clearPlaceholder(cm);
      }
      function isEmpty(cm) {
        return cm.lineCount() === 1 && cm.getLine(0) === "";
      }
    });
  });

  // node_modules/codemirror/addon/selection/active-line.js
  var require_active_line = __commonJS((exports, module) => {
    (function(mod) {
      if (typeof exports == "object" && typeof module == "object")
        mod(require_codemirror());
      else if (typeof define == "function" && define.amd)
        define(["../../lib/codemirror"], mod);
      else
        mod(CodeMirror);
    })(function(CodeMirror10) {
      "use strict";
      var WRAP_CLASS = "CodeMirror-activeline";
      var BACK_CLASS = "CodeMirror-activeline-background";
      var GUTT_CLASS = "CodeMirror-activeline-gutter";
      CodeMirror10.defineOption("styleActiveLine", false, function(cm, val, old) {
        var prev = old == CodeMirror10.Init ? false : old;
        if (val == prev)
          return;
        if (prev) {
          cm.off("beforeSelectionChange", selectionChange);
          clearActiveLines(cm);
          delete cm.state.activeLines;
        }
        if (val) {
          cm.state.activeLines = [];
          updateActiveLines(cm, cm.listSelections());
          cm.on("beforeSelectionChange", selectionChange);
        }
      });
      function clearActiveLines(cm) {
        for (var i = 0; i < cm.state.activeLines.length; i++) {
          cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
          cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
          cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
        }
      }
      function sameArray(a, b) {
        if (a.length != b.length)
          return false;
        for (var i = 0; i < a.length; i++)
          if (a[i] != b[i])
            return false;
        return true;
      }
      function updateActiveLines(cm, ranges) {
        var active = [];
        for (var i = 0; i < ranges.length; i++) {
          var range = ranges[i];
          var option = cm.getOption("styleActiveLine");
          if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
            continue;
          var line = cm.getLineHandleVisualStart(range.head.line);
          if (active[active.length - 1] != line)
            active.push(line);
        }
        if (sameArray(cm.state.activeLines, active))
          return;
        cm.operation(function() {
          clearActiveLines(cm);
          for (var i2 = 0; i2 < active.length; i2++) {
            cm.addLineClass(active[i2], "wrap", WRAP_CLASS);
            cm.addLineClass(active[i2], "background", BACK_CLASS);
            cm.addLineClass(active[i2], "gutter", GUTT_CLASS);
          }
          cm.state.activeLines = active;
        });
      }
      function selectionChange(cm, sel) {
        updateActiveLines(cm, sel.ranges);
      }
    });
  });

  // node_modules/@ungap/custom-elements/index.js
  /*! (c) Andrea Giammarchi @webreflection ISC */
  (function() {
    "use strict";
    var Lie = typeof Promise === "function" ? Promise : function(fn) {
      var queue = [], resolved = 0, value;
      fn(function($) {
        value = $;
        resolved = 1;
        queue.splice(0).forEach(then);
      });
      return {
        then
      };
      function then(fn2) {
        return resolved ? setTimeout(fn2, 0, value) : queue.push(fn2), this;
      }
    };
    var attributesObserver = function(whenDefined2, MutationObserver2) {
      var attributeChanged = function attributeChanged2(records) {
        for (var i = 0, length = records.length; i < length; i++) {
          dispatch(records[i]);
        }
      };
      var dispatch = function dispatch2(_ref2) {
        var target = _ref2.target, attributeName = _ref2.attributeName, oldValue = _ref2.oldValue;
        target.attributeChangedCallback(attributeName, oldValue, target.getAttribute(attributeName));
      };
      return function(target, is2) {
        var attributeFilter = target.constructor.observedAttributes;
        if (attributeFilter) {
          whenDefined2(is2).then(function() {
            new MutationObserver2(attributeChanged).observe(target, {
              attributes: true,
              attributeOldValue: true,
              attributeFilter
            });
            for (var i = 0, length = attributeFilter.length; i < length; i++) {
              if (target.hasAttribute(attributeFilter[i]))
                dispatch({
                  target,
                  attributeName: attributeFilter[i],
                  oldValue: null
                });
            }
          });
        }
        return target;
      };
    };
    var _self = self, document2 = _self.document, MutationObserver = _self.MutationObserver, Set2 = _self.Set, WeakMap = _self.WeakMap;
    var elements = function elements2(element2) {
      return "querySelectorAll" in element2;
    };
    var filter2 = [].filter;
    var qsaObserver = function(options) {
      var live = new WeakMap();
      var callback = function callback2(records) {
        var query3 = options.query;
        if (query3.length) {
          for (var i = 0, length = records.length; i < length; i++) {
            loop(filter2.call(records[i].addedNodes, elements), true, query3);
            loop(filter2.call(records[i].removedNodes, elements), false, query3);
          }
        }
      };
      var drop2 = function drop3(elements2) {
        for (var i = 0, length = elements2.length; i < length; i++) {
          live["delete"](elements2[i]);
        }
      };
      var flush2 = function flush3() {
        callback(observer.takeRecords());
      };
      var loop = function loop2(elements2, connected, query3) {
        var set = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : new Set2();
        var _loop = function _loop2(_selectors, _element, i2, length2) {
          if (!set.has(_element = elements2[i2])) {
            set.add(_element);
            if (connected) {
              for (var q, m = matches(_element), _i = 0, _length = query3.length; _i < _length; _i++) {
                if (m.call(_element, q = query3[_i])) {
                  if (!live.has(_element))
                    live.set(_element, new Set2());
                  _selectors = live.get(_element);
                  if (!_selectors.has(q)) {
                    _selectors.add(q);
                    options.handle(_element, connected, q);
                  }
                }
              }
            } else if (live.has(_element)) {
              _selectors = live.get(_element);
              live["delete"](_element);
              _selectors.forEach(function(q2) {
                options.handle(_element, connected, q2);
              });
            }
            loop2(querySelectorAll(_element), connected, query3, set);
          }
          selectors = _selectors;
          element2 = _element;
        };
        for (var selectors, element2, i = 0, length = elements2.length; i < length; i++) {
          _loop(selectors, element2, i);
        }
      };
      var matches = function matches2(element2) {
        return element2.matches || element2.webkitMatchesSelector || element2.msMatchesSelector;
      };
      var parse2 = function parse3(elements2) {
        var connected = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
        loop(elements2, connected, options.query);
      };
      var querySelectorAll = function querySelectorAll2(root3) {
        return query2.length ? root3.querySelectorAll(query2) : query2;
      };
      var observer = new MutationObserver(callback);
      var root2 = options.root || document2;
      var query2 = options.query;
      observer.observe(root2, {
        childList: true,
        subtree: true
      });
      parse2(querySelectorAll(root2));
      return {
        drop: drop2,
        flush: flush2,
        observer,
        parse: parse2
      };
    };
    var _self$1 = self, document$1 = _self$1.document, Map2 = _self$1.Map, MutationObserver$1 = _self$1.MutationObserver, Object2 = _self$1.Object, Set$1 = _self$1.Set, WeakMap$1 = _self$1.WeakMap, Element2 = _self$1.Element, HTMLElement2 = _self$1.HTMLElement, Node3 = _self$1.Node, Error2 = _self$1.Error, TypeError2 = _self$1.TypeError, Reflect = _self$1.Reflect;
    var Promise$1 = self.Promise || Lie;
    var defineProperty = Object2.defineProperty, getOwnPropertyNames = Object2.getOwnPropertyNames, setPrototypeOf = Object2.setPrototypeOf;
    var legacy = !self.customElements;
    if (legacy) {
      var HTMLBuiltIn = function HTMLBuiltIn2() {
        var constructor = this.constructor;
        if (!classes.has(constructor))
          throw new TypeError2("Illegal constructor");
        var is2 = classes.get(constructor);
        if (override)
          return augment(override, is2);
        var element2 = createElement.call(document$1, is2);
        return augment(setPrototypeOf(element2, constructor.prototype), is2);
      };
      var createElement = document$1.createElement;
      var classes = new Map2();
      var defined = new Map2();
      var prototypes = new Map2();
      var registry = new Map2();
      var query = [];
      var handle = function handle2(element2, connected, selector) {
        var proto = prototypes.get(selector);
        if (connected && !proto.isPrototypeOf(element2)) {
          override = setPrototypeOf(element2, proto);
          try {
            new proto.constructor();
          } finally {
            override = null;
          }
        }
        var method = "".concat(connected ? "" : "dis", "connectedCallback");
        if (method in proto)
          element2[method]();
      };
      var _qsaObserver = qsaObserver({
        query,
        handle
      }), parse = _qsaObserver.parse;
      var override = null;
      var whenDefined = function whenDefined2(name) {
        if (!defined.has(name)) {
          var _2, $ = new Lie(function($2) {
            _2 = $2;
          });
          defined.set(name, {
            $,
            _: _2
          });
        }
        return defined.get(name).$;
      };
      var augment = attributesObserver(whenDefined, MutationObserver$1);
      defineProperty(self, "customElements", {
        configurable: true,
        value: {
          define: function define3(is2, Class) {
            if (registry.has(is2))
              throw new Error2('the name "'.concat(is2, '" has already been used with this registry'));
            classes.set(Class, is2);
            prototypes.set(is2, Class.prototype);
            registry.set(is2, Class);
            query.push(is2);
            whenDefined(is2).then(function() {
              parse(document$1.querySelectorAll(is2));
            });
            defined.get(is2)._(Class);
          },
          get: function get3(is2) {
            return registry.get(is2);
          },
          whenDefined
        }
      });
      defineProperty(HTMLBuiltIn.prototype = HTMLElement2.prototype, "constructor", {
        value: HTMLBuiltIn
      });
      defineProperty(self, "HTMLElement", {
        configurable: true,
        value: HTMLBuiltIn
      });
      defineProperty(document$1, "createElement", {
        configurable: true,
        value: function value(name, options) {
          var is2 = options && options.is;
          var Class = is2 ? registry.get(is2) : registry.get(name);
          return Class ? new Class() : createElement.call(document$1, name);
        }
      });
      if (!("isConnected" in Node3.prototype))
        defineProperty(Node3.prototype, "isConnected", {
          configurable: true,
          get: function get3() {
            return !(this.ownerDocument.compareDocumentPosition(this) & this.DOCUMENT_POSITION_DISCONNECTED);
          }
        });
    } else {
      try {
        var LI = function LI2() {
          return self.Reflect.construct(HTMLLIElement, [], LI2);
        };
        LI.prototype = HTMLLIElement.prototype;
        var is = "extends-li";
        self.customElements.define("extends-li", LI, {
          extends: "li"
        });
        legacy = document$1.createElement("li", {
          is
        }).outerHTML.indexOf(is) < 0;
        var _self$customElements = self.customElements, get2 = _self$customElements.get, _whenDefined = _self$customElements.whenDefined;
        defineProperty(self.customElements, "whenDefined", {
          configurable: true,
          value: function value(is2) {
            var _this = this;
            return _whenDefined.call(this, is2).then(function(Class) {
              return Class || get2.call(_this, is2);
            });
          }
        });
      } catch (o_O) {
        legacy = !legacy;
      }
    }
    if (legacy) {
      var parseShadow = function parseShadow2(element2) {
        var _shadowRoots$get = shadowRoots.get(element2), parse2 = _shadowRoots$get.parse, root2 = _shadowRoots$get.root;
        parse2(root2.querySelectorAll(this), element2.isConnected);
      };
      var customElements2 = self.customElements;
      var attachShadow = Element2.prototype.attachShadow;
      var _createElement = document$1.createElement;
      var define2 = customElements2.define, _get = customElements2.get;
      var _ref = Reflect || {
        construct: function construct2(HTMLElement3) {
          return HTMLElement3.call(this);
        }
      }, construct = _ref.construct;
      var shadowRoots = new WeakMap$1();
      var shadows = new Set$1();
      var _classes = new Map2();
      var _defined = new Map2();
      var _prototypes = new Map2();
      var _registry = new Map2();
      var shadowed = [];
      var _query = [];
      var getCE = function getCE2(is2) {
        return _registry.get(is2) || _get.call(customElements2, is2);
      };
      var _handle = function _handle2(element2, connected, selector) {
        var proto = _prototypes.get(selector);
        if (connected && !proto.isPrototypeOf(element2)) {
          _override = setPrototypeOf(element2, proto);
          try {
            new proto.constructor();
          } finally {
            _override = null;
          }
        }
        var method = "".concat(connected ? "" : "dis", "connectedCallback");
        if (method in proto)
          element2[method]();
      };
      var _qsaObserver2 = qsaObserver({
        query: _query,
        handle: _handle
      }), _parse = _qsaObserver2.parse;
      var _qsaObserver3 = qsaObserver({
        query: shadowed,
        handle: function handle2(element2, connected) {
          if (shadowRoots.has(element2)) {
            if (connected)
              shadows.add(element2);
            else
              shadows["delete"](element2);
            parseShadow.call(_query, element2);
          }
        }
      }), parseShadowed = _qsaObserver3.parse;
      var _whenDefined2 = function _whenDefined22(name) {
        if (!_defined.has(name)) {
          var _2, $ = new Promise$1(function($2) {
            _2 = $2;
          });
          _defined.set(name, {
            $,
            _: _2
          });
        }
        return _defined.get(name).$;
      };
      var _augment = attributesObserver(_whenDefined2, MutationObserver$1);
      var _override = null;
      getOwnPropertyNames(self).filter(function(k) {
        return /^HTML/.test(k);
      }).forEach(function(k) {
        var HTMLElement3 = self[k];
        function HTMLBuiltIn2() {
          var constructor = this.constructor;
          if (!_classes.has(constructor))
            throw new TypeError2("Illegal constructor");
          var _classes$get = _classes.get(constructor), is2 = _classes$get.is, tag = _classes$get.tag;
          if (is2) {
            if (_override)
              return _augment(_override, is2);
            var element2 = _createElement.call(document$1, tag);
            element2.setAttribute("is", is2);
            return _augment(setPrototypeOf(element2, constructor.prototype), is2);
          } else
            return construct.call(this, HTMLElement3, [], constructor);
        }
        defineProperty(HTMLBuiltIn2.prototype = HTMLElement3.prototype, "constructor", {
          value: HTMLBuiltIn2
        });
        defineProperty(self, k, {
          value: HTMLBuiltIn2
        });
      });
      defineProperty(document$1, "createElement", {
        value: function value(name, options) {
          var is2 = options && options.is;
          if (is2) {
            var Class = _registry.get(is2);
            if (Class && _classes.get(Class).tag === name)
              return new Class();
          }
          var element2 = _createElement.call(document$1, name);
          if (is2)
            element2.setAttribute("is", is2);
          return element2;
        }
      });
      if (attachShadow)
        defineProperty(Element2.prototype, "attachShadow", {
          value: function value() {
            var root2 = attachShadow.apply(this, arguments);
            var _qsaObserver4 = qsaObserver({
              query: _query,
              root: root2,
              handle: _handle
            }), parse2 = _qsaObserver4.parse;
            shadowRoots.set(this, {
              root: root2,
              parse: parse2
            });
            return root2;
          }
        });
      defineProperty(customElements2, "get", {
        configurable: true,
        value: getCE
      });
      defineProperty(customElements2, "whenDefined", {
        configurable: true,
        value: _whenDefined2
      });
      defineProperty(customElements2, "define", {
        configurable: true,
        value: function value(is2, Class, options) {
          if (getCE(is2))
            throw new Error2("'".concat(is2, "' has already been defined as a custom element"));
          var selector;
          var tag = options && options["extends"];
          _classes.set(Class, tag ? {
            is: is2,
            tag
          } : {
            is: "",
            tag: is2
          });
          if (tag) {
            selector = "".concat(tag, '[is="').concat(is2, '"]');
            _prototypes.set(selector, Class.prototype);
            _registry.set(is2, Class);
            _query.push(selector);
          } else {
            define2.apply(customElements2, arguments);
            shadowed.push(selector = is2);
          }
          _whenDefined2(is2).then(function() {
            if (tag) {
              _parse(document$1.querySelectorAll(selector));
              shadows.forEach(parseShadow, [selector]);
            } else
              parseShadowed(document$1.querySelectorAll(selector));
          });
          _defined.get(is2)._(Class);
        }
      });
    }
  })();

  // node_modules/d3-format/src/formatDecimal.js
  function formatDecimal_default(x2) {
    return Math.abs(x2 = Math.round(x2)) >= 1e21 ? x2.toLocaleString("en").replace(/,/g, "") : x2.toString(10);
  }
  function formatDecimalParts(x2, p) {
    if ((i = (x2 = p ? x2.toExponential(p - 1) : x2.toExponential()).indexOf("e")) < 0)
      return null;
    var i, coefficient = x2.slice(0, i);
    return [
      coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
      +x2.slice(i + 1)
    ];
  }

  // node_modules/d3-format/src/exponent.js
  function exponent_default(x2) {
    return x2 = formatDecimalParts(Math.abs(x2)), x2 ? x2[1] : NaN;
  }

  // node_modules/d3-format/src/formatGroup.js
  function formatGroup_default(grouping, thousands) {
    return function(value, width) {
      var i = value.length, t = [], j = 0, g = grouping[0], length = 0;
      while (i > 0 && g > 0) {
        if (length + g + 1 > width)
          g = Math.max(1, width - length);
        t.push(value.substring(i -= g, i + g));
        if ((length += g + 1) > width)
          break;
        g = grouping[j = (j + 1) % grouping.length];
      }
      return t.reverse().join(thousands);
    };
  }

  // node_modules/d3-format/src/formatNumerals.js
  function formatNumerals_default(numerals) {
    return function(value) {
      return value.replace(/[0-9]/g, function(i) {
        return numerals[+i];
      });
    };
  }

  // node_modules/d3-format/src/formatSpecifier.js
  var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
  function formatSpecifier(specifier) {
    if (!(match = re.exec(specifier)))
      throw new Error("invalid format: " + specifier);
    var match;
    return new FormatSpecifier({
      fill: match[1],
      align: match[2],
      sign: match[3],
      symbol: match[4],
      zero: match[5],
      width: match[6],
      comma: match[7],
      precision: match[8] && match[8].slice(1),
      trim: match[9],
      type: match[10]
    });
  }
  formatSpecifier.prototype = FormatSpecifier.prototype;
  function FormatSpecifier(specifier) {
    this.fill = specifier.fill === void 0 ? " " : specifier.fill + "";
    this.align = specifier.align === void 0 ? ">" : specifier.align + "";
    this.sign = specifier.sign === void 0 ? "-" : specifier.sign + "";
    this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + "";
    this.zero = !!specifier.zero;
    this.width = specifier.width === void 0 ? void 0 : +specifier.width;
    this.comma = !!specifier.comma;
    this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision;
    this.trim = !!specifier.trim;
    this.type = specifier.type === void 0 ? "" : specifier.type + "";
  }
  FormatSpecifier.prototype.toString = function() {
    return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
  };

  // node_modules/d3-format/src/formatTrim.js
  function formatTrim_default(s) {
    out:
      for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
        switch (s[i]) {
          case ".":
            i0 = i1 = i;
            break;
          case "0":
            if (i0 === 0)
              i0 = i;
            i1 = i;
            break;
          default:
            if (!+s[i])
              break out;
            if (i0 > 0)
              i0 = 0;
            break;
        }
      }
    return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
  }

  // node_modules/d3-format/src/formatPrefixAuto.js
  var prefixExponent;
  function formatPrefixAuto_default(x2, p) {
    var d = formatDecimalParts(x2, p);
    if (!d)
      return x2 + "";
    var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length;
    return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x2, Math.max(0, p + i - 1))[0];
  }

  // node_modules/d3-format/src/formatRounded.js
  function formatRounded_default(x2, p) {
    var d = formatDecimalParts(x2, p);
    if (!d)
      return x2 + "";
    var coefficient = d[0], exponent = d[1];
    return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0");
  }

  // node_modules/d3-format/src/formatTypes.js
  var formatTypes_default = {
    "%": (x2, p) => (x2 * 100).toFixed(p),
    b: (x2) => Math.round(x2).toString(2),
    c: (x2) => x2 + "",
    d: formatDecimal_default,
    e: (x2, p) => x2.toExponential(p),
    f: (x2, p) => x2.toFixed(p),
    g: (x2, p) => x2.toPrecision(p),
    o: (x2) => Math.round(x2).toString(8),
    p: (x2, p) => formatRounded_default(x2 * 100, p),
    r: formatRounded_default,
    s: formatPrefixAuto_default,
    X: (x2) => Math.round(x2).toString(16).toUpperCase(),
    x: (x2) => Math.round(x2).toString(16)
  };

  // node_modules/d3-format/src/identity.js
  function identity_default(x2) {
    return x2;
  }

  // node_modules/d3-format/src/locale.js
  var map = Array.prototype.map;
  var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
  function locale_default(locale3) {
    var group = locale3.grouping === void 0 || locale3.thousands === void 0 ? identity_default : formatGroup_default(map.call(locale3.grouping, Number), locale3.thousands + ""), currencyPrefix = locale3.currency === void 0 ? "" : locale3.currency[0] + "", currencySuffix = locale3.currency === void 0 ? "" : locale3.currency[1] + "", decimal = locale3.decimal === void 0 ? "." : locale3.decimal + "", numerals = locale3.numerals === void 0 ? identity_default : formatNumerals_default(map.call(locale3.numerals, String)), percent = locale3.percent === void 0 ? "%" : locale3.percent + "", minus = locale3.minus === void 0 ? "\u2212" : locale3.minus + "", nan = locale3.nan === void 0 ? "NaN" : locale3.nan + "";
    function newFormat(specifier) {
      specifier = formatSpecifier(specifier);
      var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero2 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type;
      if (type === "n")
        comma = true, type = "g";
      else if (!formatTypes_default[type])
        precision === void 0 && (precision = 12), trim = true, type = "g";
      if (zero2 || fill === "0" && align === "=")
        zero2 = true, fill = "0", align = "=";
      var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
      var formatType = formatTypes_default[type], maybeSuffix = /[defgprs%]/.test(type);
      precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
      function format2(value) {
        var valuePrefix = prefix, valueSuffix = suffix, i, n, c;
        if (type === "c") {
          valueSuffix = formatType(value) + valueSuffix;
          value = "";
        } else {
          value = +value;
          var valueNegative = value < 0 || 1 / value < 0;
          value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
          if (trim)
            value = formatTrim_default(value);
          if (valueNegative && +value === 0 && sign !== "+")
            valueNegative = false;
          valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
          valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
          if (maybeSuffix) {
            i = -1, n = value.length;
            while (++i < n) {
              if (c = value.charCodeAt(i), 48 > c || c > 57) {
                valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
                value = value.slice(0, i);
                break;
              }
            }
          }
        }
        if (comma && !zero2)
          value = group(value, Infinity);
        var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
        if (comma && zero2)
          value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
        switch (align) {
          case "<":
            value = valuePrefix + value + valueSuffix + padding;
            break;
          case "=":
            value = valuePrefix + padding + value + valueSuffix;
            break;
          case "^":
            value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
            break;
          default:
            value = padding + valuePrefix + value + valueSuffix;
            break;
        }
        return numerals(value);
      }
      format2.toString = function() {
        return specifier + "";
      };
      return format2;
    }
    function formatPrefix2(specifier, value) {
      var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3];
      return function(value2) {
        return f(k * value2) + prefix;
      };
    }
    return {
      format: newFormat,
      formatPrefix: formatPrefix2
    };
  }

  // node_modules/d3-format/src/defaultLocale.js
  var locale;
  var format;
  var formatPrefix;
  defaultLocale({
    thousands: ",",
    grouping: [3],
    currency: ["$", ""]
  });
  function defaultLocale(definition) {
    locale = locale_default(definition);
    format = locale.format;
    formatPrefix = locale.formatPrefix;
    return locale;
  }

  // node_modules/d3-format/src/precisionFixed.js
  function precisionFixed_default(step) {
    return Math.max(0, -exponent_default(Math.abs(step)));
  }

  // node_modules/d3-format/src/precisionPrefix.js
  function precisionPrefix_default(step, value) {
    return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step)));
  }

  // node_modules/d3-format/src/precisionRound.js
  function precisionRound_default(step, max3) {
    step = Math.abs(step), max3 = Math.abs(max3) - step;
    return Math.max(0, exponent_default(max3) - exponent_default(step)) + 1;
  }

  // node_modules/d3-time/src/interval.js
  var t0 = new Date();
  var t1 = new Date();
  function newInterval(floori, offseti, count2, field) {
    function interval2(date3) {
      return floori(date3 = arguments.length === 0 ? new Date() : new Date(+date3)), date3;
    }
    interval2.floor = function(date3) {
      return floori(date3 = new Date(+date3)), date3;
    };
    interval2.ceil = function(date3) {
      return floori(date3 = new Date(date3 - 1)), offseti(date3, 1), floori(date3), date3;
    };
    interval2.round = function(date3) {
      var d0 = interval2(date3), d1 = interval2.ceil(date3);
      return date3 - d0 < d1 - date3 ? d0 : d1;
    };
    interval2.offset = function(date3, step) {
      return offseti(date3 = new Date(+date3), step == null ? 1 : Math.floor(step)), date3;
    };
    interval2.range = function(start, stop, step) {
      var range = [], previous;
      start = interval2.ceil(start);
      step = step == null ? 1 : Math.floor(step);
      if (!(start < stop) || !(step > 0))
        return range;
      do
        range.push(previous = new Date(+start)), offseti(start, step), floori(start);
      while (previous < start && start < stop);
      return range;
    };
    interval2.filter = function(test) {
      return newInterval(function(date3) {
        if (date3 >= date3)
          while (floori(date3), !test(date3))
            date3.setTime(date3 - 1);
      }, function(date3, step) {
        if (date3 >= date3) {
          if (step < 0)
            while (++step <= 0) {
              while (offseti(date3, -1), !test(date3)) {
              }
            }
          else
            while (--step >= 0) {
              while (offseti(date3, 1), !test(date3)) {
              }
            }
        }
      });
    };
    if (count2) {
      interval2.count = function(start, end) {
        t0.setTime(+start), t1.setTime(+end);
        floori(t0), floori(t1);
        return Math.floor(count2(t0, t1));
      };
      interval2.every = function(step) {
        step = Math.floor(step);
        return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval2 : interval2.filter(field ? function(d) {
          return field(d) % step === 0;
        } : function(d) {
          return interval2.count(0, d) % step === 0;
        });
      };
    }
    return interval2;
  }

  // node_modules/d3-time/src/millisecond.js
  var millisecond = newInterval(function() {
  }, function(date3, step) {
    date3.setTime(+date3 + step);
  }, function(start, end) {
    return end - start;
  });
  millisecond.every = function(k) {
    k = Math.floor(k);
    if (!isFinite(k) || !(k > 0))
      return null;
    if (!(k > 1))
      return millisecond;
    return newInterval(function(date3) {
      date3.setTime(Math.floor(date3 / k) * k);
    }, function(date3, step) {
      date3.setTime(+date3 + step * k);
    }, function(start, end) {
      return (end - start) / k;
    });
  };
  var millisecond_default = millisecond;
  var milliseconds = millisecond.range;

  // node_modules/d3-time/src/duration.js
  var durationSecond = 1e3;
  var durationMinute = 6e4;
  var durationHour = 36e5;
  var durationDay = 864e5;
  var durationWeek = 6048e5;

  // node_modules/d3-time/src/second.js
  var second = newInterval(function(date3) {
    date3.setTime(date3 - date3.getMilliseconds());
  }, function(date3, step) {
    date3.setTime(+date3 + step * durationSecond);
  }, function(start, end) {
    return (end - start) / durationSecond;
  }, function(date3) {
    return date3.getUTCSeconds();
  });
  var second_default = second;
  var seconds = second.range;

  // node_modules/d3-time/src/day.js
  var day = newInterval((date3) => date3.setHours(0, 0, 0, 0), (date3, step) => date3.setDate(date3.getDate() + step), (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay, (date3) => date3.getDate() - 1);
  var day_default = day;
  var days = day.range;

  // node_modules/d3-time/src/week.js
  function weekday(i) {
    return newInterval(function(date3) {
      date3.setDate(date3.getDate() - (date3.getDay() + 7 - i) % 7);
      date3.setHours(0, 0, 0, 0);
    }, function(date3, step) {
      date3.setDate(date3.getDate() + step * 7);
    }, function(start, end) {
      return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
    });
  }
  var sunday = weekday(0);
  var monday = weekday(1);
  var tuesday = weekday(2);
  var wednesday = weekday(3);
  var thursday = weekday(4);
  var friday = weekday(5);
  var saturday = weekday(6);
  var sundays = sunday.range;
  var mondays = monday.range;
  var tuesdays = tuesday.range;
  var wednesdays = wednesday.range;
  var thursdays = thursday.range;
  var fridays = friday.range;
  var saturdays = saturday.range;

  // node_modules/d3-time/src/year.js
  var year = newInterval(function(date3) {
    date3.setMonth(0, 1);
    date3.setHours(0, 0, 0, 0);
  }, function(date3, step) {
    date3.setFullYear(date3.getFullYear() + step);
  }, function(start, end) {
    return end.getFullYear() - start.getFullYear();
  }, function(date3) {
    return date3.getFullYear();
  });
  year.every = function(k) {
    return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date3) {
      date3.setFullYear(Math.floor(date3.getFullYear() / k) * k);
      date3.setMonth(0, 1);
      date3.setHours(0, 0, 0, 0);
    }, function(date3, step) {
      date3.setFullYear(date3.getFullYear() + step * k);
    });
  };
  var year_default = year;
  var years = year.range;

  // node_modules/d3-time/src/utcMinute.js
  var utcMinute = newInterval(function(date3) {
    date3.setUTCSeconds(0, 0);
  }, function(date3, step) {
    date3.setTime(+date3 + step * durationMinute);
  }, function(start, end) {
    return (end - start) / durationMinute;
  }, function(date3) {
    return date3.getUTCMinutes();
  });
  var utcMinute_default = utcMinute;
  var utcMinutes = utcMinute.range;

  // node_modules/d3-time/src/utcHour.js
  var utcHour = newInterval(function(date3) {
    date3.setUTCMinutes(0, 0, 0);
  }, function(date3, step) {
    date3.setTime(+date3 + step * durationHour);
  }, function(start, end) {
    return (end - start) / durationHour;
  }, function(date3) {
    return date3.getUTCHours();
  });
  var utcHour_default = utcHour;
  var utcHours = utcHour.range;

  // node_modules/d3-time/src/utcDay.js
  var utcDay = newInterval(function(date3) {
    date3.setUTCHours(0, 0, 0, 0);
  }, function(date3, step) {
    date3.setUTCDate(date3.getUTCDate() + step);
  }, function(start, end) {
    return (end - start) / durationDay;
  }, function(date3) {
    return date3.getUTCDate() - 1;
  });
  var utcDay_default = utcDay;
  var utcDays = utcDay.range;

  // node_modules/d3-time/src/utcWeek.js
  function utcWeekday(i) {
    return newInterval(function(date3) {
      date3.setUTCDate(date3.getUTCDate() - (date3.getUTCDay() + 7 - i) % 7);
      date3.setUTCHours(0, 0, 0, 0);
    }, function(date3, step) {
      date3.setUTCDate(date3.getUTCDate() + step * 7);
    }, function(start, end) {
      return (end - start) / durationWeek;
    });
  }
  var utcSunday = utcWeekday(0);
  var utcMonday = utcWeekday(1);
  var utcTuesday = utcWeekday(2);
  var utcWednesday = utcWeekday(3);
  var utcThursday = utcWeekday(4);
  var utcFriday = utcWeekday(5);
  var utcSaturday = utcWeekday(6);
  var utcSundays = utcSunday.range;
  var utcMondays = utcMonday.range;
  var utcTuesdays = utcTuesday.range;
  var utcWednesdays = utcWednesday.range;
  var utcThursdays = utcThursday.range;
  var utcFridays = utcFriday.range;
  var utcSaturdays = utcSaturday.range;

  // node_modules/d3-time/src/utcMonth.js
  var utcMonth = newInterval(function(date3) {
    date3.setUTCDate(1);
    date3.setUTCHours(0, 0, 0, 0);
  }, function(date3, step) {
    date3.setUTCMonth(date3.getUTCMonth() + step);
  }, function(start, end) {
    return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
  }, function(date3) {
    return date3.getUTCMonth();
  });
  var utcMonth_default = utcMonth;
  var utcMonths = utcMonth.range;

  // node_modules/d3-time/src/utcYear.js
  var utcYear = newInterval(function(date3) {
    date3.setUTCMonth(0, 1);
    date3.setUTCHours(0, 0, 0, 0);
  }, function(date3, step) {
    date3.setUTCFullYear(date3.getUTCFullYear() + step);
  }, function(start, end) {
    return end.getUTCFullYear() - start.getUTCFullYear();
  }, function(date3) {
    return date3.getUTCFullYear();
  });
  utcYear.every = function(k) {
    return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date3) {
      date3.setUTCFullYear(Math.floor(date3.getUTCFullYear() / k) * k);
      date3.setUTCMonth(0, 1);
      date3.setUTCHours(0, 0, 0, 0);
    }, function(date3, step) {
      date3.setUTCFullYear(date3.getUTCFullYear() + step * k);
    });
  };
  var utcYear_default = utcYear;
  var utcYears = utcYear.range;

  // node_modules/d3-time-format/src/locale.js
  function localDate(d) {
    if (0 <= d.y && d.y < 100) {
      var date3 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
      date3.setFullYear(d.y);
      return date3;
    }
    return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
  }
  function utcDate(d) {
    if (0 <= d.y && d.y < 100) {
      var date3 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
      date3.setUTCFullYear(d.y);
      return date3;
    }
    return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
  }
  function newDate(y2, m, d) {
    return {y: y2, m, d, H: 0, M: 0, S: 0, L: 0};
  }
  function formatLocale(locale3) {
    var locale_dateTime = locale3.dateTime, locale_date = locale3.date, locale_time = locale3.time, locale_periods = locale3.periods, locale_weekdays = locale3.days, locale_shortWeekdays = locale3.shortDays, locale_months = locale3.months, locale_shortMonths = locale3.shortMonths;
    var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths);
    var formats = {
      a: formatShortWeekday,
      A: formatWeekday,
      b: formatShortMonth,
      B: formatMonth,
      c: null,
      d: formatDayOfMonth,
      e: formatDayOfMonth,
      f: formatMicroseconds,
      g: formatYearISO,
      G: formatFullYearISO,
      H: formatHour24,
      I: formatHour12,
      j: formatDayOfYear,
      L: formatMilliseconds,
      m: formatMonthNumber,
      M: formatMinutes,
      p: formatPeriod,
      q: formatQuarter,
      Q: formatUnixTimestamp,
      s: formatUnixTimestampSeconds,
      S: formatSeconds,
      u: formatWeekdayNumberMonday,
      U: formatWeekNumberSunday,
      V: formatWeekNumberISO,
      w: formatWeekdayNumberSunday,
      W: formatWeekNumberMonday,
      x: null,
      X: null,
      y: formatYear,
      Y: formatFullYear,
      Z: formatZone,
      "%": formatLiteralPercent
    };
    var utcFormats = {
      a: formatUTCShortWeekday,
      A: formatUTCWeekday,
      b: formatUTCShortMonth,
      B: formatUTCMonth,
      c: null,
      d: formatUTCDayOfMonth,
      e: formatUTCDayOfMonth,
      f: formatUTCMicroseconds,
      g: formatUTCYearISO,
      G: formatUTCFullYearISO,
      H: formatUTCHour24,
      I: formatUTCHour12,
      j: formatUTCDayOfYear,
      L: formatUTCMilliseconds,
      m: formatUTCMonthNumber,
      M: formatUTCMinutes,
      p: formatUTCPeriod,
      q: formatUTCQuarter,
      Q: formatUnixTimestamp,
      s: formatUnixTimestampSeconds,
      S: formatUTCSeconds,
      u: formatUTCWeekdayNumberMonday,
      U: formatUTCWeekNumberSunday,
      V: formatUTCWeekNumberISO,
      w: formatUTCWeekdayNumberSunday,
      W: formatUTCWeekNumberMonday,
      x: null,
      X: null,
      y: formatUTCYear,
      Y: formatUTCFullYear,
      Z: formatUTCZone,
      "%": formatLiteralPercent
    };
    var parses = {
      a: parseShortWeekday,
      A: parseWeekday,
      b: parseShortMonth,
      B: parseMonth,
      c: parseLocaleDateTime,
      d: parseDayOfMonth,
      e: parseDayOfMonth,
      f: parseMicroseconds,
      g: parseYear,
      G: parseFullYear,
      H: parseHour24,
      I: parseHour24,
      j: parseDayOfYear,
      L: parseMilliseconds,
      m: parseMonthNumber,
      M: parseMinutes,
      p: parsePeriod,
      q: parseQuarter,
      Q: parseUnixTimestamp,
      s: parseUnixTimestampSeconds,
      S: parseSeconds,
      u: parseWeekdayNumberMonday,
      U: parseWeekNumberSunday,
      V: parseWeekNumberISO,
      w: parseWeekdayNumberSunday,
      W: parseWeekNumberMonday,
      x: parseLocaleDate,
      X: parseLocaleTime,
      y: parseYear,
      Y: parseFullYear,
      Z: parseZone,
      "%": parseLiteralPercent
    };
    formats.x = newFormat(locale_date, formats);
    formats.X = newFormat(locale_time, formats);
    formats.c = newFormat(locale_dateTime, formats);
    utcFormats.x = newFormat(locale_date, utcFormats);
    utcFormats.X = newFormat(locale_time, utcFormats);
    utcFormats.c = newFormat(locale_dateTime, utcFormats);
    function newFormat(specifier, formats2) {
      return function(date3) {
        var string2 = [], i = -1, j = 0, n = specifier.length, c, pad2, format2;
        if (!(date3 instanceof Date))
          date3 = new Date(+date3);
        while (++i < n) {
          if (specifier.charCodeAt(i) === 37) {
            string2.push(specifier.slice(j, i));
            if ((pad2 = pads[c = specifier.charAt(++i)]) != null)
              c = specifier.charAt(++i);
            else
              pad2 = c === "e" ? " " : "0";
            if (format2 = formats2[c])
              c = format2(date3, pad2);
            string2.push(c);
            j = i + 1;
          }
        }
        string2.push(specifier.slice(j, i));
        return string2.join("");
      };
    }
    function newParse(specifier, Z) {
      return function(string2) {
        var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string2 += "", 0), week, day2;
        if (i != string2.length)
          return null;
        if ("Q" in d)
          return new Date(d.Q);
        if ("s" in d)
          return new Date(d.s * 1e3 + ("L" in d ? d.L : 0));
        if (Z && !("Z" in d))
          d.Z = 0;
        if ("p" in d)
          d.H = d.H % 12 + d.p * 12;
        if (d.m === void 0)
          d.m = "q" in d ? d.q : 0;
        if ("V" in d) {
          if (d.V < 1 || d.V > 53)
            return null;
          if (!("w" in d))
            d.w = 1;
          if ("Z" in d) {
            week = utcDate(newDate(d.y, 0, 1)), day2 = week.getUTCDay();
            week = day2 > 4 || day2 === 0 ? utcMonday.ceil(week) : utcMonday(week);
            week = utcDay_default.offset(week, (d.V - 1) * 7);
            d.y = week.getUTCFullYear();
            d.m = week.getUTCMonth();
            d.d = week.getUTCDate() + (d.w + 6) % 7;
          } else {
            week = localDate(newDate(d.y, 0, 1)), day2 = week.getDay();
            week = day2 > 4 || day2 === 0 ? monday.ceil(week) : monday(week);
            week = day_default.offset(week, (d.V - 1) * 7);
            d.y = week.getFullYear();
            d.m = week.getMonth();
            d.d = week.getDate() + (d.w + 6) % 7;
          }
        } else if ("W" in d || "U" in d) {
          if (!("w" in d))
            d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
          day2 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();
          d.m = 0;
          d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day2 + 5) % 7 : d.w + d.U * 7 - (day2 + 6) % 7;
        }
        if ("Z" in d) {
          d.H += d.Z / 100 | 0;
          d.M += d.Z % 100;
          return utcDate(d);
        }
        return localDate(d);
      };
    }
    function parseSpecifier(d, specifier, string2, j) {
      var i = 0, n = specifier.length, m = string2.length, c, parse;
      while (i < n) {
        if (j >= m)
          return -1;
        c = specifier.charCodeAt(i++);
        if (c === 37) {
          c = specifier.charAt(i++);
          parse = parses[c in pads ? specifier.charAt(i++) : c];
          if (!parse || (j = parse(d, string2, j)) < 0)
            return -1;
        } else if (c != string2.charCodeAt(j++)) {
          return -1;
        }
      }
      return j;
    }
    function parsePeriod(d, string2, i) {
      var n = periodRe.exec(string2.slice(i));
      return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function parseShortWeekday(d, string2, i) {
      var n = shortWeekdayRe.exec(string2.slice(i));
      return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function parseWeekday(d, string2, i) {
      var n = weekdayRe.exec(string2.slice(i));
      return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function parseShortMonth(d, string2, i) {
      var n = shortMonthRe.exec(string2.slice(i));
      return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function parseMonth(d, string2, i) {
      var n = monthRe.exec(string2.slice(i));
      return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function parseLocaleDateTime(d, string2, i) {
      return parseSpecifier(d, locale_dateTime, string2, i);
    }
    function parseLocaleDate(d, string2, i) {
      return parseSpecifier(d, locale_date, string2, i);
    }
    function parseLocaleTime(d, string2, i) {
      return parseSpecifier(d, locale_time, string2, i);
    }
    function formatShortWeekday(d) {
      return locale_shortWeekdays[d.getDay()];
    }
    function formatWeekday(d) {
      return locale_weekdays[d.getDay()];
    }
    function formatShortMonth(d) {
      return locale_shortMonths[d.getMonth()];
    }
    function formatMonth(d) {
      return locale_months[d.getMonth()];
    }
    function formatPeriod(d) {
      return locale_periods[+(d.getHours() >= 12)];
    }
    function formatQuarter(d) {
      return 1 + ~~(d.getMonth() / 3);
    }
    function formatUTCShortWeekday(d) {
      return locale_shortWeekdays[d.getUTCDay()];
    }
    function formatUTCWeekday(d) {
      return locale_weekdays[d.getUTCDay()];
    }
    function formatUTCShortMonth(d) {
      return locale_shortMonths[d.getUTCMonth()];
    }
    function formatUTCMonth(d) {
      return locale_months[d.getUTCMonth()];
    }
    function formatUTCPeriod(d) {
      return locale_periods[+(d.getUTCHours() >= 12)];
    }
    function formatUTCQuarter(d) {
      return 1 + ~~(d.getUTCMonth() / 3);
    }
    return {
      format: function(specifier) {
        var f = newFormat(specifier += "", formats);
        f.toString = function() {
          return specifier;
        };
        return f;
      },
      parse: function(specifier) {
        var p = newParse(specifier += "", false);
        p.toString = function() {
          return specifier;
        };
        return p;
      },
      utcFormat: function(specifier) {
        var f = newFormat(specifier += "", utcFormats);
        f.toString = function() {
          return specifier;
        };
        return f;
      },
      utcParse: function(specifier) {
        var p = newParse(specifier += "", true);
        p.toString = function() {
          return specifier;
        };
        return p;
      }
    };
  }
  var pads = {"-": "", _: " ", "0": "0"};
  var numberRe = /^\s*\d+/;
  var percentRe = /^%/;
  var requoteRe = /[\\^$*+?|[\]().{}]/g;
  function pad(value, fill, width) {
    var sign = value < 0 ? "-" : "", string2 = (sign ? -value : value) + "", length = string2.length;
    return sign + (length < width ? new Array(width - length + 1).join(fill) + string2 : string2);
  }
  function requote(s) {
    return s.replace(requoteRe, "\\$&");
  }
  function formatRe(names) {
    return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
  }
  function formatLookup(names) {
    return new Map(names.map((name, i) => [name.toLowerCase(), i]));
  }
  function parseWeekdayNumberSunday(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 1));
    return n ? (d.w = +n[0], i + n[0].length) : -1;
  }
  function parseWeekdayNumberMonday(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 1));
    return n ? (d.u = +n[0], i + n[0].length) : -1;
  }
  function parseWeekNumberSunday(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.U = +n[0], i + n[0].length) : -1;
  }
  function parseWeekNumberISO(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.V = +n[0], i + n[0].length) : -1;
  }
  function parseWeekNumberMonday(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.W = +n[0], i + n[0].length) : -1;
  }
  function parseFullYear(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 4));
    return n ? (d.y = +n[0], i + n[0].length) : -1;
  }
  function parseYear(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1;
  }
  function parseZone(d, string2, i) {
    var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string2.slice(i, i + 6));
    return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
  }
  function parseQuarter(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 1));
    return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
  }
  function parseMonthNumber(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
  }
  function parseDayOfMonth(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.d = +n[0], i + n[0].length) : -1;
  }
  function parseDayOfYear(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 3));
    return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
  }
  function parseHour24(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.H = +n[0], i + n[0].length) : -1;
  }
  function parseMinutes(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.M = +n[0], i + n[0].length) : -1;
  }
  function parseSeconds(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 2));
    return n ? (d.S = +n[0], i + n[0].length) : -1;
  }
  function parseMilliseconds(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 3));
    return n ? (d.L = +n[0], i + n[0].length) : -1;
  }
  function parseMicroseconds(d, string2, i) {
    var n = numberRe.exec(string2.slice(i, i + 6));
    return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1;
  }
  function parseLiteralPercent(d, string2, i) {
    var n = percentRe.exec(string2.slice(i, i + 1));
    return n ? i + n[0].length : -1;
  }
  function parseUnixTimestamp(d, string2, i) {
    var n = numberRe.exec(string2.slice(i));
    return n ? (d.Q = +n[0], i + n[0].length) : -1;
  }
  function parseUnixTimestampSeconds(d, string2, i) {
    var n = numberRe.exec(string2.slice(i));
    return n ? (d.s = +n[0], i + n[0].length) : -1;
  }
  function formatDayOfMonth(d, p) {
    return pad(d.getDate(), p, 2);
  }
  function formatHour24(d, p) {
    return pad(d.getHours(), p, 2);
  }
  function formatHour12(d, p) {
    return pad(d.getHours() % 12 || 12, p, 2);
  }
  function formatDayOfYear(d, p) {
    return pad(1 + day_default.count(year_default(d), d), p, 3);
  }
  function formatMilliseconds(d, p) {
    return pad(d.getMilliseconds(), p, 3);
  }
  function formatMicroseconds(d, p) {
    return formatMilliseconds(d, p) + "000";
  }
  function formatMonthNumber(d, p) {
    return pad(d.getMonth() + 1, p, 2);
  }
  function formatMinutes(d, p) {
    return pad(d.getMinutes(), p, 2);
  }
  function formatSeconds(d, p) {
    return pad(d.getSeconds(), p, 2);
  }
  function formatWeekdayNumberMonday(d) {
    var day2 = d.getDay();
    return day2 === 0 ? 7 : day2;
  }
  function formatWeekNumberSunday(d, p) {
    return pad(sunday.count(year_default(d) - 1, d), p, 2);
  }
  function dISO(d) {
    var day2 = d.getDay();
    return day2 >= 4 || day2 === 0 ? thursday(d) : thursday.ceil(d);
  }
  function formatWeekNumberISO(d, p) {
    d = dISO(d);
    return pad(thursday.count(year_default(d), d) + (year_default(d).getDay() === 4), p, 2);
  }
  function formatWeekdayNumberSunday(d) {
    return d.getDay();
  }
  function formatWeekNumberMonday(d, p) {
    return pad(monday.count(year_default(d) - 1, d), p, 2);
  }
  function formatYear(d, p) {
    return pad(d.getFullYear() % 100, p, 2);
  }
  function formatYearISO(d, p) {
    d = dISO(d);
    return pad(d.getFullYear() % 100, p, 2);
  }
  function formatFullYear(d, p) {
    return pad(d.getFullYear() % 1e4, p, 4);
  }
  function formatFullYearISO(d, p) {
    var day2 = d.getDay();
    d = day2 >= 4 || day2 === 0 ? thursday(d) : thursday.ceil(d);
    return pad(d.getFullYear() % 1e4, p, 4);
  }
  function formatZone(d) {
    var z = d.getTimezoneOffset();
    return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
  }
  function formatUTCDayOfMonth(d, p) {
    return pad(d.getUTCDate(), p, 2);
  }
  function formatUTCHour24(d, p) {
    return pad(d.getUTCHours(), p, 2);
  }
  function formatUTCHour12(d, p) {
    return pad(d.getUTCHours() % 12 || 12, p, 2);
  }
  function formatUTCDayOfYear(d, p) {
    return pad(1 + utcDay_default.count(utcYear_default(d), d), p, 3);
  }
  function formatUTCMilliseconds(d, p) {
    return pad(d.getUTCMilliseconds(), p, 3);
  }
  function formatUTCMicroseconds(d, p) {
    return formatUTCMilliseconds(d, p) + "000";
  }
  function formatUTCMonthNumber(d, p) {
    return pad(d.getUTCMonth() + 1, p, 2);
  }
  function formatUTCMinutes(d, p) {
    return pad(d.getUTCMinutes(), p, 2);
  }
  function formatUTCSeconds(d, p) {
    return pad(d.getUTCSeconds(), p, 2);
  }
  function formatUTCWeekdayNumberMonday(d) {
    var dow = d.getUTCDay();
    return dow === 0 ? 7 : dow;
  }
  function formatUTCWeekNumberSunday(d, p) {
    return pad(utcSunday.count(utcYear_default(d) - 1, d), p, 2);
  }
  function UTCdISO(d) {
    var day2 = d.getUTCDay();
    return day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d);
  }
  function formatUTCWeekNumberISO(d, p) {
    d = UTCdISO(d);
    return pad(utcThursday.count(utcYear_default(d), d) + (utcYear_default(d).getUTCDay() === 4), p, 2);
  }
  function formatUTCWeekdayNumberSunday(d) {
    return d.getUTCDay();
  }
  function formatUTCWeekNumberMonday(d, p) {
    return pad(utcMonday.count(utcYear_default(d) - 1, d), p, 2);
  }
  function formatUTCYear(d, p) {
    return pad(d.getUTCFullYear() % 100, p, 2);
  }
  function formatUTCYearISO(d, p) {
    d = UTCdISO(d);
    return pad(d.getUTCFullYear() % 100, p, 2);
  }
  function formatUTCFullYear(d, p) {
    return pad(d.getUTCFullYear() % 1e4, p, 4);
  }
  function formatUTCFullYearISO(d, p) {
    var day2 = d.getUTCDay();
    d = day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d);
    return pad(d.getUTCFullYear() % 1e4, p, 4);
  }
  function formatUTCZone() {
    return "+0000";
  }
  function formatLiteralPercent() {
    return "%";
  }
  function formatUnixTimestamp(d) {
    return +d;
  }
  function formatUnixTimestampSeconds(d) {
    return Math.floor(+d / 1e3);
  }

  // node_modules/d3-time-format/src/defaultLocale.js
  var locale2;
  var timeFormat;
  var timeParse;
  var utcFormat;
  var utcParse;
  defaultLocale2({
    dateTime: "%x, %X",
    date: "%-m/%-d/%Y",
    time: "%-I:%M:%S %p",
    periods: ["AM", "PM"],
    days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  });
  function defaultLocale2(definition) {
    locale2 = formatLocale(definition);
    timeFormat = locale2.format;
    timeParse = locale2.parse;
    utcFormat = locale2.utcFormat;
    utcParse = locale2.utcParse;
    return locale2;
  }

  // node_modules/svelte/internal/index.mjs
  function noop() {
  }
  function assign(tar, src) {
    for (const k in src)
      tar[k] = src[k];
    return tar;
  }
  function is_promise(value) {
    return value && typeof value === "object" && typeof value.then === "function";
  }
  function run(fn) {
    return fn();
  }
  function blank_object() {
    return 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 subscribe(store, ...callbacks) {
    if (store == null) {
      return noop;
    }
    const unsub = store.subscribe(...callbacks);
    return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
  }
  function get_store_value(store) {
    let value;
    subscribe(store, (_2) => value = _2)();
    return value;
  }
  function component_subscribe(component, store, callback) {
    component.$$.on_destroy.push(subscribe(store, callback));
  }
  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(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) {
    const slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_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 null_to_empty(value) {
    return value == null ? "" : value;
  }
  function set_store_value(store, ret, value = ret) {
    store.set(value);
    return ret;
  }
  function action_destroyer(action_result) {
    return action_result && is_function(action_result.destroy) ? action_result.destroy : noop;
  }
  var is_client = typeof window !== "undefined";
  var tasks = new Set();
  function append(target, node) {
    target.appendChild(node);
  }
  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 empty() {
    return text("");
  }
  function listen(node, event, handler, options) {
    node.addEventListener(event, handler, options);
    return () => node.removeEventListener(event, handler, options);
  }
  function prevent_default(fn) {
    return function(event) {
      event.preventDefault();
      return fn.call(this, event);
    };
  }
  function self2(fn) {
    return function(event) {
      if (event.target === this)
        fn.call(this, event);
    };
  }
  function attr(node, attribute, value) {
    if (value == null)
      node.removeAttribute(attribute);
    else if (node.getAttribute(attribute) !== value)
      node.setAttribute(attribute, value);
  }
  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) {
    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;
      }
    }
  }
  function select_value(select) {
    const selected_option = select.querySelector(":checked") || select.options[0];
    return selected_option && selected_option.__value;
  }
  var crossorigin;
  function is_crossorigin() {
    if (crossorigin === void 0) {
      crossorigin = false;
      try {
        if (typeof window !== "undefined" && window.parent) {
          void window.parent.document;
        }
      } catch (error) {
        crossorigin = true;
      }
    }
    return crossorigin;
  }
  function add_resize_listener(node, fn) {
    const computed_style = getComputedStyle(node);
    if (computed_style.position === "static") {
      node.style.position = "relative";
    }
    const iframe = element("iframe");
    iframe.setAttribute("style", "display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;");
    iframe.setAttribute("aria-hidden", "true");
    iframe.tabIndex = -1;
    const crossorigin2 = is_crossorigin();
    let unsubscribe;
    if (crossorigin2) {
      iframe.src = "data:text/html,<script>onresize=function(){parent.postMessage(0,'*')}</script>";
      unsubscribe = listen(window, "message", (event) => {
        if (event.source === iframe.contentWindow)
          fn();
      });
    } else {
      iframe.src = "about:blank";
      iframe.onload = () => {
        unsubscribe = listen(iframe.contentWindow, "resize", fn);
      };
    }
    append(node, iframe);
    return () => {
      if (crossorigin2) {
        unsubscribe();
      } else if (unsubscribe && iframe.contentWindow) {
        unsubscribe();
      }
      detach(iframe);
    };
  }
  function toggle_class(element2, name, toggle) {
    element2.classList[toggle ? "add" : "remove"](name);
  }
  function custom_event(type, detail) {
    const e = document.createEvent("CustomEvent");
    e.initCustomEvent(type, false, false, detail);
    return e;
  }
  var HtmlTag = class {
    constructor(anchor = null) {
      this.a = anchor;
      this.e = this.n = null;
    }
    m(html, target, anchor = null) {
      if (!this.e) {
        this.e = element(target.nodeName);
        this.t = target;
        this.h(html);
      }
      this.i(anchor);
    }
    h(html) {
      this.e.innerHTML = html;
      this.n = Array.from(this.e.childNodes);
    }
    i(anchor) {
      for (let i = 0; i < this.n.length; i += 1) {
        insert(this.t, this.n[i], anchor);
      }
    }
    p(html) {
      this.d();
      this.h(html);
      this.i(this.a);
    }
    d() {
      this.n.forEach(detach);
    }
  };
  var active_docs = new Set();
  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) => {
      const callbacks = component.$$.callbacks[type];
      if (callbacks) {
        const event = custom_event(type, detail);
        callbacks.slice().forEach((fn) => {
          fn.call(component, event);
        });
      }
    };
  }
  function setContext(key, context) {
    get_current_component().$$.context.set(key, context);
  }
  function getContext(key) {
    return get_current_component().$$.context.get(key);
  }
  function bubble(component, event) {
    const callbacks = component.$$.callbacks[event.type];
    if (callbacks) {
      callbacks.slice().forEach((fn) => fn(event));
    }
  }
  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 tick() {
    schedule_update();
    return resolved_promise;
  }
  function add_render_callback(fn) {
    render_callbacks.push(fn);
  }
  function add_flush_callback(fn) {
    flush_callbacks.push(fn);
  }
  var flushing = false;
  var seen_callbacks = new Set();
  function flush() {
    if (flushing)
      return;
    flushing = true;
    do {
      for (let i = 0; i < dirty_components.length; i += 1) {
        const component = dirty_components[i];
        set_current_component(component);
        update(component.$$);
      }
      set_current_component(null);
      dirty_components.length = 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;
    flushing = false;
    seen_callbacks.clear();
  }
  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 = new Set();
  var outros;
  function group_outros() {
    outros = {
      r: 0,
      c: [],
      p: outros
    };
  }
  function check_outros() {
    if (!outros.r) {
      run_all(outros.c);
    }
    outros = outros.p;
  }
  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);
    }
  }
  function handle_promise(promise, info) {
    const token = info.token = {};
    function update2(type, index, key, value) {
      if (info.token !== token)
        return;
      info.resolved = value;
      let child_ctx = info.ctx;
      if (key !== void 0) {
        child_ctx = child_ctx.slice();
        child_ctx[key] = value;
      }
      const block = type && (info.current = type)(child_ctx);
      let needs_flush = false;
      if (info.block) {
        if (info.blocks) {
          info.blocks.forEach((block2, i) => {
            if (i !== index && block2) {
              group_outros();
              transition_out(block2, 1, 1, () => {
                if (info.blocks[i] === block2) {
                  info.blocks[i] = null;
                }
              });
              check_outros();
            }
          });
        } else {
          info.block.d(1);
        }
        block.c();
        transition_in(block, 1);
        block.m(info.mount(), info.anchor);
        needs_flush = true;
      }
      info.block = block;
      if (info.blocks)
        info.blocks[index] = block;
      if (needs_flush) {
        flush();
      }
    }
    if (is_promise(promise)) {
      const current_component2 = get_current_component();
      promise.then((value) => {
        set_current_component(current_component2);
        update2(info.then, 1, info.value, value);
        set_current_component(null);
      }, (error) => {
        set_current_component(current_component2);
        update2(info.catch, 2, info.error, error);
        set_current_component(null);
        if (!info.hasCatch) {
          throw error;
        }
      });
      if (info.current !== info.pending) {
        update2(info.pending, 0);
        return true;
      }
    } else {
      if (info.current !== info.then) {
        update2(info.then, 1, info.value, promise);
        return true;
      }
      info.resolved = promise;
    }
  }
  var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global;
  function outro_and_destroy_block(block, lookup) {
    transition_out(block, 1, 1, () => {
      lookup.delete(block.key);
    });
  }
  function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block21, next, get_context) {
    let o = old_blocks.length;
    let n = list.length;
    let i = o;
    const old_indexes = {};
    while (i--)
      old_indexes[old_blocks[i].key] = i;
    const new_blocks = [];
    const new_lookup = new Map();
    const deltas = new Map();
    i = n;
    while (i--) {
      const child_ctx = get_context(ctx, list, i);
      const key = get_key(child_ctx);
      let block = lookup.get(key);
      if (!block) {
        block = create_each_block21(key, child_ctx);
        block.c();
      } else if (dynamic) {
        block.p(child_ctx, dirty);
      }
      new_lookup.set(key, new_blocks[i] = block);
      if (key in old_indexes)
        deltas.set(key, Math.abs(i - old_indexes[key]));
    }
    const will_move = new Set();
    const did_move = new Set();
    function insert2(block) {
      transition_in(block, 1);
      block.m(node, next);
      lookup.set(block.key, block);
      next = block.first;
      n--;
    }
    while (o && n) {
      const new_block = new_blocks[n - 1];
      const old_block = old_blocks[o - 1];
      const new_key = new_block.key;
      const old_key = old_block.key;
      if (new_block === old_block) {
        next = new_block.first;
        o--;
        n--;
      } else if (!new_lookup.has(old_key)) {
        destroy(old_block, lookup);
        o--;
      } else if (!lookup.has(new_key) || will_move.has(new_key)) {
        insert2(new_block);
      } else if (did_move.has(old_key)) {
        o--;
      } else if (deltas.get(new_key) > deltas.get(old_key)) {
        did_move.add(new_key);
        insert2(new_block);
      } else {
        will_move.add(old_key);
        o--;
      }
    }
    while (o--) {
      const old_block = old_blocks[o];
      if (!new_lookup.has(old_block.key))
        destroy(old_block, lookup);
    }
    while (n)
      insert2(new_blocks[n - 1]);
    return new_blocks;
  }
  var boolean_attributes = new Set([
    "allowfullscreen",
    "allowpaymentrequest",
    "async",
    "autofocus",
    "autoplay",
    "checked",
    "controls",
    "default",
    "defer",
    "disabled",
    "formnovalidate",
    "hidden",
    "ismap",
    "loop",
    "multiple",
    "muted",
    "nomodule",
    "novalidate",
    "open",
    "playsinline",
    "readonly",
    "required",
    "reversed",
    "selected"
  ]);
  function bind(component, name, callback) {
    const index = component.$$.props[name];
    if (index !== void 0) {
      component.$$.bound[index] = callback;
      callback(component.$$.ctx[index]);
    }
  }
  function create_component(block) {
    block && block.c();
  }
  function mount_component(component, target, anchor) {
    const {fragment, on_mount, on_destroy, after_update} = component.$$;
    fragment && fragment.m(target, anchor);
    add_render_callback(() => {
      const new_on_destroy = on_mount.map(run).filter(is_function);
      if (on_destroy) {
        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, instance41, create_fragment42, not_equal, props, dirty = [-1]) {
    const parent_component = current_component;
    set_current_component(component);
    const prop_values = options.props || {};
    const $$ = component.$$ = {
      fragment: null,
      ctx: null,
      props,
      update: noop,
      not_equal,
      bound: blank_object(),
      on_mount: [],
      on_destroy: [],
      before_update: [],
      after_update: [],
      context: new Map(parent_component ? parent_component.$$.context : []),
      callbacks: blank_object(),
      dirty,
      skip_bound: false
    };
    let ready = false;
    $$.ctx = instance41 ? instance41(component, prop_values, (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_fragment42 ? create_fragment42($$.ctx) : false;
    if (options.target) {
      if (options.hydrate) {
        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);
      flush();
    }
    set_current_component(parent_component);
  }
  var SvelteElement;
  if (typeof HTMLElement === "function") {
    SvelteElement = class extends HTMLElement {
      constructor() {
        super();
        this.attachShadow({mode: "open"});
      }
      connectedCallback() {
        for (const key in this.$$.slotted) {
          this.appendChild(this.$$.slotted[key]);
        }
      }
      attributeChangedCallback(attr2, _oldValue, newValue) {
        this[attr2] = newValue;
      }
      $destroy() {
        destroy_component(this, 1);
        this.$destroy = noop;
      }
      $on(type, callback) {
        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) {
      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;
      }
    }
  };

  // node_modules/svelte/store/index.mjs
  var subscriber_queue = [];
  function readable(value, start) {
    return {
      subscribe: writable(value, start).subscribe
    };
  }
  function writable(value, start = noop) {
    let stop;
    const subscribers = [];
    function set(new_value) {
      if (safe_not_equal(value, new_value)) {
        value = new_value;
        if (stop) {
          const run_queue = !subscriber_queue.length;
          for (let i = 0; i < subscribers.length; i += 1) {
            const s = subscribers[i];
            s[1]();
            subscriber_queue.push(s, value);
          }
          if (run_queue) {
            for (let i = 0; i < subscriber_queue.length; i += 2) {
              subscriber_queue[i][0](subscriber_queue[i + 1]);
            }
            subscriber_queue.length = 0;
          }
        }
      }
    }
    function update2(fn) {
      set(fn(value));
    }
    function subscribe2(run2, invalidate = noop) {
      const subscriber = [run2, invalidate];
      subscribers.push(subscriber);
      if (subscribers.length === 1) {
        stop = start(set) || noop;
      }
      run2(value);
      return () => {
        const index = subscribers.indexOf(subscriber);
        if (index !== -1) {
          subscribers.splice(index, 1);
        }
        if (subscribers.length === 0) {
          stop();
          stop = null;
        }
      };
    }
    return {set, update: update2, subscribe: subscribe2};
  }
  function derived(stores, fn, initial_value) {
    const single = !Array.isArray(stores);
    const stores_array = single ? [stores] : stores;
    const auto = fn.length < 2;
    return readable(initial_value, (set) => {
      let inited = false;
      const values = [];
      let pending = 0;
      let cleanup = noop;
      const sync = () => {
        if (pending) {
          return;
        }
        cleanup();
        const result = fn(single ? values[0] : values, set);
        if (auto) {
          set(result);
        } else {
          cleanup = is_function(result) ? result : noop;
        }
      };
      const unsubscribers = stores_array.map((store, i) => subscribe(store, (value) => {
        values[i] = value;
        pending &= ~(1 << i);
        if (inited) {
          sync();
        }
      }, () => {
        pending |= 1 << i;
      }));
      inited = true;
      sync();
      return function stop() {
        run_all(unsubscribers);
        cleanup();
      };
    });
  }

  // src/lib/equals.ts
  function shallow_equal(a, b) {
    const l = a.length;
    if (l !== b.length) {
      return false;
    }
    for (let i = 0; i < l; i += 1) {
      if (a[i] !== b[i]) {
        return false;
      }
    }
    return true;
  }

  // src/lib/store.ts
  function derived_array(store, getter) {
    let val = [];
    return derived(store, (store_val, set) => {
      const newVal = getter(store_val);
      if (!shallow_equal(val, newVal)) {
        set(newVal);
        val = newVal;
      }
    }, val);
  }
  function localStorageSyncedStore(key, validator, init3) {
    const stored_val = localStorage.getItem(key);
    const initial = stored_val ? validator(JSON.parse(stored_val)) : init3();
    const store = writable(initial);
    store.subscribe((val) => {
      localStorage.setItem(key, JSON.stringify(val));
    });
    return store;
  }

  // src/lib/validation.ts
  var ValidationError = class extends Error {
  };
  function defaultValue(validator, value) {
    return (json) => {
      try {
        return validator(json);
      } catch (err) {
        return value;
      }
    };
  }
  function unknown(json) {
    return json;
  }
  function string(json) {
    if (typeof json === "string") {
      return json;
    }
    throw new ValidationError(`Expected a string, got '${json}' instead.`);
  }
  var optional_string = defaultValue(string, "");
  function boolean(json) {
    if (typeof json === "boolean") {
      return json;
    }
    throw new ValidationError(`Expected a boolean, got '${json}' instead.`);
  }
  function number(json) {
    if (typeof json === "number") {
      return json;
    }
    throw new ValidationError(`Expected a number, got '${json}' instead.`);
  }
  function date(json) {
    if (typeof json === "string" || json instanceof Date) {
      const parsed = new Date(json);
      if (Number.isNaN(+parsed)) {
        throw new ValidationError(`Expected a date: ${json}`);
      }
      return parsed;
    }
    throw new ValidationError(`Expected a date: ${json}`);
  }
  function constant(value) {
    return (json) => {
      if (json === value) {
        return json;
      }
      throw new ValidationError(`Expected a constant: ${json}`);
    };
  }
  function union(...args) {
    return (json) => {
      for (const validator of args) {
        try {
          return validator(json);
        } catch (exc) {
        }
      }
      throw new ValidationError("Validating union failed");
    };
  }
  function lazy(func) {
    return (json) => func()(json);
  }
  function array(validator) {
    return (json) => {
      if (Array.isArray(json)) {
        const result = [];
        json.forEach((element2) => {
          result.push(validator(element2));
        });
        return result;
      }
      throw new ValidationError(`Expected an array: ${json}`);
    };
  }
  function tuple(decoders) {
    return (json) => {
      if (Array.isArray(json) && json.length === 2) {
        const result = [];
        for (let i = 0; i < decoders.length; i += 1) {
          result[i] = decoders[i](json[i]);
        }
        return result;
      }
      throw new ValidationError(`Expected a tuple: ${json}`);
    };
  }
  function isJsonObject(json) {
    return typeof json === "object" && json !== null && !Array.isArray(json);
  }
  function object(validators) {
    return (json) => {
      if (isJsonObject(json)) {
        const obj = {};
        for (const key in validators) {
          if (Object.prototype.hasOwnProperty.call(validators, key)) {
            obj[key] = validators[key](json[key]);
          }
        }
        return obj;
      }
      throw new ValidationError("Validating object failed");
    };
  }
  function record(decoder) {
    return (json) => {
      if (isJsonObject(json)) {
        const ret = {};
        for (const [key, value] of Object.entries(json)) {
          ret[key] = decoder(value);
        }
        return ret;
      }
      throw new ValidationError();
    };
  }

  // src/stores/url.ts
  var baseURL = writable("");
  var urlSyncedParams = [
    "account",
    "charts",
    "conversion",
    "filter",
    "interval",
    "time"
  ];

  // src/stores/index.ts
  var urlHash = writable("");
  var conversion = writable("");
  var interval = writable("month");
  var favaAPIValidator = object({
    accounts: array(string),
    baseURL: string,
    currencies: array(string),
    documentTitle: string,
    errors: number,
    favaOptions: object({
      "auto-reload": boolean,
      "currency-column": number,
      conversion: string,
      interval: string,
      locale: union(string, constant(null))
    }),
    have_excel: boolean,
    incognito: boolean,
    links: array(string),
    options: object({
      documents: array(string),
      operating_currency: array(string)
    }),
    pageTitle: string,
    payees: array(string),
    tags: array(string),
    years: array(string)
  });
  var favaAPI = {
    accounts: [],
    baseURL: "",
    currencies: [],
    documentTitle: "",
    errors: 0,
    favaOptions: {
      "auto-reload": false,
      "currency-column": 80,
      conversion: "at_cost",
      interval: "month",
      locale: null
    },
    have_excel: false,
    incognito: false,
    links: [],
    pageTitle: "",
    payees: [],
    options: {
      documents: [],
      operating_currency: []
    },
    tags: [],
    years: []
  };
  var favaAPIStore = writable(favaAPI);
  var HAVE_EXCEL = derived(favaAPIStore, (val) => val.have_excel);
  var accounts = derived_array(favaAPIStore, (val) => val.accounts);
  var currencies = derived_array(favaAPIStore, (val) => val.currencies);
  var links = derived_array(favaAPIStore, (val) => val.links);
  var payees = derived_array(favaAPIStore, (val) => val.payees);
  var tags = derived_array(favaAPIStore, (val) => val.tags);
  var years2 = derived_array(favaAPIStore, (val) => val.years);
  var operating_currency = derived_array(favaAPIStore, (val) => val.options.operating_currency.sort());
  var currencies_sorted = derived_array(currencies, (val) => [...val].sort());
  var errorCount = writable(0);
  favaAPIStore.subscribe((val) => {
    Object.assign(favaAPI, val);
    errorCount.set(favaAPI.errors);
    baseURL.set(favaAPI.baseURL);
  });
  function getCompletion(type) {
    return favaAPI[type];
  }
  function closeOverlay() {
    if (window.location.hash) {
      window.history.pushState({}, "", "#");
    }
    urlHash.set("");
  }

  // src/format.ts
  var formatter;
  var incognito;
  function localeFormatter(locale3) {
    if (!locale3) {
      return format(".2f");
    }
    const opts = {
      minimumFractionDigits: 2
    };
    const fmt = new Intl.NumberFormat(locale3.replace("_", "-"), opts);
    return fmt.format.bind(fmt);
  }
  favaAPIStore.subscribe((favaAPI2) => {
    const {locale: locale3} = favaAPI2.favaOptions;
    formatter = localeFormatter(locale3);
    incognito = favaAPI2.incognito ? (num) => num.replace(/[0-9]/g, "X") : (num) => num;
  });
  function formatCurrency(number5) {
    return incognito(formatter(number5));
  }
  var formatterPer = format(".2f");
  function formatPercentage(number5) {
    return `${formatterPer(Math.abs(number5) * 100)}%`;
  }
  var formatterShort = format(".3s");
  function formatCurrencyShort(number5) {
    return incognito(formatterShort(number5));
  }
  var dateFormat = {
    year: utcFormat("%Y"),
    quarter: (date3) => `${date3.getUTCFullYear()}Q${Math.floor(date3.getUTCMonth() / 3) + 1}`,
    month: utcFormat("%b %Y"),
    week: utcFormat("%YW%W"),
    day: utcFormat("%Y-%m-%d")
  };
  var timeFilterDateFormat = {
    year: utcFormat("%Y"),
    quarter: (date3) => `${date3.getUTCFullYear()}-Q${Math.floor(date3.getUTCMonth() / 3) + 1}`,
    month: utcFormat("%Y-%m"),
    week: utcFormat("%Y-W%W"),
    day: utcFormat("%Y-%m-%d")
  };
  function todayAsString() {
    return timeFormat("%Y-%m-%d")(new Date());
  }
  var currentDateFormat = derived(interval, (val) => dateFormat[val]);
  var currentTimeFilterDateFormat = derived(interval, (val) => timeFilterDateFormat[val]);

  // src/entries.ts
  var postingValidator = object({
    account: string,
    amount: string
  });
  function emptyPosting() {
    return {
      account: "",
      amount: ""
    };
  }
  var EntryBase = class {
    constructor(type) {
      this.type = type;
      this.meta = {};
      this.date = todayAsString();
    }
  };
  var validatorBase = {
    type: string,
    date: string,
    meta: record(unknown)
  };
  var Balance = class extends EntryBase {
    constructor() {
      super("Balance");
      this.account = "";
      this.amount = {
        number: "",
        currency: ""
      };
    }
  };
  Balance.validator = object({
    ...validatorBase,
    type: constant("Balance"),
    account: string,
    amount: object({number: string, currency: string})
  });
  var Note = class extends EntryBase {
    constructor() {
      super("Note");
      this.account = "";
      this.comment = "";
    }
  };
  Note.validator = object({
    ...validatorBase,
    type: constant("Note"),
    account: string,
    comment: string
  });
  var Transaction2 = class extends EntryBase {
    constructor() {
      super("Transaction");
      this.flag = "*";
      this.payee = "";
      this.narration = "";
      this.postings = [emptyPosting(), emptyPosting()];
    }
    toString() {
      const postings = this.postings.map((p) => `  ${p.account}  ${p.amount}`);
      return `${this.date} ${this.flag} "${this.payee}" "${this.narration}"
${postings.join("\n")}`;
    }
    static fromJSON(json) {
      return Object.assign(new Transaction2(), Transaction2.validator(json));
    }
  };
  var Transaction = Transaction2;
  Transaction.validator = object({
    ...validatorBase,
    type: constant("Transaction"),
    flag: string,
    payee: optional_string,
    narration: optional_string,
    postings: array(postingValidator)
  });
  var entryValidator = union(Balance.validator, Note.validator, Transaction.validator);
  var constructors = {
    Balance,
    Note,
    Transaction
  };
  function create(type) {
    return new constructors[type]();
  }

  // src/helpers.ts
  var baseURL_val = "";
  baseURL.subscribe((val) => {
    baseURL_val = val;
  });
  function urlFor(report, params, update2 = true) {
    const url = `${baseURL_val}${report}`;
    const urlParams = new URLSearchParams();
    if (update2) {
      const oldParams = new URL(window.location.href).searchParams;
      for (const name of urlSyncedParams) {
        const value = oldParams.get(name);
        if (value) {
          urlParams.set(name, value);
        }
      }
    }
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        urlParams.set(key, value);
      });
    }
    const urlParamString = urlParams.toString();
    return urlParamString ? `${url}?${urlParams.toString()}` : url;
  }
  function accountUrl(account2) {
    return new URL(urlFor(`account/${account2}`), window.location.href).toString();
  }

  // src/lib/fetch.ts
  function fetch(input, init3 = {}) {
    return window.fetch(input, {
      credentials: "same-origin",
      ...init3
    });
  }
  async function handleJSON(response) {
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    const data = await response.json();
    if (!isJsonObject(data)) {
      throw new Error("Invalid response");
    }
    if (!data.success) {
      throw new Error(string(data.error));
    }
    return data;
  }
  async function handleText(response) {
    if (!response.ok) {
      const msg = await response.text();
      throw new Error(msg || response.statusText);
    }
    return response.text();
  }

  // src/notifications.ts
  var notificationList = document.createElement("div");
  notificationList.className = "notifications";
  document.body.appendChild(notificationList);
  function notify(msg, cls = "info", callback) {
    const notification = document.createElement("li");
    notification.classList.add(cls);
    notification.appendChild(document.createTextNode(msg));
    notificationList.append(notification);
    notification.addEventListener("click", () => {
      notification.remove();
      callback?.();
    });
    setTimeout(() => {
      notification.remove();
    }, 5e3);
  }

  // src/lib/events.ts
  var Events = class {
    constructor() {
      this.events = new Map();
    }
    on(event, callback) {
      const events = this.events.get(event) ?? [];
      this.events.set(event, [...events, callback]);
    }
    once(event, callback) {
      const runOnce = () => {
        this.remove(event, runOnce);
        callback();
      };
      this.on(event, runOnce);
    }
    remove(event, callback) {
      const events = this.events.get(event);
      if (events) {
        this.events.set(event, events.filter((c) => c !== callback));
      }
    }
    trigger(event) {
      const events = this.events.get(event);
      events?.forEach((callback) => {
        callback();
      });
    }
  };
  function delegate(element2, type, selector, callback) {
    element2.addEventListener(type, (event) => {
      let {target} = event;
      if (!(target instanceof Node)) {
        return;
      }
      if (!(target instanceof Element)) {
        target = target.parentNode;
      }
      if (target instanceof Element) {
        const closest = target.closest(selector);
        if (closest) {
          callback(event, closest);
        }
      }
    });
  }
  function once(element2, event, callback) {
    function runOnce(ev) {
      element2.removeEventListener(event, runOnce);
      callback.apply(element2, [ev]);
    }
    element2.addEventListener(event, runOnce);
  }

  // src/lib/dom.ts
  function getScriptTagJSON(selector) {
    const el = document.querySelector(selector);
    return el ? JSON.parse(el.innerHTML) : null;
  }

  // src/i18n.ts
  var translations;
  function _(text2) {
    if (translations === void 0) {
      translations = record(string)(getScriptTagJSON("#translations"));
    }
    return translations[text2] || text2;
  }

  // src/lib/iso4217.ts
  var iso4217_default = new Set([
    "AED",
    "AFN",
    "ALL",
    "AMD",
    "ANG",
    "AOA",
    "ARS",
    "AUD",
    "AWG",
    "AZN",
    "BAM",
    "BBD",
    "BDT",
    "BGN",
    "BHD",
    "BIF",
    "BMD",
    "BND",
    "BOB",
    "BOV",
    "BRL",
    "BSD",
    "BTN",
    "BWP",
    "BYN",
    "BZD",
    "CAD",
    "CDF",
    "CHE",
    "CHF",
    "CHW",
    "CLF",
    "CLP",
    "CNY",
    "COP",
    "COU",
    "CRC",
    "CUC",
    "CUP",
    "CVE",
    "CZK",
    "DJF",
    "DKK",
    "DOP",
    "DZD",
    "EGP",
    "ERN",
    "ETB",
    "EUR",
    "FJD",
    "FKP",
    "GBP",
    "GEL",
    "GHS",
    "GIP",
    "GMD",
    "GNF",
    "GTQ",
    "GYD",
    "HKD",
    "HNL",
    "HRK",
    "HTG",
    "HUF",
    "IDR",
    "ILS",
    "INR",
    "IQD",
    "IRR",
    "ISK",
    "JMD",
    "JOD",
    "JPY",
    "KES",
    "KGS",
    "KHR",
    "KMF",
    "KPW",
    "KRW",
    "KWD",
    "KYD",
    "KZT",
    "LAK",
    "LBP",
    "LKR",
    "LRD",
    "LSL",
    "LYD",
    "MAD",
    "MDL",
    "MGA",
    "MKD",
    "MMK",
    "MNT",
    "MOP",
    "MRU",
    "MUR",
    "MVR",
    "MWK",
    "MXN",
    "MXV",
    "MYR",
    "MZN",
    "NAD",
    "NGN",
    "NIO",
    "NOK",
    "NPR",
    "NZD",
    "OMR",
    "PAB",
    "PEN",
    "PGK",
    "PHP",
    "PKR",
    "PLN",
    "PYG",
    "QAR",
    "RON",
    "RSD",
    "RUB",
    "RWF",
    "SAR",
    "SBD",
    "SCR",
    "SDG",
    "SEK",
    "SGD",
    "SHP",
    "SLL",
    "SOS",
    "SRD",
    "SSP",
    "STN",
    "SVC",
    "SYP",
    "SZL",
    "THB",
    "TJS",
    "TMT",
    "TND",
    "TOP",
    "TRY",
    "TTD",
    "TWD",
    "TZS",
    "UAH",
    "UGX",
    "USD",
    "USN",
    "UYI",
    "UYU",
    "UYW",
    "UZS",
    "VES",
    "VND",
    "VUV",
    "WST",
    "XAF",
    "XAG",
    "XAU",
    "XBA",
    "XBB",
    "XBC",
    "XBD",
    "XCD",
    "XDR",
    "XOF",
    "XPD",
    "XPF",
    "XPT",
    "XSU",
    "XTS",
    "XUA",
    "XXX",
    "YER",
    "ZAR",
    "ZMW",
    "ZWL"
  ]);

  // src/stores/chart.ts
  var showCharts = writable(true);
  var activeChart = writable(void 0);
  var chartMode = writable("treemap");
  var lineChartMode = writable("line");
  var chartCurrency = writable("");
  var currencySuggestions = derived([operating_currency, currencies_sorted], ([operating_currency_val, currencies_sorted_val]) => [
    ...operating_currency_val,
    ...currencies_sorted_val.filter((c) => !operating_currency_val.includes(c) && iso4217_default.has(c))
  ]);
  var conversions = derived(currencySuggestions, (currencySuggestions_val) => [
    ["at_cost", _("At Cost")],
    ["at_value", _("At Market Value")],
    ["units", _("Units")],
    ...currencySuggestions_val.map((currency) => [
      currency,
      `Converted to ${currency}`
    ])
  ]);

  // src/stores/filters.ts
  var time_filter = writable("");
  var account_filter = writable("");
  var fql_filter = writable("");
  function getFilterParams() {
    return {
      account: get_store_value(account_filter),
      filter: get_store_value(fql_filter),
      time: get_store_value(time_filter)
    };
  }

  // src/router.ts
  var Router = class extends Events {
    constructor() {
      super();
      this.hash = window.location.hash;
      this.pathname = window.location.pathname;
      this.search = window.location.search;
      this.interruptHandlers = new Set();
    }
    shouldInterrupt() {
      for (const handler of this.interruptHandlers) {
        const ret = handler();
        if (ret) {
          return ret;
        }
      }
      return null;
    }
    init() {
      urlHash.set(window.location.hash.slice(1));
      this.updateState();
      window.addEventListener("beforeunload", (event) => {
        const leaveMessage = this.shouldInterrupt();
        if (leaveMessage) {
          event.returnValue = leaveMessage;
        }
      });
      window.addEventListener("popstate", () => {
        urlHash.set(window.location.hash.slice(1));
        if (window.location.hash !== this.hash && window.location.pathname === this.pathname && window.location.search === this.search) {
          this.updateState();
        } else if (window.location.pathname !== this.pathname || window.location.search !== this.search) {
          this.loadURL(window.location.href, false);
        }
      });
      this.takeOverLinks();
    }
    navigate(url, load = true) {
      if (load) {
        this.loadURL(url);
      } else {
        window.history.pushState(null, "", url);
        this.updateState();
      }
    }
    async loadURL(url, historyState = true) {
      const leaveMessage = this.shouldInterrupt();
      if (leaveMessage) {
        if (!window.confirm(leaveMessage)) {
          return;
        }
      }
      const getUrl = new URL(url);
      getUrl.searchParams.set("partial", "true");
      const svg = document.querySelector(".fava-icon");
      svg?.classList.add("loading");
      try {
        const content = await fetch(getUrl.toString()).then(handleText);
        if (historyState) {
          window.history.pushState(null, "", url);
          window.scroll(0, 0);
        }
        this.updateState();
        const article = document.querySelector("article");
        if (article) {
          article.innerHTML = content;
        }
        this.trigger("page-loaded");
        urlHash.set(window.location.hash.slice(1));
      } catch (error) {
        notify(`Loading ${url} failed: ${error.message}`, "error");
      } finally {
        svg?.classList.remove("loading");
      }
    }
    updateState() {
      this.hash = window.location.hash;
      this.pathname = window.location.pathname;
      this.search = window.location.search;
    }
    takeOverLinks() {
      delegate(document, "click", "a", (event, link) => {
        if (link.getAttribute("href")?.charAt(0) === "#" || link.hasAttribute("data-remote") || link.host !== window.location.host || link.protocol.indexOf("http") !== 0 || event.defaultPrevented) {
          return;
        }
        if (link.closest("aside")) {
          const newURL = new URL(link.href);
          const oldParams = new URL(window.location.href).searchParams;
          for (const name of urlSyncedParams) {
            const value = oldParams.get(name);
            if (value) {
              newURL.searchParams.set(name, value);
            } else {
              newURL.searchParams.delete(name);
            }
          }
          link.href = newURL.toString();
        }
        if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
          return;
        }
        event.preventDefault();
        this.navigate(link.href);
      });
    }
    reload() {
      this.loadURL(window.location.href, false);
    }
  };
  var router = new Router();
  var router_default = router;
  function syncStoreValueToUrl(store, name, defaultValue2, shouldLoad = true) {
    let value;
    const params = new URL(window.location.href).searchParams;
    if (typeof defaultValue2 === "boolean") {
      value = params.get(name) !== "false" && defaultValue2;
    } else {
      value = params.get(name) || defaultValue2;
    }
    store.set(value);
    store.subscribe((val) => {
      const newURL = new URL(window.location.href);
      newURL.searchParams.set(name, val.toString());
      if (val === defaultValue2) {
        newURL.searchParams.delete(name);
      }
      if (newURL.href !== window.location.href) {
        router.navigate(newURL.href, shouldLoad);
      }
    });
  }
  function initSyncedStoreValues() {
    syncStoreValueToUrl(account_filter, "account", "");
    syncStoreValueToUrl(fql_filter, "filter", "");
    syncStoreValueToUrl(time_filter, "time", "");
    syncStoreValueToUrl(interval, "interval", favaAPI.favaOptions.interval);
    syncStoreValueToUrl(conversion, "conversion", favaAPI.favaOptions.conversion);
    syncStoreValueToUrl(showCharts, "charts", true, false);
  }

  // src/api.ts
  var validateAPIResponse = object({data: unknown});
  var putAPIValidators = {
    add_document: string,
    add_entries: string,
    attach_document: string,
    format_source: string,
    source: string,
    source_slice: string
  };
  async function put(endpoint, body) {
    const opts = body instanceof FormData ? {body} : {
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    };
    const res = await fetch(urlFor(`api/${endpoint}`), {
      method: "PUT",
      ...opts
    }).then(handleJSON);
    const {data} = validateAPIResponse(res);
    return putAPIValidators[endpoint](data);
  }
  var getAPIValidators = {
    changed: boolean,
    context: object({
      content: string,
      sha256sum: string,
      slice: string
    }),
    errors: number,
    extract: array(entryValidator),
    payee_accounts: array(string),
    move: string,
    payee_transaction: Transaction.validator,
    query_result: object({
      chart: unknown,
      table: string
    })
  };
  async function get(endpoint, params) {
    const url = urlFor(`api/${endpoint}`, params, false);
    const responseData = await fetch(url);
    const json = await handleJSON(responseData);
    const {data} = validateAPIResponse(json);
    return getAPIValidators[endpoint](data);
  }
  async function moveDocument(filename, account2, newName) {
    try {
      const msg = await get("move", {
        filename,
        account: account2,
        newName
      });
      notify(string(msg));
      return true;
    } catch (error) {
      notify(error, "error");
      return false;
    }
  }
  async function deleteDocument(filename) {
    try {
      const url = urlFor("api/document", {filename}, false);
      const res = await fetch(url, {method: "DELETE"}).then(handleJSON);
      const {data} = validateAPIResponse(res);
      notify(string(data));
      return true;
    } catch (error) {
      notify(error, "error");
      return false;
    }
  }
  async function saveEntries(entries) {
    if (!entries.length) {
      return;
    }
    try {
      const data = await put("add_entries", {entries});
      router_default.reload();
      notify(data);
    } catch (error) {
      notify(`Saving failed: ${error}`, "error");
      throw error;
    }
  }

  // src/clipboard.ts
  function copyToClipboard(text2) {
    if (!text2) {
      return;
    }
    const textarea = document.createElement("textarea");
    textarea.value = text2;
    textarea.style.position = "fixed";
    textarea.style.top = "0";
    textarea.style.left = "0";
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();
    try {
      document.execCommand("copy");
    } catch (err) {
      console.error("Unable to copy", err);
    }
    textarea.remove();
  }
  var CopyableText = class extends HTMLElement {
    constructor() {
      super();
      this.addEventListener("click", (event) => {
        copyToClipboard(this.getAttribute("data-clipboard-text"));
        event.stopPropagation();
      });
    }
  };

  // src/editor.ts
  var import_codemirror7 = __toModule(require_codemirror());
  var import_simple = __toModule(require_simple());
  var import_dialog = __toModule(require_dialog());
  var import_searchcursor = __toModule(require_searchcursor());
  var import_search = __toModule(require_search());
  var import_rulers = __toModule(require_rulers());
  var import_trailingspace = __toModule(require_trailingspace());
  var import_foldcode = __toModule(require_foldcode());
  var import_foldgutter = __toModule(require_foldgutter());
  var import_show_hint = __toModule(require_show_hint());
  var import_comment = __toModule(require_comment());
  var import_placeholder = __toModule(require_placeholder());
  var import_active_line = __toModule(require_active_line());

  // src/codemirror/fold-beancount.ts
  var import_codemirror = __toModule(require_codemirror());
  import_codemirror.default.registerHelper("fold", "beancount", (cm, start) => {
    const maxDepth = 100;
    function headerLevel(lineNo) {
      const line = cm.getDoc().getLine(lineNo);
      const match = line && /^\*+/.exec(line);
      if (match) {
        return match[0].length;
      }
      return maxDepth;
    }
    const level = headerLevel(start.line);
    if (level === maxDepth) {
      return void 0;
    }
    const doc = cm.getDoc();
    const lastLineNo = doc.lastLine();
    let end = start.line;
    while (end < lastLineNo) {
      if (headerLevel(end + 1) <= level) {
        break;
      }
      end += 1;
    }
    return {
      from: new import_codemirror.default.Pos(start.line, doc.getLine(start.line).length),
      to: new import_codemirror.default.Pos(end, doc.getLine(end).length)
    };
  });

  // src/codemirror/hint-beancount.ts
  var import_codemirror3 = __toModule(require_codemirror());

  // src/codemirror/helpers.ts
  var import_codemirror2 = __toModule(require_codemirror());

  // src/lib/fuzzy.ts
  function fuzzytest(pattern, text2) {
    const casesensitive = pattern === pattern.toLowerCase();
    const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
    if (exact > -1) {
      return pattern.length ** 2;
    }
    let score = 0;
    let localScore = 0;
    let pindex = 0;
    for (let index = 0; index < text2.length; index += 1) {
      const char = text2[index];
      const search = pattern[pindex];
      if (char === search || char.toLowerCase() === search) {
        pindex += 1;
        localScore += 1;
      } else {
        localScore = 0;
      }
      score += localScore;
    }
    return pindex === pattern.length ? score : 0;
  }
  function fuzzyfilter(pattern, suggestions) {
    if (!pattern) {
      return suggestions;
    }
    return suggestions.map((s) => [s, fuzzytest(pattern, s)]).filter(([, score]) => score).sort((a, b) => b[1] - a[1]).map(([s]) => s);
  }
  function fuzzywrap(pattern, text2) {
    if (!pattern) {
      return text2;
    }
    const casesensitive = pattern === pattern.toLowerCase();
    const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
    if (exact > -1) {
      const before = text2.slice(0, exact);
      const match = text2.slice(exact, exact + pattern.length);
      const after = text2.slice(exact + pattern.length);
      return `${before}<span>${match}</span>${after}`;
    }
    let pindex = 0;
    let inMatch = false;
    const result = [];
    for (let index = 0; index < text2.length; index += 1) {
      const char = text2[index];
      const search = pattern[pindex];
      if (char === search || char.toLowerCase() === search) {
        if (!inMatch) {
          result.push("<span>");
          inMatch = true;
        }
        result.push(char);
        pindex += 1;
      } else {
        if (inMatch) {
          result.push("</span>");
          inMatch = false;
        }
        result.push(char);
      }
    }
    if (inMatch) {
      result.push("</span>");
    }
    return result.join("");
  }

  // src/codemirror/helpers.ts
  function getCurrentWord(cursor, line) {
    const lineUpToCursor = line.slice(0, cursor.ch);
    return /(\S*)$/.exec(lineUpToCursor)?.[0] || "";
  }
  function fuzzyMatch(cursor, currentWord, completions) {
    return {
      list: fuzzyfilter(currentWord, completions),
      from: new import_codemirror2.default.Pos(cursor.line, cursor.ch - currentWord.length),
      to: cursor
    };
  }

  // src/codemirror/hint-beancount.ts
  var completionSources = {
    undatedDirectives: ["option", "plugin", "include"],
    datedDirectives: [
      "open",
      "close",
      "commodity",
      "balance",
      "pad",
      "note",
      "document",
      "price",
      "event",
      "query"
    ]
  };
  var directiveCompletions = {
    open: ["accounts", "currencies"],
    close: ["accounts"],
    commodity: ["currencies"],
    balance: ["accounts", null, "currencies"],
    pad: ["accounts", "accounts"],
    note: ["accounts"],
    document: ["accounts"],
    price: ["currencies", null, "currencies"]
  };
  import_codemirror3.default.registerHelper("hint", "beancount", (cm) => {
    const doc = cm.getDoc();
    const cursor = doc.getCursor();
    const line = doc.getLine(cursor.line);
    const token = cm.getTokenAt(cursor);
    const currentCharacter = line[cursor.ch - 1];
    const currentWord = getCurrentWord(cursor, line);
    if (currentCharacter === "#" || currentCharacter === "^") {
      const list = currentCharacter === "#" ? getCompletion("tags") : getCompletion("links");
      return {
        list,
        from: cursor,
        to: cursor
      };
    }
    if (token.type === "tag" || token.type === "link") {
      const list = token.type === "tag" ? getCompletion("tags") : getCompletion("links");
      return {
        list: list.filter((d) => d.startsWith(currentWord.slice(1))),
        from: new import_codemirror3.default.Pos(cursor.line, token.start + 1),
        to: new import_codemirror3.default.Pos(cursor.line, token.end)
      };
    }
    if (currentWord === line && line.length > 0) {
      return {
        list: completionSources.undatedDirectives.filter((d) => d.startsWith(currentWord)),
        from: new import_codemirror3.default.Pos(cursor.line, 0),
        to: cursor
      };
    }
    const lineTokens = cm.getLineTokens(cursor.line);
    if (lineTokens.length > 0) {
      const startCurrentWord = cursor.ch - currentWord.length;
      const previousTokens = lineTokens.filter((d) => d.end <= startCurrentWord);
      if (lineTokens[0].type === "whitespace") {
        if (previousTokens.length === 1) {
          return fuzzyMatch(cursor, currentWord, getCompletion("accounts"));
        }
      }
      if (lineTokens[0].type === "date") {
        if (previousTokens.length === 2) {
          return {
            list: completionSources.datedDirectives.filter((d) => d.startsWith(currentWord)),
            from: new import_codemirror3.default.Pos(cursor.line, cursor.ch - currentWord.length),
            to: cursor
          };
        }
        const tokenLength = previousTokens.filter((t) => t.type != null).length;
        if (tokenLength % 2 === 0) {
          const directiveType = previousTokens[2].string;
          if (directiveType in directiveCompletions) {
            const complType = directiveCompletions[directiveType][tokenLength / 2 - 2];
            if (complType) {
              return fuzzyMatch(cursor, currentWord, getCompletion(complType));
            }
          }
        }
      }
    }
    return {
      list: []
    };
  });

  // src/codemirror/mode-beancount.ts
  var import_codemirror4 = __toModule(require_codemirror());

  // src/codemirror/account-regex.ts
  var account_regex_default = /(?:(?:[A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u037F\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0528\u052A\u052C\u052E\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u13A0-\u13F5\u1C90-\u1CBA\u1CBD-\u1CBF\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA698\uA69A\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA796\uA798\uA79A\uA79C\uA79E\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA-\uA7AE\uA7B0-\uA7B4\uA7B6\uA7B8\uA7BA\uA7BC\uA7BE\uA7C2\uA7C4-\uA7C7\uA7C9\uA7F5\uFF21-\uFF3A]|\uD801[\uDC00-\uDC27\uDCB0-\uDCD3]|\uD803[\uDC80-\uDCB2]|\uD806[\uDCA0-\uDCBF]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA]|\uD83A[\uDD00-\uDD21])(?:[\x2D0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BEF\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D66-\u0D6F\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F29\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD30-\uDD39\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC66-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF39]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCE9\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])*)(?::(?:[0-9A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u037F\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0528\u052A\u052C\u052E\u0531-\u0556\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u13A0-\u13F5\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u1C90-\u1CBA\u1CBD-\u1CBF\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA620-\uA629\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA698\uA69A\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA796\uA798\uA79A\uA79C\uA79E\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA-\uA7AE\uA7B0-\uA7B4\uA7B6\uA7B8\uA7BA\uA7BC\uA7BE\uA7C2\uA7C4-\uA7C7\uA7C9\uA7F5\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19\uFF21-\uFF3A]|\uD801[\uDC00-\uDC27\uDCA0-\uDCA9\uDCB0-\uDCD3]|\uD803[\uDC80-\uDCB2\uDD30-\uDD39]|\uD804[\uDC66-\uDC6F\uDCF0-\uDCF9\uDD36-\uDD3F\uDDD0-\uDDD9\uDEF0-\uDEF9]|[\uD805\uD807][\uDC50-\uDC59\uDCD0-\uDCD9\uDE50-\uDE59\uDEC0-\uDEC9\uDF30-\uDF39]|\uD806[\uDCA0-\uDCBF\uDCE0-\uDCE9\uDD50-\uDD59]|\uD81A[\uDE60-\uDE69\uDF50-\uDF59]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA\uDFCE-\uDFFF]|\uD838[\uDD40-\uDD49\uDEF0-\uDEF9]|\uD83A[\uDD00-\uDD21\uDD50-\uDD59]|\uD83E[\uDFF0-\uDFF9])(?:[\x2D0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BEF\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D66-\u0D6F\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F29\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD30-\uDD39\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC66-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF39]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCE9\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])*)+/;

  // src/codemirror/mode-beancount.ts
  import_codemirror4.default.defineSimpleMode("beancount", {
    start: [
      {
        regex: /\*.*/,
        token: "comment section",
        sol: true
      },
      {
        regex: /[#*;].*/,
        token: "comment",
        sol: true
      },
      {
        regex: /;.*/,
        token: "comment"
      },
      {
        regex: /(query)(\s*)("[^"]*")(\s*)(")/,
        token: ["directive", "", "string", "", "string"],
        mode: {
          spec: "beancount-query",
          end: /"/
        }
      },
      {
        regex: /"(?:[^\\]|\\.)*?"/,
        token: "string"
      },
      {
        regex: /@|@@|{|}/,
        token: "bracket"
      },
      {
        regex: /\s+/,
        token: "whitespace"
      },
      {
        regex: /#[A-Za-z0-9\-_\/.]+/,
        token: "tag"
      },
      {
        regex: /[A-Z][A-Z0-9'\._\-]{0,22}[A-Z0-9]/,
        token: "commodity keyword"
      },
      {
        regex: /TRUE|FALSE/,
        token: "bool atom"
      },
      {
        regex: account_regex_default,
        token: "account"
      },
      {
        regex: /[*!&#?%PSTCURM]|txn/,
        token: "directive transaction"
      },
      {
        regex: /balance|open|close|commodity|pad|event|custom|price|note|document/,
        token: "directive"
      },
      {
        regex: /pushtag|poptag|pushmeta|popmeta|option|plugin|include/,
        token: "directive",
        sol: true
      },
      {
        regex: /[0-9]{4,}[\-\/][0-9]+[\-\/][0-9]+/,
        token: "date"
      },
      {
        regex: /(?:[0-9]+|[0-9][0-9,]+[0-9])(?:\.[0-9]*)?/,
        token: "number"
      },
      {
        regex: /\^[A-Za-z0-9\-_\/.]+/,
        token: "attribute"
      },
      {
        regex: /[a-z][a-za-z0-9\-_]+:/,
        token: "meta"
      }
    ]
  });

  // src/codemirror/hint-query.ts
  var import_codemirror5 = __toModule(require_codemirror());

  // src/codemirror/bql-grammar.ts
  var bql_grammar_default = {
    columns: [
      "account",
      "balance",
      "change",
      "cost_currency",
      "cost_date",
      "cost_label",
      "cost_number",
      "currency",
      "date",
      "day",
      "description",
      "filename",
      "flag",
      "id",
      "lineno",
      "links",
      "location",
      "month",
      "narration",
      "number",
      "other_accounts",
      "payee",
      "position",
      "posting_flag",
      "price",
      "tags",
      "type",
      "weight",
      "year"
    ],
    functions: [
      "abs",
      "account_sortkey",
      "any_meta",
      "close_date",
      "coalesce",
      "commodity",
      "commodity_meta",
      "convert",
      "cost",
      "count",
      "currency",
      "currency_meta",
      "date",
      "date_add",
      "date_diff",
      "day",
      "entry_meta",
      "filter_currency",
      "findfirst",
      "first",
      "getitem",
      "getprice",
      "grep",
      "grepn",
      "joinstr",
      "last",
      "leaf",
      "length",
      "lower",
      "max",
      "maxwidth",
      "meta",
      "min",
      "month",
      "neg",
      "number",
      "only",
      "open_date",
      "open_meta",
      "parent",
      "possign",
      "quarter",
      "root",
      "safediv",
      "str",
      "subst",
      "sum",
      "today",
      "units",
      "upper",
      "value",
      "weekday",
      "year",
      "ymonth"
    ],
    keywords: [
      "and",
      "as",
      "asc",
      "at",
      "balances",
      "by",
      "clear",
      "close",
      "desc",
      "distinct",
      "errors",
      "explain",
      "false",
      "flatten",
      "from",
      "group",
      "having",
      "in",
      "journal",
      "limit",
      "not",
      "null",
      "on",
      "open",
      "or",
      "order",
      "pivot",
      "print",
      "reload",
      "run",
      "select",
      "true",
      "where"
    ]
  };

  // src/codemirror/hint-query.ts
  var {columns, functions, keywords} = bql_grammar_default;
  var functionCompletions = functions.map((f) => `${f}(`);
  var commands = ["select"];
  import_codemirror5.default.registerHelper("hint", "beancount-query", (cm) => {
    const doc = cm.getDoc();
    const cursor = doc.getCursor();
    const line = doc.getLine(cursor.line);
    const currentWord = getCurrentWord(cursor, line);
    if (currentWord === line) {
      return {
        list: commands.filter((d) => d.startsWith(currentWord)),
        from: new import_codemirror5.default.Pos(cursor.line, 0),
        to: cursor
      };
    }
    return fuzzyMatch(cursor, currentWord, columns.concat(functionCompletions, keywords));
  });

  // src/codemirror/mode-query.ts
  var import_codemirror6 = __toModule(require_codemirror());
  var {columns: columns2, functions: functions2, keywords: keywords2} = bql_grammar_default;
  import_codemirror6.default.defineSimpleMode("beancount-query", {
    start: [
      {
        regex: new RegExp(`(?=^|\\s)(${keywords2.join("|")})(?=\\s|$)`, "i"),
        token: "keyword"
      },
      {
        regex: /(\"[^\"]*\"|\'[^\']*\')/,
        token: "string"
      },
      {
        regex: /(?:\#(?:\"[^\"]*\"|\'[^\']*\')|\d\d\d\d-\d\d-\d\d)/,
        token: "date"
      },
      {
        regex: /[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)/,
        token: "number"
      },
      {
        regex: /[-+]?[0-9]+/,
        token: "number"
      },
      {
        regex: new RegExp(`(${columns2.join("|")})(?=\\)|\\s|,|$)`, "i"),
        token: "variable-2"
      },
      {
        regex: new RegExp(`(${functions2.join("|")})(?=\\()`, "i"),
        token: "variable-3"
      }
    ]
  });

  // src/editor.ts
  import_codemirror7.default.commands.favaFormat = (cm) => {
    put("format_source", {source: cm.getValue()}).then((data) => {
      const scrollPosition = cm.getScrollInfo().top;
      cm.setValue(data);
      cm.scrollTo(null, scrollPosition);
    }, (error) => {
      notify(error, "error");
    });
  };
  import_codemirror7.default.commands.favaToggleComment = (cm) => {
    const doc = cm.getDoc();
    const args = {
      from: doc.getCursor("start"),
      to: doc.getCursor("end"),
      options: {lineComment: ";"}
    };
    if (!cm.uncomment(args.from, args.to, args.options)) {
      cm.lineComment(args.from, args.to, args.options);
    }
  };
  function ignoreKey(key) {
    switch (key) {
      case "ArrowDown":
      case "ArrowUp":
      case "ArrowLeft":
      case "ArrowRight":
      case "PageDown":
      case "PageUp":
      case "Home":
      case "End":
      case "Escape":
      case "Enter":
      case "Alt":
      case "Control":
      case "Meta":
      case "Shift":
      case "CapsLock":
        return true;
      default:
        return false;
    }
  }
  function enableAutomaticCompletions(editor) {
    editor.on("keyup", (cm, event) => {
      if (!cm.state.completionActive && !ignoreKey(event.key)) {
        import_codemirror7.default.commands.autocomplete(cm, void 0, {
          completeSingle: false
        });
      }
    });
  }
  function centerCursor(cm) {
    const {top: top2} = cm.cursorCoords(true, "local");
    const height4 = cm.getScrollInfo().clientHeight;
    cm.scrollTo(null, top2 - height4 / 2);
  }
  function jumpToMarker(cm) {
    const doc = cm.getDoc();
    const cursor = cm.getSearchCursor("FAVA-INSERT-MARKER");
    if (cursor.findNext()) {
      cm.focus();
      doc.setCursor(cursor.from());
      cm.execCommand("goLineUp");
      centerCursor(cm);
    } else {
      doc.setCursor(doc.lastLine(), 0);
    }
  }
  var BeancountTextarea = class extends HTMLTextAreaElement {
    constructor() {
      super();
      import_codemirror7.default.fromTextArea(this, {
        mode: "beancount",
        readOnly: true
      });
    }
  };
  function sourceEditorOptions(save) {
    const currencyColumn = favaAPI.favaOptions["currency-column"];
    const rulers = currencyColumn ? [{column: currencyColumn - 1, lineStyle: "dotted"}] : void 0;
    return {
      mode: "beancount",
      indentUnit: 4,
      lineNumbers: true,
      foldGutter: true,
      showTrailingSpace: true,
      styleActiveLine: true,
      gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
      rulers,
      extraKeys: {
        "Ctrl-Space": "autocomplete",
        "Ctrl-S": save,
        "Cmd-S": save,
        "Ctrl-D": "favaFormat",
        "Cmd-D": "favaFormat",
        "Ctrl-Y": "favaToggleComment",
        "Cmd-Y": "favaToggleComment",
        Tab: (cm) => {
          if (cm.getDoc().somethingSelected()) {
            cm.execCommand("indentMore");
          } else {
            cm.execCommand("insertSoftTab");
          }
        }
      }
    };
  }
  function initSourceEditor(editor) {
    enableAutomaticCompletions(editor);
    const line = parseInt(new URLSearchParams(window.location.search).get("line") || "0", 10);
    if (line > 0) {
      editor.getDoc().setCursor(line - 1, 0);
      centerCursor(editor);
    } else {
      jumpToMarker(editor);
    }
  }

  // src/sort.ts
  function parseNumber(num) {
    const cleaned = num.replace(/[^\-?0-9.]/g, "");
    const n = parseFloat(cleaned);
    return Number.isNaN(n) ? 0 : n;
  }
  function stringComparator(A, B) {
    const a = A.toLowerCase();
    const b = B.toLowerCase();
    if (a === b) {
      return 0;
    }
    return a < b ? -1 : 1;
  }
  function numComparator(a, b) {
    return parseNumber(a) - parseNumber(b);
  }
  function getValue(el) {
    return el?.getAttribute("data-sort-value") || el?.textContent || "";
  }
  function sortFunc(type, order, getter) {
    const comparator = type === "num" ? numComparator : stringComparator;
    function func(a, b) {
      return (order === "asc" ? 1 : -1) * comparator(getter(a), getter(b));
    }
    return func;
  }
  function sortElements(parent2, elements, selector, order, type) {
    const sortFunction = sortFunc(type, order, (a) => getValue(selector(a)));
    const fragment = document.createDocumentFragment();
    elements.sort(sortFunction).forEach((el) => {
      fragment.appendChild(el);
    });
    parent2.appendChild(fragment);
  }
  function getSortOrder(headerElement) {
    if (!headerElement.getAttribute("data-order")) {
      return headerElement.getAttribute("data-sort-default") === "desc" ? "desc" : "asc";
    }
    return headerElement.getAttribute("data-order") === "asc" ? "desc" : "asc";
  }
  function sortableJournal(ol) {
    const head = ol.querySelector(".head");
    if (!head) {
      return;
    }
    const headers = head.querySelectorAll("span[data-sort]");
    headers.forEach((header) => {
      header.addEventListener("click", () => {
        const order = getSortOrder(header);
        const type = header.getAttribute("data-sort");
        const headerClass = header.classList[0];
        headers.forEach((el) => {
          el.removeAttribute("data-order");
        });
        header.setAttribute("data-order", order);
        sortElements(ol, [].slice.call(ol.children, 1), (li) => li.querySelector(`.${headerClass}`), order, type);
      });
    });
  }
  var SortableTable = class extends HTMLTableElement {
    constructor() {
      super();
      const body = this.tBodies.item(0);
      if (!this.tHead || !body) {
        return;
      }
      const headers = [...this.tHead.querySelectorAll("th[data-sort]")];
      headers.forEach((header) => {
        header.addEventListener("click", () => {
          const order = getSortOrder(header);
          const type = header.getAttribute("data-sort");
          const index = headers.indexOf(header);
          headers.forEach((el) => {
            el.removeAttribute("data-order");
          });
          header.setAttribute("data-order", order);
          sortElements(body, [...body.querySelectorAll("tr")], (tr) => tr.cells.item(index), order, type);
        });
      });
    }
  };

  // src/journal.ts
  function escape(value) {
    return value.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
  }
  function addFilter(value) {
    fql_filter.update((fql_filter_val) => fql_filter_val ? `${fql_filter_val} ${value}` : value);
  }
  function handleClick({target}) {
    if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
      return;
    }
    if (target.className === "tag" || target.className === "link") {
      addFilter(target.innerText);
    } else if (target.className === "payee") {
      addFilter(`payee:"^${escape(target.innerText)}$"`);
    } else if (target.tagName === "DT") {
      const expr = `${target.innerText}""`;
      if (target.closest(".postings")) {
        addFilter(`any(${expr})`);
      } else {
        addFilter(expr);
      }
    } else if (target.tagName === "DD") {
      const key = target.previousElementSibling.innerText;
      const value = `"^${escape(target.innerText)}$"`;
      const expr = `${key}${value}`;
      if (target.closest(".postings")) {
        addFilter(`any(${expr})`);
      } else {
        addFilter(expr);
      }
    } else if (target.closest(".indicators")) {
      const entry = target.closest(".transaction");
      if (entry) {
        entry.classList.toggle("show-postings");
      }
    }
  }
  var FavaJournal = class extends HTMLElement {
    constructor() {
      super();
      const ol = this.querySelector("ol");
      const form = this.querySelector("form");
      if (!ol || !form) {
        throw new Error("fava-journal is missing its <ol> or <form>");
      }
      sortableJournal(ol);
      delegate(this, "click", "li", handleClick);
      const entryButtons = form.querySelectorAll("button");
      entryButtons.forEach((button) => {
        button.addEventListener("click", () => {
          const type = button.getAttribute("data-type");
          const shouldShow = button.classList.contains("inactive");
          button.classList.toggle("inactive", !shouldShow);
          if (type === "transaction" || type === "custom" || type === "document") {
            form.querySelectorAll(`.${type}-toggle`).forEach((el) => {
              el.classList.toggle("inactive", !shouldShow);
            });
          }
          ol.classList.toggle(`show-${type}`, shouldShow);
          const filterShow = [];
          entryButtons.forEach((el) => {
            const datatype = el.getAttribute("data-type");
            if (datatype && !el.classList.contains("inactive")) {
              filterShow.push(datatype);
            }
          });
          const url = new URL(window.location.href);
          url.searchParams.delete("show");
          filterShow.forEach((filter2) => {
            url.searchParams.append("show", filter2);
          });
          router_default.navigate(url.toString(), false);
        });
      });
    }
  };

  // src/keyboard-shortcuts.ts
  function showTooltip(target) {
    const tooltip2 = document.createElement("div");
    const isHidden = target.classList.contains("hidden");
    if (isHidden) {
      target.classList.remove("hidden");
    }
    tooltip2.className = "keyboard-tooltip";
    tooltip2.innerHTML = target.getAttribute("data-key") || "";
    document.body.appendChild(tooltip2);
    const parentCoords = target.getBoundingClientRect();
    const left2 = parentCoords.left + Math.min((target.offsetWidth - tooltip2.offsetWidth) / 2, 10);
    const top2 = parentCoords.top + (target.offsetHeight - tooltip2.offsetHeight) / 2;
    tooltip2.style.left = `${left2}px`;
    tooltip2.style.top = `${top2 + window.pageYOffset}px`;
    return () => {
      tooltip2.remove();
      if (isHidden) {
        target.classList.add("hidden");
      }
    };
  }
  function showTooltips() {
    const removes = [];
    document.querySelectorAll("[data-key]").forEach((el) => {
      if (el instanceof HTMLElement) {
        removes.push(showTooltip(el));
      }
    });
    return () => {
      removes.forEach((r) => r());
    };
  }
  function isEditableElement(element2) {
    return element2 instanceof HTMLElement && (element2 instanceof HTMLInputElement || element2 instanceof HTMLSelectElement || element2 instanceof HTMLTextAreaElement || element2.isContentEditable);
  }
  var keyboardShortcuts = new Map();
  var lastChar = "";
  function keydown(event) {
    if (isEditableElement(event.target)) {
      return;
    }
    let eventKey = event.key;
    if (event.metaKey) {
      eventKey = `Meta+${eventKey}`;
    }
    if (event.altKey) {
      eventKey = `Alt+${eventKey}`;
    }
    if (event.ctrlKey) {
      eventKey = `Control+${eventKey}`;
    }
    const lastTwoKeys = `${lastChar} ${eventKey}`;
    const handler = keyboardShortcuts.get(lastTwoKeys) ?? keyboardShortcuts.get(eventKey);
    if (handler) {
      if (handler instanceof HTMLInputElement) {
        event.preventDefault();
        handler.focus();
      } else if (handler instanceof HTMLElement) {
        handler.click();
      } else {
        handler(event);
      }
    }
    if (event.key !== "Alt" && event.key !== "Control" && event.key !== "Shift") {
      lastChar = eventKey;
    }
  }
  document.addEventListener("keydown", keydown);
  function bindKey(key, handler) {
    const sequence = key.split(" ");
    if (sequence.length > 2) {
      console.error("Only key sequences of length <=2 are supported: ", key);
    }
    if (keyboardShortcuts.has(key)) {
      console.warn("Duplicate keyboard shortcut: ", key, handler);
    }
    keyboardShortcuts.set(key, handler);
    return () => {
      keyboardShortcuts.delete(key);
    };
  }
  function keyboardShortcut(node, key) {
    if (!key) {
      return {};
    }
    node.setAttribute("data-key", key);
    const destroy = bindKey(key, node);
    return {destroy};
  }
  function initCurrentKeyboardShortcuts() {
    for (const [key, action] of keyboardShortcuts.entries()) {
      if (action instanceof HTMLElement && !document.contains(action)) {
        keyboardShortcuts.delete(key);
      }
    }
    document.querySelectorAll("[data-keyboard-shortcut]").forEach((element2) => {
      const key = element2.getAttribute("data-keyboard-shortcut");
      if (key && element2 instanceof HTMLElement) {
        element2.removeAttribute("data-keyboard-shortcut");
        element2.setAttribute("data-key", key);
        bindKey(key, element2);
      }
    });
  }
  function initGlobalKeyboardShortcuts() {
    bindKey("?", () => {
      const hide2 = showTooltips();
      once(document, "mousedown", hide2);
      once(document, "keydown", hide2);
    });
    bindKey("Escape", closeOverlay);
  }

  // src/sidebar/index.ts
  function updateSidebar() {
    document.querySelectorAll("aside a").forEach((el) => {
      el.classList.remove("selected");
      const href = el.getAttribute("href");
      if (!el.hasAttribute("data-remote") && href?.includes(window.location.pathname)) {
        el.classList.add("selected");
      }
    });
  }
  function initSidebar() {
    const errorCountEl = document.getElementById("error-count");
    if (errorCountEl instanceof HTMLLIElement) {
      errorCount.subscribe((errorCount_val) => {
        errorCountEl.classList.toggle("hidden", errorCount_val === 0);
        const span = errorCountEl.querySelector("span");
        if (span) {
          span.innerHTML = `${errorCount_val}`;
        }
      });
    }
    const asideButton = document.getElementById("aside-button");
    if (asideButton instanceof HTMLButtonElement) {
      asideButton.addEventListener("click", () => {
        document.querySelector("aside")?.classList.toggle("active");
        asideButton.classList.toggle("active");
      });
    }
  }

  // node_modules/d3-hierarchy/src/hierarchy/count.js
  function count(node) {
    var sum = 0, children3 = node.children, i = children3 && children3.length;
    if (!i)
      sum = 1;
    else
      while (--i >= 0)
        sum += children3[i].value;
    node.value = sum;
  }
  function count_default() {
    return this.eachAfter(count);
  }

  // node_modules/d3-hierarchy/src/hierarchy/each.js
  function each_default(callback, that) {
    let index = -1;
    for (const node of this) {
      callback.call(that, node, ++index, this);
    }
    return this;
  }

  // node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
  function eachBefore_default(callback, that) {
    var node = this, nodes = [node], children3, i, index = -1;
    while (node = nodes.pop()) {
      callback.call(that, node, ++index, this);
      if (children3 = node.children) {
        for (i = children3.length - 1; i >= 0; --i) {
          nodes.push(children3[i]);
        }
      }
    }
    return this;
  }

  // node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
  function eachAfter_default(callback, that) {
    var node = this, nodes = [node], next = [], children3, i, n, index = -1;
    while (node = nodes.pop()) {
      next.push(node);
      if (children3 = node.children) {
        for (i = 0, n = children3.length; i < n; ++i) {
          nodes.push(children3[i]);
        }
      }
    }
    while (node = next.pop()) {
      callback.call(that, node, ++index, this);
    }
    return this;
  }

  // node_modules/d3-hierarchy/src/hierarchy/find.js
  function find_default(callback, that) {
    let index = -1;
    for (const node of this) {
      if (callback.call(that, node, ++index, this)) {
        return node;
      }
    }
  }

  // node_modules/d3-hierarchy/src/hierarchy/sum.js
  function sum_default(value) {
    return this.eachAfter(function(node) {
      var sum = +value(node.data) || 0, children3 = node.children, i = children3 && children3.length;
      while (--i >= 0)
        sum += children3[i].value;
      node.value = sum;
    });
  }

  // node_modules/d3-hierarchy/src/hierarchy/sort.js
  function sort_default(compare) {
    return this.eachBefore(function(node) {
      if (node.children) {
        node.children.sort(compare);
      }
    });
  }

  // node_modules/d3-hierarchy/src/hierarchy/path.js
  function path_default(end) {
    var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
    while (start !== ancestor) {
      start = start.parent;
      nodes.push(start);
    }
    var k = nodes.length;
    while (end !== ancestor) {
      nodes.splice(k, 0, end);
      end = end.parent;
    }
    return nodes;
  }
  function leastCommonAncestor(a, b) {
    if (a === b)
      return a;
    var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
    a = aNodes.pop();
    b = bNodes.pop();
    while (a === b) {
      c = a;
      a = aNodes.pop();
      b = bNodes.pop();
    }
    return c;
  }

  // node_modules/d3-hierarchy/src/hierarchy/ancestors.js
  function ancestors_default() {
    var node = this, nodes = [node];
    while (node = node.parent) {
      nodes.push(node);
    }
    return nodes;
  }

  // node_modules/d3-hierarchy/src/hierarchy/descendants.js
  function descendants_default() {
    return Array.from(this);
  }

  // node_modules/d3-hierarchy/src/hierarchy/leaves.js
  function leaves_default() {
    var leaves = [];
    this.eachBefore(function(node) {
      if (!node.children) {
        leaves.push(node);
      }
    });
    return leaves;
  }

  // node_modules/d3-hierarchy/src/hierarchy/links.js
  function links_default() {
    var root2 = this, links2 = [];
    root2.each(function(node) {
      if (node !== root2) {
        links2.push({source: node.parent, target: node});
      }
    });
    return links2;
  }

  // node_modules/d3-hierarchy/src/hierarchy/iterator.js
  function* iterator_default() {
    var node = this, current, next = [node], children3, i, n;
    do {
      current = next.reverse(), next = [];
      while (node = current.pop()) {
        yield node;
        if (children3 = node.children) {
          for (i = 0, n = children3.length; i < n; ++i) {
            next.push(children3[i]);
          }
        }
      }
    } while (next.length);
  }

  // node_modules/d3-hierarchy/src/hierarchy/index.js
  function hierarchy(data, children3) {
    if (data instanceof Map) {
      data = [void 0, data];
      if (children3 === void 0)
        children3 = mapChildren;
    } else if (children3 === void 0) {
      children3 = objectChildren;
    }
    var root2 = new Node2(data), node, nodes = [root2], child, childs, i, n;
    while (node = nodes.pop()) {
      if ((childs = children3(node.data)) && (n = (childs = Array.from(childs)).length)) {
        node.children = childs;
        for (i = n - 1; i >= 0; --i) {
          nodes.push(child = childs[i] = new Node2(childs[i]));
          child.parent = node;
          child.depth = node.depth + 1;
        }
      }
    }
    return root2.eachBefore(computeHeight);
  }
  function node_copy() {
    return hierarchy(this).eachBefore(copyData);
  }
  function objectChildren(d) {
    return d.children;
  }
  function mapChildren(d) {
    return Array.isArray(d) ? d[1] : null;
  }
  function copyData(node) {
    if (node.data.value !== void 0)
      node.value = node.data.value;
    node.data = node.data.data;
  }
  function computeHeight(node) {
    var height4 = 0;
    do
      node.height = height4;
    while ((node = node.parent) && node.height < ++height4);
  }
  function Node2(data) {
    this.data = data;
    this.depth = this.height = 0;
    this.parent = null;
  }
  Node2.prototype = hierarchy.prototype = {
    constructor: Node2,
    count: count_default,
    each: each_default,
    eachAfter: eachAfter_default,
    eachBefore: eachBefore_default,
    find: find_default,
    sum: sum_default,
    sort: sort_default,
    path: path_default,
    ancestors: ancestors_default,
    descendants: descendants_default,
    leaves: leaves_default,
    links: links_default,
    copy: node_copy,
    [Symbol.iterator]: iterator_default
  };

  // node_modules/d3-hierarchy/src/accessors.js
  function required(f) {
    if (typeof f !== "function")
      throw new Error();
    return f;
  }

  // node_modules/d3-hierarchy/src/constant.js
  function constantZero() {
    return 0;
  }
  function constant_default(x2) {
    return function() {
      return x2;
    };
  }

  // node_modules/d3-hierarchy/src/treemap/round.js
  function round_default(node) {
    node.x0 = Math.round(node.x0);
    node.y0 = Math.round(node.y0);
    node.x1 = Math.round(node.x1);
    node.y1 = Math.round(node.y1);
  }

  // node_modules/d3-hierarchy/src/treemap/dice.js
  function dice_default(parent2, x0, y0, x1, y1) {
    var nodes = parent2.children, node, i = -1, n = nodes.length, k = parent2.value && (x1 - x0) / parent2.value;
    while (++i < n) {
      node = nodes[i], node.y0 = y0, node.y1 = y1;
      node.x0 = x0, node.x1 = x0 += node.value * k;
    }
  }

  // node_modules/d3-hierarchy/src/partition.js
  function partition_default() {
    var dx = 1, dy = 1, padding = 0, round = false;
    function partition(root2) {
      var n = root2.height + 1;
      root2.x0 = root2.y0 = padding;
      root2.x1 = dx;
      root2.y1 = dy / n;
      root2.eachBefore(positionNode(dy, n));
      if (round)
        root2.eachBefore(round_default);
      return root2;
    }
    function positionNode(dy2, n) {
      return function(node) {
        if (node.children) {
          dice_default(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n);
        }
        var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding;
        if (x1 < x0)
          x0 = x1 = (x0 + x1) / 2;
        if (y1 < y0)
          y0 = y1 = (y0 + y1) / 2;
        node.x0 = x0;
        node.y0 = y0;
        node.x1 = x1;
        node.y1 = y1;
      };
    }
    partition.round = function(x2) {
      return arguments.length ? (round = !!x2, partition) : round;
    };
    partition.size = function(x2) {
      return arguments.length ? (dx = +x2[0], dy = +x2[1], partition) : [dx, dy];
    };
    partition.padding = function(x2) {
      return arguments.length ? (padding = +x2, partition) : padding;
    };
    return partition;
  }

  // node_modules/d3-hierarchy/src/treemap/slice.js
  function slice_default(parent2, x0, y0, x1, y1) {
    var nodes = parent2.children, node, i = -1, n = nodes.length, k = parent2.value && (y1 - y0) / parent2.value;
    while (++i < n) {
      node = nodes[i], node.x0 = x0, node.x1 = x1;
      node.y0 = y0, node.y1 = y0 += node.value * k;
    }
  }

  // node_modules/d3-hierarchy/src/treemap/squarify.js
  var phi = (1 + Math.sqrt(5)) / 2;
  function squarifyRatio(ratio, parent2, x0, y0, x1, y1) {
    var rows = [], nodes = parent2.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent2.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
    while (i0 < n) {
      dx = x1 - x0, dy = y1 - y0;
      do
        sumValue = nodes[i1++].value;
      while (!sumValue && i1 < n);
      minValue = maxValue = sumValue;
      alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
      beta = sumValue * sumValue * alpha;
      minRatio = Math.max(maxValue / beta, beta / minValue);
      for (; i1 < n; ++i1) {
        sumValue += nodeValue = nodes[i1].value;
        if (nodeValue < minValue)
          minValue = nodeValue;
        if (nodeValue > maxValue)
          maxValue = nodeValue;
        beta = sumValue * sumValue * alpha;
        newRatio = Math.max(maxValue / beta, beta / minValue);
        if (newRatio > minRatio) {
          sumValue -= nodeValue;
          break;
        }
        minRatio = newRatio;
      }
      rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});
      if (row.dice)
        dice_default(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
      else
        slice_default(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
      value -= sumValue, i0 = i1;
    }
    return rows;
  }
  var squarify_default = function custom(ratio) {
    function squarify(parent2, x0, y0, x1, y1) {
      squarifyRatio(ratio, parent2, x0, y0, x1, y1);
    }
    squarify.ratio = function(x2) {
      return custom((x2 = +x2) > 1 ? x2 : 1);
    };
    return squarify;
  }(phi);

  // node_modules/d3-hierarchy/src/treemap/index.js
  function treemap_default() {
    var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
    function treemap(root2) {
      root2.x0 = root2.y0 = 0;
      root2.x1 = dx;
      root2.y1 = dy;
      root2.eachBefore(positionNode);
      paddingStack = [0];
      if (round)
        root2.eachBefore(round_default);
      return root2;
    }
    function positionNode(node) {
      var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
      if (x1 < x0)
        x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0)
        y0 = y1 = (y0 + y1) / 2;
      node.x0 = x0;
      node.y0 = y0;
      node.x1 = x1;
      node.y1 = y1;
      if (node.children) {
        p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
        x0 += paddingLeft(node) - p;
        y0 += paddingTop(node) - p;
        x1 -= paddingRight(node) - p;
        y1 -= paddingBottom(node) - p;
        if (x1 < x0)
          x0 = x1 = (x0 + x1) / 2;
        if (y1 < y0)
          y0 = y1 = (y0 + y1) / 2;
        tile(node, x0, y0, x1, y1);
      }
    }
    treemap.round = function(x2) {
      return arguments.length ? (round = !!x2, treemap) : round;
    };
    treemap.size = function(x2) {
      return arguments.length ? (dx = +x2[0], dy = +x2[1], treemap) : [dx, dy];
    };
    treemap.tile = function(x2) {
      return arguments.length ? (tile = required(x2), treemap) : tile;
    };
    treemap.padding = function(x2) {
      return arguments.length ? treemap.paddingInner(x2).paddingOuter(x2) : treemap.paddingInner();
    };
    treemap.paddingInner = function(x2) {
      return arguments.length ? (paddingInner = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingInner;
    };
    treemap.paddingOuter = function(x2) {
      return arguments.length ? treemap.paddingTop(x2).paddingRight(x2).paddingBottom(x2).paddingLeft(x2) : treemap.paddingTop();
    };
    treemap.paddingTop = function(x2) {
      return arguments.length ? (paddingTop = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingTop;
    };
    treemap.paddingRight = function(x2) {
      return arguments.length ? (paddingRight = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingRight;
    };
    treemap.paddingBottom = function(x2) {
      return arguments.length ? (paddingBottom = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingBottom;
    };
    treemap.paddingLeft = function(x2) {
      return arguments.length ? (paddingLeft = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingLeft;
    };
    return treemap;
  }

  // src/lib/account.ts
  function parent(name) {
    const parentEnd = name.lastIndexOf(":");
    return parentEnd > 0 ? name.slice(0, parentEnd) : "";
  }
  function leaf(name) {
    const parentEnd = name.lastIndexOf(":");
    return parentEnd > 0 ? name.slice(parentEnd + 1) : name;
  }

  // src/lib/tree.ts
  function stratify(data, id, init3) {
    const root2 = {children: [], ...init3("")};
    const map2 = new Map();
    map2.set("", root2);
    function addAccount(name, datum2) {
      const existing = map2.get(name);
      if (existing) {
        Object.assign(existing, init3(name, datum2));
        return existing;
      }
      const node = {children: [], ...init3(name, datum2)};
      map2.set(name, node);
      const parentName = parent(name);
      const parentNode = map2.get(parentName) ?? addAccount(parentName);
      parentNode.children.push(node);
      return node;
    }
    [...data].sort((a, b) => id(a).localeCompare(id(b))).forEach((datum2) => addAccount(id(datum2), datum2));
    return root2;
  }

  // src/charts/index.ts
  function addInternalNodesAsLeaves(node) {
    if (node.children.length) {
      node.children.forEach(addInternalNodesAsLeaves);
      node.children.push({...node, children: [], dummy: true});
      node.balance = {};
    }
  }
  var operatingCurrenciesWithConversion = derived([operating_currency, conversion], ([operating_currency_val, conversion_val]) => {
    if (!conversion_val || ["at_cost", "at_value", "units"].includes(conversion_val) || operating_currency_val.includes(conversion_val)) {
      return operating_currency_val;
    }
    return [...operating_currency_val, conversion_val];
  });
  function balances(json) {
    const validator = array(object({
      date,
      balance: record(number)
    }));
    const parsedData = validator(json);
    const groups = new Map();
    for (const {date: date_, balance} of parsedData) {
      Object.entries(balance).forEach(([currency, value]) => {
        const group = groups.get(currency);
        const datum2 = {date: date_, value, name: currency};
        if (group) {
          group.push(datum2);
        } else {
          groups.set(currency, [datum2]);
        }
      });
    }
    const data = [...groups.entries()].map(([name, values]) => ({
      name,
      values
    }));
    return {
      data,
      type: "linechart",
      tooltipText: (d) => `${formatCurrency(d.value)} ${d.name}<em>${dateFormat.day(d.date)}</em>`
    };
  }
  function commodities(json, label) {
    const validator = object({
      quote: string,
      base: string,
      prices: array(tuple([date, number]))
    });
    const {base, quote, prices} = validator(json);
    const values = prices.map((d) => ({name: label, date: d[0], value: d[1]}));
    return {
      data: [{name: label, values}],
      type: "linechart",
      tooltipText(d) {
        return `1 ${base} = ${formatCurrency(d.value)} ${quote}<em>${dateFormat.day(d.date)}</em>`;
      }
    };
  }
  function bar(json) {
    const validator = array(object({date, budgets: record(number), balance: record(number)}));
    const parsedData = validator(json);
    const currentDateFmt = get_store_value(currentDateFormat);
    const data = parsedData.map((d) => ({
      values: get_store_value(operatingCurrenciesWithConversion).map((name) => ({
        name,
        value: d.balance[name] || 0,
        budget: d.budgets[name] || 0
      })),
      date: d.date,
      label: currentDateFmt(d.date)
    }));
    function tooltipText(d) {
      let text2 = "";
      d.values.forEach((a) => {
        text2 += `${formatCurrency(a.value)} ${a.name}`;
        if (a.budget) {
          text2 += ` / ${formatCurrency(a.budget)} ${a.name}`;
        }
        text2 += "<br>";
      });
      text2 += `<em>${d.label}</em>`;
      return text2;
    }
    return {data, tooltipText, type: "barchart"};
  }
  function scatterplot(json) {
    const validator = array(object({type: string, date, description: string}));
    return {type: "scatterplot", data: validator(json)};
  }
  function hierarchy2(json) {
    const hierarchyValidator = object({
      account: string,
      balance: record(number),
      children: lazy(() => array(hierarchyValidator))
    });
    const validator = object({root: hierarchyValidator, modifier: number});
    const {root: root2, modifier} = validator(json);
    addInternalNodesAsLeaves(root2);
    const data = new Map();
    get_store_value(operatingCurrenciesWithConversion).forEach((currency) => {
      const currencyHierarchy = hierarchy(root2).sum((d) => (d.balance[currency] || 0) * modifier).sort((a, b) => (b.value || 0) - (a.value || 0));
      if (currencyHierarchy.value) {
        data.set(currency, currencyHierarchy);
      }
    });
    return {type: "hierarchy", data};
  }
  var parsers = {
    balances,
    commodities,
    bar,
    hierarchy: hierarchy2,
    scatterplot
  };
  function parseChartData() {
    const json = getScriptTagJSON("#chart-data");
    const validator = array(object({
      label: string,
      type: string,
      data: unknown
    }));
    const chartData = validator(json);
    const result = [];
    chartData.forEach((chart) => {
      const parser = parsers[chart.type];
      if (parser) {
        result.push({
          name: chart.label,
          ...parser(chart.data, chart.label)
        });
      }
    });
    return result;
  }
  function parseGroupedQueryChart(json, currencies2) {
    const validator = array(object({group: string, balance: record(number)}));
    const grouped = defaultValue(validator, null)(json);
    if (!grouped) {
      return null;
    }
    const root2 = stratify(grouped, (d) => d.group, (account2, d) => ({account: account2, balance: d?.balance ?? {}}));
    root2.account = "(root)";
    const data = new Map();
    currencies2.forEach((currency) => {
      const currencyHierarchy = hierarchy(root2).sum((d) => d.balance[currency] || 0).sort((a, b) => (b.value || 0) - (a.value || 0));
      if (currencyHierarchy.value !== void 0) {
        data.set(currency, currencyHierarchy);
      }
    });
    return {type: "hierarchy", data};
  }
  function parseQueryChart(json) {
    const currencies2 = get_store_value(operatingCurrenciesWithConversion);
    const tree = parseGroupedQueryChart(json, currencies2);
    if (tree) {
      return tree;
    }
    const dated = defaultValue(array(unknown), null)(json);
    if (dated) {
      try {
        return balances(dated);
      } catch (error) {
      }
    }
    return null;
  }

  // src/charts/ConversionAndInterval.svelte
  function get_each_context(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[6] = list[i][0];
    child_ctx[7] = list[i][1];
    return child_ctx;
  }
  function get_each_context_1(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[10] = list[i][0];
    child_ctx[11] = list[i][1];
    return child_ctx;
  }
  function create_each_block_1(ctx) {
    let option;
    let t_value = ctx[11] + "";
    let t;
    let option_value_value;
    return {
      c() {
        option = element("option");
        t = text(t_value);
        option.__value = option_value_value = ctx[10];
        option.value = option.__value;
      },
      m(target, anchor) {
        insert(target, option, anchor);
        append(option, t);
      },
      p(ctx2, dirty) {
        if (dirty & 2 && t_value !== (t_value = ctx2[11] + ""))
          set_data(t, t_value);
        if (dirty & 2 && option_value_value !== (option_value_value = ctx2[10])) {
          option.__value = option_value_value;
          option.value = option.__value;
        }
      },
      d(detaching) {
        if (detaching)
          detach(option);
      }
    };
  }
  function create_each_block(ctx) {
    let option;
    let t_value = ctx[7] + "";
    let t;
    let option_value_value;
    return {
      c() {
        option = element("option");
        t = text(t_value);
        option.__value = option_value_value = ctx[6];
        option.value = option.__value;
      },
      m(target, anchor) {
        insert(target, option, anchor);
        append(option, t);
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(option);
      }
    };
  }
  function create_fragment(ctx) {
    let select0;
    let t;
    let select1;
    let mounted;
    let dispose;
    let each_value_1 = ctx[1];
    let each_blocks_1 = [];
    for (let i = 0; i < each_value_1.length; i += 1) {
      each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
    }
    let each_value = ctx[3];
    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));
    }
    return {
      c() {
        select0 = element("select");
        for (let i = 0; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].c();
        }
        t = space();
        select1 = element("select");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        if (ctx[0] === void 0)
          add_render_callback(() => ctx[4].call(select0));
        if (ctx[2] === void 0)
          add_render_callback(() => ctx[5].call(select1));
      },
      m(target, anchor) {
        insert(target, select0, anchor);
        for (let i = 0; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].m(select0, null);
        }
        select_option(select0, ctx[0]);
        insert(target, t, anchor);
        insert(target, select1, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(select1, null);
        }
        select_option(select1, ctx[2]);
        if (!mounted) {
          dispose = [
            listen(select0, "change", ctx[4]),
            listen(select1, "change", ctx[5])
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 2) {
          each_value_1 = ctx2[1];
          let i;
          for (i = 0; i < each_value_1.length; i += 1) {
            const child_ctx = get_each_context_1(ctx2, each_value_1, i);
            if (each_blocks_1[i]) {
              each_blocks_1[i].p(child_ctx, dirty);
            } else {
              each_blocks_1[i] = create_each_block_1(child_ctx);
              each_blocks_1[i].c();
              each_blocks_1[i].m(select0, null);
            }
          }
          for (; i < each_blocks_1.length; i += 1) {
            each_blocks_1[i].d(1);
          }
          each_blocks_1.length = each_value_1.length;
        }
        if (dirty & 3) {
          select_option(select0, ctx2[0]);
        }
        if (dirty & 8) {
          each_value = ctx2[3];
          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(select1, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (dirty & 12) {
          select_option(select1, ctx2[2]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(select0);
        destroy_each(each_blocks_1, detaching);
        if (detaching)
          detach(t);
        if (detaching)
          detach(select1);
        destroy_each(each_blocks, detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance($$self, $$props, $$invalidate) {
    let $conversion;
    let $conversions;
    let $interval;
    component_subscribe($$self, conversion, ($$value) => $$invalidate(0, $conversion = $$value));
    component_subscribe($$self, conversions, ($$value) => $$invalidate(1, $conversions = $$value));
    component_subscribe($$self, interval, ($$value) => $$invalidate(2, $interval = $$value));
    const intervals = [
      ["year", _("Yearly")],
      ["quarter", _("Quarterly")],
      ["month", _("Monthly")],
      ["week", _("Weekly")],
      ["day", _("Daily")]
    ];
    function select0_change_handler() {
      $conversion = select_value(this);
      conversion.set($conversion);
    }
    function select1_change_handler() {
      $interval = select_value(this);
      interval.set($interval);
      $$invalidate(3, intervals);
    }
    return [
      $conversion,
      $conversions,
      $interval,
      intervals,
      select0_change_handler,
      select1_change_handler
    ];
  }
  var ConversionAndInterval = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance, create_fragment, safe_not_equal, {});
    }
  };
  var ConversionAndInterval_default = ConversionAndInterval;

  // src/charts/ChartLegend.svelte
  function get_each_context2(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[1] = list[i][0];
    child_ctx[2] = list[i][1];
    return child_ctx;
  }
  function create_each_block2(ctx) {
    let span;
    let i;
    let t03;
    let t1_value = ctx[1] + "";
    let t13;
    let t22;
    return {
      c() {
        span = element("span");
        i = element("i");
        t03 = space();
        t13 = text(t1_value);
        t22 = space();
        set_style(i, "background-color", ctx[2]);
        attr(i, "class", "svelte-1unp29f");
        attr(span, "class", "svelte-1unp29f");
      },
      m(target, anchor) {
        insert(target, span, anchor);
        append(span, i);
        append(span, t03);
        append(span, t13);
        append(span, t22);
      },
      p(ctx2, dirty) {
        if (dirty & 1) {
          set_style(i, "background-color", ctx2[2]);
        }
        if (dirty & 1 && t1_value !== (t1_value = ctx2[1] + ""))
          set_data(t13, t1_value);
      },
      d(detaching) {
        if (detaching)
          detach(span);
      }
    };
  }
  function create_fragment2(ctx) {
    let each_1_anchor;
    let each_value = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i));
    }
    return {
      c() {
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        each_1_anchor = empty();
      },
      m(target, anchor) {
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(target, anchor);
        }
        insert(target, each_1_anchor, anchor);
      },
      p(ctx2, [dirty]) {
        if (dirty & 1) {
          each_value = ctx2[0];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context2(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block2(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        destroy_each(each_blocks, detaching);
        if (detaching)
          detach(each_1_anchor);
      }
    };
  }
  function instance2($$self, $$props, $$invalidate) {
    let {legend} = $$props;
    $$self.$$set = ($$props2) => {
      if ("legend" in $$props2)
        $$invalidate(0, legend = $$props2.legend);
    };
    return [legend];
  }
  var ChartLegend = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance2, create_fragment2, safe_not_equal, {legend: 0});
    }
  };
  var ChartLegend_default = ChartLegend;

  // node_modules/d3-array/src/ascending.js
  function ascending_default(a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  }

  // node_modules/d3-array/src/bisector.js
  function bisector_default(f) {
    let delta = f;
    let compare = f;
    if (f.length === 1) {
      delta = (d, x2) => f(d) - x2;
      compare = ascendingComparator(f);
    }
    function left2(a, x2, lo, hi) {
      if (lo == null)
        lo = 0;
      if (hi == null)
        hi = a.length;
      while (lo < hi) {
        const mid = lo + hi >>> 1;
        if (compare(a[mid], x2) < 0)
          lo = mid + 1;
        else
          hi = mid;
      }
      return lo;
    }
    function right2(a, x2, lo, hi) {
      if (lo == null)
        lo = 0;
      if (hi == null)
        hi = a.length;
      while (lo < hi) {
        const mid = lo + hi >>> 1;
        if (compare(a[mid], x2) > 0)
          hi = mid;
        else
          lo = mid + 1;
      }
      return lo;
    }
    function center2(a, x2, lo, hi) {
      if (lo == null)
        lo = 0;
      if (hi == null)
        hi = a.length;
      const i = left2(a, x2, lo, hi - 1);
      return i > lo && delta(a[i - 1], x2) > -delta(a[i], x2) ? i - 1 : i;
    }
    return {left: left2, center: center2, right: right2};
  }
  function ascendingComparator(f) {
    return (d, x2) => ascending_default(f(d), x2);
  }

  // node_modules/d3-array/src/number.js
  function number_default(x2) {
    return x2 === null ? NaN : +x2;
  }

  // node_modules/d3-array/src/bisect.js
  var ascendingBisect = bisector_default(ascending_default);
  var bisectRight = ascendingBisect.right;
  var bisectLeft = ascendingBisect.left;
  var bisectCenter = bisector_default(number_default).center;
  var bisect_default = bisectRight;

  // node_modules/d3-array/src/extent.js
  function extent_default(values, valueof) {
    let min3;
    let max3;
    if (valueof === void 0) {
      for (const value of values) {
        if (value != null) {
          if (min3 === void 0) {
            if (value >= value)
              min3 = max3 = value;
          } else {
            if (min3 > value)
              min3 = value;
            if (max3 < value)
              max3 = value;
          }
        }
      }
    } else {
      let index = -1;
      for (let value of values) {
        if ((value = valueof(value, ++index, values)) != null) {
          if (min3 === void 0) {
            if (value >= value)
              min3 = max3 = value;
          } else {
            if (min3 > value)
              min3 = value;
            if (max3 < value)
              max3 = value;
          }
        }
      }
    }
    return [min3, max3];
  }

  // node_modules/d3-array/src/ticks.js
  var e10 = Math.sqrt(50);
  var e5 = Math.sqrt(10);
  var e2 = Math.sqrt(2);
  function ticks_default(start, stop, count2) {
    var reverse, i = -1, n, ticks, step;
    stop = +stop, start = +start, count2 = +count2;
    if (start === stop && count2 > 0)
      return [start];
    if (reverse = stop < start)
      n = start, start = stop, stop = n;
    if ((step = tickIncrement(start, stop, count2)) === 0 || !isFinite(step))
      return [];
    if (step > 0) {
      start = Math.ceil(start / step);
      stop = Math.floor(stop / step);
      ticks = new Array(n = Math.ceil(stop - start + 1));
      while (++i < n)
        ticks[i] = (start + i) * step;
    } else {
      step = -step;
      start = Math.ceil(start * step);
      stop = Math.floor(stop * step);
      ticks = new Array(n = Math.ceil(stop - start + 1));
      while (++i < n)
        ticks[i] = (start + i) / step;
    }
    if (reverse)
      ticks.reverse();
    return ticks;
  }
  function tickIncrement(start, stop, count2) {
    var step = (stop - start) / Math.max(0, count2), power = Math.floor(Math.log(step) / Math.LN10), error = step / Math.pow(10, power);
    return power >= 0 ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power) : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
  }
  function tickStep(start, stop, count2) {
    var step0 = Math.abs(stop - start) / Math.max(0, count2), step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), error = step0 / step1;
    if (error >= e10)
      step1 *= 10;
    else if (error >= e5)
      step1 *= 5;
    else if (error >= e2)
      step1 *= 2;
    return stop < start ? -step1 : step1;
  }

  // node_modules/d3-array/src/max.js
  function max(values, valueof) {
    let max3;
    if (valueof === void 0) {
      for (const value of values) {
        if (value != null && (max3 < value || max3 === void 0 && value >= value)) {
          max3 = value;
        }
      }
    } else {
      let index = -1;
      for (let value of values) {
        if ((value = valueof(value, ++index, values)) != null && (max3 < value || max3 === void 0 && value >= value)) {
          max3 = value;
        }
      }
    }
    return max3;
  }

  // node_modules/d3-array/src/min.js
  function min(values, valueof) {
    let min3;
    if (valueof === void 0) {
      for (const value of values) {
        if (value != null && (min3 > value || min3 === void 0 && value >= value)) {
          min3 = value;
        }
      }
    } else {
      let index = -1;
      for (let value of values) {
        if ((value = valueof(value, ++index, values)) != null && (min3 > value || min3 === void 0 && value >= value)) {
          min3 = value;
        }
      }
    }
    return min3;
  }

  // node_modules/d3-array/src/merge.js
  function* flatten(arrays) {
    for (const array2 of arrays) {
      yield* array2;
    }
  }
  function merge(arrays) {
    return Array.from(flatten(arrays));
  }

  // node_modules/d3-array/src/range.js
  function range_default(start, stop, step) {
    start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
    var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range = new Array(n);
    while (++i < n) {
      range[i] = start + i * step;
    }
    return range;
  }

  // node_modules/d3-axis/src/array.js
  var slice = Array.prototype.slice;

  // node_modules/d3-axis/src/identity.js
  function identity_default2(x2) {
    return x2;
  }

  // node_modules/d3-axis/src/axis.js
  var top = 1;
  var right = 2;
  var bottom = 3;
  var left = 4;
  var epsilon = 1e-6;
  function translateX(x2) {
    return "translate(" + (x2 + 0.5) + ",0)";
  }
  function translateY(y2) {
    return "translate(0," + (y2 + 0.5) + ")";
  }
  function number2(scale) {
    return (d) => +scale(d);
  }
  function center(scale) {
    var offset = Math.max(0, scale.bandwidth() - 1) / 2;
    if (scale.round())
      offset = Math.round(offset);
    return function(d) {
      return +scale(d) + offset;
    };
  }
  function entering() {
    return !this.__axis;
  }
  function axis(orient, scale) {
    var tickArguments = [], tickValues = null, tickFormat2 = null, tickSizeInner = 6, tickSizeOuter = 6, tickPadding = 3, k = orient === top || orient === left ? -1 : 1, x2 = orient === left || orient === right ? "x" : "y", transform = orient === top || orient === bottom ? translateX : translateY;
    function axis3(context) {
      var values = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain() : tickValues, format2 = tickFormat2 == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity_default2 : tickFormat2, spacing = Math.max(tickSizeInner, 0) + tickPadding, range = scale.range(), range0 = +range[0] + 0.5, range1 = +range[range.length - 1] + 0.5, position = (scale.bandwidth ? center : number2)(scale.copy()), selection2 = context.selection ? context.selection() : context, path2 = selection2.selectAll(".domain").data([null]), tick2 = selection2.selectAll(".tick").data(values, scale).order(), tickExit = tick2.exit(), tickEnter = tick2.enter().append("g").attr("class", "tick"), line = tick2.select("line"), text2 = tick2.select("text");
      path2 = path2.merge(path2.enter().insert("path", ".tick").attr("class", "domain").attr("stroke", "currentColor"));
      tick2 = tick2.merge(tickEnter);
      line = line.merge(tickEnter.append("line").attr("stroke", "currentColor").attr(x2 + "2", k * tickSizeInner));
      text2 = text2.merge(tickEnter.append("text").attr("fill", "currentColor").attr(x2, k * spacing).attr("dy", orient === top ? "0em" : orient === bottom ? "0.71em" : "0.32em"));
      if (context !== selection2) {
        path2 = path2.transition(context);
        tick2 = tick2.transition(context);
        line = line.transition(context);
        text2 = text2.transition(context);
        tickExit = tickExit.transition(context).attr("opacity", epsilon).attr("transform", function(d) {
          return isFinite(d = position(d)) ? transform(d) : this.getAttribute("transform");
        });
        tickEnter.attr("opacity", epsilon).attr("transform", function(d) {
          var p = this.parentNode.__axis;
          return transform(p && isFinite(p = p(d)) ? p : position(d));
        });
      }
      tickExit.remove();
      path2.attr("d", orient === left || orient == right ? tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H0.5V" + range1 + "H" + k * tickSizeOuter : "M0.5," + range0 + "V" + range1 : tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V0.5H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + ",0.5H" + range1);
      tick2.attr("opacity", 1).attr("transform", function(d) {
        return transform(position(d));
      });
      line.attr(x2 + "2", k * tickSizeInner);
      text2.attr(x2, k * spacing).text(format2);
      selection2.filter(entering).attr("fill", "none").attr("font-size", 10).attr("font-family", "sans-serif").attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");
      selection2.each(function() {
        this.__axis = position;
      });
    }
    axis3.scale = function(_2) {
      return arguments.length ? (scale = _2, axis3) : scale;
    };
    axis3.ticks = function() {
      return tickArguments = slice.call(arguments), axis3;
    };
    axis3.tickArguments = function(_2) {
      return arguments.length ? (tickArguments = _2 == null ? [] : slice.call(_2), axis3) : tickArguments.slice();
    };
    axis3.tickValues = function(_2) {
      return arguments.length ? (tickValues = _2 == null ? null : slice.call(_2), axis3) : tickValues && tickValues.slice();
    };
    axis3.tickFormat = function(_2) {
      return arguments.length ? (tickFormat2 = _2, axis3) : tickFormat2;
    };
    axis3.tickSize = function(_2) {
      return arguments.length ? (tickSizeInner = tickSizeOuter = +_2, axis3) : tickSizeInner;
    };
    axis3.tickSizeInner = function(_2) {
      return arguments.length ? (tickSizeInner = +_2, axis3) : tickSizeInner;
    };
    axis3.tickSizeOuter = function(_2) {
      return arguments.length ? (tickSizeOuter = +_2, axis3) : tickSizeOuter;
    };
    axis3.tickPadding = function(_2) {
      return arguments.length ? (tickPadding = +_2, axis3) : tickPadding;
    };
    return axis3;
  }
  function axisBottom(scale) {
    return axis(bottom, scale);
  }
  function axisLeft(scale) {
    return axis(left, scale);
  }

  // node_modules/d3-scale/src/init.js
  function initRange(domain, range) {
    switch (arguments.length) {
      case 0:
        break;
      case 1:
        this.range(domain);
        break;
      default:
        this.range(range).domain(domain);
        break;
    }
    return this;
  }

  // node_modules/d3-scale/src/ordinal.js
  var implicit = Symbol("implicit");
  function ordinal() {
    var index = new Map(), domain = [], range = [], unknown2 = implicit;
    function scale(d) {
      var key = d + "", i = index.get(key);
      if (!i) {
        if (unknown2 !== implicit)
          return unknown2;
        index.set(key, i = domain.push(d));
      }
      return range[(i - 1) % range.length];
    }
    scale.domain = function(_2) {
      if (!arguments.length)
        return domain.slice();
      domain = [], index = new Map();
      for (const value of _2) {
        const key = value + "";
        if (index.has(key))
          continue;
        index.set(key, domain.push(value));
      }
      return scale;
    };
    scale.range = function(_2) {
      return arguments.length ? (range = Array.from(_2), scale) : range.slice();
    };
    scale.unknown = function(_2) {
      return arguments.length ? (unknown2 = _2, scale) : unknown2;
    };
    scale.copy = function() {
      return ordinal(domain, range).unknown(unknown2);
    };
    initRange.apply(scale, arguments);
    return scale;
  }

  // node_modules/d3-scale/src/band.js
  function band() {
    var scale = ordinal().unknown(void 0), domain = scale.domain, ordinalRange = scale.range, r0 = 0, r1 = 1, step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5;
    delete scale.unknown;
    function rescale() {
      var n = domain().length, reverse = r1 < r0, start = reverse ? r1 : r0, stop = reverse ? r0 : r1;
      step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
      if (round)
        step = Math.floor(step);
      start += (stop - start - step * (n - paddingInner)) * align;
      bandwidth = step * (1 - paddingInner);
      if (round)
        start = Math.round(start), bandwidth = Math.round(bandwidth);
      var values = range_default(n).map(function(i) {
        return start + step * i;
      });
      return ordinalRange(reverse ? values.reverse() : values);
    }
    scale.domain = function(_2) {
      return arguments.length ? (domain(_2), rescale()) : domain();
    };
    scale.range = function(_2) {
      return arguments.length ? ([r0, r1] = _2, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
    };
    scale.rangeRound = function(_2) {
      return [r0, r1] = _2, r0 = +r0, r1 = +r1, round = true, rescale();
    };
    scale.bandwidth = function() {
      return bandwidth;
    };
    scale.step = function() {
      return step;
    };
    scale.round = function(_2) {
      return arguments.length ? (round = !!_2, rescale()) : round;
    };
    scale.padding = function(_2) {
      return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_2), rescale()) : paddingInner;
    };
    scale.paddingInner = function(_2) {
      return arguments.length ? (paddingInner = Math.min(1, _2), rescale()) : paddingInner;
    };
    scale.paddingOuter = function(_2) {
      return arguments.length ? (paddingOuter = +_2, rescale()) : paddingOuter;
    };
    scale.align = function(_2) {
      return arguments.length ? (align = Math.max(0, Math.min(1, _2)), rescale()) : align;
    };
    scale.copy = function() {
      return band(domain(), [r0, r1]).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
    };
    return initRange.apply(rescale(), arguments);
  }
  function pointish(scale) {
    var copy2 = scale.copy;
    scale.padding = scale.paddingOuter;
    delete scale.paddingInner;
    delete scale.paddingOuter;
    scale.copy = function() {
      return pointish(copy2());
    };
    return scale;
  }
  function point() {
    return pointish(band.apply(null, arguments).paddingInner(1));
  }

  // node_modules/d3-color/src/define.js
  function define_default(constructor, factory, prototype) {
    constructor.prototype = factory.prototype = prototype;
    prototype.constructor = constructor;
  }
  function extend(parent2, definition) {
    var prototype = Object.create(parent2.prototype);
    for (var key in definition)
      prototype[key] = definition[key];
    return prototype;
  }

  // node_modules/d3-color/src/color.js
  function Color() {
  }
  var darker = 0.7;
  var brighter = 1 / darker;
  var reI = "\\s*([+-]?\\d+)\\s*";
  var reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*";
  var reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
  var reHex = /^#([0-9a-f]{3,8})$/;
  var reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$");
  var reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$");
  var reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$");
  var reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$");
  var reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$");
  var reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
  var named = {
    aliceblue: 15792383,
    antiquewhite: 16444375,
    aqua: 65535,
    aquamarine: 8388564,
    azure: 15794175,
    beige: 16119260,
    bisque: 16770244,
    black: 0,
    blanchedalmond: 16772045,
    blue: 255,
    blueviolet: 9055202,
    brown: 10824234,
    burlywood: 14596231,
    cadetblue: 6266528,
    chartreuse: 8388352,
    chocolate: 13789470,
    coral: 16744272,
    cornflowerblue: 6591981,
    cornsilk: 16775388,
    crimson: 14423100,
    cyan: 65535,
    darkblue: 139,
    darkcyan: 35723,
    darkgoldenrod: 12092939,
    darkgray: 11119017,
    darkgreen: 25600,
    darkgrey: 11119017,
    darkkhaki: 12433259,
    darkmagenta: 9109643,
    darkolivegreen: 5597999,
    darkorange: 16747520,
    darkorchid: 10040012,
    darkred: 9109504,
    darksalmon: 15308410,
    darkseagreen: 9419919,
    darkslateblue: 4734347,
    darkslategray: 3100495,
    darkslategrey: 3100495,
    darkturquoise: 52945,
    darkviolet: 9699539,
    deeppink: 16716947,
    deepskyblue: 49151,
    dimgray: 6908265,
    dimgrey: 6908265,
    dodgerblue: 2003199,
    firebrick: 11674146,
    floralwhite: 16775920,
    forestgreen: 2263842,
    fuchsia: 16711935,
    gainsboro: 14474460,
    ghostwhite: 16316671,
    gold: 16766720,
    goldenrod: 14329120,
    gray: 8421504,
    green: 32768,
    greenyellow: 11403055,
    grey: 8421504,
    honeydew: 15794160,
    hotpink: 16738740,
    indianred: 13458524,
    indigo: 4915330,
    ivory: 16777200,
    khaki: 15787660,
    lavender: 15132410,
    lavenderblush: 16773365,
    lawngreen: 8190976,
    lemonchiffon: 16775885,
    lightblue: 11393254,
    lightcoral: 15761536,
    lightcyan: 14745599,
    lightgoldenrodyellow: 16448210,
    lightgray: 13882323,
    lightgreen: 9498256,
    lightgrey: 13882323,
    lightpink: 16758465,
    lightsalmon: 16752762,
    lightseagreen: 2142890,
    lightskyblue: 8900346,
    lightslategray: 7833753,
    lightslategrey: 7833753,
    lightsteelblue: 11584734,
    lightyellow: 16777184,
    lime: 65280,
    limegreen: 3329330,
    linen: 16445670,
    magenta: 16711935,
    maroon: 8388608,
    mediumaquamarine: 6737322,
    mediumblue: 205,
    mediumorchid: 12211667,
    mediumpurple: 9662683,
    mediumseagreen: 3978097,
    mediumslateblue: 8087790,
    mediumspringgreen: 64154,
    mediumturquoise: 4772300,
    mediumvioletred: 13047173,
    midnightblue: 1644912,
    mintcream: 16121850,
    mistyrose: 16770273,
    moccasin: 16770229,
    navajowhite: 16768685,
    navy: 128,
    oldlace: 16643558,
    olive: 8421376,
    olivedrab: 7048739,
    orange: 16753920,
    orangered: 16729344,
    orchid: 14315734,
    palegoldenrod: 15657130,
    palegreen: 10025880,
    paleturquoise: 11529966,
    palevioletred: 14381203,
    papayawhip: 16773077,
    peachpuff: 16767673,
    peru: 13468991,
    pink: 16761035,
    plum: 14524637,
    powderblue: 11591910,
    purple: 8388736,
    rebeccapurple: 6697881,
    red: 16711680,
    rosybrown: 12357519,
    royalblue: 4286945,
    saddlebrown: 9127187,
    salmon: 16416882,
    sandybrown: 16032864,
    seagreen: 3050327,
    seashell: 16774638,
    sienna: 10506797,
    silver: 12632256,
    skyblue: 8900331,
    slateblue: 6970061,
    slategray: 7372944,
    slategrey: 7372944,
    snow: 16775930,
    springgreen: 65407,
    steelblue: 4620980,
    tan: 13808780,
    teal: 32896,
    thistle: 14204888,
    tomato: 16737095,
    turquoise: 4251856,
    violet: 15631086,
    wheat: 16113331,
    white: 16777215,
    whitesmoke: 16119285,
    yellow: 16776960,
    yellowgreen: 10145074
  };
  define_default(Color, color, {
    copy: function(channels) {
      return Object.assign(new this.constructor(), this, channels);
    },
    displayable: function() {
      return this.rgb().displayable();
    },
    hex: color_formatHex,
    formatHex: color_formatHex,
    formatHsl: color_formatHsl,
    formatRgb: color_formatRgb,
    toString: color_formatRgb
  });
  function color_formatHex() {
    return this.rgb().formatHex();
  }
  function color_formatHsl() {
    return hslConvert(this).formatHsl();
  }
  function color_formatRgb() {
    return this.rgb().formatRgb();
  }
  function color(format2) {
    var m, l;
    format2 = (format2 + "").trim().toLowerCase();
    return (m = reHex.exec(format2)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
  }
  function rgbn(n) {
    return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
  }
  function rgba(r, g, b, a) {
    if (a <= 0)
      r = g = b = NaN;
    return new Rgb(r, g, b, a);
  }
  function rgbConvert(o) {
    if (!(o instanceof Color))
      o = color(o);
    if (!o)
      return new Rgb();
    o = o.rgb();
    return new Rgb(o.r, o.g, o.b, o.opacity);
  }
  function rgb(r, g, b, opacity) {
    return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
  }
  function Rgb(r, g, b, opacity) {
    this.r = +r;
    this.g = +g;
    this.b = +b;
    this.opacity = +opacity;
  }
  define_default(Rgb, rgb, extend(Color, {
    brighter: function(k) {
      k = k == null ? brighter : Math.pow(brighter, k);
      return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
    },
    darker: function(k) {
      k = k == null ? darker : Math.pow(darker, k);
      return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
    },
    rgb: function() {
      return this;
    },
    displayable: function() {
      return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
    },
    hex: rgb_formatHex,
    formatHex: rgb_formatHex,
    formatRgb: rgb_formatRgb,
    toString: rgb_formatRgb
  }));
  function rgb_formatHex() {
    return "#" + hex(this.r) + hex(this.g) + hex(this.b);
  }
  function rgb_formatRgb() {
    var a = this.opacity;
    a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (a === 1 ? ")" : ", " + a + ")");
  }
  function hex(value) {
    value = Math.max(0, Math.min(255, Math.round(value) || 0));
    return (value < 16 ? "0" : "") + value.toString(16);
  }
  function hsla(h, s, l, a) {
    if (a <= 0)
      h = s = l = NaN;
    else if (l <= 0 || l >= 1)
      h = s = NaN;
    else if (s <= 0)
      h = NaN;
    return new Hsl(h, s, l, a);
  }
  function hslConvert(o) {
    if (o instanceof Hsl)
      return new Hsl(o.h, o.s, o.l, o.opacity);
    if (!(o instanceof Color))
      o = color(o);
    if (!o)
      return new Hsl();
    if (o instanceof Hsl)
      return o;
    o = o.rgb();
    var r = o.r / 255, g = o.g / 255, b = o.b / 255, min3 = Math.min(r, g, b), max3 = Math.max(r, g, b), h = NaN, s = max3 - min3, l = (max3 + min3) / 2;
    if (s) {
      if (r === max3)
        h = (g - b) / s + (g < b) * 6;
      else if (g === max3)
        h = (b - r) / s + 2;
      else
        h = (r - g) / s + 4;
      s /= l < 0.5 ? max3 + min3 : 2 - max3 - min3;
      h *= 60;
    } else {
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new Hsl(h, s, l, o.opacity);
  }
  function hsl(h, s, l, opacity) {
    return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
  }
  function Hsl(h, s, l, opacity) {
    this.h = +h;
    this.s = +s;
    this.l = +l;
    this.opacity = +opacity;
  }
  define_default(Hsl, hsl, extend(Color, {
    brighter: function(k) {
      k = k == null ? brighter : Math.pow(brighter, k);
      return new Hsl(this.h, this.s, this.l * k, this.opacity);
    },
    darker: function(k) {
      k = k == null ? darker : Math.pow(darker, k);
      return new Hsl(this.h, this.s, this.l * k, this.opacity);
    },
    rgb: function() {
      var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
      return new Rgb(hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity);
    },
    displayable: function() {
      return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
    },
    formatHsl: function() {
      var a = this.opacity;
      a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
      return (a === 1 ? "hsl(" : "hsla(") + (this.h || 0) + ", " + (this.s || 0) * 100 + "%, " + (this.l || 0) * 100 + "%" + (a === 1 ? ")" : ", " + a + ")");
    }
  }));
  function hsl2rgb(h, m1, m2) {
    return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
  }

  // node_modules/d3-color/src/math.js
  var radians = Math.PI / 180;
  var degrees = 180 / Math.PI;

  // node_modules/d3-color/src/lab.js
  var K = 18;
  var Xn = 0.96422;
  var Yn = 1;
  var Zn = 0.82521;
  var t02 = 4 / 29;
  var t12 = 6 / 29;
  var t2 = 3 * t12 * t12;
  var t3 = t12 * t12 * t12;
  function labConvert(o) {
    if (o instanceof Lab)
      return new Lab(o.l, o.a, o.b, o.opacity);
    if (o instanceof Hcl)
      return hcl2lab(o);
    if (!(o instanceof Rgb))
      o = rgbConvert(o);
    var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y2 = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x2, z;
    if (r === g && g === b)
      x2 = z = y2;
    else {
      x2 = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
      z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
    }
    return new Lab(116 * y2 - 16, 500 * (x2 - y2), 200 * (y2 - z), o.opacity);
  }
  function lab(l, a, b, opacity) {
    return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
  }
  function Lab(l, a, b, opacity) {
    this.l = +l;
    this.a = +a;
    this.b = +b;
    this.opacity = +opacity;
  }
  define_default(Lab, lab, extend(Color, {
    brighter: function(k) {
      return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
    },
    darker: function(k) {
      return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
    },
    rgb: function() {
      var y2 = (this.l + 16) / 116, x2 = isNaN(this.a) ? y2 : y2 + this.a / 500, z = isNaN(this.b) ? y2 : y2 - this.b / 200;
      x2 = Xn * lab2xyz(x2);
      y2 = Yn * lab2xyz(y2);
      z = Zn * lab2xyz(z);
      return new Rgb(lrgb2rgb(3.1338561 * x2 - 1.6168667 * y2 - 0.4906146 * z), lrgb2rgb(-0.9787684 * x2 + 1.9161415 * y2 + 0.033454 * z), lrgb2rgb(0.0719453 * x2 - 0.2289914 * y2 + 1.4052427 * z), this.opacity);
    }
  }));
  function xyz2lab(t) {
    return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t02;
  }
  function lab2xyz(t) {
    return t > t12 ? t * t * t : t2 * (t - t02);
  }
  function lrgb2rgb(x2) {
    return 255 * (x2 <= 31308e-7 ? 12.92 * x2 : 1.055 * Math.pow(x2, 1 / 2.4) - 0.055);
  }
  function rgb2lrgb(x2) {
    return (x2 /= 255) <= 0.04045 ? x2 / 12.92 : Math.pow((x2 + 0.055) / 1.055, 2.4);
  }
  function hclConvert(o) {
    if (o instanceof Hcl)
      return new Hcl(o.h, o.c, o.l, o.opacity);
    if (!(o instanceof Lab))
      o = labConvert(o);
    if (o.a === 0 && o.b === 0)
      return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
    var h = Math.atan2(o.b, o.a) * degrees;
    return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
  }
  function hcl(h, c, l, opacity) {
    return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
  }
  function Hcl(h, c, l, opacity) {
    this.h = +h;
    this.c = +c;
    this.l = +l;
    this.opacity = +opacity;
  }
  function hcl2lab(o) {
    if (isNaN(o.h))
      return new Lab(o.l, 0, 0, o.opacity);
    var h = o.h * radians;
    return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  }
  define_default(Hcl, hcl, extend(Color, {
    brighter: function(k) {
      return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
    },
    darker: function(k) {
      return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
    },
    rgb: function() {
      return hcl2lab(this).rgb();
    }
  }));

  // node_modules/d3-interpolate/src/basis.js
  function basis(t13, v0, v1, v2, v3) {
    var t22 = t13 * t13, t32 = t22 * t13;
    return ((1 - 3 * t13 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t13 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6;
  }
  function basis_default(values) {
    var n = values.length - 1;
    return function(t) {
      var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
      return basis((t - i / n) * n, v0, v1, v2, v3);
    };
  }

  // node_modules/d3-interpolate/src/basisClosed.js
  function basisClosed_default(values) {
    var n = values.length;
    return function(t) {
      var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n];
      return basis((t - i / n) * n, v0, v1, v2, v3);
    };
  }

  // node_modules/d3-interpolate/src/constant.js
  var constant_default2 = (x2) => () => x2;

  // node_modules/d3-interpolate/src/color.js
  function linear(a, d) {
    return function(t) {
      return a + t * d;
    };
  }
  function exponential(a, b, y2) {
    return a = Math.pow(a, y2), b = Math.pow(b, y2) - a, y2 = 1 / y2, function(t) {
      return Math.pow(a + t * b, y2);
    };
  }
  function gamma(y2) {
    return (y2 = +y2) === 1 ? nogamma : function(a, b) {
      return b - a ? exponential(a, b, y2) : constant_default2(isNaN(a) ? b : a);
    };
  }
  function nogamma(a, b) {
    var d = b - a;
    return d ? linear(a, d) : constant_default2(isNaN(a) ? b : a);
  }

  // node_modules/d3-interpolate/src/rgb.js
  var rgb_default = function rgbGamma(y2) {
    var color2 = gamma(y2);
    function rgb2(start, end) {
      var r = color2((start = rgb(start)).r, (end = rgb(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.r = r(t);
        start.g = g(t);
        start.b = b(t);
        start.opacity = opacity(t);
        return start + "";
      };
    }
    rgb2.gamma = rgbGamma;
    return rgb2;
  }(1);
  function rgbSpline(spline) {
    return function(colors) {
      var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2;
      for (i = 0; i < n; ++i) {
        color2 = rgb(colors[i]);
        r[i] = color2.r || 0;
        g[i] = color2.g || 0;
        b[i] = color2.b || 0;
      }
      r = spline(r);
      g = spline(g);
      b = spline(b);
      color2.opacity = 1;
      return function(t) {
        color2.r = r(t);
        color2.g = g(t);
        color2.b = b(t);
        return color2 + "";
      };
    };
  }
  var rgbBasis = rgbSpline(basis_default);
  var rgbBasisClosed = rgbSpline(basisClosed_default);

  // node_modules/d3-interpolate/src/numberArray.js
  function numberArray_default(a, b) {
    if (!b)
      b = [];
    var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i;
    return function(t) {
      for (i = 0; i < n; ++i)
        c[i] = a[i] * (1 - t) + b[i] * t;
      return c;
    };
  }
  function isNumberArray(x2) {
    return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
  }

  // node_modules/d3-interpolate/src/array.js
  function genericArray(a, b) {
    var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x2 = new Array(na), c = new Array(nb), i;
    for (i = 0; i < na; ++i)
      x2[i] = value_default(a[i], b[i]);
    for (; i < nb; ++i)
      c[i] = b[i];
    return function(t) {
      for (i = 0; i < na; ++i)
        c[i] = x2[i](t);
      return c;
    };
  }

  // node_modules/d3-interpolate/src/date.js
  function date_default(a, b) {
    var d = new Date();
    return a = +a, b = +b, function(t) {
      return d.setTime(a * (1 - t) + b * t), d;
    };
  }

  // node_modules/d3-interpolate/src/number.js
  function number_default2(a, b) {
    return a = +a, b = +b, function(t) {
      return a * (1 - t) + b * t;
    };
  }

  // node_modules/d3-interpolate/src/object.js
  function object_default(a, b) {
    var i = {}, c = {}, k;
    if (a === null || typeof a !== "object")
      a = {};
    if (b === null || typeof b !== "object")
      b = {};
    for (k in b) {
      if (k in a) {
        i[k] = value_default(a[k], b[k]);
      } else {
        c[k] = b[k];
      }
    }
    return function(t) {
      for (k in i)
        c[k] = i[k](t);
      return c;
    };
  }

  // node_modules/d3-interpolate/src/string.js
  var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
  var reB = new RegExp(reA.source, "g");
  function zero(b) {
    return function() {
      return b;
    };
  }
  function one(b) {
    return function(t) {
      return b(t) + "";
    };
  }
  function string_default(a, b) {
    var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
    a = a + "", b = b + "";
    while ((am = reA.exec(a)) && (bm = reB.exec(b))) {
      if ((bs = bm.index) > bi) {
        bs = b.slice(bi, bs);
        if (s[i])
          s[i] += bs;
        else
          s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s[i])
          s[i] += bm;
        else
          s[++i] = bm;
      } else {
        s[++i] = null;
        q.push({i, x: number_default2(am, bm)});
      }
      bi = reB.lastIndex;
    }
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i])
        s[i] += bs;
      else
        s[++i] = bs;
    }
    return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) {
      for (var i2 = 0, o; i2 < b; ++i2)
        s[(o = q[i2]).i] = o.x(t);
      return s.join("");
    });
  }

  // node_modules/d3-interpolate/src/value.js
  function value_default(a, b) {
    var t = typeof b, c;
    return b == null || t === "boolean" ? constant_default2(b) : (t === "number" ? number_default2 : t === "string" ? (c = color(b)) ? (b = c, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default2)(a, b);
  }

  // node_modules/d3-interpolate/src/round.js
  function round_default2(a, b) {
    return a = +a, b = +b, function(t) {
      return Math.round(a * (1 - t) + b * t);
    };
  }

  // node_modules/d3-scale/src/constant.js
  function constants(x2) {
    return function() {
      return x2;
    };
  }

  // node_modules/d3-scale/src/number.js
  function number3(x2) {
    return +x2;
  }

  // node_modules/d3-scale/src/continuous.js
  var unit = [0, 1];
  function identity(x2) {
    return x2;
  }
  function normalize(a, b) {
    return (b -= a = +a) ? function(x2) {
      return (x2 - a) / b;
    } : constants(isNaN(b) ? NaN : 0.5);
  }
  function clamper(a, b) {
    var t;
    if (a > b)
      t = a, a = b, b = t;
    return function(x2) {
      return Math.max(a, Math.min(b, x2));
    };
  }
  function bimap(domain, range, interpolate) {
    var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
    if (d1 < d0)
      d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
    else
      d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
    return function(x2) {
      return r0(d0(x2));
    };
  }
  function polymap(domain, range, interpolate) {
    var j = Math.min(domain.length, range.length) - 1, d = new Array(j), r = new Array(j), i = -1;
    if (domain[j] < domain[0]) {
      domain = domain.slice().reverse();
      range = range.slice().reverse();
    }
    while (++i < j) {
      d[i] = normalize(domain[i], domain[i + 1]);
      r[i] = interpolate(range[i], range[i + 1]);
    }
    return function(x2) {
      var i2 = bisect_default(domain, x2, 1, j) - 1;
      return r[i2](d[i2](x2));
    };
  }
  function copy(source, target) {
    return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
  }
  function transformer() {
    var domain = unit, range = unit, interpolate = value_default, transform, untransform, unknown2, clamp = identity, piecewise, output, input;
    function rescale() {
      var n = Math.min(domain.length, range.length);
      if (clamp !== identity)
        clamp = clamper(domain[0], domain[n - 1]);
      piecewise = n > 2 ? polymap : bimap;
      output = input = null;
      return scale;
    }
    function scale(x2) {
      return isNaN(x2 = +x2) ? unknown2 : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x2)));
    }
    scale.invert = function(y2) {
      return clamp(untransform((input || (input = piecewise(range, domain.map(transform), number_default2)))(y2)));
    };
    scale.domain = function(_2) {
      return arguments.length ? (domain = Array.from(_2, number3), rescale()) : domain.slice();
    };
    scale.range = function(_2) {
      return arguments.length ? (range = Array.from(_2), rescale()) : range.slice();
    };
    scale.rangeRound = function(_2) {
      return range = Array.from(_2), interpolate = round_default2, rescale();
    };
    scale.clamp = function(_2) {
      return arguments.length ? (clamp = _2 ? true : identity, rescale()) : clamp !== identity;
    };
    scale.interpolate = function(_2) {
      return arguments.length ? (interpolate = _2, rescale()) : interpolate;
    };
    scale.unknown = function(_2) {
      return arguments.length ? (unknown2 = _2, scale) : unknown2;
    };
    return function(t, u) {
      transform = t, untransform = u;
      return rescale();
    };
  }
  function continuous() {
    return transformer()(identity, identity);
  }

  // node_modules/d3-scale/src/tickFormat.js
  function tickFormat(start, stop, count2, specifier) {
    var step = tickStep(start, stop, count2), precision;
    specifier = formatSpecifier(specifier == null ? ",f" : specifier);
    switch (specifier.type) {
      case "s": {
        var value = Math.max(Math.abs(start), Math.abs(stop));
        if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value)))
          specifier.precision = precision;
        return formatPrefix(specifier, value);
      }
      case "":
      case "e":
      case "g":
      case "p":
      case "r": {
        if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start), Math.abs(stop)))))
          specifier.precision = precision - (specifier.type === "e");
        break;
      }
      case "f":
      case "%": {
        if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step)))
          specifier.precision = precision - (specifier.type === "%") * 2;
        break;
      }
    }
    return format(specifier);
  }

  // node_modules/d3-scale/src/linear.js
  function linearish(scale) {
    var domain = scale.domain;
    scale.ticks = function(count2) {
      var d = domain();
      return ticks_default(d[0], d[d.length - 1], count2 == null ? 10 : count2);
    };
    scale.tickFormat = function(count2, specifier) {
      var d = domain();
      return tickFormat(d[0], d[d.length - 1], count2 == null ? 10 : count2, specifier);
    };
    scale.nice = function(count2) {
      if (count2 == null)
        count2 = 10;
      var d = domain();
      var i0 = 0;
      var i1 = d.length - 1;
      var start = d[i0];
      var stop = d[i1];
      var prestep;
      var step;
      var maxIter = 10;
      if (stop < start) {
        step = start, start = stop, stop = step;
        step = i0, i0 = i1, i1 = step;
      }
      while (maxIter-- > 0) {
        step = tickIncrement(start, stop, count2);
        if (step === prestep) {
          d[i0] = start;
          d[i1] = stop;
          return domain(d);
        } else if (step > 0) {
          start = Math.floor(start / step) * step;
          stop = Math.ceil(stop / step) * step;
        } else if (step < 0) {
          start = Math.ceil(start * step) / step;
          stop = Math.floor(stop * step) / step;
        } else {
          break;
        }
        prestep = step;
      }
      return scale;
    };
    return scale;
  }
  function linear2() {
    var scale = continuous();
    scale.copy = function() {
      return copy(scale, linear2());
    };
    initRange.apply(scale, arguments);
    return linearish(scale);
  }

  // node_modules/d3-scale/src/nice.js
  function nice(domain, interval2) {
    domain = domain.slice();
    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], t;
    if (x1 < x0) {
      t = i0, i0 = i1, i1 = t;
      t = x0, x0 = x1, x1 = t;
    }
    domain[i0] = interval2.floor(x0);
    domain[i1] = interval2.ceil(x1);
    return domain;
  }

  // node_modules/d3-scale/src/pow.js
  function transformPow(exponent) {
    return function(x2) {
      return x2 < 0 ? -Math.pow(-x2, exponent) : Math.pow(x2, exponent);
    };
  }
  function transformSqrt(x2) {
    return x2 < 0 ? -Math.sqrt(-x2) : Math.sqrt(x2);
  }
  function transformSquare(x2) {
    return x2 < 0 ? -x2 * x2 : x2 * x2;
  }
  function powish(transform) {
    var scale = transform(identity, identity), exponent = 1;
    function rescale() {
      return exponent === 1 ? transform(identity, identity) : exponent === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent));
    }
    scale.exponent = function(_2) {
      return arguments.length ? (exponent = +_2, rescale()) : exponent;
    };
    return linearish(scale);
  }
  function pow() {
    var scale = powish(transformer());
    scale.copy = function() {
      return copy(scale, pow()).exponent(scale.exponent());
    };
    initRange.apply(scale, arguments);
    return scale;
  }
  function sqrt() {
    return pow.apply(null, arguments).exponent(0.5);
  }

  // node_modules/d3-scale/src/time.js
  var durationSecond2 = 1e3;
  var durationMinute2 = durationSecond2 * 60;
  var durationHour2 = durationMinute2 * 60;
  var durationDay2 = durationHour2 * 24;
  var durationWeek2 = durationDay2 * 7;
  var durationMonth = durationDay2 * 30;
  var durationYear = durationDay2 * 365;
  function date2(t) {
    return new Date(t);
  }
  function number4(t) {
    return t instanceof Date ? +t : +new Date(+t);
  }
  function calendar(year2, month, week, day2, hour, minute, second2, millisecond2, format2) {
    var scale = continuous(), invert = scale.invert, domain = scale.domain;
    var formatMillisecond = format2(".%L"), formatSecond = format2(":%S"), formatMinute = format2("%I:%M"), formatHour = format2("%I %p"), formatDay = format2("%a %d"), formatWeek = format2("%b %d"), formatMonth = format2("%B"), formatYear2 = format2("%Y");
    var tickIntervals = [
      [second2, 1, durationSecond2],
      [second2, 5, 5 * durationSecond2],
      [second2, 15, 15 * durationSecond2],
      [second2, 30, 30 * durationSecond2],
      [minute, 1, durationMinute2],
      [minute, 5, 5 * durationMinute2],
      [minute, 15, 15 * durationMinute2],
      [minute, 30, 30 * durationMinute2],
      [hour, 1, durationHour2],
      [hour, 3, 3 * durationHour2],
      [hour, 6, 6 * durationHour2],
      [hour, 12, 12 * durationHour2],
      [day2, 1, durationDay2],
      [day2, 2, 2 * durationDay2],
      [week, 1, durationWeek2],
      [month, 1, durationMonth],
      [month, 3, 3 * durationMonth],
      [year2, 1, durationYear]
    ];
    function tickFormat2(date3) {
      return (second2(date3) < date3 ? formatMillisecond : minute(date3) < date3 ? formatSecond : hour(date3) < date3 ? formatMinute : day2(date3) < date3 ? formatHour : month(date3) < date3 ? week(date3) < date3 ? formatDay : formatWeek : year2(date3) < date3 ? formatMonth : formatYear2)(date3);
    }
    function tickInterval(interval2, start, stop) {
      if (interval2 == null)
        interval2 = 10;
      if (typeof interval2 === "number") {
        var target = Math.abs(stop - start) / interval2, i = bisector_default(function(i2) {
          return i2[2];
        }).right(tickIntervals, target), step;
        if (i === tickIntervals.length) {
          step = tickStep(start / durationYear, stop / durationYear, interval2);
          interval2 = year2;
        } else if (i) {
          i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
          step = i[1];
          interval2 = i[0];
        } else {
          step = Math.max(tickStep(start, stop, interval2), 1);
          interval2 = millisecond2;
        }
        return interval2.every(step);
      }
      return interval2;
    }
    scale.invert = function(y2) {
      return new Date(invert(y2));
    };
    scale.domain = function(_2) {
      return arguments.length ? domain(Array.from(_2, number4)) : domain().map(date2);
    };
    scale.ticks = function(interval2) {
      var d = domain(), t03 = d[0], t13 = d[d.length - 1], r = t13 < t03, t;
      if (r)
        t = t03, t03 = t13, t13 = t;
      t = tickInterval(interval2, t03, t13);
      t = t ? t.range(t03, t13 + 1) : [];
      return r ? t.reverse() : t;
    };
    scale.tickFormat = function(count2, specifier) {
      return specifier == null ? tickFormat2 : format2(specifier);
    };
    scale.nice = function(interval2) {
      var d = domain();
      return (interval2 = tickInterval(interval2, d[0], d[d.length - 1])) ? domain(nice(d, interval2)) : scale;
    };
    scale.copy = function() {
      return copy(scale, calendar(year2, month, week, day2, hour, minute, second2, millisecond2, format2));
    };
    return scale;
  }

  // node_modules/d3-scale/src/utcTime.js
  function utcTime() {
    return initRange.apply(calendar(utcYear_default, utcMonth_default, utcSunday, utcDay_default, utcHour_default, utcMinute_default, second_default, millisecond_default, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
  }

  // node_modules/d3-selection/src/namespaces.js
  var xhtml = "http://www.w3.org/1999/xhtml";
  var namespaces_default = {
    svg: "http://www.w3.org/2000/svg",
    xhtml,
    xlink: "http://www.w3.org/1999/xlink",
    xml: "http://www.w3.org/XML/1998/namespace",
    xmlns: "http://www.w3.org/2000/xmlns/"
  };

  // node_modules/d3-selection/src/namespace.js
  function namespace_default(name) {
    var prefix = name += "", i = prefix.indexOf(":");
    if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns")
      name = name.slice(i + 1);
    return namespaces_default.hasOwnProperty(prefix) ? {space: namespaces_default[prefix], local: name} : name;
  }

  // node_modules/d3-selection/src/creator.js
  function creatorInherit(name) {
    return function() {
      var document2 = this.ownerDocument, uri = this.namespaceURI;
      return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name) : document2.createElementNS(uri, name);
    };
  }
  function creatorFixed(fullname) {
    return function() {
      return this.ownerDocument.createElementNS(fullname.space, fullname.local);
    };
  }
  function creator_default(name) {
    var fullname = namespace_default(name);
    return (fullname.local ? creatorFixed : creatorInherit)(fullname);
  }

  // node_modules/d3-selection/src/selector.js
  function none() {
  }
  function selector_default(selector) {
    return selector == null ? none : function() {
      return this.querySelector(selector);
    };
  }

  // node_modules/d3-selection/src/selection/select.js
  function select_default(select) {
    if (typeof select !== "function")
      select = selector_default(select);
    for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
      for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
        if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
          if ("__data__" in node)
            subnode.__data__ = node.__data__;
          subgroup[i] = subnode;
        }
      }
    }
    return new Selection(subgroups, this._parents);
  }

  // node_modules/d3-selection/src/array.js
  function array_default(x2) {
    return typeof x2 === "object" && "length" in x2 ? x2 : Array.from(x2);
  }

  // node_modules/d3-selection/src/selectorAll.js
  function empty2() {
    return [];
  }
  function selectorAll_default(selector) {
    return selector == null ? empty2 : function() {
      return this.querySelectorAll(selector);
    };
  }

  // node_modules/d3-selection/src/selection/selectAll.js
  function arrayAll(select) {
    return function() {
      var group = select.apply(this, arguments);
      return group == null ? [] : array_default(group);
    };
  }
  function selectAll_default(select) {
    if (typeof select === "function")
      select = arrayAll(select);
    else
      select = selectorAll_default(select);
    for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
      for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
        if (node = group[i]) {
          subgroups.push(select.call(node, node.__data__, i, group));
          parents.push(node);
        }
      }
    }
    return new Selection(subgroups, parents);
  }

  // node_modules/d3-selection/src/matcher.js
  function matcher_default(selector) {
    return function() {
      return this.matches(selector);
    };
  }
  function childMatcher(selector) {
    return function(node) {
      return node.matches(selector);
    };
  }

  // node_modules/d3-selection/src/selection/selectChild.js
  var find = Array.prototype.find;
  function childFind(match) {
    return function() {
      return find.call(this.children, match);
    };
  }
  function childFirst() {
    return this.firstElementChild;
  }
  function selectChild_default(match) {
    return this.select(match == null ? childFirst : childFind(typeof match === "function" ? match : childMatcher(match)));
  }

  // node_modules/d3-selection/src/selection/selectChildren.js
  var filter = Array.prototype.filter;
  function children2() {
    return this.children;
  }
  function childrenFilter(match) {
    return function() {
      return filter.call(this.children, match);
    };
  }
  function selectChildren_default(match) {
    return this.selectAll(match == null ? children2 : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
  }

  // node_modules/d3-selection/src/selection/filter.js
  function filter_default(match) {
    if (typeof match !== "function")
      match = matcher_default(match);
    for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
      for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
        if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
          subgroup.push(node);
        }
      }
    }
    return new Selection(subgroups, this._parents);
  }

  // node_modules/d3-selection/src/selection/sparse.js
  function sparse_default(update2) {
    return new Array(update2.length);
  }

  // node_modules/d3-selection/src/selection/enter.js
  function enter_default() {
    return new Selection(this._enter || this._groups.map(sparse_default), this._parents);
  }
  function EnterNode(parent2, datum2) {
    this.ownerDocument = parent2.ownerDocument;
    this.namespaceURI = parent2.namespaceURI;
    this._next = null;
    this._parent = parent2;
    this.__data__ = datum2;
  }
  EnterNode.prototype = {
    constructor: EnterNode,
    appendChild: function(child) {
      return this._parent.insertBefore(child, this._next);
    },
    insertBefore: function(child, next) {
      return this._parent.insertBefore(child, next);
    },
    querySelector: function(selector) {
      return this._parent.querySelector(selector);
    },
    querySelectorAll: function(selector) {
      return this._parent.querySelectorAll(selector);
    }
  };

  // node_modules/d3-selection/src/constant.js
  function constant_default3(x2) {
    return function() {
      return x2;
    };
  }

  // node_modules/d3-selection/src/selection/data.js
  function bindIndex(parent2, group, enter, update2, exit, data) {
    var i = 0, node, groupLength = group.length, dataLength = data.length;
    for (; i < dataLength; ++i) {
      if (node = group[i]) {
        node.__data__ = data[i];
        update2[i] = node;
      } else {
        enter[i] = new EnterNode(parent2, data[i]);
      }
    }
    for (; i < groupLength; ++i) {
      if (node = group[i]) {
        exit[i] = node;
      }
    }
  }
  function bindKey2(parent2, group, enter, update2, exit, data, key) {
    var i, node, nodeByKeyValue = new Map(), groupLength = group.length, dataLength = data.length, keyValues = new Array(groupLength), keyValue;
    for (i = 0; i < groupLength; ++i) {
      if (node = group[i]) {
        keyValues[i] = keyValue = key.call(node, node.__data__, i, group) + "";
        if (nodeByKeyValue.has(keyValue)) {
          exit[i] = node;
        } else {
          nodeByKeyValue.set(keyValue, node);
        }
      }
    }
    for (i = 0; i < dataLength; ++i) {
      keyValue = key.call(parent2, data[i], i, data) + "";
      if (node = nodeByKeyValue.get(keyValue)) {
        update2[i] = node;
        node.__data__ = data[i];
        nodeByKeyValue.delete(keyValue);
      } else {
        enter[i] = new EnterNode(parent2, data[i]);
      }
    }
    for (i = 0; i < groupLength; ++i) {
      if ((node = group[i]) && nodeByKeyValue.get(keyValues[i]) === node) {
        exit[i] = node;
      }
    }
  }
  function datum(node) {
    return node.__data__;
  }
  function data_default(value, key) {
    if (!arguments.length)
      return Array.from(this, datum);
    var bind2 = key ? bindKey2 : bindIndex, parents = this._parents, groups = this._groups;
    if (typeof value !== "function")
      value = constant_default3(value);
    for (var m = groups.length, update2 = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
      var parent2 = parents[j], group = groups[j], groupLength = group.length, data = array_default(value.call(parent2, parent2 && parent2.__data__, j, parents)), dataLength = data.length, enterGroup = enter[j] = new Array(dataLength), updateGroup = update2[j] = new Array(dataLength), exitGroup = exit[j] = new Array(groupLength);
      bind2(parent2, group, enterGroup, updateGroup, exitGroup, data, key);
      for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
        if (previous = enterGroup[i0]) {
          if (i0 >= i1)
            i1 = i0 + 1;
          while (!(next = updateGroup[i1]) && ++i1 < dataLength)
            ;
          previous._next = next || null;
        }
      }
    }
    update2 = new Selection(update2, parents);
    update2._enter = enter;
    update2._exit = exit;
    return update2;
  }

  // node_modules/d3-selection/src/selection/exit.js
  function exit_default() {
    return new Selection(this._exit || this._groups.map(sparse_default), this._parents);
  }

  // node_modules/d3-selection/src/selection/join.js
  function join_default(onenter, onupdate, onexit) {
    var enter = this.enter(), update2 = this, exit = this.exit();
    enter = typeof onenter === "function" ? onenter(enter) : enter.append(onenter + "");
    if (onupdate != null)
      update2 = onupdate(update2);
    if (onexit == null)
      exit.remove();
    else
      onexit(exit);
    return enter && update2 ? enter.merge(update2).order() : update2;
  }

  // node_modules/d3-selection/src/selection/merge.js
  function merge_default(selection2) {
    if (!(selection2 instanceof Selection))
      throw new Error("invalid merge");
    for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
      for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge2 = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
        if (node = group0[i] || group1[i]) {
          merge2[i] = node;
        }
      }
    }
    for (; j < m0; ++j) {
      merges[j] = groups0[j];
    }
    return new Selection(merges, this._parents);
  }

  // node_modules/d3-selection/src/selection/order.js
  function order_default() {
    for (var groups = this._groups, j = -1, m = groups.length; ++j < m; ) {
      for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
        if (node = group[i]) {
          if (next && node.compareDocumentPosition(next) ^ 4)
            next.parentNode.insertBefore(node, next);
          next = node;
        }
      }
    }
    return this;
  }

  // node_modules/d3-selection/src/selection/sort.js
  function sort_default2(compare) {
    if (!compare)
      compare = ascending;
    function compareNode(a, b) {
      return a && b ? compare(a.__data__, b.__data__) : !a - !b;
    }
    for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
      for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
        if (node = group[i]) {
          sortgroup[i] = node;
        }
      }
      sortgroup.sort(compareNode);
    }
    return new Selection(sortgroups, this._parents).order();
  }
  function ascending(a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  }

  // node_modules/d3-selection/src/selection/call.js
  function call_default() {
    var callback = arguments[0];
    arguments[0] = this;
    callback.apply(null, arguments);
    return this;
  }

  // node_modules/d3-selection/src/selection/nodes.js
  function nodes_default() {
    return Array.from(this);
  }

  // node_modules/d3-selection/src/selection/node.js
  function node_default() {
    for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
      for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
        var node = group[i];
        if (node)
          return node;
      }
    }
    return null;
  }

  // node_modules/d3-selection/src/selection/size.js
  function size_default() {
    let size = 0;
    for (const node of this)
      ++size;
    return size;
  }

  // node_modules/d3-selection/src/selection/empty.js
  function empty_default() {
    return !this.node();
  }

  // node_modules/d3-selection/src/selection/each.js
  function each_default2(callback) {
    for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
      for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
        if (node = group[i])
          callback.call(node, node.__data__, i, group);
      }
    }
    return this;
  }

  // node_modules/d3-selection/src/selection/attr.js
  function attrRemove(name) {
    return function() {
      this.removeAttribute(name);
    };
  }
  function attrRemoveNS(fullname) {
    return function() {
      this.removeAttributeNS(fullname.space, fullname.local);
    };
  }
  function attrConstant(name, value) {
    return function() {
      this.setAttribute(name, value);
    };
  }
  function attrConstantNS(fullname, value) {
    return function() {
      this.setAttributeNS(fullname.space, fullname.local, value);
    };
  }
  function attrFunction(name, value) {
    return function() {
      var v = value.apply(this, arguments);
      if (v == null)
        this.removeAttribute(name);
      else
        this.setAttribute(name, v);
    };
  }
  function attrFunctionNS(fullname, value) {
    return function() {
      var v = value.apply(this, arguments);
      if (v == null)
        this.removeAttributeNS(fullname.space, fullname.local);
      else
        this.setAttributeNS(fullname.space, fullname.local, v);
    };
  }
  function attr_default(name, value) {
    var fullname = namespace_default(name);
    if (arguments.length < 2) {
      var node = this.node();
      return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
    }
    return this.each((value == null ? fullname.local ? attrRemoveNS : attrRemove : typeof value === "function" ? fullname.local ? attrFunctionNS : attrFunction : fullname.local ? attrConstantNS : attrConstant)(fullname, value));
  }

  // node_modules/d3-selection/src/window.js
  function window_default(node) {
    return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
  }

  // node_modules/d3-selection/src/selection/style.js
  function styleRemove(name) {
    return function() {
      this.style.removeProperty(name);
    };
  }
  function styleConstant(name, value, priority) {
    return function() {
      this.style.setProperty(name, value, priority);
    };
  }
  function styleFunction(name, value, priority) {
    return function() {
      var v = value.apply(this, arguments);
      if (v == null)
        this.style.removeProperty(name);
      else
        this.style.setProperty(name, v, priority);
    };
  }
  function style_default(name, value, priority) {
    return arguments.length > 1 ? this.each((value == null ? styleRemove : typeof value === "function" ? styleFunction : styleConstant)(name, value, priority == null ? "" : priority)) : styleValue(this.node(), name);
  }
  function styleValue(node, name) {
    return node.style.getPropertyValue(name) || window_default(node).getComputedStyle(node, null).getPropertyValue(name);
  }

  // node_modules/d3-selection/src/selection/property.js
  function propertyRemove(name) {
    return function() {
      delete this[name];
    };
  }
  function propertyConstant(name, value) {
    return function() {
      this[name] = value;
    };
  }
  function propertyFunction(name, value) {
    return function() {
      var v = value.apply(this, arguments);
      if (v == null)
        delete this[name];
      else
        this[name] = v;
    };
  }
  function property_default(name, value) {
    return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name, value)) : this.node()[name];
  }

  // node_modules/d3-selection/src/selection/classed.js
  function classArray(string2) {
    return string2.trim().split(/^|\s+/);
  }
  function classList(node) {
    return node.classList || new ClassList(node);
  }
  function ClassList(node) {
    this._node = node;
    this._names = classArray(node.getAttribute("class") || "");
  }
  ClassList.prototype = {
    add: function(name) {
      var i = this._names.indexOf(name);
      if (i < 0) {
        this._names.push(name);
        this._node.setAttribute("class", this._names.join(" "));
      }
    },
    remove: function(name) {
      var i = this._names.indexOf(name);
      if (i >= 0) {
        this._names.splice(i, 1);
        this._node.setAttribute("class", this._names.join(" "));
      }
    },
    contains: function(name) {
      return this._names.indexOf(name) >= 0;
    }
  };
  function classedAdd(node, names) {
    var list = classList(node), i = -1, n = names.length;
    while (++i < n)
      list.add(names[i]);
  }
  function classedRemove(node, names) {
    var list = classList(node), i = -1, n = names.length;
    while (++i < n)
      list.remove(names[i]);
  }
  function classedTrue(names) {
    return function() {
      classedAdd(this, names);
    };
  }
  function classedFalse(names) {
    return function() {
      classedRemove(this, names);
    };
  }
  function classedFunction(names, value) {
    return function() {
      (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
    };
  }
  function classed_default(name, value) {
    var names = classArray(name + "");
    if (arguments.length < 2) {
      var list = classList(this.node()), i = -1, n = names.length;
      while (++i < n)
        if (!list.contains(names[i]))
          return false;
      return true;
    }
    return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
  }

  // node_modules/d3-selection/src/selection/text.js
  function textRemove() {
    this.textContent = "";
  }
  function textConstant(value) {
    return function() {
      this.textContent = value;
    };
  }
  function textFunction(value) {
    return function() {
      var v = value.apply(this, arguments);
      this.textContent = v == null ? "" : v;
    };
  }
  function text_default(value) {
    return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction : textConstant)(value)) : this.node().textContent;
  }

  // node_modules/d3-selection/src/selection/html.js
  function htmlRemove() {
    this.innerHTML = "";
  }
  function htmlConstant(value) {
    return function() {
      this.innerHTML = value;
    };
  }
  function htmlFunction(value) {
    return function() {
      var v = value.apply(this, arguments);
      this.innerHTML = v == null ? "" : v;
    };
  }
  function html_default(value) {
    return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
  }

  // node_modules/d3-selection/src/selection/raise.js
  function raise() {
    if (this.nextSibling)
      this.parentNode.appendChild(this);
  }
  function raise_default() {
    return this.each(raise);
  }

  // node_modules/d3-selection/src/selection/lower.js
  function lower() {
    if (this.previousSibling)
      this.parentNode.insertBefore(this, this.parentNode.firstChild);
  }
  function lower_default() {
    return this.each(lower);
  }

  // node_modules/d3-selection/src/selection/append.js
  function append_default(name) {
    var create2 = typeof name === "function" ? name : creator_default(name);
    return this.select(function() {
      return this.appendChild(create2.apply(this, arguments));
    });
  }

  // node_modules/d3-selection/src/selection/insert.js
  function constantNull() {
    return null;
  }
  function insert_default(name, before) {
    var create2 = typeof name === "function" ? name : creator_default(name), select = before == null ? constantNull : typeof before === "function" ? before : selector_default(before);
    return this.select(function() {
      return this.insertBefore(create2.apply(this, arguments), select.apply(this, arguments) || null);
    });
  }

  // node_modules/d3-selection/src/selection/remove.js
  function remove() {
    var parent2 = this.parentNode;
    if (parent2)
      parent2.removeChild(this);
  }
  function remove_default() {
    return this.each(remove);
  }

  // node_modules/d3-selection/src/selection/clone.js
  function selection_cloneShallow() {
    var clone = this.cloneNode(false), parent2 = this.parentNode;
    return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
  }
  function selection_cloneDeep() {
    var clone = this.cloneNode(true), parent2 = this.parentNode;
    return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
  }
  function clone_default(deep) {
    return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
  }

  // node_modules/d3-selection/src/selection/datum.js
  function datum_default(value) {
    return arguments.length ? this.property("__data__", value) : this.node().__data__;
  }

  // node_modules/d3-selection/src/selection/on.js
  function contextListener(listener) {
    return function(event) {
      listener.call(this, event, this.__data__);
    };
  }
  function parseTypenames(typenames) {
    return typenames.trim().split(/^|\s+/).map(function(t) {
      var name = "", i = t.indexOf(".");
      if (i >= 0)
        name = t.slice(i + 1), t = t.slice(0, i);
      return {type: t, name};
    });
  }
  function onRemove(typename) {
    return function() {
      var on = this.__on;
      if (!on)
        return;
      for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
        if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
          this.removeEventListener(o.type, o.listener, o.options);
        } else {
          on[++i] = o;
        }
      }
      if (++i)
        on.length = i;
      else
        delete this.__on;
    };
  }
  function onAdd(typename, value, options) {
    return function() {
      var on = this.__on, o, listener = contextListener(value);
      if (on)
        for (var j = 0, m = on.length; j < m; ++j) {
          if ((o = on[j]).type === typename.type && o.name === typename.name) {
            this.removeEventListener(o.type, o.listener, o.options);
            this.addEventListener(o.type, o.listener = listener, o.options = options);
            o.value = value;
            return;
          }
        }
      this.addEventListener(typename.type, listener, options);
      o = {type: typename.type, name: typename.name, value, listener, options};
      if (!on)
        this.__on = [o];
      else
        on.push(o);
    };
  }
  function on_default(typename, value, options) {
    var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;
    if (arguments.length < 2) {
      var on = this.node().__on;
      if (on)
        for (var j = 0, m = on.length, o; j < m; ++j) {
          for (i = 0, o = on[j]; i < n; ++i) {
            if ((t = typenames[i]).type === o.type && t.name === o.name) {
              return o.value;
            }
          }
        }
      return;
    }
    on = value ? onAdd : onRemove;
    for (i = 0; i < n; ++i)
      this.each(on(typenames[i], value, options));
    return this;
  }

  // node_modules/d3-selection/src/selection/dispatch.js
  function dispatchEvent(node, type, params) {
    var window2 = window_default(node), event = window2.CustomEvent;
    if (typeof event === "function") {
      event = new event(type, params);
    } else {
      event = window2.document.createEvent("Event");
      if (params)
        event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
      else
        event.initEvent(type, false, false);
    }
    node.dispatchEvent(event);
  }
  function dispatchConstant(type, params) {
    return function() {
      return dispatchEvent(this, type, params);
    };
  }
  function dispatchFunction(type, params) {
    return function() {
      return dispatchEvent(this, type, params.apply(this, arguments));
    };
  }
  function dispatch_default(type, params) {
    return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
  }

  // node_modules/d3-selection/src/selection/iterator.js
  function* iterator_default2() {
    for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
      for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
        if (node = group[i])
          yield node;
      }
    }
  }

  // node_modules/d3-selection/src/selection/index.js
  var root = [null];
  function Selection(groups, parents) {
    this._groups = groups;
    this._parents = parents;
  }
  function selection() {
    return new Selection([[document.documentElement]], root);
  }
  function selection_selection() {
    return this;
  }
  Selection.prototype = selection.prototype = {
    constructor: Selection,
    select: select_default,
    selectAll: selectAll_default,
    selectChild: selectChild_default,
    selectChildren: selectChildren_default,
    filter: filter_default,
    data: data_default,
    enter: enter_default,
    exit: exit_default,
    join: join_default,
    merge: merge_default,
    selection: selection_selection,
    order: order_default,
    sort: sort_default2,
    call: call_default,
    nodes: nodes_default,
    node: node_default,
    size: size_default,
    empty: empty_default,
    each: each_default2,
    attr: attr_default,
    style: style_default,
    property: property_default,
    classed: classed_default,
    text: text_default,
    html: html_default,
    raise: raise_default,
    lower: lower_default,
    append: append_default,
    insert: insert_default,
    remove: remove_default,
    clone: clone_default,
    datum: datum_default,
    on: on_default,
    dispatch: dispatch_default,
    [Symbol.iterator]: iterator_default2
  };

  // node_modules/d3-selection/src/select.js
  function select_default2(selector) {
    return typeof selector === "string" ? new Selection([[document.querySelector(selector)]], [document.documentElement]) : new Selection([[selector]], root);
  }

  // node_modules/d3-selection/src/sourceEvent.js
  function sourceEvent_default(event) {
    let sourceEvent;
    while (sourceEvent = event.sourceEvent)
      event = sourceEvent;
    return event;
  }

  // node_modules/d3-selection/src/pointer.js
  function pointer_default(event, node) {
    event = sourceEvent_default(event);
    if (node === void 0)
      node = event.currentTarget;
    if (node) {
      var svg = node.ownerSVGElement || node;
      if (svg.createSVGPoint) {
        var point2 = svg.createSVGPoint();
        point2.x = event.clientX, point2.y = event.clientY;
        point2 = point2.matrixTransform(node.getScreenCTM().inverse());
        return [point2.x, point2.y];
      }
      if (node.getBoundingClientRect) {
        var rect = node.getBoundingClientRect();
        return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
      }
    }
    return [event.pageX, event.pageY];
  }

  // src/charts/axis.ts
  function axis2(node, ax) {
    const selection2 = select_default2(node);
    ax(selection2);
    return {
      update(a) {
        a(selection2);
      }
    };
  }

  // src/charts/helpers.ts
  function setTimeFilter(date3) {
    time_filter.set(get_store_value(currentTimeFilterDateFormat)(date3));
  }
  function hclColorRange(count2, chroma = 45, luminance = 70) {
    const offset = 270;
    const delta = 360 / count2;
    const colors = [...Array(count2).keys()].map((index) => {
      const hue = (index * delta + offset) % 360;
      return hcl(hue, chroma, luminance);
    });
    return colors.map((c) => c.toString());
  }
  var colors10 = hclColorRange(10);
  var colors15 = hclColorRange(15, 30, 80);
  var scatterplotScale = ordinal(colors10);
  var treemapScale = derived(accounts, (accounts_val) => ordinal(colors15).domain(accounts_val));
  var sunburstScale = derived(accounts, (accounts_val) => ordinal(colors10).domain(accounts_val));
  var currenciesScale = derived([operating_currency, currencies_sorted], ([operating_currency_val, currencies_sorted_val]) => ordinal(colors10).domain([
    ...operating_currency_val,
    ...currencies_sorted_val
  ]));

  // src/charts/tooltip.ts
  function createTooltip() {
    const tooltip2 = document.createElement("div");
    tooltip2.className = "tooltip";
    document.body.appendChild(tooltip2);
    const hide2 = () => {
      tooltip2.style.opacity = "0";
    };
    return [tooltip2, hide2];
  }
  var [tooltip, hide] = createTooltip();
  function followingTooltip(node, text2) {
    let getter = text2;
    function followMouse(event) {
      tooltip.style.opacity = "1";
      tooltip.style.left = `${event.pageX}px`;
      tooltip.style.top = `${event.pageY - 15}px`;
    }
    node.addEventListener("mouseenter", () => {
      tooltip.innerHTML = getter();
    });
    node.addEventListener("mousemove", followMouse);
    node.addEventListener("mouseleave", hide);
    return {
      destroy: hide,
      update(t) {
        getter = t;
      }
    };
  }
  function positionedTooltip(node, find2) {
    function mousemove(event) {
      const [xPointer, yPointer] = pointer_default(event);
      const res = find2(xPointer, yPointer);
      const matrix = node.getScreenCTM();
      if (res && matrix) {
        const [x2, y2, content] = res;
        tooltip.style.opacity = "1";
        tooltip.innerHTML = content;
        tooltip.style.left = `${window.scrollX + x2 + matrix.e}px`;
        tooltip.style.top = `${window.scrollY + y2 + matrix.f - 15}px`;
      } else {
        hide();
      }
    }
    node.addEventListener("mousemove", mousemove);
    node.addEventListener("mouseleave", hide);
    return {
      destroy: hide
    };
  }

  // src/charts/BarChart.svelte
  function get_each_context3(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[20] = list[i];
    return child_ctx;
  }
  function get_each_context_12(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[23] = list[i];
    return child_ctx;
  }
  function create_each_block_12(ctx) {
    let rect0;
    let rect0_fill_value;
    let rect0_width_value;
    let rect0_x_value;
    let rect0_y_value;
    let rect0_height_value;
    let rect1;
    let rect1_width_value;
    let rect1_x_value;
    let rect1_y_value;
    let rect1_height_value;
    return {
      c() {
        rect0 = svg_element("rect");
        rect1 = svg_element("rect");
        attr(rect0, "fill", rect0_fill_value = ctx[7](ctx[23].name));
        attr(rect0, "width", rect0_width_value = ctx[5].bandwidth());
        attr(rect0, "x", rect0_x_value = ctx[5](ctx[23].name));
        attr(rect0, "y", rect0_y_value = ctx[6](Math.max(0, ctx[23].value)));
        attr(rect0, "height", rect0_height_value = Math.abs(ctx[6](ctx[23].value) - ctx[6](0)));
        attr(rect1, "class", "budget svelte-1es9imu");
        attr(rect1, "width", rect1_width_value = ctx[5].bandwidth());
        attr(rect1, "x", rect1_x_value = ctx[5](ctx[23].name));
        attr(rect1, "y", rect1_y_value = ctx[6](Math.max(0, ctx[23].budget)));
        attr(rect1, "height", rect1_height_value = Math.abs(ctx[6](ctx[23].budget) - ctx[6](0)));
      },
      m(target, anchor) {
        insert(target, rect0, anchor);
        insert(target, rect1, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 129 && rect0_fill_value !== (rect0_fill_value = ctx2[7](ctx2[23].name))) {
          attr(rect0, "fill", rect0_fill_value);
        }
        if (dirty & 32 && rect0_width_value !== (rect0_width_value = ctx2[5].bandwidth())) {
          attr(rect0, "width", rect0_width_value);
        }
        if (dirty & 33 && rect0_x_value !== (rect0_x_value = ctx2[5](ctx2[23].name))) {
          attr(rect0, "x", rect0_x_value);
        }
        if (dirty & 65 && rect0_y_value !== (rect0_y_value = ctx2[6](Math.max(0, ctx2[23].value)))) {
          attr(rect0, "y", rect0_y_value);
        }
        if (dirty & 65 && rect0_height_value !== (rect0_height_value = Math.abs(ctx2[6](ctx2[23].value) - ctx2[6](0)))) {
          attr(rect0, "height", rect0_height_value);
        }
        if (dirty & 32 && rect1_width_value !== (rect1_width_value = ctx2[5].bandwidth())) {
          attr(rect1, "width", rect1_width_value);
        }
        if (dirty & 33 && rect1_x_value !== (rect1_x_value = ctx2[5](ctx2[23].name))) {
          attr(rect1, "x", rect1_x_value);
        }
        if (dirty & 65 && rect1_y_value !== (rect1_y_value = ctx2[6](Math.max(0, ctx2[23].budget)))) {
          attr(rect1, "y", rect1_y_value);
        }
        if (dirty & 65 && rect1_height_value !== (rect1_height_value = Math.abs(ctx2[6](ctx2[23].budget) - ctx2[6](0)))) {
          attr(rect1, "height", rect1_height_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(rect0);
        if (detaching)
          detach(rect1);
      }
    };
  }
  function create_each_block3(ctx) {
    let g;
    let rect0;
    let rect0_x_value;
    let rect0_width_value;
    let rect1;
    let rect1_transform_value;
    let rect1_width_value;
    let rect1_height_value;
    let g_transform_value;
    let followingTooltip_action;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[16](ctx[20]);
    }
    let each_value_1 = ctx[20].values;
    let each_blocks = [];
    for (let i = 0; i < each_value_1.length; i += 1) {
      each_blocks[i] = create_each_block_12(get_each_context_12(ctx, each_value_1, i));
    }
    function followingTooltip_function() {
      return ctx[17](ctx[20]);
    }
    return {
      c() {
        g = svg_element("g");
        rect0 = svg_element("rect");
        rect1 = svg_element("rect");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(rect0, "class", "group-box svelte-1es9imu");
        attr(rect0, "x", rect0_x_value = (ctx[4].bandwidth() - ctx[4].step()) / 2);
        attr(rect0, "width", rect0_width_value = ctx[4].step());
        attr(rect0, "height", ctx[3]);
        attr(rect1, "class", "axis-group-box svelte-1es9imu");
        attr(rect1, "transform", rect1_transform_value = `translate(0,${ctx[3]})`);
        attr(rect1, "width", rect1_width_value = ctx[4].bandwidth());
        attr(rect1, "height", rect1_height_value = ctx[11].bottom);
        attr(g, "class", "group svelte-1es9imu");
        attr(g, "transform", g_transform_value = `translate(${ctx[4](ctx[20].label)},0)`);
      },
      m(target, anchor) {
        insert(target, g, anchor);
        append(g, rect0);
        append(g, rect1);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g, null);
        }
        if (!mounted) {
          dispose = [
            listen(rect1, "click", click_handler),
            action_destroyer(followingTooltip_action = followingTooltip.call(null, g, followingTooltip_function))
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 16 && rect0_x_value !== (rect0_x_value = (ctx[4].bandwidth() - ctx[4].step()) / 2)) {
          attr(rect0, "x", rect0_x_value);
        }
        if (dirty & 16 && rect0_width_value !== (rect0_width_value = ctx[4].step())) {
          attr(rect0, "width", rect0_width_value);
        }
        if (dirty & 8) {
          attr(rect0, "height", ctx[3]);
        }
        if (dirty & 8 && rect1_transform_value !== (rect1_transform_value = `translate(0,${ctx[3]})`)) {
          attr(rect1, "transform", rect1_transform_value);
        }
        if (dirty & 16 && rect1_width_value !== (rect1_width_value = ctx[4].bandwidth())) {
          attr(rect1, "width", rect1_width_value);
        }
        if (dirty & 225) {
          each_value_1 = ctx[20].values;
          let i;
          for (i = 0; i < each_value_1.length; i += 1) {
            const child_ctx = get_each_context_12(ctx, each_value_1, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block_12(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value_1.length;
        }
        if (dirty & 17 && g_transform_value !== (g_transform_value = `translate(${ctx[4](ctx[20].label)},0)`)) {
          attr(g, "transform", g_transform_value);
        }
        if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty & 5)
          followingTooltip_action.update.call(null, followingTooltip_function);
      },
      d(detaching) {
        if (detaching)
          detach(g);
        destroy_each(each_blocks, detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_fragment3(ctx) {
    let svg;
    let g2;
    let g0;
    let g0_transform_value;
    let axis_action;
    let g1;
    let axis_action_1;
    let g2_transform_value;
    let mounted;
    let dispose;
    let each_value = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block3(get_each_context3(ctx, each_value, i));
    }
    return {
      c() {
        svg = svg_element("svg");
        g2 = svg_element("g");
        g0 = svg_element("g");
        g1 = svg_element("g");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(g0, "class", "x axis");
        attr(g0, "transform", g0_transform_value = `translate(0,${ctx[3]})`);
        attr(g1, "class", "y axis");
        attr(g2, "transform", g2_transform_value = `translate(${ctx[8]},${ctx[11].top})`);
        attr(svg, "width", ctx[1]);
        attr(svg, "height", height);
      },
      m(target, anchor) {
        insert(target, svg, anchor);
        append(svg, g2);
        append(g2, g0);
        append(g2, g1);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g2, null);
        }
        if (!mounted) {
          dispose = [
            action_destroyer(axis_action = axis2.call(null, g0, ctx[9])),
            action_destroyer(axis_action_1 = axis2.call(null, g1, ctx[10]))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 8 && g0_transform_value !== (g0_transform_value = `translate(0,${ctx2[3]})`)) {
          attr(g0, "transform", g0_transform_value);
        }
        if (axis_action && is_function(axis_action.update) && dirty & 512)
          axis_action.update.call(null, ctx2[9]);
        if (axis_action_1 && is_function(axis_action_1.update) && dirty & 1024)
          axis_action_1.update.call(null, ctx2[10]);
        if (dirty & 2301) {
          each_value = ctx2[0];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context3(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block3(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g2, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (dirty & 256 && g2_transform_value !== (g2_transform_value = `translate(${ctx2[8]},${ctx2[11].top})`)) {
          attr(g2, "transform", g2_transform_value);
        }
        if (dirty & 2) {
          attr(svg, "width", ctx2[1]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(svg);
        destroy_each(each_blocks, detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  var maxColumnWidth = 100;
  var height = 250;
  function instance3($$self, $$props, $$invalidate) {
    let innerHeight;
    let maxWidth;
    let offset;
    let innerWidth;
    let x0;
    let x1;
    let y2;
    let xAxis;
    let yAxis;
    let $currenciesScale;
    component_subscribe($$self, currenciesScale, ($$value) => $$invalidate(7, $currenciesScale = $$value));
    let {data} = $$props;
    let {width} = $$props;
    let {tooltipText} = $$props;
    const margin = {top: 10, right: 10, bottom: 30, left: 40};
    let yMin = 0;
    let yMax = 0;
    const legend = getContext("chart-legend");
    function filterTicks(domain) {
      const labelsCount = innerWidth / 70;
      if (domain.length <= labelsCount) {
        return domain;
      }
      const showIndices = Math.ceil(domain.length / labelsCount);
      return domain.filter((d, i) => i % showIndices === 0);
    }
    const click_handler = (group) => {
      setTimeFilter(group.date);
    };
    const followingTooltip_function = (group) => tooltipText(group);
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(0, data = $$props2.data);
      if ("width" in $$props2)
        $$invalidate(1, width = $$props2.width);
      if ("tooltipText" in $$props2)
        $$invalidate(2, tooltipText = $$props2.tooltipText);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(14, maxWidth = data.length * maxColumnWidth);
      }
      if ($$self.$$.dirty & 16386) {
        $:
          $$invalidate(8, offset = margin.left + Math.max(0, width - maxWidth) / 2);
      }
      if ($$self.$$.dirty & 16386) {
        $:
          $$invalidate(15, innerWidth = Math.min(width - margin.left - margin.right, maxWidth));
      }
      if ($$self.$$.dirty & 32769) {
        $:
          $$invalidate(4, x0 = band().padding(0.1).domain(data.map((d) => d.label)).range([0, innerWidth]));
      }
      if ($$self.$$.dirty & 17) {
        $:
          $$invalidate(5, x1 = band().domain(data[0].values.map((d) => d.name)).range([0, x0.bandwidth()]));
      }
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(12, [yMin, yMax] = extent_default(merge(data.map((d) => d.values)), (d) => d.value), yMin, ($$invalidate(13, yMax), $$invalidate(0, data)));
      }
      if ($$self.$$.dirty & 12296) {
        $:
          $$invalidate(6, y2 = linear2().range([innerHeight, 0]).domain([Math.min(0, yMin), Math.max(0, yMax)]));
      }
      if ($$self.$$.dirty & 160) {
        $:
          legend.set(x1.domain().sort().map((c) => [c, $currenciesScale(c)]));
      }
      if ($$self.$$.dirty & 16) {
        $:
          $$invalidate(9, xAxis = axisBottom(x0).tickSizeOuter(0).tickValues(filterTicks(x0.domain())));
      }
      if ($$self.$$.dirty & 32832) {
        $:
          $$invalidate(10, yAxis = axisLeft(y2).tickSize(-innerWidth).tickFormat(formatCurrencyShort));
      }
    };
    $:
      $$invalidate(3, innerHeight = height - margin.top - margin.bottom);
    return [
      data,
      width,
      tooltipText,
      innerHeight,
      x0,
      x1,
      y2,
      $currenciesScale,
      offset,
      xAxis,
      yAxis,
      margin,
      yMin,
      yMax,
      maxWidth,
      innerWidth,
      click_handler,
      followingTooltip_function
    ];
  }
  var BarChart = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance3, create_fragment3, safe_not_equal, {data: 0, width: 1, tooltipText: 2});
    }
  };
  var BarChart_default = BarChart;

  // node_modules/d3-path/src/path.js
  var pi = Math.PI;
  var tau = 2 * pi;
  var epsilon2 = 1e-6;
  var tauEpsilon = tau - epsilon2;
  function Path() {
    this._x0 = this._y0 = this._x1 = this._y1 = null;
    this._ = "";
  }
  function path() {
    return new Path();
  }
  Path.prototype = path.prototype = {
    constructor: Path,
    moveTo: function(x2, y2) {
      this._ += "M" + (this._x0 = this._x1 = +x2) + "," + (this._y0 = this._y1 = +y2);
    },
    closePath: function() {
      if (this._x1 !== null) {
        this._x1 = this._x0, this._y1 = this._y0;
        this._ += "Z";
      }
    },
    lineTo: function(x2, y2) {
      this._ += "L" + (this._x1 = +x2) + "," + (this._y1 = +y2);
    },
    quadraticCurveTo: function(x1, y1, x2, y2) {
      this._ += "Q" + +x1 + "," + +y1 + "," + (this._x1 = +x2) + "," + (this._y1 = +y2);
    },
    bezierCurveTo: function(x1, y1, x2, y2, x3, y3) {
      this._ += "C" + +x1 + "," + +y1 + "," + +x2 + "," + +y2 + "," + (this._x1 = +x3) + "," + (this._y1 = +y3);
    },
    arcTo: function(x1, y1, x2, y2, r) {
      x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
      var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
      if (r < 0)
        throw new Error("negative radius: " + r);
      if (this._x1 === null) {
        this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
      } else if (!(l01_2 > epsilon2))
        ;
      else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon2) || !r) {
        this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
      } else {
        var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
        if (Math.abs(t01 - 1) > epsilon2) {
          this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
        }
        this._ += "A" + r + "," + r + ",0,0," + +(y01 * x20 > x01 * y20) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
      }
    },
    arc: function(x2, y2, r, a0, a1, ccw) {
      x2 = +x2, y2 = +y2, r = +r, ccw = !!ccw;
      var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x2 + dx, y0 = y2 + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
      if (r < 0)
        throw new Error("negative radius: " + r);
      if (this._x1 === null) {
        this._ += "M" + x0 + "," + y0;
      } else if (Math.abs(this._x1 - x0) > epsilon2 || Math.abs(this._y1 - y0) > epsilon2) {
        this._ += "L" + x0 + "," + y0;
      }
      if (!r)
        return;
      if (da < 0)
        da = da % tau + tau;
      if (da > tauEpsilon) {
        this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x2 - dx) + "," + (y2 - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
      } else if (da > epsilon2) {
        this._ += "A" + r + "," + r + ",0," + +(da >= pi) + "," + cw + "," + (this._x1 = x2 + r * Math.cos(a1)) + "," + (this._y1 = y2 + r * Math.sin(a1));
      }
    },
    rect: function(x2, y2, w, h) {
      this._ += "M" + (this._x0 = this._x1 = +x2) + "," + (this._y0 = this._y1 = +y2) + "h" + +w + "v" + +h + "h" + -w + "Z";
    },
    toString: function() {
      return this._;
    }
  };
  var path_default2 = path;

  // node_modules/d3-shape/src/constant.js
  function constant_default4(x2) {
    return function constant2() {
      return x2;
    };
  }

  // node_modules/d3-shape/src/math.js
  var abs = Math.abs;
  var atan2 = Math.atan2;
  var cos = Math.cos;
  var max2 = Math.max;
  var min2 = Math.min;
  var sin = Math.sin;
  var sqrt2 = Math.sqrt;
  var epsilon3 = 1e-12;
  var pi2 = Math.PI;
  var halfPi = pi2 / 2;
  var tau2 = 2 * pi2;
  function acos(x2) {
    return x2 > 1 ? 0 : x2 < -1 ? pi2 : Math.acos(x2);
  }
  function asin(x2) {
    return x2 >= 1 ? halfPi : x2 <= -1 ? -halfPi : Math.asin(x2);
  }

  // node_modules/d3-shape/src/arc.js
  function arcInnerRadius(d) {
    return d.innerRadius;
  }
  function arcOuterRadius(d) {
    return d.outerRadius;
  }
  function arcStartAngle(d) {
    return d.startAngle;
  }
  function arcEndAngle(d) {
    return d.endAngle;
  }
  function arcPadAngle(d) {
    return d && d.padAngle;
  }
  function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
    var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t = y32 * x10 - x32 * y10;
    if (t * t < epsilon3)
      return;
    t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
    return [x0 + t * x10, y0 + t * y10];
  }
  function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
    var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / sqrt2(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = r1 - rc, D = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * sqrt2(max2(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00;
    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1)
      cx0 = cx1, cy0 = cy1;
    return {
      cx: cx0,
      cy: cy0,
      x01: -ox,
      y01: -oy,
      x11: cx0 * (r1 / r - 1),
      y11: cy0 * (r1 / r - 1)
    };
  }
  function arc_default() {
    var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant_default4(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context = null;
    function arc() {
      var buffer, r, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da = abs(a1 - a0), cw = a1 > a0;
      if (!context)
        context = buffer = path_default2();
      if (r1 < r0)
        r = r1, r1 = r0, r0 = r;
      if (!(r1 > epsilon3))
        context.moveTo(0, 0);
      else if (da > tau2 - epsilon3) {
        context.moveTo(r1 * cos(a0), r1 * sin(a0));
        context.arc(0, 0, r1, a0, a1, !cw);
        if (r0 > epsilon3) {
          context.moveTo(r0 * cos(a1), r0 * sin(a1));
          context.arc(0, 0, r0, a1, a0, cw);
        }
      } else {
        var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = ap > epsilon3 && (padRadius ? +padRadius.apply(this, arguments) : sqrt2(r0 * r0 + r1 * r1)), rc = min2(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t03, t13;
        if (rp > epsilon3) {
          var p0 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
          if ((da0 -= p0 * 2) > epsilon3)
            p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0;
          else
            da0 = 0, a00 = a10 = (a0 + a1) / 2;
          if ((da1 -= p1 * 2) > epsilon3)
            p1 *= cw ? 1 : -1, a01 += p1, a11 -= p1;
          else
            da1 = 0, a01 = a11 = (a0 + a1) / 2;
        }
        var x01 = r1 * cos(a01), y01 = r1 * sin(a01), x10 = r0 * cos(a10), y10 = r0 * sin(a10);
        if (rc > epsilon3) {
          var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x00 = r0 * cos(a00), y00 = r0 * sin(a00), oc;
          if (da < pi2 && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
            var ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt2(ax * ax + ay * ay) * sqrt2(bx * bx + by * by))) / 2), lc = sqrt2(oc[0] * oc[0] + oc[1] * oc[1]);
            rc0 = min2(rc, (r0 - lc) / (kc - 1));
            rc1 = min2(rc, (r1 - lc) / (kc + 1));
          }
        }
        if (!(da1 > epsilon3))
          context.moveTo(x01, y01);
        else if (rc1 > epsilon3) {
          t03 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
          t13 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
          context.moveTo(t03.cx + t03.x01, t03.cy + t03.y01);
          if (rc1 < rc)
            context.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
          else {
            context.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
            context.arc(0, 0, r1, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), !cw);
            context.arc(t13.cx, t13.cy, rc1, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
          }
        } else
          context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);
        if (!(r0 > epsilon3) || !(da0 > epsilon3))
          context.lineTo(x10, y10);
        else if (rc0 > epsilon3) {
          t03 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
          t13 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
          context.lineTo(t03.cx + t03.x01, t03.cy + t03.y01);
          if (rc0 < rc)
            context.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
          else {
            context.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
            context.arc(0, 0, r0, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), cw);
            context.arc(t13.cx, t13.cy, rc0, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
          }
        } else
          context.arc(0, 0, r0, a10, a00, cw);
      }
      context.closePath();
      if (buffer)
        return context = null, buffer + "" || null;
    }
    arc.centroid = function() {
      var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi2 / 2;
      return [cos(a) * r, sin(a) * r];
    };
    arc.innerRadius = function(_2) {
      return arguments.length ? (innerRadius = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : innerRadius;
    };
    arc.outerRadius = function(_2) {
      return arguments.length ? (outerRadius = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : outerRadius;
    };
    arc.cornerRadius = function(_2) {
      return arguments.length ? (cornerRadius = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : cornerRadius;
    };
    arc.padRadius = function(_2) {
      return arguments.length ? (padRadius = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : padRadius;
    };
    arc.startAngle = function(_2) {
      return arguments.length ? (startAngle = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : startAngle;
    };
    arc.endAngle = function(_2) {
      return arguments.length ? (endAngle = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : endAngle;
    };
    arc.padAngle = function(_2) {
      return arguments.length ? (padAngle = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : padAngle;
    };
    arc.context = function(_2) {
      return arguments.length ? (context = _2 == null ? null : _2, arc) : context;
    };
    return arc;
  }

  // node_modules/d3-shape/src/array.js
  var slice2 = Array.prototype.slice;
  function array_default2(x2) {
    return typeof x2 === "object" && "length" in x2 ? x2 : Array.from(x2);
  }

  // node_modules/d3-shape/src/curve/linear.js
  function Linear(context) {
    this._context = context;
  }
  Linear.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._point = 0;
    },
    lineEnd: function() {
      if (this._line || this._line !== 0 && this._point === 1)
        this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x2, y2) {
      x2 = +x2, y2 = +y2;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
          break;
        case 1:
          this._point = 2;
        default:
          this._context.lineTo(x2, y2);
          break;
      }
    }
  };
  function linear_default(context) {
    return new Linear(context);
  }

  // node_modules/d3-shape/src/point.js
  function x(p) {
    return p[0];
  }
  function y(p) {
    return p[1];
  }

  // node_modules/d3-shape/src/line.js
  function line_default(x2, y2) {
    var defined = constant_default4(true), context = null, curve = linear_default, output = null;
    x2 = typeof x2 === "function" ? x2 : x2 === void 0 ? x : constant_default4(x2);
    y2 = typeof y2 === "function" ? y2 : y2 === void 0 ? y : constant_default4(y2);
    function line(data) {
      var i, n = (data = array_default2(data)).length, d, defined0 = false, buffer;
      if (context == null)
        output = curve(buffer = path_default2());
      for (i = 0; i <= n; ++i) {
        if (!(i < n && defined(d = data[i], i, data)) === defined0) {
          if (defined0 = !defined0)
            output.lineStart();
          else
            output.lineEnd();
        }
        if (defined0)
          output.point(+x2(d, i, data), +y2(d, i, data));
      }
      if (buffer)
        return output = null, buffer + "" || null;
    }
    line.x = function(_2) {
      return arguments.length ? (x2 = typeof _2 === "function" ? _2 : constant_default4(+_2), line) : x2;
    };
    line.y = function(_2) {
      return arguments.length ? (y2 = typeof _2 === "function" ? _2 : constant_default4(+_2), line) : y2;
    };
    line.defined = function(_2) {
      return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default4(!!_2), line) : defined;
    };
    line.curve = function(_2) {
      return arguments.length ? (curve = _2, context != null && (output = curve(context)), line) : curve;
    };
    line.context = function(_2) {
      return arguments.length ? (_2 == null ? context = output = null : output = curve(context = _2), line) : context;
    };
    return line;
  }

  // node_modules/d3-shape/src/area.js
  function area_default(x0, y0, y1) {
    var x1 = null, defined = constant_default4(true), context = null, curve = linear_default, output = null;
    x0 = typeof x0 === "function" ? x0 : x0 === void 0 ? x : constant_default4(+x0);
    y0 = typeof y0 === "function" ? y0 : y0 === void 0 ? constant_default4(0) : constant_default4(+y0);
    y1 = typeof y1 === "function" ? y1 : y1 === void 0 ? y : constant_default4(+y1);
    function area(data) {
      var i, j, k, n = (data = array_default2(data)).length, d, defined0 = false, buffer, x0z = new Array(n), y0z = new Array(n);
      if (context == null)
        output = curve(buffer = path_default2());
      for (i = 0; i <= n; ++i) {
        if (!(i < n && defined(d = data[i], i, data)) === defined0) {
          if (defined0 = !defined0) {
            j = i;
            output.areaStart();
            output.lineStart();
          } else {
            output.lineEnd();
            output.lineStart();
            for (k = i - 1; k >= j; --k) {
              output.point(x0z[k], y0z[k]);
            }
            output.lineEnd();
            output.areaEnd();
          }
        }
        if (defined0) {
          x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
          output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
        }
      }
      if (buffer)
        return output = null, buffer + "" || null;
    }
    function arealine() {
      return line_default().defined(defined).curve(curve).context(context);
    }
    area.x = function(_2) {
      return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default4(+_2), x1 = null, area) : x0;
    };
    area.x0 = function(_2) {
      return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default4(+_2), area) : x0;
    };
    area.x1 = function(_2) {
      return arguments.length ? (x1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default4(+_2), area) : x1;
    };
    area.y = function(_2) {
      return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default4(+_2), y1 = null, area) : y0;
    };
    area.y0 = function(_2) {
      return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default4(+_2), area) : y0;
    };
    area.y1 = function(_2) {
      return arguments.length ? (y1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default4(+_2), area) : y1;
    };
    area.lineX0 = area.lineY0 = function() {
      return arealine().x(x0).y(y0);
    };
    area.lineY1 = function() {
      return arealine().x(x0).y(y1);
    };
    area.lineX1 = function() {
      return arealine().x(x1).y(y0);
    };
    area.defined = function(_2) {
      return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default4(!!_2), area) : defined;
    };
    area.curve = function(_2) {
      return arguments.length ? (curve = _2, context != null && (output = curve(context)), area) : curve;
    };
    area.context = function(_2) {
      return arguments.length ? (_2 == null ? context = output = null : output = curve(context = _2), area) : context;
    };
    return area;
  }

  // src/charts/Sunburst.svelte
  function get_each_context4(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[18] = list[i];
    return child_ctx;
  }
  function create_each_block4(ctx) {
    let path2;
    let path_fill_value;
    let path_d_value;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[13](ctx[18]);
    }
    function mouseover_handler() {
      return ctx[14](ctx[18]);
    }
    return {
      c() {
        path2 = svg_element("path");
        attr(path2, "fill-rule", "evenodd");
        attr(path2, "fill", path_fill_value = ctx[9](ctx[18].data.account));
        attr(path2, "d", path_d_value = ctx[8](ctx[18]));
        attr(path2, "class", "svelte-1as0v9d");
        toggle_class(path2, "half", ctx[2] && !ctx[6].startsWith(ctx[18].data.account));
      },
      m(target, anchor) {
        insert(target, path2, anchor);
        if (!mounted) {
          dispose = [
            listen(path2, "click", click_handler),
            listen(path2, "mouseover", mouseover_handler)
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 544 && path_fill_value !== (path_fill_value = ctx[9](ctx[18].data.account))) {
          attr(path2, "fill", path_fill_value);
        }
        if (dirty & 288 && path_d_value !== (path_d_value = ctx[8](ctx[18]))) {
          attr(path2, "d", path_d_value);
        }
        if (dirty & 100) {
          toggle_class(path2, "half", ctx[2] && !ctx[6].startsWith(ctx[18].data.account));
        }
      },
      d(detaching) {
        if (detaching)
          detach(path2);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_fragment4(ctx) {
    let g;
    let circle;
    let text0;
    let t0_value = (ctx[6] || ctx[4].data.account) + "";
    let t03;
    let text1;
    let t13;
    let g_transform_value;
    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_block4(get_each_context4(ctx, each_value, i));
    }
    return {
      c() {
        g = svg_element("g");
        circle = svg_element("circle");
        text0 = svg_element("text");
        t03 = text(t0_value);
        text1 = svg_element("text");
        t13 = text(ctx[7]);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        set_style(circle, "opacity", "0");
        attr(circle, "r", ctx[3]);
        attr(text0, "class", "account svelte-1as0v9d");
        attr(text0, "text-anchor", "middle");
        attr(text1, "class", "balance svelte-1as0v9d");
        attr(text1, "dy", "1.2em");
        attr(text1, "text-anchor", "middle");
        attr(g, "width", ctx[0]);
        attr(g, "height", ctx[1]);
        attr(g, "transform", g_transform_value = `translate(${ctx[0] / 2},${ctx[1] / 2})`);
      },
      m(target, anchor) {
        insert(target, g, anchor);
        append(g, circle);
        append(g, text0);
        append(text0, t03);
        append(g, text1);
        append(text1, t13);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g, null);
        }
        if (!mounted) {
          dispose = listen(g, "mouseleave", ctx[15]);
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 8) {
          attr(circle, "r", ctx2[3]);
        }
        if (dirty & 80 && t0_value !== (t0_value = (ctx2[6] || ctx2[4].data.account) + ""))
          set_data(t03, t0_value);
        if (dirty & 128)
          set_data(t13, ctx2[7]);
        if (dirty & 868) {
          each_value = ctx2[5];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context4(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block4(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (dirty & 1) {
          attr(g, "width", ctx2[0]);
        }
        if (dirty & 2) {
          attr(g, "height", ctx2[1]);
        }
        if (dirty & 3 && g_transform_value !== (g_transform_value = `translate(${ctx2[0] / 2},${ctx2[1] / 2})`)) {
          attr(g, "transform", g_transform_value);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(g);
        destroy_each(each_blocks, detaching);
        mounted = false;
        dispose();
      }
    };
  }
  function instance4($$self, $$props, $$invalidate) {
    let radius;
    let root2;
    let leaves;
    let currentAccount;
    let currentBalance;
    let y2;
    let arcShape;
    let $sunburstScale;
    component_subscribe($$self, sunburstScale, ($$value) => $$invalidate(9, $sunburstScale = $$value));
    let {data} = $$props;
    let {currency} = $$props;
    let {width} = $$props;
    let {height: height4} = $$props;
    function balanceText(d) {
      const val = d.value || 0;
      const rootVal = root2.value || 1;
      return `${formatCurrency(val)} ${currency} (${formatPercentage(val / rootVal)})`;
    }
    let current = null;
    const x2 = linear2().range([0, 2 * Math.PI]);
    const click_handler = (d) => router_default.navigate(accountUrl(d.data.account));
    const mouseover_handler = (d) => {
      $$invalidate(2, current = d);
    };
    const mouseleave_handler = () => {
      $$invalidate(2, current = null);
    };
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(10, data = $$props2.data);
      if ("currency" in $$props2)
        $$invalidate(11, currency = $$props2.currency);
      if ("width" in $$props2)
        $$invalidate(0, width = $$props2.width);
      if ("height" in $$props2)
        $$invalidate(1, height4 = $$props2.height);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 3) {
        $:
          $$invalidate(3, radius = Math.min(width, height4) / 2);
      }
      if ($$self.$$.dirty & 1024) {
        $:
          $$invalidate(4, root2 = partition_default()(data));
      }
      if ($$self.$$.dirty & 16) {
        $:
          $$invalidate(5, leaves = root2.descendants().filter((d) => !d.data.dummy && d.depth));
      }
      if ($$self.$$.dirty & 16) {
        $:
          if (root2) {
            $$invalidate(2, current = null);
          }
      }
      if ($$self.$$.dirty & 20) {
        $:
          $$invalidate(6, currentAccount = current ? current.data.account : root2.data.account);
      }
      if ($$self.$$.dirty & 20) {
        $:
          $$invalidate(7, currentBalance = current ? balanceText(current) : balanceText(root2));
      }
      if ($$self.$$.dirty & 8) {
        $:
          $$invalidate(12, y2 = sqrt().range([0, radius]));
      }
      if ($$self.$$.dirty & 4096) {
        $:
          $$invalidate(8, arcShape = arc_default().startAngle((d) => x2(d.x0)).endAngle((d) => x2(d.x1)).innerRadius((d) => y2(d.y0)).outerRadius((d) => y2(d.y1)));
      }
    };
    return [
      width,
      height4,
      current,
      radius,
      root2,
      leaves,
      currentAccount,
      currentBalance,
      arcShape,
      $sunburstScale,
      data,
      currency,
      y2,
      click_handler,
      mouseover_handler,
      mouseleave_handler
    ];
  }
  var Sunburst = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance4, create_fragment4, safe_not_equal, {
        data: 10,
        currency: 11,
        width: 0,
        height: 1
      });
    }
  };
  var Sunburst_default = Sunburst;

  // src/charts/Treemap.svelte
  function get_each_context5(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[12] = list[i];
    return child_ctx;
  }
  function create_each_block5(ctx) {
    let g;
    let rect;
    let rect_fill_value;
    let rect_width_value;
    let rect_height_value;
    let text_1;
    let t_value = (ctx[12].data.account.split(":").pop() || "") + "";
    let t;
    let text_1_x_value;
    let text_1_y_value;
    let setOpacity_action;
    let g_transform_value;
    let followingTooltip_action;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[8](ctx[12]);
    }
    function followingTooltip_function() {
      return ctx[9](ctx[12]);
    }
    return {
      c() {
        g = svg_element("g");
        rect = svg_element("rect");
        text_1 = svg_element("text");
        t = text(t_value);
        attr(rect, "fill", rect_fill_value = ctx[3](ctx[12]));
        attr(rect, "width", rect_width_value = ctx[12].x1 - ctx[12].x0);
        attr(rect, "height", rect_height_value = ctx[12].y1 - ctx[12].y0);
        attr(rect, "class", "svelte-lrs8nl");
        attr(text_1, "dy", ".5em");
        attr(text_1, "x", text_1_x_value = (ctx[12].x1 - ctx[12].x0) / 2);
        attr(text_1, "y", text_1_y_value = (ctx[12].y1 - ctx[12].y0) / 2);
        attr(text_1, "text-anchor", "middle");
        attr(text_1, "class", "svelte-lrs8nl");
        attr(g, "transform", g_transform_value = `translate(${ctx[12].x0},${ctx[12].y0})`);
      },
      m(target, anchor) {
        insert(target, g, anchor);
        append(g, rect);
        append(g, text_1);
        append(text_1, t);
        if (!mounted) {
          dispose = [
            action_destroyer(setOpacity_action = setOpacity.call(null, text_1, ctx[12])),
            listen(text_1, "click", click_handler),
            action_destroyer(followingTooltip_action = followingTooltip.call(null, g, followingTooltip_function))
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 4 && rect_fill_value !== (rect_fill_value = ctx[3](ctx[12]))) {
          attr(rect, "fill", rect_fill_value);
        }
        if (dirty & 4 && rect_width_value !== (rect_width_value = ctx[12].x1 - ctx[12].x0)) {
          attr(rect, "width", rect_width_value);
        }
        if (dirty & 4 && rect_height_value !== (rect_height_value = ctx[12].y1 - ctx[12].y0)) {
          attr(rect, "height", rect_height_value);
        }
        if (dirty & 4 && t_value !== (t_value = (ctx[12].data.account.split(":").pop() || "") + ""))
          set_data(t, t_value);
        if (dirty & 4 && text_1_x_value !== (text_1_x_value = (ctx[12].x1 - ctx[12].x0) / 2)) {
          attr(text_1, "x", text_1_x_value);
        }
        if (dirty & 4 && text_1_y_value !== (text_1_y_value = (ctx[12].y1 - ctx[12].y0) / 2)) {
          attr(text_1, "y", text_1_y_value);
        }
        if (setOpacity_action && is_function(setOpacity_action.update) && dirty & 4)
          setOpacity_action.update.call(null, ctx[12]);
        if (dirty & 4 && g_transform_value !== (g_transform_value = `translate(${ctx[12].x0},${ctx[12].y0})`)) {
          attr(g, "transform", g_transform_value);
        }
        if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty & 4)
          followingTooltip_action.update.call(null, followingTooltip_function);
      },
      d(detaching) {
        if (detaching)
          detach(g);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_fragment5(ctx) {
    let svg;
    let each_value = ctx[2];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block5(get_each_context5(ctx, each_value, i));
    }
    return {
      c() {
        svg = svg_element("svg");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(svg, "width", ctx[0]);
        attr(svg, "height", ctx[1]);
        attr(svg, "class", "svelte-lrs8nl");
      },
      m(target, anchor) {
        insert(target, svg, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(svg, null);
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 28) {
          each_value = ctx2[2];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context5(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block5(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(svg, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (dirty & 1) {
          attr(svg, "width", ctx2[0]);
        }
        if (dirty & 2) {
          attr(svg, "height", ctx2[1]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(svg);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function setOpacity(node, param) {
    function update2(d) {
      const length = node.getComputedTextLength();
      node.style.opacity = d.x1 - d.x0 > length + 4 && d.y1 - d.y0 > 14 ? "1" : "0";
    }
    update2(param);
    return {update: update2};
  }
  function instance5($$self, $$props, $$invalidate) {
    let height4;
    let root2;
    let leaves;
    let $treemapScale;
    component_subscribe($$self, treemapScale, ($$value) => $$invalidate(10, $treemapScale = $$value));
    let {data} = $$props;
    let {width} = $$props;
    let {currency} = $$props;
    const tree = treemap_default().paddingInner(1);
    function fill(d) {
      const node = d.data.dummy && d.parent ? d.parent : d;
      if (node.depth === 1 || !node.parent) {
        return $treemapScale(node.data.account);
      }
      return $treemapScale(node.parent.data.account);
    }
    function tooltipText(d) {
      const val = d.value || 0;
      const rootValue = root2.value || 1;
      return `${formatCurrency(val)} ${currency} (${formatPercentage(val / rootValue)})<em>${d.data.account}</em>`;
    }
    const click_handler = (d) => router_default.navigate(accountUrl(d.data.account));
    const followingTooltip_function = (d) => tooltipText(d);
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(5, data = $$props2.data);
      if ("width" in $$props2)
        $$invalidate(0, width = $$props2.width);
      if ("currency" in $$props2)
        $$invalidate(6, currency = $$props2.currency);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(1, height4 = Math.min(width / 2.5, 400));
      }
      if ($$self.$$.dirty & 35) {
        $:
          $$invalidate(7, root2 = tree.size([width, height4])(data));
      }
      if ($$self.$$.dirty & 128) {
        $:
          $$invalidate(2, leaves = root2.leaves().filter((d) => d.value));
      }
    };
    return [
      width,
      height4,
      leaves,
      fill,
      tooltipText,
      data,
      currency,
      root2,
      click_handler,
      followingTooltip_function
    ];
  }
  var Treemap = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance5, create_fragment5, safe_not_equal, {data: 5, width: 0, currency: 6});
    }
  };
  var Treemap_default = Treemap;

  // src/charts/HierarchyContainer.svelte
  function get_each_context6(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[4] = list[i][0];
    child_ctx[7] = list[i][1];
    child_ctx[9] = i;
    return child_ctx;
  }
  function create_if_block_2(ctx) {
    let svg;
    let each_blocks = [];
    let each_1_lookup = new Map();
    let svg_height_value;
    let current;
    let each_value = [...ctx[0]];
    const get_key = (ctx2) => ctx2[4];
    for (let i = 0; i < each_value.length; i += 1) {
      let child_ctx = get_each_context6(ctx, each_value, i);
      let key = get_key(child_ctx);
      each_1_lookup.set(key, each_blocks[i] = create_each_block6(key, child_ctx));
    }
    return {
      c() {
        svg = svg_element("svg");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(svg, "width", ctx[1]);
        attr(svg, "height", svg_height_value = 500);
      },
      m(target, anchor) {
        insert(target, svg, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(svg, null);
        }
        current = true;
      },
      p(ctx2, dirty) {
        if (dirty & 7) {
          each_value = [...ctx2[0]];
          group_outros();
          each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, svg, outro_and_destroy_block, create_each_block6, null, get_each_context6);
          check_outros();
        }
        if (!current || dirty & 2) {
          attr(svg, "width", ctx2[1]);
        }
      },
      i(local) {
        if (current)
          return;
        for (let i = 0; i < each_value.length; i += 1) {
          transition_in(each_blocks[i]);
        }
        current = true;
      },
      o(local) {
        for (let i = 0; i < each_blocks.length; i += 1) {
          transition_out(each_blocks[i]);
        }
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(svg);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].d();
        }
      }
    };
  }
  function create_if_block_1(ctx) {
    let treemap;
    let current;
    treemap = new Treemap_default({
      props: {
        data: ctx[0].get(ctx[4]),
        currency: ctx[4],
        width: ctx[1]
      }
    });
    return {
      c() {
        create_component(treemap.$$.fragment);
      },
      m(target, anchor) {
        mount_component(treemap, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const treemap_changes = {};
        if (dirty & 17)
          treemap_changes.data = ctx2[0].get(ctx2[4]);
        if (dirty & 16)
          treemap_changes.currency = ctx2[4];
        if (dirty & 2)
          treemap_changes.width = ctx2[1];
        treemap.$set(treemap_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(treemap.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(treemap.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(treemap, detaching);
      }
    };
  }
  function create_if_block(ctx) {
    let svg;
    let text_1;
    let t;
    let text_1_x_value;
    let text_1_y_value;
    return {
      c() {
        svg = svg_element("svg");
        text_1 = svg_element("text");
        t = text("Chart is empty.");
        attr(text_1, "x", text_1_x_value = ctx[1] / 2);
        attr(text_1, "y", text_1_y_value = 80);
        attr(text_1, "text-anchor", "middle");
        attr(svg, "width", ctx[1]);
      },
      m(target, anchor) {
        insert(target, svg, anchor);
        append(svg, text_1);
        append(text_1, t);
      },
      p(ctx2, dirty) {
        if (dirty & 2 && text_1_x_value !== (text_1_x_value = ctx2[1] / 2)) {
          attr(text_1, "x", text_1_x_value);
        }
        if (dirty & 2) {
          attr(svg, "width", ctx2[1]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(svg);
      }
    };
  }
  function create_each_block6(key_1, ctx) {
    let g;
    let sunburst;
    let g_transform_value;
    let current;
    sunburst = new Sunburst_default({
      props: {
        data: ctx[7],
        currency: ctx[4],
        width: ctx[1] / ctx[2].length,
        height: 500
      }
    });
    return {
      key: key_1,
      first: null,
      c() {
        g = svg_element("g");
        create_component(sunburst.$$.fragment);
        attr(g, "transform", g_transform_value = `translate(${ctx[1] * ctx[9] / ctx[2].length},0)`);
        this.first = g;
      },
      m(target, anchor) {
        insert(target, g, anchor);
        mount_component(sunburst, g, null);
        current = true;
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        const sunburst_changes = {};
        if (dirty & 1)
          sunburst_changes.data = ctx[7];
        if (dirty & 1)
          sunburst_changes.currency = ctx[4];
        if (dirty & 6)
          sunburst_changes.width = ctx[1] / ctx[2].length;
        sunburst.$set(sunburst_changes);
        if (!current || dirty & 7 && g_transform_value !== (g_transform_value = `translate(${ctx[1] * ctx[9] / ctx[2].length},0)`)) {
          attr(g, "transform", g_transform_value);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(sunburst.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(sunburst.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(g);
        destroy_component(sunburst);
      }
    };
  }
  function create_fragment6(ctx) {
    let show_if;
    let current_block_type_index;
    let if_block;
    let if_block_anchor;
    let current;
    const if_block_creators = [create_if_block, create_if_block_1, create_if_block_2];
    const if_blocks = [];
    function select_block_type(ctx2, dirty) {
      if (ctx2[2].length === 0)
        return 0;
      if (dirty & 25)
        show_if = !!(ctx2[3] === "treemap" && ctx2[0].get(ctx2[4]));
      if (show_if)
        return 1;
      if (ctx2[3] === "sunburst")
        return 2;
      return -1;
    }
    if (~(current_block_type_index = select_block_type(ctx, -1))) {
      if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
    }
    return {
      c() {
        if (if_block)
          if_block.c();
        if_block_anchor = empty();
      },
      m(target, anchor) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].m(target, anchor);
        }
        insert(target, if_block_anchor, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        let previous_block_index = current_block_type_index;
        current_block_type_index = select_block_type(ctx2, dirty);
        if (current_block_type_index === previous_block_index) {
          if (~current_block_type_index) {
            if_blocks[current_block_type_index].p(ctx2, dirty);
          }
        } else {
          if (if_block) {
            group_outros();
            transition_out(if_blocks[previous_block_index], 1, 1, () => {
              if_blocks[previous_block_index] = null;
            });
            check_outros();
          }
          if (~current_block_type_index) {
            if_block = if_blocks[current_block_type_index];
            if (!if_block) {
              if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
              if_block.c();
            } else {
              if_block.p(ctx2, dirty);
            }
            transition_in(if_block, 1);
            if_block.m(if_block_anchor.parentNode, if_block_anchor);
          } else {
            if_block = null;
          }
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].d(detaching);
        }
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function instance6($$self, $$props, $$invalidate) {
    let currencies2;
    let currency;
    let $chartCurrency;
    let $chartMode;
    component_subscribe($$self, chartCurrency, ($$value) => $$invalidate(5, $chartCurrency = $$value));
    component_subscribe($$self, chartMode, ($$value) => $$invalidate(3, $chartMode = $$value));
    const context = getContext("chart-currencies");
    let {data} = $$props;
    let {width} = $$props;
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(0, data = $$props2.data);
      if ("width" in $$props2)
        $$invalidate(1, width = $$props2.width);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(2, currencies2 = [...data.keys()]);
      }
      if ($$self.$$.dirty & 36) {
        $:
          $$invalidate(4, currency = $chartCurrency || currencies2[0]);
      }
      if ($$self.$$.dirty & 4) {
        $:
          context.set(currencies2);
      }
    };
    return [data, width, currencies2, $chartMode, currency, $chartCurrency];
  }
  var HierarchyContainer = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance6, create_fragment6, safe_not_equal, {data: 0, width: 1});
    }
  };
  var HierarchyContainer_default = HierarchyContainer;

  // node_modules/d3-quadtree/src/add.js
  function add_default(d) {
    const x2 = +this._x.call(null, d), y2 = +this._y.call(null, d);
    return add(this.cover(x2, y2), x2, y2, d);
  }
  function add(tree, x2, y2, d) {
    if (isNaN(x2) || isNaN(y2))
      return tree;
    var parent2, node = tree._root, leaf2 = {data: d}, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right2, bottom2, i, j;
    if (!node)
      return tree._root = leaf2, tree;
    while (node.length) {
      if (right2 = x2 >= (xm = (x0 + x1) / 2))
        x0 = xm;
      else
        x1 = xm;
      if (bottom2 = y2 >= (ym = (y0 + y1) / 2))
        y0 = ym;
      else
        y1 = ym;
      if (parent2 = node, !(node = node[i = bottom2 << 1 | right2]))
        return parent2[i] = leaf2, tree;
    }
    xp = +tree._x.call(null, node.data);
    yp = +tree._y.call(null, node.data);
    if (x2 === xp && y2 === yp)
      return leaf2.next = node, parent2 ? parent2[i] = leaf2 : tree._root = leaf2, tree;
    do {
      parent2 = parent2 ? parent2[i] = new Array(4) : tree._root = new Array(4);
      if (right2 = x2 >= (xm = (x0 + x1) / 2))
        x0 = xm;
      else
        x1 = xm;
      if (bottom2 = y2 >= (ym = (y0 + y1) / 2))
        y0 = ym;
      else
        y1 = ym;
    } while ((i = bottom2 << 1 | right2) === (j = (yp >= ym) << 1 | xp >= xm));
    return parent2[j] = node, parent2[i] = leaf2, tree;
  }
  function addAll(data) {
    var d, i, n = data.length, x2, y2, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (i = 0; i < n; ++i) {
      if (isNaN(x2 = +this._x.call(null, d = data[i])) || isNaN(y2 = +this._y.call(null, d)))
        continue;
      xz[i] = x2;
      yz[i] = y2;
      if (x2 < x0)
        x0 = x2;
      if (x2 > x1)
        x1 = x2;
      if (y2 < y0)
        y0 = y2;
      if (y2 > y1)
        y1 = y2;
    }
    if (x0 > x1 || y0 > y1)
      return this;
    this.cover(x0, y0).cover(x1, y1);
    for (i = 0; i < n; ++i) {
      add(this, xz[i], yz[i], data[i]);
    }
    return this;
  }

  // node_modules/d3-quadtree/src/cover.js
  function cover_default(x2, y2) {
    if (isNaN(x2 = +x2) || isNaN(y2 = +y2))
      return this;
    var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
    if (isNaN(x0)) {
      x1 = (x0 = Math.floor(x2)) + 1;
      y1 = (y0 = Math.floor(y2)) + 1;
    } else {
      var z = x1 - x0 || 1, node = this._root, parent2, i;
      while (x0 > x2 || x2 >= x1 || y0 > y2 || y2 >= y1) {
        i = (y2 < y0) << 1 | x2 < x0;
        parent2 = new Array(4), parent2[i] = node, node = parent2, z *= 2;
        switch (i) {
          case 0:
            x1 = x0 + z, y1 = y0 + z;
            break;
          case 1:
            x0 = x1 - z, y1 = y0 + z;
            break;
          case 2:
            x1 = x0 + z, y0 = y1 - z;
            break;
          case 3:
            x0 = x1 - z, y0 = y1 - z;
            break;
        }
      }
      if (this._root && this._root.length)
        this._root = node;
    }
    this._x0 = x0;
    this._y0 = y0;
    this._x1 = x1;
    this._y1 = y1;
    return this;
  }

  // node_modules/d3-quadtree/src/data.js
  function data_default2() {
    var data = [];
    this.visit(function(node) {
      if (!node.length)
        do
          data.push(node.data);
        while (node = node.next);
    });
    return data;
  }

  // node_modules/d3-quadtree/src/extent.js
  function extent_default2(_2) {
    return arguments.length ? this.cover(+_2[0][0], +_2[0][1]).cover(+_2[1][0], +_2[1][1]) : isNaN(this._x0) ? void 0 : [[this._x0, this._y0], [this._x1, this._y1]];
  }

  // node_modules/d3-quadtree/src/quad.js
  function quad_default(node, x0, y0, x1, y1) {
    this.node = node;
    this.x0 = x0;
    this.y0 = y0;
    this.x1 = x1;
    this.y1 = y1;
  }

  // node_modules/d3-quadtree/src/find.js
  function find_default2(x2, y2, radius) {
    var data, x0 = this._x0, y0 = this._y0, x1, y1, x22, y22, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i;
    if (node)
      quads.push(new quad_default(node, x0, y0, x3, y3));
    if (radius == null)
      radius = Infinity;
    else {
      x0 = x2 - radius, y0 = y2 - radius;
      x3 = x2 + radius, y3 = y2 + radius;
      radius *= radius;
    }
    while (q = quads.pop()) {
      if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x22 = q.x1) < x0 || (y22 = q.y1) < y0)
        continue;
      if (node.length) {
        var xm = (x1 + x22) / 2, ym = (y1 + y22) / 2;
        quads.push(new quad_default(node[3], xm, ym, x22, y22), new quad_default(node[2], x1, ym, xm, y22), new quad_default(node[1], xm, y1, x22, ym), new quad_default(node[0], x1, y1, xm, ym));
        if (i = (y2 >= ym) << 1 | x2 >= xm) {
          q = quads[quads.length - 1];
          quads[quads.length - 1] = quads[quads.length - 1 - i];
          quads[quads.length - 1 - i] = q;
        }
      } else {
        var dx = x2 - +this._x.call(null, node.data), dy = y2 - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
        if (d2 < radius) {
          var d = Math.sqrt(radius = d2);
          x0 = x2 - d, y0 = y2 - d;
          x3 = x2 + d, y3 = y2 + d;
          data = node.data;
        }
      }
    }
    return data;
  }

  // node_modules/d3-quadtree/src/remove.js
  function remove_default2(d) {
    if (isNaN(x2 = +this._x.call(null, d)) || isNaN(y2 = +this._y.call(null, d)))
      return this;
    var parent2, node = this._root, retainer, previous, next, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x2, y2, xm, ym, right2, bottom2, i, j;
    if (!node)
      return this;
    if (node.length)
      while (true) {
        if (right2 = x2 >= (xm = (x0 + x1) / 2))
          x0 = xm;
        else
          x1 = xm;
        if (bottom2 = y2 >= (ym = (y0 + y1) / 2))
          y0 = ym;
        else
          y1 = ym;
        if (!(parent2 = node, node = node[i = bottom2 << 1 | right2]))
          return this;
        if (!node.length)
          break;
        if (parent2[i + 1 & 3] || parent2[i + 2 & 3] || parent2[i + 3 & 3])
          retainer = parent2, j = i;
      }
    while (node.data !== d)
      if (!(previous = node, node = node.next))
        return this;
    if (next = node.next)
      delete node.next;
    if (previous)
      return next ? previous.next = next : delete previous.next, this;
    if (!parent2)
      return this._root = next, this;
    next ? parent2[i] = next : delete parent2[i];
    if ((node = parent2[0] || parent2[1] || parent2[2] || parent2[3]) && node === (parent2[3] || parent2[2] || parent2[1] || parent2[0]) && !node.length) {
      if (retainer)
        retainer[j] = node;
      else
        this._root = node;
    }
    return this;
  }
  function removeAll(data) {
    for (var i = 0, n = data.length; i < n; ++i)
      this.remove(data[i]);
    return this;
  }

  // node_modules/d3-quadtree/src/root.js
  function root_default() {
    return this._root;
  }

  // node_modules/d3-quadtree/src/size.js
  function size_default2() {
    var size = 0;
    this.visit(function(node) {
      if (!node.length)
        do
          ++size;
        while (node = node.next);
    });
    return size;
  }

  // node_modules/d3-quadtree/src/visit.js
  function visit_default(callback) {
    var quads = [], q, node = this._root, child, x0, y0, x1, y1;
    if (node)
      quads.push(new quad_default(node, this._x0, this._y0, this._x1, this._y1));
    while (q = quads.pop()) {
      if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
        var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
        if (child = node[3])
          quads.push(new quad_default(child, xm, ym, x1, y1));
        if (child = node[2])
          quads.push(new quad_default(child, x0, ym, xm, y1));
        if (child = node[1])
          quads.push(new quad_default(child, xm, y0, x1, ym));
        if (child = node[0])
          quads.push(new quad_default(child, x0, y0, xm, ym));
      }
    }
    return this;
  }

  // node_modules/d3-quadtree/src/visitAfter.js
  function visitAfter_default(callback) {
    var quads = [], next = [], q;
    if (this._root)
      quads.push(new quad_default(this._root, this._x0, this._y0, this._x1, this._y1));
    while (q = quads.pop()) {
      var node = q.node;
      if (node.length) {
        var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
        if (child = node[0])
          quads.push(new quad_default(child, x0, y0, xm, ym));
        if (child = node[1])
          quads.push(new quad_default(child, xm, y0, x1, ym));
        if (child = node[2])
          quads.push(new quad_default(child, x0, ym, xm, y1));
        if (child = node[3])
          quads.push(new quad_default(child, xm, ym, x1, y1));
      }
      next.push(q);
    }
    while (q = next.pop()) {
      callback(q.node, q.x0, q.y0, q.x1, q.y1);
    }
    return this;
  }

  // node_modules/d3-quadtree/src/x.js
  function defaultX(d) {
    return d[0];
  }
  function x_default(_2) {
    return arguments.length ? (this._x = _2, this) : this._x;
  }

  // node_modules/d3-quadtree/src/y.js
  function defaultY(d) {
    return d[1];
  }
  function y_default(_2) {
    return arguments.length ? (this._y = _2, this) : this._y;
  }

  // node_modules/d3-quadtree/src/quadtree.js
  function quadtree(nodes, x2, y2) {
    var tree = new Quadtree(x2 == null ? defaultX : x2, y2 == null ? defaultY : y2, NaN, NaN, NaN, NaN);
    return nodes == null ? tree : tree.addAll(nodes);
  }
  function Quadtree(x2, y2, x0, y0, x1, y1) {
    this._x = x2;
    this._y = y2;
    this._x0 = x0;
    this._y0 = y0;
    this._x1 = x1;
    this._y1 = y1;
    this._root = void 0;
  }
  function leaf_copy(leaf2) {
    var copy2 = {data: leaf2.data}, next = copy2;
    while (leaf2 = leaf2.next)
      next = next.next = {data: leaf2.data};
    return copy2;
  }
  var treeProto = quadtree.prototype = Quadtree.prototype;
  treeProto.copy = function() {
    var copy2 = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child;
    if (!node)
      return copy2;
    if (!node.length)
      return copy2._root = leaf_copy(node), copy2;
    nodes = [{source: node, target: copy2._root = new Array(4)}];
    while (node = nodes.pop()) {
      for (var i = 0; i < 4; ++i) {
        if (child = node.source[i]) {
          if (child.length)
            nodes.push({source: child, target: node.target[i] = new Array(4)});
          else
            node.target[i] = leaf_copy(child);
        }
      }
    }
    return copy2;
  };
  treeProto.add = add_default;
  treeProto.addAll = addAll;
  treeProto.cover = cover_default;
  treeProto.data = data_default2;
  treeProto.extent = extent_default2;
  treeProto.find = find_default2;
  treeProto.remove = remove_default2;
  treeProto.removeAll = removeAll;
  treeProto.root = root_default;
  treeProto.size = size_default2;
  treeProto.visit = visit_default;
  treeProto.visitAfter = visitAfter_default;
  treeProto.x = x_default;
  treeProto.y = y_default;

  // src/charts/LineChart.svelte
  function get_each_context7(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[21] = list[i];
    return child_ctx;
  }
  function get_each_context_13(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[24] = list[i];
    return child_ctx;
  }
  function get_each_context_2(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[21] = list[i];
    return child_ctx;
  }
  function get_each_context_3(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[21] = list[i];
    return child_ctx;
  }
  function create_if_block_12(ctx) {
    let g;
    let each_value_3 = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value_3.length; i += 1) {
      each_blocks[i] = create_each_block_3(get_each_context_3(ctx, each_value_3, i));
    }
    return {
      c() {
        g = svg_element("g");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(g, "class", "area svelte-1f3fe4k");
      },
      m(target, anchor) {
        insert(target, g, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g, null);
        }
      },
      p(ctx2, dirty) {
        if (dirty & 141) {
          each_value_3 = ctx2[0];
          let i;
          for (i = 0; i < each_value_3.length; i += 1) {
            const child_ctx = get_each_context_3(ctx2, each_value_3, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block_3(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value_3.length;
        }
      },
      d(detaching) {
        if (detaching)
          detach(g);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function create_each_block_3(ctx) {
    let path2;
    let path_d_value;
    let path_fill_value;
    return {
      c() {
        path2 = svg_element("path");
        attr(path2, "d", path_d_value = ctx[7](ctx[21].values, ctx[2]));
        attr(path2, "fill", path_fill_value = ctx[3](ctx[21].name));
        attr(path2, "class", "svelte-1f3fe4k");
      },
      m(target, anchor) {
        insert(target, path2, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 133 && path_d_value !== (path_d_value = ctx2[7](ctx2[21].values, ctx2[2]))) {
          attr(path2, "d", path_d_value);
        }
        if (dirty & 9 && path_fill_value !== (path_fill_value = ctx2[3](ctx2[21].name))) {
          attr(path2, "fill", path_fill_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(path2);
      }
    };
  }
  function create_each_block_2(ctx) {
    let path2;
    let path_d_value;
    let path_stroke_value;
    return {
      c() {
        path2 = svg_element("path");
        attr(path2, "d", path_d_value = ctx[6](ctx[21].values));
        attr(path2, "stroke", path_stroke_value = ctx[3](ctx[21].name));
        attr(path2, "class", "svelte-1f3fe4k");
      },
      m(target, anchor) {
        insert(target, path2, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 65 && path_d_value !== (path_d_value = ctx2[6](ctx2[21].values))) {
          attr(path2, "d", path_d_value);
        }
        if (dirty & 9 && path_stroke_value !== (path_stroke_value = ctx2[3](ctx2[21].name))) {
          attr(path2, "stroke", path_stroke_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(path2);
      }
    };
  }
  function create_if_block2(ctx) {
    let g;
    let each_value = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block7(get_each_context7(ctx, each_value, i));
    }
    return {
      c() {
        g = svg_element("g");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
      },
      m(target, anchor) {
        insert(target, g, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g, null);
        }
      },
      p(ctx2, dirty) {
        if (dirty & 57) {
          each_value = ctx2[0];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context7(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block7(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
      },
      d(detaching) {
        if (detaching)
          detach(g);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function create_each_block_13(ctx) {
    let circle;
    let circle_cx_value;
    let circle_cy_value;
    return {
      c() {
        circle = svg_element("circle");
        attr(circle, "r", "2");
        attr(circle, "cx", circle_cx_value = ctx[4](ctx[24].date));
        attr(circle, "cy", circle_cy_value = ctx[5](ctx[24].value));
      },
      m(target, anchor) {
        insert(target, circle, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 17 && circle_cx_value !== (circle_cx_value = ctx2[4](ctx2[24].date))) {
          attr(circle, "cx", circle_cx_value);
        }
        if (dirty & 33 && circle_cy_value !== (circle_cy_value = ctx2[5](ctx2[24].value))) {
          attr(circle, "cy", circle_cy_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(circle);
      }
    };
  }
  function create_each_block7(ctx) {
    let g;
    let g_fill_value;
    let each_value_1 = ctx[21].values;
    let each_blocks = [];
    for (let i = 0; i < each_value_1.length; i += 1) {
      each_blocks[i] = create_each_block_13(get_each_context_13(ctx, each_value_1, i));
    }
    return {
      c() {
        g = svg_element("g");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(g, "fill", g_fill_value = ctx[3](ctx[21].name));
      },
      m(target, anchor) {
        insert(target, g, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g, null);
        }
      },
      p(ctx2, dirty) {
        if (dirty & 49) {
          each_value_1 = ctx2[21].values;
          let i;
          for (i = 0; i < each_value_1.length; i += 1) {
            const child_ctx = get_each_context_13(ctx2, each_value_1, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block_13(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value_1.length;
        }
        if (dirty & 9 && g_fill_value !== (g_fill_value = ctx2[3](ctx2[21].name))) {
          attr(g, "fill", g_fill_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(g);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function create_fragment7(ctx) {
    let svg;
    let g3;
    let g0;
    let g0_transform_value;
    let axis_action;
    let g1;
    let axis_action_1;
    let g2;
    let g3_transform_value;
    let positionedTooltip_action;
    let mounted;
    let dispose;
    let if_block0 = ctx[10] === "area" && create_if_block_12(ctx);
    let each_value_2 = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value_2.length; i += 1) {
      each_blocks[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
    }
    let if_block1 = ctx[10] !== "area" && create_if_block2(ctx);
    return {
      c() {
        svg = svg_element("svg");
        g3 = svg_element("g");
        g0 = svg_element("g");
        g1 = svg_element("g");
        if (if_block0)
          if_block0.c();
        g2 = svg_element("g");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        if (if_block1)
          if_block1.c();
        attr(g0, "class", "x axis");
        attr(g0, "transform", g0_transform_value = `translate(0,${ctx[2]})`);
        attr(g1, "class", "y axis");
        attr(g2, "class", "lines svelte-1f3fe4k");
        attr(g3, "transform", g3_transform_value = `translate(${ctx[11].left},${ctx[11].top})`);
        attr(g3, "class", "svelte-1f3fe4k");
        attr(svg, "width", ctx[1]);
        attr(svg, "height", height2);
        attr(svg, "class", "svelte-1f3fe4k");
      },
      m(target, anchor) {
        insert(target, svg, anchor);
        append(svg, g3);
        append(g3, g0);
        append(g3, g1);
        if (if_block0)
          if_block0.m(g3, null);
        append(g3, g2);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g2, null);
        }
        if (if_block1)
          if_block1.m(g3, null);
        if (!mounted) {
          dispose = [
            action_destroyer(axis_action = axis2.call(null, g0, ctx[8])),
            action_destroyer(axis_action_1 = axis2.call(null, g1, ctx[9])),
            action_destroyer(positionedTooltip_action = positionedTooltip.call(null, g3, ctx[12]))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 4 && g0_transform_value !== (g0_transform_value = `translate(0,${ctx2[2]})`)) {
          attr(g0, "transform", g0_transform_value);
        }
        if (axis_action && is_function(axis_action.update) && dirty & 256)
          axis_action.update.call(null, ctx2[8]);
        if (axis_action_1 && is_function(axis_action_1.update) && dirty & 512)
          axis_action_1.update.call(null, ctx2[9]);
        if (ctx2[10] === "area") {
          if (if_block0) {
            if_block0.p(ctx2, dirty);
          } else {
            if_block0 = create_if_block_12(ctx2);
            if_block0.c();
            if_block0.m(g3, g2);
          }
        } else if (if_block0) {
          if_block0.d(1);
          if_block0 = null;
        }
        if (dirty & 73) {
          each_value_2 = ctx2[0];
          let i;
          for (i = 0; i < each_value_2.length; i += 1) {
            const child_ctx = get_each_context_2(ctx2, each_value_2, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block_2(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g2, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value_2.length;
        }
        if (ctx2[10] !== "area") {
          if (if_block1) {
            if_block1.p(ctx2, dirty);
          } else {
            if_block1 = create_if_block2(ctx2);
            if_block1.c();
            if_block1.m(g3, null);
          }
        } else if (if_block1) {
          if_block1.d(1);
          if_block1 = null;
        }
        if (dirty & 2) {
          attr(svg, "width", ctx2[1]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(svg);
        if (if_block0)
          if_block0.d();
        destroy_each(each_blocks, detaching);
        if (if_block1)
          if_block1.d();
        mounted = false;
        run_all(dispose);
      }
    };
  }
  var height2 = 250;
  function instance7($$self, $$props, $$invalidate) {
    let innerWidth;
    let innerHeight;
    let allValues;
    let xDomain;
    let x2;
    let y2;
    let quad;
    let lineShape;
    let areaShape;
    let xAxis;
    let yAxis;
    let $currenciesScale;
    let $lineChartMode;
    component_subscribe($$self, currenciesScale, ($$value) => $$invalidate(3, $currenciesScale = $$value));
    component_subscribe($$self, lineChartMode, ($$value) => $$invalidate(10, $lineChartMode = $$value));
    let {data} = $$props;
    let {width} = $$props;
    let {tooltipText} = $$props;
    const margin = {top: 10, right: 10, bottom: 30, left: 40};
    const legend = getContext("chart-legend");
    let yMin = 0;
    let yMax = 0;
    function tooltipInfo(xPos, yPos) {
      const d = quad.find(xPos, yPos);
      return d ? [x2(d.date), y2(d.value), tooltipText(d)] : void 0;
    }
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(0, data = $$props2.data);
      if ("width" in $$props2)
        $$invalidate(1, width = $$props2.width);
      if ("tooltipText" in $$props2)
        $$invalidate(13, tooltipText = $$props2.tooltipText);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 2) {
        $:
          $$invalidate(16, innerWidth = width - margin.left - margin.right);
      }
      if ($$self.$$.dirty & 9) {
        $:
          legend.set(data.map((d) => d.name).sort().map((c) => [c, $currenciesScale(c)]));
      }
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(17, allValues = merge(data.map((d) => d.values)));
      }
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(18, xDomain = [
            min(data, (s) => s.values[0].date),
            max(data, (s) => s.values[s.values.length - 1].date)
          ]);
      }
      if ($$self.$$.dirty & 327680) {
        $:
          $$invalidate(4, x2 = utcTime().domain(xDomain).range([0, innerWidth]));
      }
      if ($$self.$$.dirty & 131072) {
        $:
          $$invalidate(14, [yMin, yMax] = extent_default(allValues, (v) => v.value), yMin, ($$invalidate(15, yMax), $$invalidate(17, allValues), $$invalidate(0, data)));
      }
      if ($$self.$$.dirty & 49156) {
        $:
          $$invalidate(5, y2 = linear2().domain([yMin - (yMax - yMin) * 0.05, yMax + (yMax - yMin) * 0.05]).range([innerHeight, 0]));
      }
      if ($$self.$$.dirty & 131120) {
        $:
          quad = quadtree(allValues, (d) => x2(d.date), (d) => y2(d.value));
      }
      if ($$self.$$.dirty & 48) {
        $:
          $$invalidate(6, lineShape = line_default().x((d) => x2(d.date)).y((d) => y2(d.value)));
      }
      if ($$self.$$.dirty & 52) {
        $:
          $$invalidate(7, areaShape = area_default().x((d) => x2(d.date)).y1((d) => y2(d.value)).y0(Math.min(innerHeight, y2(0))));
      }
      if ($$self.$$.dirty & 16) {
        $:
          $$invalidate(8, xAxis = axisBottom(x2).tickSizeOuter(0));
      }
      if ($$self.$$.dirty & 65568) {
        $:
          $$invalidate(9, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat(formatCurrencyShort));
      }
    };
    $:
      $$invalidate(2, innerHeight = height2 - margin.top - margin.bottom);
    return [
      data,
      width,
      innerHeight,
      $currenciesScale,
      x2,
      y2,
      lineShape,
      areaShape,
      xAxis,
      yAxis,
      $lineChartMode,
      margin,
      tooltipInfo,
      tooltipText,
      yMin,
      yMax,
      innerWidth,
      allValues,
      xDomain
    ];
  }
  var LineChart = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance7, create_fragment7, safe_not_equal, {data: 0, width: 1, tooltipText: 13});
    }
  };
  var LineChart_default = LineChart;

  // src/charts/ScatterPlot.svelte
  function get_each_context8(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[13] = list[i];
    return child_ctx;
  }
  function create_each_block8(ctx) {
    let circle;
    let circle_fill_value;
    let circle_cx_value;
    let circle_cy_value;
    return {
      c() {
        circle = svg_element("circle");
        attr(circle, "r", "5");
        attr(circle, "fill", circle_fill_value = scatterplotScale(ctx[13].type));
        attr(circle, "cx", circle_cx_value = ctx[3](ctx[13].date));
        attr(circle, "cy", circle_cy_value = ctx[4](ctx[13].type));
      },
      m(target, anchor) {
        insert(target, circle, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 1 && circle_fill_value !== (circle_fill_value = scatterplotScale(ctx2[13].type))) {
          attr(circle, "fill", circle_fill_value);
        }
        if (dirty & 9 && circle_cx_value !== (circle_cx_value = ctx2[3](ctx2[13].date))) {
          attr(circle, "cx", circle_cx_value);
        }
        if (dirty & 17 && circle_cy_value !== (circle_cy_value = ctx2[4](ctx2[13].type))) {
          attr(circle, "cy", circle_cy_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(circle);
      }
    };
  }
  function create_fragment8(ctx) {
    let svg;
    let g3;
    let g0;
    let g0_transform_value;
    let axis_action;
    let g1;
    let axis_action_1;
    let g2;
    let g3_transform_value;
    let positionedTooltip_action;
    let mounted;
    let dispose;
    let each_value = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block8(get_each_context8(ctx, each_value, i));
    }
    return {
      c() {
        svg = svg_element("svg");
        g3 = svg_element("g");
        g0 = svg_element("g");
        g1 = svg_element("g");
        g2 = svg_element("g");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(g0, "class", "x axis");
        attr(g0, "transform", g0_transform_value = `translate(0,${ctx[2]})`);
        attr(g1, "class", "y axis");
        attr(g3, "transform", g3_transform_value = `translate(${ctx[7].left},${ctx[7].top})`);
        attr(g3, "class", "svelte-16xd8ih");
        attr(svg, "width", ctx[1]);
        attr(svg, "height", height3);
        attr(svg, "class", "svelte-16xd8ih");
      },
      m(target, anchor) {
        insert(target, svg, anchor);
        append(svg, g3);
        append(g3, g0);
        append(g3, g1);
        append(g3, g2);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(g2, null);
        }
        if (!mounted) {
          dispose = [
            action_destroyer(axis_action = axis2.call(null, g0, ctx[5])),
            action_destroyer(axis_action_1 = axis2.call(null, g1, ctx[6])),
            action_destroyer(positionedTooltip_action = positionedTooltip.call(null, g3, ctx[8]))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 4 && g0_transform_value !== (g0_transform_value = `translate(0,${ctx2[2]})`)) {
          attr(g0, "transform", g0_transform_value);
        }
        if (axis_action && is_function(axis_action.update) && dirty & 32)
          axis_action.update.call(null, ctx2[5]);
        if (axis_action_1 && is_function(axis_action_1.update) && dirty & 64)
          axis_action_1.update.call(null, ctx2[6]);
        if (dirty & 25) {
          each_value = ctx2[0];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context8(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block8(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(g2, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (dirty & 2) {
          attr(svg, "width", ctx2[1]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(svg);
        destroy_each(each_blocks, detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  var height3 = 250;
  function instance8($$self, $$props, $$invalidate) {
    let innerWidth;
    let innerHeight;
    let dateExtent;
    let x2;
    let y2;
    let xAxis;
    let yAxis;
    let quad;
    let {data} = $$props;
    let {width} = $$props;
    const margin = {top: 10, right: 10, bottom: 30, left: 70};
    function tooltipText(d) {
      return `${d.description}<em>${dateFormat.day(d.date)}</em>`;
    }
    function tooltipInfo(xPos, yPos) {
      const d = quad.find(xPos, yPos);
      return d ? [x2(d.date), y2(d.type) || 0, tooltipText(d)] : void 0;
    }
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(0, data = $$props2.data);
      if ("width" in $$props2)
        $$invalidate(1, width = $$props2.width);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 2) {
        $:
          $$invalidate(9, innerWidth = width - margin.left - margin.right);
      }
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(10, dateExtent = extent_default(data, (d) => d.date));
      }
      if ($$self.$$.dirty & 1536) {
        $:
          $$invalidate(3, x2 = utcTime().domain(dateExtent[0] ? dateExtent : [0, 1]).range([0, innerWidth]));
      }
      if ($$self.$$.dirty & 5) {
        $:
          $$invalidate(4, y2 = point().padding(1).domain(data.map((d) => d.type)).range([innerHeight, 0]));
      }
      if ($$self.$$.dirty & 8) {
        $:
          $$invalidate(5, xAxis = axisBottom(x2).tickSizeOuter(0));
      }
      if ($$self.$$.dirty & 528) {
        $:
          $$invalidate(6, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat((d) => d));
      }
      if ($$self.$$.dirty & 25) {
        $:
          quad = quadtree(data, (d) => x2(d.date), (d) => y2(d.type) || 0);
      }
    };
    $:
      $$invalidate(2, innerHeight = height3 - margin.top - margin.bottom);
    return [
      data,
      width,
      innerHeight,
      x2,
      y2,
      xAxis,
      yAxis,
      margin,
      tooltipInfo,
      innerWidth,
      dateExtent
    ];
  }
  var ScatterPlot = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance8, create_fragment8, safe_not_equal, {data: 0, width: 1});
    }
  };
  var ScatterPlot_default = ScatterPlot;

  // src/charts/Chart.svelte
  function get_each_context9(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[21] = list[i];
    return child_ctx;
  }
  function create_else_block_1(ctx) {
    let span;
    return {
      c() {
        span = element("span");
        attr(span, "class", "spacer");
      },
      m(target, anchor) {
        insert(target, span, anchor);
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(span);
      }
    };
  }
  function create_if_block_22(ctx) {
    let div;
    let chartlegend;
    let t03;
    let span;
    let t13;
    let if_block_anchor;
    let current;
    chartlegend = new ChartLegend_default({props: {legend: ctx[3]}});
    function select_block_type_1(ctx2, dirty) {
      if (ctx2[0].type === "hierarchy")
        return create_if_block_3;
      if (ctx2[0].type === "linechart")
        return create_if_block_5;
    }
    let current_block_type = select_block_type_1(ctx, -1);
    let if_block = current_block_type && current_block_type(ctx);
    return {
      c() {
        div = element("div");
        create_component(chartlegend.$$.fragment);
        t03 = space();
        span = element("span");
        t13 = space();
        if (if_block)
          if_block.c();
        if_block_anchor = empty();
        attr(span, "class", "spacer");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        mount_component(chartlegend, div, null);
        insert(target, t03, anchor);
        insert(target, span, anchor);
        insert(target, t13, anchor);
        if (if_block)
          if_block.m(target, anchor);
        insert(target, if_block_anchor, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const chartlegend_changes = {};
        if (dirty & 8)
          chartlegend_changes.legend = ctx2[3];
        chartlegend.$set(chartlegend_changes);
        if (current_block_type === (current_block_type = select_block_type_1(ctx2, dirty)) && if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if (if_block)
            if_block.d(1);
          if_block = current_block_type && current_block_type(ctx2);
          if (if_block) {
            if_block.c();
            if_block.m(if_block_anchor.parentNode, if_block_anchor);
          }
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(chartlegend.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(chartlegend.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        destroy_component(chartlegend);
        if (detaching)
          detach(t03);
        if (detaching)
          detach(span);
        if (detaching)
          detach(t13);
        if (if_block) {
          if_block.d(detaching);
        }
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function create_if_block_5(ctx) {
    let span2;
    let label0;
    let input0;
    let t03;
    let span0;
    let t22;
    let label1;
    let input1;
    let t32;
    let span1;
    let mounted;
    let dispose;
    return {
      c() {
        span2 = element("span");
        label0 = element("label");
        input0 = element("input");
        t03 = space();
        span0 = element("span");
        span0.textContent = `${_("Line chart")}`;
        t22 = space();
        label1 = element("label");
        input1 = element("input");
        t32 = space();
        span1 = element("span");
        span1.textContent = `${_("Area chart")}`;
        attr(input0, "type", "radio");
        input0.__value = "line";
        input0.value = input0.__value;
        ctx[15][1].push(input0);
        attr(span0, "class", "button");
        attr(input1, "type", "radio");
        input1.__value = "area";
        input1.value = input1.__value;
        ctx[15][1].push(input1);
        attr(span1, "class", "button");
        attr(span2, "class", "chart-mode");
      },
      m(target, anchor) {
        insert(target, span2, anchor);
        append(span2, label0);
        append(label0, input0);
        input0.checked = input0.__value === ctx[7];
        append(label0, t03);
        append(label0, span0);
        append(span2, t22);
        append(span2, label1);
        append(label1, input1);
        input1.checked = input1.__value === ctx[7];
        append(label1, t32);
        append(label1, span1);
        if (!mounted) {
          dispose = [
            listen(input0, "change", ctx[17]),
            listen(input1, "change", ctx[18])
          ];
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (dirty & 128) {
          input0.checked = input0.__value === ctx2[7];
        }
        if (dirty & 128) {
          input1.checked = input1.__value === ctx2[7];
        }
      },
      d(detaching) {
        if (detaching)
          detach(span2);
        ctx[15][1].splice(ctx[15][1].indexOf(input0), 1);
        ctx[15][1].splice(ctx[15][1].indexOf(input1), 1);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_if_block_3(ctx) {
    let t03;
    let span2;
    let label0;
    let input0;
    let t13;
    let span0;
    let t32;
    let label1;
    let input1;
    let t4;
    let span1;
    let mounted;
    let dispose;
    let if_block = ctx[4] === "treemap" && create_if_block_4(ctx);
    return {
      c() {
        if (if_block)
          if_block.c();
        t03 = space();
        span2 = element("span");
        label0 = element("label");
        input0 = element("input");
        t13 = space();
        span0 = element("span");
        span0.textContent = `${_("Treemap")}`;
        t32 = space();
        label1 = element("label");
        input1 = element("input");
        t4 = space();
        span1 = element("span");
        span1.textContent = `${_("Sunburst")}`;
        attr(input0, "type", "radio");
        input0.__value = "treemap";
        input0.value = input0.__value;
        ctx[15][0].push(input0);
        attr(span0, "class", "button");
        attr(input1, "type", "radio");
        input1.__value = "sunburst";
        input1.value = input1.__value;
        ctx[15][0].push(input1);
        attr(span1, "class", "button");
        attr(span2, "class", "chart-mode");
      },
      m(target, anchor) {
        if (if_block)
          if_block.m(target, anchor);
        insert(target, t03, anchor);
        insert(target, span2, anchor);
        append(span2, label0);
        append(label0, input0);
        input0.checked = input0.__value === ctx[4];
        append(label0, t13);
        append(label0, span0);
        append(span2, t32);
        append(span2, label1);
        append(label1, input1);
        input1.checked = input1.__value === ctx[4];
        append(label1, t4);
        append(label1, span1);
        if (!mounted) {
          dispose = [
            listen(input0, "change", ctx[14]),
            listen(input1, "change", ctx[16])
          ];
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (ctx2[4] === "treemap") {
          if (if_block) {
            if_block.p(ctx2, dirty);
          } else {
            if_block = create_if_block_4(ctx2);
            if_block.c();
            if_block.m(t03.parentNode, t03);
          }
        } else if (if_block) {
          if_block.d(1);
          if_block = null;
        }
        if (dirty & 16) {
          input0.checked = input0.__value === ctx2[4];
        }
        if (dirty & 16) {
          input1.checked = input1.__value === ctx2[4];
        }
      },
      d(detaching) {
        if (if_block)
          if_block.d(detaching);
        if (detaching)
          detach(t03);
        if (detaching)
          detach(span2);
        ctx[15][0].splice(ctx[15][0].indexOf(input0), 1);
        ctx[15][0].splice(ctx[15][0].indexOf(input1), 1);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_if_block_4(ctx) {
    let select;
    let mounted;
    let dispose;
    let each_value = ctx[6];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block9(get_each_context9(ctx, each_value, i));
    }
    return {
      c() {
        select = element("select");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        if (ctx[5] === void 0)
          add_render_callback(() => ctx[13].call(select));
      },
      m(target, anchor) {
        insert(target, select, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(select, null);
        }
        select_option(select, ctx[5]);
        if (!mounted) {
          dispose = listen(select, "change", ctx[13]);
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (dirty & 64) {
          each_value = ctx2[6];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context9(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block9(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 & 96) {
          select_option(select, ctx2[5]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(select);
        destroy_each(each_blocks, detaching);
        mounted = false;
        dispose();
      }
    };
  }
  function create_each_block9(ctx) {
    let option;
    let t_value = ctx[21] + "";
    let t;
    let option_value_value;
    return {
      c() {
        option = element("option");
        t = text(t_value);
        option.__value = option_value_value = ctx[21];
        option.value = option.__value;
      },
      m(target, anchor) {
        insert(target, option, anchor);
        append(option, t);
      },
      p(ctx2, dirty) {
        if (dirty & 64 && t_value !== (t_value = ctx2[21] + ""))
          set_data(t, t_value);
        if (dirty & 64 && option_value_value !== (option_value_value = ctx2[21])) {
          option.__value = option_value_value;
          option.value = option.__value;
        }
      },
      d(detaching) {
        if (detaching)
          detach(option);
      }
    };
  }
  function create_if_block3(ctx) {
    let current_block_type_index;
    let if_block;
    let if_block_anchor;
    let current;
    const if_block_creators = [create_if_block_13, create_else_block];
    const if_blocks = [];
    function select_block_type_2(ctx2, dirty) {
      if (ctx2[10][ctx2[0].type])
        return 0;
      return 1;
    }
    current_block_type_index = select_block_type_2(ctx, -1);
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
    return {
      c() {
        if_block.c();
        if_block_anchor = empty();
      },
      m(target, anchor) {
        if_blocks[current_block_type_index].m(target, anchor);
        insert(target, if_block_anchor, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        let previous_block_index = current_block_type_index;
        current_block_type_index = select_block_type_2(ctx2, dirty);
        if (current_block_type_index === previous_block_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        } else {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if_blocks[current_block_type_index].d(detaching);
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function create_else_block(ctx) {
    let t03;
    let t1_value = ctx[0].type + "";
    let t13;
    return {
      c() {
        t03 = text("Invalid chart: ");
        t13 = text(t1_value);
      },
      m(target, anchor) {
        insert(target, t03, anchor);
        insert(target, t13, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 1 && t1_value !== (t1_value = ctx2[0].type + ""))
          set_data(t13, t1_value);
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(t03);
        if (detaching)
          detach(t13);
      }
    };
  }
  function create_if_block_13(ctx) {
    let switch_instance;
    let switch_instance_anchor;
    let current;
    var switch_value = ctx[10][ctx[0].type];
    function switch_props(ctx2) {
      return {
        props: {
          data: ctx2[0].data,
          tooltipText: ctx2[0].tooltipText,
          width: ctx2[1]
        }
      };
    }
    if (switch_value) {
      switch_instance = new switch_value(switch_props(ctx));
    }
    return {
      c() {
        if (switch_instance)
          create_component(switch_instance.$$.fragment);
        switch_instance_anchor = empty();
      },
      m(target, anchor) {
        if (switch_instance) {
          mount_component(switch_instance, target, anchor);
        }
        insert(target, switch_instance_anchor, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const switch_instance_changes = {};
        if (dirty & 1)
          switch_instance_changes.data = ctx2[0].data;
        if (dirty & 1)
          switch_instance_changes.tooltipText = ctx2[0].tooltipText;
        if (dirty & 2)
          switch_instance_changes.width = ctx2[1];
        if (switch_value !== (switch_value = ctx2[10][ctx2[0].type])) {
          if (switch_instance) {
            group_outros();
            const old_component = switch_instance;
            transition_out(old_component.$$.fragment, 1, 0, () => {
              destroy_component(old_component, 1);
            });
            check_outros();
          }
          if (switch_value) {
            switch_instance = new switch_value(switch_props(ctx2));
            create_component(switch_instance.$$.fragment);
            transition_in(switch_instance.$$.fragment, 1);
            mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
          } else {
            switch_instance = null;
          }
        } else if (switch_value) {
          switch_instance.$set(switch_instance_changes);
        }
      },
      i(local) {
        if (current)
          return;
        if (switch_instance)
          transition_in(switch_instance.$$.fragment, local);
        current = true;
      },
      o(local) {
        if (switch_instance)
          transition_out(switch_instance.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(switch_instance_anchor);
        if (switch_instance)
          destroy_component(switch_instance, detaching);
      }
    };
  }
  function create_fragment9(ctx) {
    let div0;
    let current_block_type_index;
    let if_block0;
    let t03;
    let t13;
    let button;
    let keyboardShortcut_action;
    let t22;
    let div1;
    let div1_hidden_value;
    let div1_resize_listener;
    let current;
    let mounted;
    let dispose;
    const if_block_creators = [create_if_block_22, create_else_block_1];
    const if_blocks = [];
    function select_block_type(ctx2, dirty) {
      if (ctx2[2])
        return 0;
      return 1;
    }
    current_block_type_index = select_block_type(ctx, -1);
    if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
    const default_slot_template = ctx[12].default;
    const default_slot = create_slot(default_slot_template, ctx, ctx[11], null);
    let if_block1 = ctx[1] && create_if_block3(ctx);
    return {
      c() {
        div0 = element("div");
        if_block0.c();
        t03 = space();
        if (default_slot)
          default_slot.c();
        t13 = space();
        button = element("button");
        t22 = space();
        div1 = element("div");
        if (if_block1)
          if_block1.c();
        attr(button, "type", "button");
        attr(button, "class", "toggle-chart");
        toggle_class(button, "closed", !ctx[2]);
        attr(div0, "class", "flex-row");
        div1.hidden = div1_hidden_value = !ctx[2];
        add_render_callback(() => ctx[20].call(div1));
      },
      m(target, anchor) {
        insert(target, div0, anchor);
        if_blocks[current_block_type_index].m(div0, null);
        append(div0, t03);
        if (default_slot) {
          default_slot.m(div0, null);
        }
        append(div0, t13);
        append(div0, button);
        insert(target, t22, anchor);
        insert(target, div1, anchor);
        if (if_block1)
          if_block1.m(div1, null);
        div1_resize_listener = add_resize_listener(div1, ctx[20].bind(div1));
        current = true;
        if (!mounted) {
          dispose = [
            listen(button, "click", ctx[19]),
            action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, "Control+c"))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        let previous_block_index = current_block_type_index;
        current_block_type_index = select_block_type(ctx2, dirty);
        if (current_block_type_index === previous_block_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        } else {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
          if_block0 = if_blocks[current_block_type_index];
          if (!if_block0) {
            if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block0.c();
          } else {
            if_block0.p(ctx2, dirty);
          }
          transition_in(if_block0, 1);
          if_block0.m(div0, t03);
        }
        if (default_slot) {
          if (default_slot.p && dirty & 2048) {
            update_slot(default_slot, default_slot_template, ctx2, ctx2[11], dirty, null, null);
          }
        }
        if (dirty & 4) {
          toggle_class(button, "closed", !ctx2[2]);
        }
        if (ctx2[1]) {
          if (if_block1) {
            if_block1.p(ctx2, dirty);
            if (dirty & 2) {
              transition_in(if_block1, 1);
            }
          } else {
            if_block1 = create_if_block3(ctx2);
            if_block1.c();
            transition_in(if_block1, 1);
            if_block1.m(div1, null);
          }
        } else if (if_block1) {
          group_outros();
          transition_out(if_block1, 1, 1, () => {
            if_block1 = null;
          });
          check_outros();
        }
        if (!current || dirty & 4 && div1_hidden_value !== (div1_hidden_value = !ctx2[2])) {
          div1.hidden = div1_hidden_value;
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block0);
        transition_in(default_slot, local);
        transition_in(if_block1);
        current = true;
      },
      o(local) {
        transition_out(if_block0);
        transition_out(default_slot, local);
        transition_out(if_block1);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div0);
        if_blocks[current_block_type_index].d();
        if (default_slot)
          default_slot.d(detaching);
        if (detaching)
          detach(t22);
        if (detaching)
          detach(div1);
        if (if_block1)
          if_block1.d();
        div1_resize_listener();
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance9($$self, $$props, $$invalidate) {
    let $showCharts;
    let $legend;
    let $chartMode;
    let $chartCurrency;
    let $currencies;
    let $lineChartMode;
    component_subscribe($$self, showCharts, ($$value) => $$invalidate(2, $showCharts = $$value));
    component_subscribe($$self, chartMode, ($$value) => $$invalidate(4, $chartMode = $$value));
    component_subscribe($$self, chartCurrency, ($$value) => $$invalidate(5, $chartCurrency = $$value));
    component_subscribe($$self, lineChartMode, ($$value) => $$invalidate(7, $lineChartMode = $$value));
    let {$$slots: slots = {}, $$scope} = $$props;
    let {chart} = $$props;
    let width;
    const currencies2 = writable([]);
    component_subscribe($$self, currencies2, (value) => $$invalidate(6, $currencies = value));
    setContext("chart-currencies", currencies2);
    const legend = writable([]);
    component_subscribe($$self, legend, (value) => $$invalidate(3, $legend = value));
    setContext("chart-legend", legend);
    const components2 = {
      barchart: BarChart_default,
      hierarchy: HierarchyContainer_default,
      linechart: LineChart_default,
      scatterplot: ScatterPlot_default
    };
    const $$binding_groups = [[], []];
    function select_change_handler() {
      $chartCurrency = select_value(this);
      chartCurrency.set($chartCurrency);
    }
    function input0_change_handler() {
      $chartMode = this.__value;
      chartMode.set($chartMode);
    }
    function input1_change_handler() {
      $chartMode = this.__value;
      chartMode.set($chartMode);
    }
    function input0_change_handler_1() {
      $lineChartMode = this.__value;
      lineChartMode.set($lineChartMode);
    }
    function input1_change_handler_1() {
      $lineChartMode = this.__value;
      lineChartMode.set($lineChartMode);
    }
    const click_handler = () => showCharts.update((v) => !v);
    function div1_elementresize_handler() {
      width = this.clientWidth;
      $$invalidate(1, width);
    }
    $$self.$$set = ($$props2) => {
      if ("chart" in $$props2)
        $$invalidate(0, chart = $$props2.chart);
      if ("$$scope" in $$props2)
        $$invalidate(11, $$scope = $$props2.$$scope);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          if (chart) {
            legend.set([]);
          }
      }
    };
    return [
      chart,
      width,
      $showCharts,
      $legend,
      $chartMode,
      $chartCurrency,
      $currencies,
      $lineChartMode,
      currencies2,
      legend,
      components2,
      $$scope,
      slots,
      select_change_handler,
      input0_change_handler,
      $$binding_groups,
      input1_change_handler,
      input0_change_handler_1,
      input1_change_handler_1,
      click_handler,
      div1_elementresize_handler
    ];
  }
  var Chart = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance9, create_fragment9, safe_not_equal, {chart: 0});
    }
  };
  var Chart_default = Chart;

  // src/charts/ChartSwitcher.svelte
  function get_each_context10(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[4] = list[i];
    return child_ctx;
  }
  function create_if_block4(ctx) {
    let chart;
    let t;
    let div;
    let div_hidden_value;
    let current;
    chart = new Chart_default({
      props: {
        chart: ctx[1],
        $$slots: {default: [create_default_slot]},
        $$scope: {ctx}
      }
    });
    let each_value = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block10(get_each_context10(ctx, each_value, i));
    }
    return {
      c() {
        create_component(chart.$$.fragment);
        t = space();
        div = element("div");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        div.hidden = div_hidden_value = !ctx[2];
        attr(div, "class", "svelte-zrq527");
      },
      m(target, anchor) {
        mount_component(chart, target, anchor);
        insert(target, t, anchor);
        insert(target, div, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(div, null);
        }
        current = true;
      },
      p(ctx2, dirty) {
        const chart_changes = {};
        if (dirty & 2)
          chart_changes.chart = ctx2[1];
        if (dirty & 128) {
          chart_changes.$$scope = {dirty, ctx: ctx2};
        }
        chart.$set(chart_changes);
        if (dirty & 3) {
          each_value = ctx2[0];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context10(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block10(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(div, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (!current || dirty & 4 && div_hidden_value !== (div_hidden_value = !ctx2[2])) {
          div.hidden = div_hidden_value;
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(chart.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(chart.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(chart, detaching);
        if (detaching)
          detach(t);
        if (detaching)
          detach(div);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function create_default_slot(ctx) {
    let conversionandinterval;
    let current;
    conversionandinterval = new ConversionAndInterval_default({});
    return {
      c() {
        create_component(conversionandinterval.$$.fragment);
      },
      m(target, anchor) {
        mount_component(conversionandinterval, target, anchor);
        current = true;
      },
      i(local) {
        if (current)
          return;
        transition_in(conversionandinterval.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(conversionandinterval.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(conversionandinterval, detaching);
      }
    };
  }
  function create_each_block10(ctx) {
    let span;
    let t0_value = ctx[4].name + "";
    let t03;
    let t13;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[3](ctx[4]);
    }
    return {
      c() {
        span = element("span");
        t03 = text(t0_value);
        t13 = space();
        attr(span, "class", "svelte-zrq527");
        toggle_class(span, "selected", ctx[4] === ctx[1]);
      },
      m(target, anchor) {
        insert(target, span, anchor);
        append(span, t03);
        append(span, t13);
        if (!mounted) {
          dispose = listen(span, "click", click_handler);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 1 && t0_value !== (t0_value = ctx[4].name + ""))
          set_data(t03, t0_value);
        if (dirty & 3) {
          toggle_class(span, "selected", ctx[4] === ctx[1]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(span);
        mounted = false;
        dispose();
      }
    };
  }
  function create_fragment10(ctx) {
    let if_block_anchor;
    let current;
    let if_block = ctx[1] && create_if_block4(ctx);
    return {
      c() {
        if (if_block)
          if_block.c();
        if_block_anchor = empty();
      },
      m(target, anchor) {
        if (if_block)
          if_block.m(target, anchor);
        insert(target, if_block_anchor, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        if (ctx2[1]) {
          if (if_block) {
            if_block.p(ctx2, dirty);
            if (dirty & 2) {
              transition_in(if_block, 1);
            }
          } else {
            if_block = create_if_block4(ctx2);
            if_block.c();
            transition_in(if_block, 1);
            if_block.m(if_block_anchor.parentNode, if_block_anchor);
          }
        } else if (if_block) {
          group_outros();
          transition_out(if_block, 1, 1, () => {
            if_block = null;
          });
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if (if_block)
          if_block.d(detaching);
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function instance10($$self, $$props, $$invalidate) {
    let $activeChart;
    let $showCharts;
    component_subscribe($$self, activeChart, ($$value) => $$invalidate(1, $activeChart = $$value));
    component_subscribe($$self, showCharts, ($$value) => $$invalidate(2, $showCharts = $$value));
    let charts = [];
    onMount(() => {
      $$invalidate(0, charts = parseChartData());
      if (!charts.length) {
        set_store_value(activeChart, $activeChart = void 0, $activeChart);
      }
      set_store_value(activeChart, $activeChart = charts.find((c) => c.name === ($activeChart || {}).name) || charts[0], $activeChart);
      const unbind = [
        bindKey("c", () => {
          const currentIndex = charts.findIndex((e) => e === $activeChart);
          set_store_value(activeChart, $activeChart = charts[(currentIndex + 1 + charts.length) % charts.length], $activeChart);
        }),
        bindKey("C", () => {
          const currentIndex = charts.findIndex((e) => e === $activeChart);
          set_store_value(activeChart, $activeChart = charts[(currentIndex - 1 + charts.length) % charts.length], $activeChart);
        })
      ];
      return () => {
        unbind.forEach((u) => u());
      };
    });
    const click_handler = (chart) => {
      set_store_value(activeChart, $activeChart = chart, $activeChart);
    };
    return [charts, $activeChart, $showCharts, click_handler];
  }
  var ChartSwitcher = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance10, create_fragment10, safe_not_equal, {});
    }
  };
  var ChartSwitcher_default = ChartSwitcher;

  // src/lib/paths.ts
  function basename(filename) {
    const parts = filename.split(/\/|\\/);
    return parts[parts.length - 1];
  }
  function ext(filename) {
    const match = /\.(\w+)$/.exec(filename);
    return match ? match[1] : "";
  }
  function documentHasAccount(filename, account2) {
    const accountParts = account2.split(":").reverse();
    const folders = filename.split(/\/|\\/).reverse().slice(1);
    return accountParts.every((part, index) => part === folders[index]);
  }

  // src/AutocompleteInput.svelte
  function get_each_context11(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[28] = list[i].innerHTML;
    child_ctx[29] = list[i].suggestion;
    child_ctx[31] = i;
    return child_ctx;
  }
  function create_if_block_14(ctx) {
    let button;
    let button_tabindex_value;
    let mounted;
    let dispose;
    return {
      c() {
        button = element("button");
        button.textContent = "\xD7";
        attr(button, "type", "button");
        attr(button, "tabindex", button_tabindex_value = -1);
        attr(button, "class", "muted round svelte-11ahi2m");
      },
      m(target, anchor) {
        insert(target, button, anchor);
        if (!mounted) {
          dispose = listen(button, "click", ctx[25]);
          mounted = true;
        }
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(button);
        mounted = false;
        dispose();
      }
    };
  }
  function create_if_block5(ctx) {
    let ul;
    let each_value = ctx[6];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block11(get_each_context11(ctx, each_value, i));
    }
    return {
      c() {
        ul = element("ul");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        ul.hidden = ctx[9];
        attr(ul, "class", "svelte-11ahi2m");
      },
      m(target, anchor) {
        insert(target, ul, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(ul, null);
        }
      },
      p(ctx2, dirty) {
        if (dirty[0] & 4288) {
          each_value = ctx2[6];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context11(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block11(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(ul, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (dirty[0] & 512) {
          ul.hidden = ctx2[9];
        }
      },
      d(detaching) {
        if (detaching)
          detach(ul);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function create_each_block11(ctx) {
    let li;
    let html_tag;
    let raw_value = ctx[28] + "";
    let t;
    let mounted;
    let dispose;
    function mousedown_handler(...args) {
      return ctx[26](ctx[29], ...args);
    }
    return {
      c() {
        li = element("li");
        t = space();
        html_tag = new HtmlTag(t);
        attr(li, "class", "svelte-11ahi2m");
        toggle_class(li, "selected", ctx[31] === ctx[7]);
      },
      m(target, anchor) {
        insert(target, li, anchor);
        html_tag.m(raw_value, li);
        append(li, t);
        if (!mounted) {
          dispose = listen(li, "mousedown", mousedown_handler);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty[0] & 64 && raw_value !== (raw_value = ctx[28] + ""))
          html_tag.p(raw_value);
        if (dirty[0] & 128) {
          toggle_class(li, "selected", ctx[31] === ctx[7]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(li);
        mounted = false;
        dispose();
      }
    };
  }
  function create_fragment11(ctx) {
    let span;
    let input_1;
    let keyboardShortcut_action;
    let t03;
    let t13;
    let span_class_value;
    let mounted;
    let dispose;
    let if_block0 = ctx[5] && ctx[0] && create_if_block_14(ctx);
    let if_block1 = ctx[6].length && create_if_block5(ctx);
    return {
      c() {
        span = element("span");
        input_1 = element("input");
        t03 = space();
        if (if_block0)
          if_block0.c();
        t13 = space();
        if (if_block1)
          if_block1.c();
        attr(input_1, "name", ctx[1]);
        attr(input_1, "type", "text");
        attr(input_1, "autocomplete", "off");
        attr(input_1, "placeholder", ctx[2]);
        attr(input_1, "size", ctx[10]);
        attr(input_1, "class", "svelte-11ahi2m");
        attr(span, "class", span_class_value = "" + (null_to_empty(ctx[3]) + " svelte-11ahi2m"));
      },
      m(target, anchor) {
        insert(target, span, anchor);
        append(span, input_1);
        set_input_value(input_1, ctx[0]);
        ctx[21](input_1);
        append(span, t03);
        if (if_block0)
          if_block0.m(span, null);
        append(span, t13);
        if (if_block1)
          if_block1.m(span, null);
        if (!mounted) {
          dispose = [
            listen(input_1, "input", ctx[20]),
            action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, input_1, ctx[4])),
            listen(input_1, "blur", ctx[22]),
            listen(input_1, "focus", ctx[23]),
            listen(input_1, "input", ctx[24]),
            listen(input_1, "keydown", ctx[13])
          ];
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (dirty[0] & 2) {
          attr(input_1, "name", ctx2[1]);
        }
        if (dirty[0] & 4) {
          attr(input_1, "placeholder", ctx2[2]);
        }
        if (dirty[0] & 1024) {
          attr(input_1, "size", ctx2[10]);
        }
        if (dirty[0] & 1 && input_1.value !== ctx2[0]) {
          set_input_value(input_1, ctx2[0]);
        }
        if (keyboardShortcut_action && is_function(keyboardShortcut_action.update) && dirty[0] & 16)
          keyboardShortcut_action.update.call(null, ctx2[4]);
        if (ctx2[5] && ctx2[0]) {
          if (if_block0) {
            if_block0.p(ctx2, dirty);
          } else {
            if_block0 = create_if_block_14(ctx2);
            if_block0.c();
            if_block0.m(span, t13);
          }
        } else if (if_block0) {
          if_block0.d(1);
          if_block0 = null;
        }
        if (ctx2[6].length) {
          if (if_block1) {
            if_block1.p(ctx2, dirty);
          } else {
            if_block1 = create_if_block5(ctx2);
            if_block1.c();
            if_block1.m(span, null);
          }
        } else if (if_block1) {
          if_block1.d(1);
          if_block1 = null;
        }
        if (dirty[0] & 8 && span_class_value !== (span_class_value = "" + (null_to_empty(ctx2[3]) + " svelte-11ahi2m"))) {
          attr(span, "class", span_class_value);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(span);
        ctx[21](null);
        if (if_block0)
          if_block0.d();
        if (if_block1)
          if_block1.d();
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance11($$self, $$props, $$invalidate) {
    let size;
    const dispatch = createEventDispatcher();
    let {value} = $$props;
    let {suggestions} = $$props;
    let {name = ""} = $$props;
    let {placeholder = ""} = $$props;
    let {valueExtractor: valueExtractor2 = null} = $$props;
    let {valueSelector: valueSelector2 = null} = $$props;
    let {setSize = false} = $$props;
    let {className = void 0} = $$props;
    let {key = void 0} = $$props;
    let {checkValidity = void 0} = $$props;
    let {selectFirst = false} = $$props;
    let {clearButton = false} = $$props;
    let filteredSuggestions = [];
    let hidden = true;
    let index = -1;
    let input;
    function select(suggestion) {
      $$invalidate(0, value = input && valueSelector2 ? valueSelector2(suggestion, input) : suggestion);
      dispatch("select", input);
      $$invalidate(9, hidden = true);
    }
    function mousedown(event, suggestion) {
      if (event.button === 0) {
        select(suggestion);
      }
    }
    function keydown2(event) {
      if (event.key === "Enter") {
        if (index > -1) {
          event.preventDefault();
          select(filteredSuggestions[index].suggestion);
        }
      } else if (event.key === "Escape") {
        $$invalidate(9, hidden = true);
      } else if (event.key === "ArrowUp") {
        event.preventDefault();
        $$invalidate(7, index = index === 0 ? filteredSuggestions.length - 1 : index - 1);
      } else if (event.key === "ArrowDown") {
        event.preventDefault();
        $$invalidate(7, index = index === filteredSuggestions.length - 1 ? 0 : index + 1);
      }
    }
    function input_1_input_handler() {
      value = this.value;
      $$invalidate(0, value);
    }
    function input_1_binding($$value) {
      binding_callbacks[$$value ? "unshift" : "push"](() => {
        input = $$value;
        $$invalidate(8, input);
      });
    }
    const blur_handler = () => {
      $$invalidate(9, hidden = true);
      dispatch("blur");
    };
    const focus_handler = () => {
      $$invalidate(9, hidden = false);
    };
    const input_handler = () => {
      $$invalidate(9, hidden = false);
    };
    const click_handler = () => {
      $$invalidate(0, value = "");
      dispatch("select");
    };
    const mousedown_handler = (suggestion, ev) => mousedown(ev, suggestion);
    $$self.$$set = ($$props2) => {
      if ("value" in $$props2)
        $$invalidate(0, value = $$props2.value);
      if ("suggestions" in $$props2)
        $$invalidate(14, suggestions = $$props2.suggestions);
      if ("name" in $$props2)
        $$invalidate(1, name = $$props2.name);
      if ("placeholder" in $$props2)
        $$invalidate(2, placeholder = $$props2.placeholder);
      if ("valueExtractor" in $$props2)
        $$invalidate(15, valueExtractor2 = $$props2.valueExtractor);
      if ("valueSelector" in $$props2)
        $$invalidate(16, valueSelector2 = $$props2.valueSelector);
      if ("setSize" in $$props2)
        $$invalidate(17, setSize = $$props2.setSize);
      if ("className" in $$props2)
        $$invalidate(3, className = $$props2.className);
      if ("key" in $$props2)
        $$invalidate(4, key = $$props2.key);
      if ("checkValidity" in $$props2)
        $$invalidate(18, checkValidity = $$props2.checkValidity);
      if ("selectFirst" in $$props2)
        $$invalidate(19, selectFirst = $$props2.selectFirst);
      if ("clearButton" in $$props2)
        $$invalidate(5, clearButton = $$props2.clearButton);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty[0] & 131077) {
        $:
          $$invalidate(10, size = setSize ? Math.max(value.length, placeholder.length) + 1 : void 0);
      }
      if ($$self.$$.dirty[0] & 262401) {
        $:
          if (input && checkValidity) {
            input.setCustomValidity(checkValidity(value));
          }
      }
      if ($$self.$$.dirty[0] & 573889) {
        $: {
          const val = input && valueExtractor2 ? valueExtractor2(value, input) : value;
          const filtered = fuzzyfilter(val, suggestions).slice(0, 30).map((suggestion) => ({
            suggestion,
            innerHTML: fuzzywrap(val, suggestion)
          }));
          $$invalidate(6, filteredSuggestions = filtered.length === 1 && filtered[0].suggestion === val ? [] : filtered);
          $$invalidate(7, index = Math.min(index, filteredSuggestions.length - 1));
          if (selectFirst && index < 0) {
            $$invalidate(7, index = 0);
          }
        }
      }
    };
    return [
      value,
      name,
      placeholder,
      className,
      key,
      clearButton,
      filteredSuggestions,
      index,
      input,
      hidden,
      size,
      dispatch,
      mousedown,
      keydown2,
      suggestions,
      valueExtractor2,
      valueSelector2,
      setSize,
      checkValidity,
      selectFirst,
      input_1_input_handler,
      input_1_binding,
      blur_handler,
      focus_handler,
      input_handler,
      click_handler,
      mousedown_handler
    ];
  }
  var AutocompleteInput = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance11, create_fragment11, safe_not_equal, {
        value: 0,
        suggestions: 14,
        name: 1,
        placeholder: 2,
        valueExtractor: 15,
        valueSelector: 16,
        setSize: 17,
        className: 3,
        key: 4,
        checkValidity: 18,
        selectFirst: 19,
        clearButton: 5
      }, [-1, -1]);
    }
  };
  var AutocompleteInput_default = AutocompleteInput;

  // src/entry-forms/AccountInput.svelte
  function create_fragment12(ctx) {
    let autocompleteinput;
    let updating_value;
    let current;
    function autocompleteinput_value_binding(value) {
      ctx[5].call(null, value);
    }
    let autocompleteinput_props = {
      placeholder: _("Account"),
      className: ctx[2],
      checkValidity: ctx[4],
      suggestions: ctx[1] || ctx[3]
    };
    if (ctx[0] !== void 0) {
      autocompleteinput_props.value = ctx[0];
    }
    autocompleteinput = new AutocompleteInput_default({props: autocompleteinput_props});
    binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
    return {
      c() {
        create_component(autocompleteinput.$$.fragment);
      },
      m(target, anchor) {
        mount_component(autocompleteinput, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const autocompleteinput_changes = {};
        if (dirty & 4)
          autocompleteinput_changes.className = ctx2[2];
        if (dirty & 10)
          autocompleteinput_changes.suggestions = ctx2[1] || ctx2[3];
        if (!updating_value && dirty & 1) {
          updating_value = true;
          autocompleteinput_changes.value = ctx2[0];
          add_flush_callback(() => updating_value = false);
        }
        autocompleteinput.$set(autocompleteinput_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(autocompleteinput.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(autocompleteinput.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(autocompleteinput, detaching);
      }
    };
  }
  function instance12($$self, $$props, $$invalidate) {
    let $accounts;
    component_subscribe($$self, accounts, ($$value) => $$invalidate(3, $accounts = $$value));
    let {value} = $$props;
    let {suggestions = void 0} = $$props;
    let {className = void 0} = $$props;
    function checkValidity(val) {
      return !$accounts.length || $accounts.includes(val) ? "" : _("Should be one of the declared accounts");
    }
    function autocompleteinput_value_binding(value$1) {
      value = value$1;
      $$invalidate(0, value);
    }
    $$self.$$set = ($$props2) => {
      if ("value" in $$props2)
        $$invalidate(0, value = $$props2.value);
      if ("suggestions" in $$props2)
        $$invalidate(1, suggestions = $$props2.suggestions);
      if ("className" in $$props2)
        $$invalidate(2, className = $$props2.className);
    };
    return [
      value,
      suggestions,
      className,
      $accounts,
      checkValidity,
      autocompleteinput_value_binding
    ];
  }
  var AccountInput = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance12, create_fragment12, safe_not_equal, {value: 0, suggestions: 1, className: 2});
    }
  };
  var AccountInput_default = AccountInput;

  // src/modals/ModalBase.svelte
  function create_fragment13(ctx) {
    let div2;
    let div0;
    let t03;
    let div1;
    let button;
    let t22;
    let current;
    let mounted;
    let dispose;
    const default_slot_template = ctx[3].default;
    const default_slot = create_slot(default_slot_template, ctx, ctx[2], null);
    return {
      c() {
        div2 = element("div");
        div0 = element("div");
        t03 = space();
        div1 = element("div");
        button = element("button");
        button.textContent = "x";
        t22 = space();
        if (default_slot)
          default_slot.c();
        attr(div0, "class", "background svelte-x1kse4");
        attr(button, "type", "button");
        attr(button, "class", "muted close svelte-x1kse4");
        attr(div1, "class", "content svelte-x1kse4");
        attr(div2, "class", "overlay svelte-x1kse4");
        toggle_class(div2, "shown", ctx[0]);
      },
      m(target, anchor) {
        insert(target, div2, anchor);
        append(div2, div0);
        append(div2, t03);
        append(div2, div1);
        append(div1, button);
        append(div1, t22);
        if (default_slot) {
          default_slot.m(div1, null);
        }
        current = true;
        if (!mounted) {
          dispose = [
            listen(div0, "click", function() {
              if (is_function(ctx[1]))
                ctx[1].apply(this, arguments);
            }),
            listen(button, "click", function() {
              if (is_function(ctx[1]))
                ctx[1].apply(this, arguments);
            })
          ];
          mounted = true;
        }
      },
      p(new_ctx, [dirty]) {
        ctx = new_ctx;
        if (default_slot) {
          if (default_slot.p && dirty & 4) {
            update_slot(default_slot, default_slot_template, ctx, ctx[2], dirty, null, null);
          }
        }
        if (dirty & 1) {
          toggle_class(div2, "shown", ctx[0]);
        }
      },
      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(div2);
        if (default_slot)
          default_slot.d(detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance13($$self, $$props, $$invalidate) {
    let {$$slots: slots = {}, $$scope} = $$props;
    let {shown = false} = $$props;
    let {closeHandler = closeOverlay} = $$props;
    $$self.$$set = ($$props2) => {
      if ("shown" in $$props2)
        $$invalidate(0, shown = $$props2.shown);
      if ("closeHandler" in $$props2)
        $$invalidate(1, closeHandler = $$props2.closeHandler);
      if ("$$scope" in $$props2)
        $$invalidate(2, $$scope = $$props2.$$scope);
    };
    return [shown, closeHandler, $$scope, slots];
  }
  var ModalBase = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance13, create_fragment13, safe_not_equal, {shown: 0, closeHandler: 1});
    }
  };
  var ModalBase_default = ModalBase;

  // src/documents/stores.ts
  var selectedAccount = writable("");

  // src/documents/Accounts.svelte
  function get_each_context12(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[10] = list[i];
    return child_ctx;
  }
  function create_if_block_23(ctx) {
    let p;
    let span;
    let t_value = leaf(ctx[0].name) + "";
    let t;
    let p_title_value;
    let p_data_account_name_value;
    let mounted;
    let dispose;
    return {
      c() {
        p = element("p");
        span = element("span");
        t = text(t_value);
        attr(p, "title", p_title_value = ctx[0].name);
        attr(p, "class", "droptarget svelte-15y6nay");
        attr(p, "data-account-name", p_data_account_name_value = ctx[0].name);
        toggle_class(p, "expanded", expanded);
        toggle_class(p, "selected", ctx[2] === ctx[0].name);
        toggle_class(p, "drag", ctx[1]);
      },
      m(target, anchor) {
        insert(target, p, anchor);
        append(p, span);
        append(span, t);
        if (!mounted) {
          dispose = [
            listen(p, "click", ctx[3]),
            listen(p, "dragenter", ctx[4]),
            listen(p, "dragover", ctx[5]),
            listen(p, "dragleave", ctx[7]),
            listen(p, "drop", prevent_default(ctx[6]))
          ];
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (dirty & 1 && t_value !== (t_value = leaf(ctx2[0].name) + ""))
          set_data(t, t_value);
        if (dirty & 1 && p_title_value !== (p_title_value = ctx2[0].name)) {
          attr(p, "title", p_title_value);
        }
        if (dirty & 1 && p_data_account_name_value !== (p_data_account_name_value = ctx2[0].name)) {
          attr(p, "data-account-name", p_data_account_name_value);
        }
        if (dirty & 0) {
          toggle_class(p, "expanded", expanded);
        }
        if (dirty & 5) {
          toggle_class(p, "selected", ctx2[2] === ctx2[0].name);
        }
        if (dirty & 2) {
          toggle_class(p, "drag", ctx2[1]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(p);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_if_block6(ctx) {
    let ul;
    let ul_hidden_value;
    let current;
    let each_value = ctx[0].children;
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block12(get_each_context12(ctx, each_value, i));
    }
    const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
      each_blocks[i] = null;
    });
    return {
      c() {
        ul = element("ul");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(ul, "class", "flex-table svelte-15y6nay");
        ul.hidden = ul_hidden_value = !expanded;
      },
      m(target, anchor) {
        insert(target, ul, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(ul, null);
        }
        current = true;
      },
      p(ctx2, dirty) {
        if (dirty & 1) {
          each_value = ctx2[0].children;
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context12(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
              transition_in(each_blocks[i], 1);
            } else {
              each_blocks[i] = create_each_block12(child_ctx);
              each_blocks[i].c();
              transition_in(each_blocks[i], 1);
              each_blocks[i].m(ul, null);
            }
          }
          group_outros();
          for (i = each_value.length; i < each_blocks.length; i += 1) {
            out(i);
          }
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        for (let i = 0; i < each_value.length; i += 1) {
          transition_in(each_blocks[i]);
        }
        current = true;
      },
      o(local) {
        each_blocks = each_blocks.filter(Boolean);
        for (let i = 0; i < each_blocks.length; i += 1) {
          transition_out(each_blocks[i]);
        }
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(ul);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function create_else_block2(ctx) {
    let t;
    return {
      c() {
        t = text("node.name");
      },
      m(target, anchor) {
        insert(target, t, anchor);
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(t);
      }
    };
  }
  function create_if_block_15(ctx) {
    let accounts2;
    let current;
    accounts2 = new Accounts({props: {node: ctx[10]}});
    accounts2.$on("drop", ctx[8]);
    return {
      c() {
        create_component(accounts2.$$.fragment);
      },
      m(target, anchor) {
        mount_component(accounts2, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const accounts_changes = {};
        if (dirty & 1)
          accounts_changes.node = ctx2[10];
        accounts2.$set(accounts_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(accounts2.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accounts2.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(accounts2, detaching);
      }
    };
  }
  function create_each_block12(ctx) {
    let li;
    let current_block_type_index;
    let if_block;
    let t;
    let current;
    const if_block_creators = [create_if_block_15, create_else_block2];
    const if_blocks = [];
    function select_block_type(ctx2, dirty) {
      if (ctx2[0].children.length)
        return 0;
      return 1;
    }
    current_block_type_index = select_block_type(ctx, -1);
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
    return {
      c() {
        li = element("li");
        if_block.c();
        t = space();
      },
      m(target, anchor) {
        insert(target, li, anchor);
        if_blocks[current_block_type_index].m(li, null);
        append(li, t);
        current = true;
      },
      p(ctx2, dirty) {
        let previous_block_index = current_block_type_index;
        current_block_type_index = select_block_type(ctx2, dirty);
        if (current_block_type_index === previous_block_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        } else {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(li, t);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(li);
        if_blocks[current_block_type_index].d();
      }
    };
  }
  function create_fragment14(ctx) {
    let t;
    let if_block1_anchor;
    let current;
    let if_block0 = ctx[0].name && create_if_block_23(ctx);
    let if_block1 = ctx[0].children.length && create_if_block6(ctx);
    return {
      c() {
        if (if_block0)
          if_block0.c();
        t = space();
        if (if_block1)
          if_block1.c();
        if_block1_anchor = empty();
      },
      m(target, anchor) {
        if (if_block0)
          if_block0.m(target, anchor);
        insert(target, t, anchor);
        if (if_block1)
          if_block1.m(target, anchor);
        insert(target, if_block1_anchor, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        if (ctx2[0].name) {
          if (if_block0) {
            if_block0.p(ctx2, dirty);
          } else {
            if_block0 = create_if_block_23(ctx2);
            if_block0.c();
            if_block0.m(t.parentNode, t);
          }
        } else if (if_block0) {
          if_block0.d(1);
          if_block0 = null;
        }
        if (ctx2[0].children.length) {
          if (if_block1) {
            if_block1.p(ctx2, dirty);
            if (dirty & 1) {
              transition_in(if_block1, 1);
            }
          } else {
            if_block1 = create_if_block6(ctx2);
            if_block1.c();
            transition_in(if_block1, 1);
            if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
          }
        } else if (if_block1) {
          group_outros();
          transition_out(if_block1, 1, 1, () => {
            if_block1 = null;
          });
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block1);
        current = true;
      },
      o(local) {
        transition_out(if_block1);
        current = false;
      },
      d(detaching) {
        if (if_block0)
          if_block0.d(detaching);
        if (detaching)
          detach(t);
        if (if_block1)
          if_block1.d(detaching);
        if (detaching)
          detach(if_block1_anchor);
      }
    };
  }
  var expanded = true;
  function instance14($$self, $$props, $$invalidate) {
    let $selectedAccount;
    component_subscribe($$self, selectedAccount, ($$value) => $$invalidate(2, $selectedAccount = $$value));
    let {node} = $$props;
    let drag = false;
    function click() {
      set_store_value(selectedAccount, $selectedAccount = $selectedAccount === node.name ? "" : node.name, $selectedAccount);
    }
    function dragenter(event) {
      if (event.dataTransfer && event.dataTransfer.types.includes("fava/filename")) {
        event.preventDefault();
        $$invalidate(1, drag = true);
      }
    }
    const dragover2 = dragenter;
    const dispatch = createEventDispatcher();
    function drop2(event) {
      const filename = event.dataTransfer && event.dataTransfer.getData("fava/filename");
      if (filename) {
        dispatch("drop", {account: node.name, filename});
        $$invalidate(1, drag = false);
      }
    }
    const dragleave_handler = () => {
      $$invalidate(1, drag = false);
    };
    function drop_handler(event) {
      bubble($$self, event);
    }
    $$self.$$set = ($$props2) => {
      if ("node" in $$props2)
        $$invalidate(0, node = $$props2.node);
    };
    return [
      node,
      drag,
      $selectedAccount,
      click,
      dragenter,
      dragover2,
      drop2,
      dragleave_handler,
      drop_handler
    ];
  }
  var Accounts = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance14, create_fragment14, safe_not_equal, {node: 0});
    }
  };
  var Accounts_default = Accounts;

  // src/documents/Table.svelte
  function get_each_context13(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[11] = list[i].doc;
    child_ctx[12] = list[i].row;
    return child_ctx;
  }
  function get_each_context_14(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[15] = list[i];
    child_ctx[17] = i;
    return child_ctx;
  }
  function create_each_block_14(ctx) {
    let th;
    let t0_value = ctx[15].header + "";
    let t03;
    let t13;
    let th_data_order_value;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[7](ctx[17]);
    }
    return {
      c() {
        th = element("th");
        t03 = text(t0_value);
        t13 = space();
        attr(th, "data-sort", "");
        attr(th, "data-order", th_data_order_value = ctx[17] === ctx[1][0] ? ctx[1][1] : null);
      },
      m(target, anchor) {
        insert(target, th, anchor);
        append(th, t03);
        append(th, t13);
        if (!mounted) {
          dispose = listen(th, "click", click_handler);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 2 && th_data_order_value !== (th_data_order_value = ctx[17] === ctx[1][0] ? ctx[1][1] : null)) {
          attr(th, "data-order", th_data_order_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(th);
        mounted = false;
        dispose();
      }
    };
  }
  function create_each_block13(ctx) {
    let tr;
    let td0;
    let t0_value = ctx[12][0] + "";
    let t03;
    let t13;
    let td1;
    let t2_value = ctx[12][1] + "";
    let t22;
    let t32;
    let tr_draggable_value;
    let tr_title_value;
    let mounted;
    let dispose;
    function dragstart_handler(...args) {
      return ctx[8](ctx[11], ...args);
    }
    function click_handler_1() {
      return ctx[9](ctx[11]);
    }
    return {
      c() {
        tr = element("tr");
        td0 = element("td");
        t03 = text(t0_value);
        t13 = space();
        td1 = element("td");
        t22 = text(t2_value);
        t32 = space();
        attr(tr, "draggable", tr_draggable_value = true);
        attr(tr, "title", tr_title_value = ctx[11].filename);
        attr(tr, "class", "svelte-1gus9z9");
        toggle_class(tr, "selected", ctx[0] === ctx[11]);
      },
      m(target, anchor) {
        insert(target, tr, anchor);
        append(tr, td0);
        append(td0, t03);
        append(tr, t13);
        append(tr, td1);
        append(td1, t22);
        append(tr, t32);
        if (!mounted) {
          dispose = [
            listen(tr, "dragstart", dragstart_handler),
            listen(tr, "click", click_handler_1)
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 4 && t0_value !== (t0_value = ctx[12][0] + ""))
          set_data(t03, t0_value);
        if (dirty & 4 && t2_value !== (t2_value = ctx[12][1] + ""))
          set_data(t22, t2_value);
        if (dirty & 4 && tr_title_value !== (tr_title_value = ctx[11].filename)) {
          attr(tr, "title", tr_title_value);
        }
        if (dirty & 5) {
          toggle_class(tr, "selected", ctx[0] === ctx[11]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(tr);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_fragment15(ctx) {
    let table_1;
    let thead;
    let tr;
    let t;
    let tbody;
    let each_value_1 = ctx[3];
    let each_blocks_1 = [];
    for (let i = 0; i < each_value_1.length; i += 1) {
      each_blocks_1[i] = create_each_block_14(get_each_context_14(ctx, each_value_1, i));
    }
    let each_value = ctx[2];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block13(get_each_context13(ctx, each_value, i));
    }
    return {
      c() {
        table_1 = element("table");
        thead = element("thead");
        tr = element("tr");
        for (let i = 0; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].c();
        }
        t = space();
        tbody = element("tbody");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(tr, "class", "svelte-1gus9z9");
        attr(table_1, "class", "svelte-1gus9z9");
      },
      m(target, anchor) {
        insert(target, table_1, anchor);
        append(table_1, thead);
        append(thead, tr);
        for (let i = 0; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].m(tr, null);
        }
        append(table_1, t);
        append(table_1, tbody);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(tbody, null);
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 26) {
          each_value_1 = ctx2[3];
          let i;
          for (i = 0; i < each_value_1.length; i += 1) {
            const child_ctx = get_each_context_14(ctx2, each_value_1, i);
            if (each_blocks_1[i]) {
              each_blocks_1[i].p(child_ctx, dirty);
            } else {
              each_blocks_1[i] = create_each_block_14(child_ctx);
              each_blocks_1[i].c();
              each_blocks_1[i].m(tr, null);
            }
          }
          for (; i < each_blocks_1.length; i += 1) {
            each_blocks_1[i].d(1);
          }
          each_blocks_1.length = each_value_1.length;
        }
        if (dirty & 5) {
          each_value = ctx2[2];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context13(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block13(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(tbody, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(table_1);
        destroy_each(each_blocks_1, detaching);
        destroy_each(each_blocks, detaching);
      }
    };
  }
  function instance15($$self, $$props, $$invalidate) {
    let table;
    let $selectedAccount;
    component_subscribe($$self, selectedAccount, ($$value) => $$invalidate(6, $selectedAccount = $$value));
    let {data} = $$props;
    let {selected = null} = $$props;
    function name(doc) {
      const base = basename(doc.filename);
      if (`${doc.date}` === base.substring(0, 10)) {
        return base.substring(11);
      }
      return base;
    }
    const tableColumns = [
      {
        header: _("Date"),
        getter: (e) => e.date
      },
      {
        header: _("Name"),
        getter: (e) => name(e)
      }
    ];
    let sort = [0, "desc"];
    function setSort(index) {
      const [col, order] = sort;
      if (index === col) {
        $$invalidate(1, sort = [index, order === "asc" ? "desc" : "asc"]);
      } else {
        $$invalidate(1, sort = [index, "asc"]);
      }
    }
    const click_handler = (index) => setSort(index);
    const dragstart_handler = (doc, ev) => ev.dataTransfer?.setData("fava/filename", doc.filename);
    const click_handler_1 = (doc) => {
      $$invalidate(0, selected = doc);
    };
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(5, data = $$props2.data);
      if ("selected" in $$props2)
        $$invalidate(0, selected = $$props2.selected);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 98) {
        $:
          $$invalidate(2, table = data.filter((e) => e.account.startsWith($selectedAccount)).map((e) => ({
            doc: e,
            row: tableColumns.map((th) => th.getter(e))
          })).sort(sortFunc("string", sort[1], ({row}) => row[sort[0]])));
      }
    };
    return [
      selected,
      sort,
      table,
      tableColumns,
      setSort,
      data,
      $selectedAccount,
      click_handler,
      dragstart_handler,
      click_handler_1
    ];
  }
  var Table = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance15, create_fragment15, safe_not_equal, {data: 5, selected: 0});
    }
  };
  var Table_default = Table;

  // src/editor/Editor.svelte
  function create_fragment16(ctx) {
    let div;
    let initialiseEditor_action;
    let mounted;
    let dispose;
    return {
      c() {
        div = element("div");
        attr(div, "class", "svelte-1n43zu");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        if (!mounted) {
          dispose = action_destroyer(initialiseEditor_action = ctx[0].call(null, div));
          mounted = true;
        }
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(div);
        mounted = false;
        dispose();
      }
    };
  }
  function instance16($$self, $$props, $$invalidate) {
    let {value} = $$props;
    let editor;
    function initialiseEditor(div) {
      $$invalidate(2, editor = import_codemirror7.default(div, {readOnly: true, lineNumbers: true, value}));
      editor.on("changes", (cm) => {
        $$invalidate(1, value = cm.getValue());
      });
    }
    $$self.$$set = ($$props2) => {
      if ("value" in $$props2)
        $$invalidate(1, value = $$props2.value);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 6) {
        $:
          if (editor && value !== editor.getValue()) {
            editor.setValue(value);
          }
      }
    };
    return [initialiseEditor, value, editor];
  }
  var Editor5 = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance16, create_fragment16, safe_not_equal, {value: 1});
    }
  };
  var Editor_default = Editor5;

  // src/documents/DocumentPreview.svelte
  function create_else_block3(ctx) {
    let t03;
    let t13;
    let t22;
    let t32;
    let t4;
    return {
      c() {
        t03 = text("Preview for file `");
        t13 = text(ctx[0]);
        t22 = text("` with file type `");
        t32 = text(ctx[1]);
        t4 = text("` is not implemented");
      },
      m(target, anchor) {
        insert(target, t03, anchor);
        insert(target, t13, anchor);
        insert(target, t22, anchor);
        insert(target, t32, anchor);
        insert(target, t4, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 1)
          set_data(t13, ctx2[0]);
        if (dirty & 2)
          set_data(t32, ctx2[1]);
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(t03);
        if (detaching)
          detach(t13);
        if (detaching)
          detach(t22);
        if (detaching)
          detach(t32);
        if (detaching)
          detach(t4);
      }
    };
  }
  function create_if_block_16(ctx) {
    let await_block_anchor;
    let promise;
    let current;
    let info = {
      ctx,
      current: null,
      token: null,
      hasCatch: false,
      pending: create_pending_block,
      then: create_then_block,
      catch: create_catch_block,
      value: 4,
      blocks: [, , ,]
    };
    handle_promise(promise = fetch(ctx[2]).then(handleText), info);
    return {
      c() {
        await_block_anchor = empty();
        info.block.c();
      },
      m(target, anchor) {
        insert(target, await_block_anchor, anchor);
        info.block.m(target, info.anchor = anchor);
        info.mount = () => await_block_anchor.parentNode;
        info.anchor = await_block_anchor;
        current = true;
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        info.ctx = ctx;
        if (dirty & 4 && promise !== (promise = fetch(ctx[2]).then(handleText)) && handle_promise(promise, info)) {
        } else {
          const child_ctx = ctx.slice();
          child_ctx[4] = info.resolved;
          info.block.p(child_ctx, dirty);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(info.block);
        current = true;
      },
      o(local) {
        for (let i = 0; i < 3; i += 1) {
          const block = info.blocks[i];
          transition_out(block);
        }
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(await_block_anchor);
        info.block.d(detaching);
        info.token = null;
        info = null;
      }
    };
  }
  function create_if_block7(ctx) {
    let object2;
    return {
      c() {
        object2 = element("object");
        attr(object2, "title", ctx[0]);
        attr(object2, "data", ctx[2]);
        attr(object2, "class", "svelte-1lgci0p");
      },
      m(target, anchor) {
        insert(target, object2, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 1) {
          attr(object2, "title", ctx2[0]);
        }
        if (dirty & 4) {
          attr(object2, "data", ctx2[2]);
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(object2);
      }
    };
  }
  function create_catch_block(ctx) {
    return {
      c: noop,
      m: noop,
      p: noop,
      i: noop,
      o: noop,
      d: noop
    };
  }
  function create_then_block(ctx) {
    let editor;
    let current;
    editor = new Editor_default({props: {value: ctx[4]}});
    return {
      c() {
        create_component(editor.$$.fragment);
      },
      m(target, anchor) {
        mount_component(editor, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const editor_changes = {};
        if (dirty & 4)
          editor_changes.value = ctx2[4];
        editor.$set(editor_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(editor.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(editor.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(editor, detaching);
      }
    };
  }
  function create_pending_block(ctx) {
    let t;
    return {
      c() {
        t = text("Loading...");
      },
      m(target, anchor) {
        insert(target, t, anchor);
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(t);
      }
    };
  }
  function create_fragment17(ctx) {
    let show_if;
    let current_block_type_index;
    let if_block;
    let if_block_anchor;
    let current;
    const if_block_creators = [create_if_block7, create_if_block_16, create_else_block3];
    const if_blocks = [];
    function select_block_type(ctx2, dirty) {
      if (ctx2[1] === "pdf")
        return 0;
      if (dirty & 2)
        show_if = !!["csv", "txt"].includes(ctx2[1]);
      if (show_if)
        return 1;
      return 2;
    }
    current_block_type_index = select_block_type(ctx, -1);
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
    return {
      c() {
        if_block.c();
        if_block_anchor = empty();
      },
      m(target, anchor) {
        if_blocks[current_block_type_index].m(target, anchor);
        insert(target, if_block_anchor, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        let previous_block_index = current_block_type_index;
        current_block_type_index = select_block_type(ctx2, dirty);
        if (current_block_type_index === previous_block_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        } else {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if_blocks[current_block_type_index].d(detaching);
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function instance17($$self, $$props, $$invalidate) {
    let extension;
    let url;
    let $baseURL;
    component_subscribe($$self, baseURL, ($$value) => $$invalidate(3, $baseURL = $$value));
    let {filename} = $$props;
    $$self.$$set = ($$props2) => {
      if ("filename" in $$props2)
        $$invalidate(0, filename = $$props2.filename);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(1, extension = ext(filename));
      }
      if ($$self.$$.dirty & 9) {
        $:
          $$invalidate(2, url = `${$baseURL}document/?filename=${filename}`);
      }
    };
    return [filename, extension, url, $baseURL];
  }
  var DocumentPreview = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance17, create_fragment17, safe_not_equal, {filename: 0});
    }
  };
  var DocumentPreview_default = DocumentPreview;

  // src/documents/Documents.svelte
  function create_if_block_17(ctx) {
    let modalbase;
    let current;
    modalbase = new ModalBase_default({
      props: {
        shown: true,
        closeHandler: ctx[9],
        $$slots: {default: [create_default_slot2]},
        $$scope: {ctx}
      }
    });
    return {
      c() {
        create_component(modalbase.$$.fragment);
      },
      m(target, anchor) {
        mount_component(modalbase, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const modalbase_changes = {};
        if (dirty & 4)
          modalbase_changes.closeHandler = ctx2[9];
        if (dirty & 4100) {
          modalbase_changes.$$scope = {dirty, ctx: ctx2};
        }
        modalbase.$set(modalbase_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(modalbase.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(modalbase.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(modalbase, detaching);
      }
    };
  }
  function create_default_slot2(ctx) {
    let div;
    let h3;
    let t13;
    let p0;
    let code;
    let t2_value = ctx[2].filename + "";
    let t22;
    let t32;
    let p1;
    let accountinput;
    let updating_value;
    let t4;
    let input;
    let input_size_value;
    let t5;
    let button;
    let current;
    let mounted;
    let dispose;
    function accountinput_value_binding(value) {
      ctx[7].call(null, value);
    }
    let accountinput_props = {};
    if (ctx[2].account !== void 0) {
      accountinput_props.value = ctx[2].account;
    }
    accountinput = new AccountInput_default({props: accountinput_props});
    binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
    return {
      c() {
        div = element("div");
        h3 = element("h3");
        h3.textContent = `${_("Move or rename document")}`;
        t13 = space();
        p0 = element("p");
        code = element("code");
        t22 = text(t2_value);
        t32 = space();
        p1 = element("p");
        create_component(accountinput.$$.fragment);
        t4 = space();
        input = element("input");
        t5 = space();
        button = element("button");
        button.textContent = `${"Move"}`;
        attr(input, "size", input_size_value = 40);
        attr(button, "type", "button");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, h3);
        append(div, t13);
        append(div, p0);
        append(p0, code);
        append(code, t22);
        append(div, t32);
        append(div, p1);
        mount_component(accountinput, p1, null);
        append(p1, t4);
        append(p1, input);
        set_input_value(input, ctx[2].newName);
        append(p1, t5);
        append(p1, button);
        current = true;
        if (!mounted) {
          dispose = [
            listen(input, "input", ctx[8]),
            listen(button, "click", ctx[6])
          ];
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if ((!current || dirty & 4) && t2_value !== (t2_value = ctx2[2].filename + ""))
          set_data(t22, t2_value);
        const accountinput_changes = {};
        if (!updating_value && dirty & 4) {
          updating_value = true;
          accountinput_changes.value = ctx2[2].account;
          add_flush_callback(() => updating_value = false);
        }
        accountinput.$set(accountinput_changes);
        if (dirty & 4 && input.value !== ctx2[2].newName) {
          set_input_value(input, ctx2[2].newName);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(accountinput.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accountinput.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        destroy_component(accountinput);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_if_block8(ctx) {
    let documentpreview;
    let current;
    documentpreview = new DocumentPreview_default({
      props: {filename: ctx[1].filename}
    });
    return {
      c() {
        create_component(documentpreview.$$.fragment);
      },
      m(target, anchor) {
        mount_component(documentpreview, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const documentpreview_changes = {};
        if (dirty & 2)
          documentpreview_changes.filename = ctx2[1].filename;
        documentpreview.$set(documentpreview_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(documentpreview.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(documentpreview.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(documentpreview, detaching);
      }
    };
  }
  function create_fragment18(ctx) {
    let t03;
    let div1;
    let accounts2;
    let t13;
    let div0;
    let table;
    let updating_selected;
    let t22;
    let current;
    let mounted;
    let dispose;
    let if_block0 = ctx[2] && create_if_block_17(ctx);
    accounts2 = new Accounts_default({props: {node: ctx[3]}});
    accounts2.$on("drop", ctx[5]);
    function table_selected_binding(value) {
      ctx[10].call(null, value);
    }
    let table_props = {data: ctx[0]};
    if (ctx[1] !== void 0) {
      table_props.selected = ctx[1];
    }
    table = new Table_default({props: table_props});
    binding_callbacks.push(() => bind(table, "selected", table_selected_binding));
    let if_block1 = ctx[1] && create_if_block8(ctx);
    return {
      c() {
        if (if_block0)
          if_block0.c();
        t03 = space();
        div1 = element("div");
        create_component(accounts2.$$.fragment);
        t13 = space();
        div0 = element("div");
        create_component(table.$$.fragment);
        t22 = space();
        if (if_block1)
          if_block1.c();
        attr(div1, "class", "fixed-fullsize-container svelte-11pwv1r");
      },
      m(target, anchor) {
        if (if_block0)
          if_block0.m(target, anchor);
        insert(target, t03, anchor);
        insert(target, div1, anchor);
        mount_component(accounts2, div1, null);
        append(div1, t13);
        append(div1, div0);
        mount_component(table, div0, null);
        append(div1, t22);
        if (if_block1)
          if_block1.m(div1, null);
        current = true;
        if (!mounted) {
          dispose = listen(window, "keyup", ctx[4]);
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (ctx2[2]) {
          if (if_block0) {
            if_block0.p(ctx2, dirty);
            if (dirty & 4) {
              transition_in(if_block0, 1);
            }
          } else {
            if_block0 = create_if_block_17(ctx2);
            if_block0.c();
            transition_in(if_block0, 1);
            if_block0.m(t03.parentNode, t03);
          }
        } else if (if_block0) {
          group_outros();
          transition_out(if_block0, 1, 1, () => {
            if_block0 = null;
          });
          check_outros();
        }
        const accounts_changes = {};
        if (dirty & 8)
          accounts_changes.node = ctx2[3];
        accounts2.$set(accounts_changes);
        const table_changes = {};
        if (dirty & 1)
          table_changes.data = ctx2[0];
        if (!updating_selected && dirty & 2) {
          updating_selected = true;
          table_changes.selected = ctx2[1];
          add_flush_callback(() => updating_selected = false);
        }
        table.$set(table_changes);
        if (ctx2[1]) {
          if (if_block1) {
            if_block1.p(ctx2, dirty);
            if (dirty & 2) {
              transition_in(if_block1, 1);
            }
          } else {
            if_block1 = create_if_block8(ctx2);
            if_block1.c();
            transition_in(if_block1, 1);
            if_block1.m(div1, null);
          }
        } else if (if_block1) {
          group_outros();
          transition_out(if_block1, 1, 1, () => {
            if_block1 = null;
          });
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block0);
        transition_in(accounts2.$$.fragment, local);
        transition_in(table.$$.fragment, local);
        transition_in(if_block1);
        current = true;
      },
      o(local) {
        transition_out(if_block0);
        transition_out(accounts2.$$.fragment, local);
        transition_out(table.$$.fragment, local);
        transition_out(if_block1);
        current = false;
      },
      d(detaching) {
        if (if_block0)
          if_block0.d(detaching);
        if (detaching)
          detach(t03);
        if (detaching)
          detach(div1);
        destroy_component(accounts2);
        destroy_component(table);
        if (if_block1)
          if_block1.d();
        mounted = false;
        dispose();
      }
    };
  }
  function instance18($$self, $$props, $$invalidate) {
    let node;
    let {data} = $$props;
    let selected;
    let moving = null;
    function copyMoveable(doc) {
      return {
        account: doc.account,
        filename: doc.filename,
        newName: basename(doc.filename)
      };
    }
    function keyup(ev) {
      if (ev.key === "F2" && selected) {
        $$invalidate(2, moving = copyMoveable(selected));
      }
    }
    function drop2(ev) {
      $$invalidate(2, moving = copyMoveable(ev.detail));
    }
    async function move() {
      const moved = moving && await moveDocument(moving.filename, moving.account, moving.newName);
      if (moved) {
        $$invalidate(2, moving = null);
        router_default.reload();
      }
    }
    function accountinput_value_binding(value) {
      moving.account = value;
      $$invalidate(2, moving);
    }
    function input_input_handler() {
      moving.newName = this.value;
      $$invalidate(2, moving);
    }
    const func = () => {
      $$invalidate(2, moving = null);
    };
    function table_selected_binding(value) {
      selected = value;
      $$invalidate(1, selected);
    }
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(0, data = $$props2.data);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(3, node = stratify(new Set(data.map((e) => e.account)), (s) => s, (name) => ({name})));
      }
    };
    return [
      data,
      selected,
      moving,
      node,
      keyup,
      drop2,
      move,
      accountinput_value_binding,
      input_input_handler,
      func,
      table_selected_binding
    ];
  }
  var Documents = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance18, create_fragment18, safe_not_equal, {data: 0});
    }
  };
  var Documents_default = Documents;

  // src/editor/EditorMenu.svelte
  function get_each_context14(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[9] = list[i];
    return child_ctx;
  }
  function create_each_block14(ctx) {
    let li;
    let a;
    let t0_value = ctx[9] + "";
    let t03;
    let a_href_value;
    let t13;
    return {
      c() {
        li = element("li");
        a = element("a");
        t03 = text(t0_value);
        t13 = space();
        attr(a, "href", a_href_value = urlFor("editor", {file_path: ctx[9]}));
        attr(li, "class", "svelte-1hul25p");
        toggle_class(li, "selected", ctx[9] === ctx[1]);
      },
      m(target, anchor) {
        insert(target, li, anchor);
        append(li, a);
        append(a, t03);
        append(li, t13);
      },
      p(ctx2, dirty) {
        if (dirty & 1 && t0_value !== (t0_value = ctx2[9] + ""))
          set_data(t03, t0_value);
        if (dirty & 1 && a_href_value !== (a_href_value = urlFor("editor", {file_path: ctx2[9]}))) {
          attr(a, "href", a_href_value);
        }
        if (dirty & 3) {
          toggle_class(li, "selected", ctx2[9] === ctx2[1]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(li);
      }
    };
  }
  function create_fragment19(ctx) {
    let div;
    let ul2;
    let li0;
    let t0_value = _("File") + "";
    let t03;
    let t13;
    let ul0;
    let t22;
    let li5;
    let t3_value = _("Edit") + "";
    let t32;
    let t4;
    let ul1;
    let li1;
    let t5_value = _("Align Amounts") + "";
    let t5;
    let t6;
    let span0;
    let t122;
    let li2;
    let t13_value = _("Toggle Comment (selection)") + "";
    let t132;
    let t14;
    let span1;
    let t20;
    let li3;
    let t222;
    let li4;
    let t24;
    let current;
    let mounted;
    let dispose;
    let each_value = ctx[0];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block14(get_each_context14(ctx, each_value, i));
    }
    const default_slot_template = ctx[4].default;
    const default_slot = create_slot(default_slot_template, ctx, ctx[3], null);
    return {
      c() {
        div = element("div");
        ul2 = element("ul");
        li0 = element("li");
        t03 = text(t0_value);
        t13 = text("\xA0\u25BE\n\n      ");
        ul0 = element("ul");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        t22 = space();
        li5 = element("li");
        t32 = text(t3_value);
        t4 = text("\n      \xA0\u25BE\n      ");
        ul1 = element("ul");
        li1 = element("li");
        t5 = text(t5_value);
        t6 = space();
        span0 = element("span");
        span0.innerHTML = `<kbd>Ctrl</kbd> / <kbd>Cmd</kbd> + <kbd>d</kbd>`;
        t122 = space();
        li2 = element("li");
        t132 = text(t13_value);
        t14 = space();
        span1 = element("span");
        span1.innerHTML = `<kbd>Ctrl</kbd> / <kbd>Cmd</kbd> + <kbd>y</kbd>`;
        t20 = space();
        li3 = element("li");
        li3.textContent = `${_("Open all folds")}`;
        t222 = space();
        li4 = element("li");
        li4.textContent = `${_("Close all folds")}`;
        t24 = space();
        if (default_slot)
          default_slot.c();
        attr(ul0, "class", "svelte-1hul25p");
        attr(li0, "class", "svelte-1hul25p");
        attr(span0, "class", "svelte-1hul25p");
        attr(li1, "class", "svelte-1hul25p");
        attr(span1, "class", "svelte-1hul25p");
        attr(li2, "class", "svelte-1hul25p");
        attr(li3, "class", "svelte-1hul25p");
        attr(li4, "class", "svelte-1hul25p");
        attr(ul1, "class", "svelte-1hul25p");
        attr(li5, "class", "svelte-1hul25p");
        attr(ul2, "class", "dropdown svelte-1hul25p");
        attr(div, "class", "fieldset svelte-1hul25p");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, ul2);
        append(ul2, li0);
        append(li0, t03);
        append(li0, t13);
        append(li0, ul0);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(ul0, null);
        }
        append(ul2, t22);
        append(ul2, li5);
        append(li5, t32);
        append(li5, t4);
        append(li5, ul1);
        append(ul1, li1);
        append(li1, t5);
        append(li1, t6);
        append(li1, span0);
        append(ul1, t122);
        append(ul1, li2);
        append(li2, t132);
        append(li2, t14);
        append(li2, span1);
        append(ul1, t20);
        append(ul1, li3);
        append(ul1, t222);
        append(ul1, li4);
        append(div, t24);
        if (default_slot) {
          default_slot.m(div, null);
        }
        current = true;
        if (!mounted) {
          dispose = [
            listen(li1, "click", ctx[5]),
            listen(li2, "click", ctx[6]),
            listen(li3, "click", ctx[7]),
            listen(li4, "click", ctx[8])
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 3) {
          each_value = ctx2[0];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context14(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block14(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(ul0, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        if (default_slot) {
          if (default_slot.p && dirty & 8) {
            update_slot(default_slot, default_slot_template, ctx2, ctx2[3], dirty, null, null);
          }
        }
      },
      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);
        destroy_each(each_blocks, detaching);
        if (default_slot)
          default_slot.d(detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance19($$self, $$props, $$invalidate) {
    let {$$slots: slots = {}, $$scope} = $$props;
    let {sources} = $$props;
    let {file_path} = $$props;
    const dispatch = createEventDispatcher();
    const click_handler = () => dispatch("command", "favaFormat");
    const click_handler_1 = () => dispatch("command", "favaToggleComment");
    const click_handler_2 = () => dispatch("command", "unfoldAll");
    const click_handler_3 = () => dispatch("command", "foldAll");
    $$self.$$set = ($$props2) => {
      if ("sources" in $$props2)
        $$invalidate(0, sources = $$props2.sources);
      if ("file_path" in $$props2)
        $$invalidate(1, file_path = $$props2.file_path);
      if ("$$scope" in $$props2)
        $$invalidate(3, $$scope = $$props2.$$scope);
    };
    return [
      sources,
      file_path,
      dispatch,
      $$scope,
      slots,
      click_handler,
      click_handler_1,
      click_handler_2,
      click_handler_3
    ];
  }
  var EditorMenu = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance19, create_fragment19, safe_not_equal, {sources: 0, file_path: 1});
    }
  };
  var EditorMenu_default = EditorMenu;

  // src/editor/SaveButton.svelte
  function create_fragment20(ctx) {
    let button;
    let t;
    let button_disabled_value;
    let button_title_value;
    return {
      c() {
        button = element("button");
        t = text(ctx[1]);
        button.disabled = button_disabled_value = !ctx[0];
        attr(button, "title", button_title_value = "" + (_("Save") + " (Ctrl/Cmd+s)"));
      },
      m(target, anchor) {
        insert(target, button, anchor);
        append(button, t);
      },
      p(ctx2, [dirty]) {
        if (dirty & 2)
          set_data(t, ctx2[1]);
        if (dirty & 1 && button_disabled_value !== (button_disabled_value = !ctx2[0])) {
          button.disabled = button_disabled_value;
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(button);
      }
    };
  }
  function instance20($$self, $$props, $$invalidate) {
    let buttonContent;
    let {changed} = $$props;
    let {saving} = $$props;
    $$self.$$set = ($$props2) => {
      if ("changed" in $$props2)
        $$invalidate(0, changed = $$props2.changed);
      if ("saving" in $$props2)
        $$invalidate(2, saving = $$props2.saving);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 4) {
        $:
          $$invalidate(1, buttonContent = saving ? _("Saving...") : _("Save"));
      }
    };
    return [changed, buttonContent, saving];
  }
  var SaveButton = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance20, create_fragment20, safe_not_equal, {changed: 0, saving: 2});
    }
  };
  var SaveButton_default = SaveButton;

  // src/editor/SourceEditor.svelte
  function create_default_slot3(ctx) {
    let savebutton;
    let current;
    savebutton = new SaveButton_default({
      props: {
        changed: ctx[0],
        saving: ctx[3]
      }
    });
    return {
      c() {
        create_component(savebutton.$$.fragment);
      },
      m(target, anchor) {
        mount_component(savebutton, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const savebutton_changes = {};
        if (dirty & 1)
          savebutton_changes.changed = ctx2[0];
        if (dirty & 8)
          savebutton_changes.saving = ctx2[3];
        savebutton.$set(savebutton_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(savebutton.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(savebutton.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(savebutton, detaching);
      }
    };
  }
  function create_fragment21(ctx) {
    let form;
    let editormenu;
    let t;
    let div;
    let sourceEditor_action;
    let current;
    let mounted;
    let dispose;
    editormenu = new EditorMenu_default({
      props: {
        file_path: ctx[1],
        sources: ctx[2],
        $$slots: {default: [create_default_slot3]},
        $$scope: {ctx}
      }
    });
    editormenu.$on("command", ctx[6]);
    return {
      c() {
        form = element("form");
        create_component(editormenu.$$.fragment);
        t = space();
        div = element("div");
        attr(div, "class", "svelte-9k35va");
        attr(form, "class", "fixed-fullsize-container svelte-9k35va");
      },
      m(target, anchor) {
        insert(target, form, anchor);
        mount_component(editormenu, form, null);
        append(form, t);
        append(form, div);
        current = true;
        if (!mounted) {
          dispose = [
            action_destroyer(sourceEditor_action = ctx[5].call(null, div)),
            listen(form, "submit", prevent_default(ctx[4]))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        const editormenu_changes = {};
        if (dirty & 2)
          editormenu_changes.file_path = ctx2[1];
        if (dirty & 4)
          editormenu_changes.sources = ctx2[2];
        if (dirty & 4105) {
          editormenu_changes.$$scope = {dirty, ctx: ctx2};
        }
        editormenu.$set(editormenu_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(editormenu.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(editormenu.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(form);
        destroy_component(editormenu);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance21($$self, $$props, $$invalidate) {
    let {data} = $$props;
    let editor;
    let changed = false;
    let value = "";
    let file_path = "";
    let sha256sum = "";
    let sources = [];
    let saving = false;
    async function save() {
      if (!editor) {
        return;
      }
      $$invalidate(3, saving = true);
      try {
        sha256sum = await put("source", {file_path, source: value, sha256sum});
        $$invalidate(0, changed = false);
        editor.focus();
        editor.getDoc().markClean();
        errorCount.set(await get("errors"));
      } catch (error) {
        notify(error, "error");
      } finally {
        $$invalidate(3, saving = false);
      }
    }
    function checkEditorChanges() {
      if (editor && !editor.getDoc().isClean()) {
        return "There are unsaved changes. Are you sure you want to leave?";
      }
      return null;
    }
    onMount(() => {
      sha256sum = data.sha256sum;
      $$invalidate(1, file_path = data.file_path);
      $$invalidate(2, sources = data.sources);
      const unbind = [
        ...["Control+s", "Meta+s"].map((key) => bindKey(key, (event) => {
          event.preventDefault();
          save();
        })),
        ...["Control+d", "Meta+d"].map((key) => bindKey(key, (event) => {
          event.preventDefault();
          editor?.execCommand("favaFormat");
        }))
      ];
      router_default.interruptHandlers.add(checkEditorChanges);
      return () => {
        router_default.interruptHandlers.delete(checkEditorChanges);
        unbind.forEach((u) => u());
      };
    });
    function sourceEditor(div) {
      $$invalidate(9, value = data.source);
      const options = {
        ...sourceEditorOptions(save),
        autofocus: true,
        value
      };
      $$invalidate(8, editor = import_codemirror7.default(div, options));
      initSourceEditor(editor);
      editor.on("changes", (cm) => {
        $$invalidate(9, value = cm.getValue());
        $$invalidate(0, changed = !cm.getDoc().isClean());
      });
    }
    function command(ev) {
      editor?.execCommand(ev.detail);
    }
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(7, data = $$props2.data);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 768) {
        $:
          if (editor && value !== editor.getValue()) {
            editor.setValue(value);
          }
      }
    };
    return [
      changed,
      file_path,
      sources,
      saving,
      save,
      sourceEditor,
      command,
      data,
      editor,
      value
    ];
  }
  var SourceEditor = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance21, create_fragment21, safe_not_equal, {data: 7});
    }
  };
  var SourceEditor_default = SourceEditor;

  // src/header/FilterForm.svelte
  function create_fragment22(ctx) {
    let form;
    let autocompleteinput0;
    let updating_value;
    let t03;
    let autocompleteinput1;
    let updating_value_1;
    let t13;
    let autocompleteinput2;
    let updating_value_2;
    let t22;
    let button;
    let current;
    let mounted;
    let dispose;
    function autocompleteinput0_value_binding(value) {
      ctx[10].call(null, value);
    }
    let autocompleteinput0_props = {
      placeholder: _("Time"),
      suggestions: ctx[4],
      key: "f t",
      clearButton: true,
      setSize: true
    };
    if (ctx[2] !== void 0) {
      autocompleteinput0_props.value = ctx[2];
    }
    autocompleteinput0 = new AutocompleteInput_default({props: autocompleteinput0_props});
    binding_callbacks.push(() => bind(autocompleteinput0, "value", autocompleteinput0_value_binding));
    autocompleteinput0.$on("blur", ctx[6]);
    autocompleteinput0.$on("select", ctx[6]);
    function autocompleteinput1_value_binding(value) {
      ctx[11].call(null, value);
    }
    let autocompleteinput1_props = {
      placeholder: _("Account"),
      suggestions: ctx[5],
      key: "f a",
      clearButton: true,
      setSize: true
    };
    if (ctx[0] !== void 0) {
      autocompleteinput1_props.value = ctx[0];
    }
    autocompleteinput1 = new AutocompleteInput_default({props: autocompleteinput1_props});
    binding_callbacks.push(() => bind(autocompleteinput1, "value", autocompleteinput1_value_binding));
    autocompleteinput1.$on("blur", ctx[6]);
    autocompleteinput1.$on("select", ctx[6]);
    function autocompleteinput2_value_binding(value) {
      ctx[12].call(null, value);
    }
    let autocompleteinput2_props = {
      placeholder: _("Filter by tag, payee, ..."),
      suggestions: ctx[3],
      key: "f f",
      clearButton: true,
      setSize: true,
      valueExtractor,
      valueSelector
    };
    if (ctx[1] !== void 0) {
      autocompleteinput2_props.value = ctx[1];
    }
    autocompleteinput2 = new AutocompleteInput_default({props: autocompleteinput2_props});
    binding_callbacks.push(() => bind(autocompleteinput2, "value", autocompleteinput2_value_binding));
    autocompleteinput2.$on("blur", ctx[6]);
    autocompleteinput2.$on("select", ctx[6]);
    return {
      c() {
        form = element("form");
        create_component(autocompleteinput0.$$.fragment);
        t03 = space();
        create_component(autocompleteinput1.$$.fragment);
        t13 = space();
        create_component(autocompleteinput2.$$.fragment);
        t22 = space();
        button = element("button");
        attr(button, "type", "submit");
        attr(button, "class", "svelte-1m3xpwc");
        attr(form, "class", "svelte-1m3xpwc");
      },
      m(target, anchor) {
        insert(target, form, anchor);
        mount_component(autocompleteinput0, form, null);
        append(form, t03);
        mount_component(autocompleteinput1, form, null);
        append(form, t13);
        mount_component(autocompleteinput2, form, null);
        append(form, t22);
        append(form, button);
        current = true;
        if (!mounted) {
          dispose = listen(form, "submit", prevent_default(ctx[6]));
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        const autocompleteinput0_changes = {};
        if (dirty & 16)
          autocompleteinput0_changes.suggestions = ctx2[4];
        if (!updating_value && dirty & 4) {
          updating_value = true;
          autocompleteinput0_changes.value = ctx2[2];
          add_flush_callback(() => updating_value = false);
        }
        autocompleteinput0.$set(autocompleteinput0_changes);
        const autocompleteinput1_changes = {};
        if (dirty & 32)
          autocompleteinput1_changes.suggestions = ctx2[5];
        if (!updating_value_1 && dirty & 1) {
          updating_value_1 = true;
          autocompleteinput1_changes.value = ctx2[0];
          add_flush_callback(() => updating_value_1 = false);
        }
        autocompleteinput1.$set(autocompleteinput1_changes);
        const autocompleteinput2_changes = {};
        if (dirty & 8)
          autocompleteinput2_changes.suggestions = ctx2[3];
        if (!updating_value_2 && dirty & 2) {
          updating_value_2 = true;
          autocompleteinput2_changes.value = ctx2[1];
          add_flush_callback(() => updating_value_2 = false);
        }
        autocompleteinput2.$set(autocompleteinput2_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(autocompleteinput0.$$.fragment, local);
        transition_in(autocompleteinput1.$$.fragment, local);
        transition_in(autocompleteinput2.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(autocompleteinput0.$$.fragment, local);
        transition_out(autocompleteinput1.$$.fragment, local);
        transition_out(autocompleteinput2.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(form);
        destroy_component(autocompleteinput0);
        destroy_component(autocompleteinput1);
        destroy_component(autocompleteinput2);
        mounted = false;
        dispose();
      }
    };
  }
  function valueExtractor(value, input) {
    const match = value.slice(0, input.selectionStart || void 0).match(/\S*$/);
    return match ? match[0] : value;
  }
  function valueSelector(value, input) {
    const selectionStart = input.selectionStart || 0;
    const match = input.value.slice(0, selectionStart).match(/\S*$/);
    return match ? `${input.value.slice(0, selectionStart - match[0].length)}${value}${input.value.slice(selectionStart)}` : value;
  }
  function instance22($$self, $$props, $$invalidate) {
    let fql_filter_suggestions;
    let $tags;
    let $links;
    let $payees;
    let $years;
    let $accounts;
    component_subscribe($$self, tags, ($$value) => $$invalidate(7, $tags = $$value));
    component_subscribe($$self, links, ($$value) => $$invalidate(8, $links = $$value));
    component_subscribe($$self, payees, ($$value) => $$invalidate(9, $payees = $$value));
    component_subscribe($$self, years2, ($$value) => $$invalidate(4, $years = $$value));
    component_subscribe($$self, accounts, ($$value) => $$invalidate(5, $accounts = $$value));
    let account_filter_value = "";
    let fql_filter_value = "";
    let time_filter_value = "";
    account_filter.subscribe((v) => {
      $$invalidate(0, account_filter_value = v);
    });
    fql_filter.subscribe((v) => {
      $$invalidate(1, fql_filter_value = v);
    });
    time_filter.subscribe((v) => {
      $$invalidate(2, time_filter_value = v);
    });
    function submit() {
      account_filter.set(account_filter_value);
      fql_filter.set(fql_filter_value);
      time_filter.set(time_filter_value);
    }
    function autocompleteinput0_value_binding(value) {
      time_filter_value = value;
      $$invalidate(2, time_filter_value);
    }
    function autocompleteinput1_value_binding(value) {
      account_filter_value = value;
      $$invalidate(0, account_filter_value);
    }
    function autocompleteinput2_value_binding(value) {
      fql_filter_value = value;
      $$invalidate(1, fql_filter_value);
    }
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 896) {
        $:
          $$invalidate(3, fql_filter_suggestions = [
            ...$tags.map((tag) => `#${tag}`),
            ...$links.map((link) => `^${link}`),
            ...$payees.map((payee) => `payee:"${payee}"`)
          ]);
      }
    };
    return [
      account_filter_value,
      fql_filter_value,
      time_filter_value,
      fql_filter_suggestions,
      $years,
      $accounts,
      submit,
      $tags,
      $links,
      $payees,
      autocompleteinput0_value_binding,
      autocompleteinput1_value_binding,
      autocompleteinput2_value_binding
    ];
  }
  var FilterForm = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance22, create_fragment22, safe_not_equal, {});
    }
  };
  var FilterForm_default = FilterForm;

  // src/import/helpers.ts
  function isDuplicate(e) {
    return !!e.meta.__duplicate__;
  }
  function newFilename(date3, basename2) {
    if (/^\d{4}-\d{2}-\d{2}/.test(basename2)) {
      return basename2;
    }
    if (!date3 || !basename2) {
      return "";
    }
    return `${date3} ${basename2}`;
  }
  function preprocessData(arr) {
    const today = todayAsString();
    return arr.map((file) => {
      const importers = file.importers.map(({account: account2, importer_name, date: date3, name}) => ({
        account: account2,
        importer_name,
        newName: newFilename(date3, name)
      }));
      if (importers.length === 0) {
        const newName = newFilename(today, file.basename);
        importers.push({account: "", newName, importer_name: ""});
      }
      return {...file, importers};
    });
  }

  // src/entry-forms/AddMetadataButton.svelte
  function create_fragment23(ctx) {
    let button;
    let t;
    let button_tabindex_value;
    let button_title_value;
    let mounted;
    let dispose;
    return {
      c() {
        button = element("button");
        t = text("m");
        attr(button, "class", "muted round");
        attr(button, "type", "button");
        attr(button, "tabindex", button_tabindex_value = -1);
        attr(button, "title", button_title_value = _("Add metadata"));
      },
      m(target, anchor) {
        insert(target, button, anchor);
        append(button, t);
        if (!mounted) {
          dispose = listen(button, "click", ctx[0]);
          mounted = true;
        }
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(button);
        mounted = false;
        dispose();
      }
    };
  }
  function instance23($$self, $$props, $$invalidate) {
    let {meta} = $$props;
    function addMetadata() {
      $$invalidate(1, meta[""] = "", meta);
      $$invalidate(1, meta);
    }
    $$self.$$set = ($$props2) => {
      if ("meta" in $$props2)
        $$invalidate(1, meta = $$props2.meta);
    };
    return [addMetadata, meta];
  }
  var AddMetadataButton = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance23, create_fragment23, safe_not_equal, {meta: 1});
    }
  };
  var AddMetadataButton_default = AddMetadataButton;

  // src/entry-forms/EntryMetadata.svelte
  function get_each_context15(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[8] = list[i];
    child_ctx[9] = list;
    child_ctx[10] = i;
    return child_ctx;
  }
  function create_if_block9(ctx) {
    let button;
    let t;
    let button_title_value;
    let mounted;
    let dispose;
    return {
      c() {
        button = element("button");
        t = text("+");
        attr(button, "class", "muted round");
        attr(button, "type", "button");
        attr(button, "title", button_title_value = _("Add metadata"));
      },
      m(target, anchor) {
        insert(target, button, anchor);
        append(button, t);
        if (!mounted) {
          dispose = listen(button, "click", ctx[4]);
          mounted = true;
        }
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(button);
        mounted = false;
        dispose();
      }
    };
  }
  function create_each_block15(ctx) {
    let div;
    let button;
    let button_tabindex_value;
    let t13;
    let input0;
    let input0_placeholder_value;
    let input0_value_value;
    let t22;
    let input1;
    let input1_placeholder_value;
    let t32;
    let t4;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[5](ctx[8]);
    }
    function change_handler(...args) {
      return ctx[6](ctx[8], ...args);
    }
    function input1_input_handler() {
      ctx[7].call(input1, ctx[8]);
    }
    let if_block = ctx[10] === ctx[1].length - 1 && create_if_block9(ctx);
    return {
      c() {
        div = element("div");
        button = element("button");
        button.textContent = "\xD7";
        t13 = space();
        input0 = element("input");
        t22 = space();
        input1 = element("input");
        t32 = space();
        if (if_block)
          if_block.c();
        t4 = space();
        attr(button, "class", "muted round remove-row");
        attr(button, "type", "button");
        attr(button, "tabindex", button_tabindex_value = -1);
        attr(input0, "type", "text");
        attr(input0, "class", "key svelte-1v6bu4l");
        attr(input0, "placeholder", input0_placeholder_value = _("Key"));
        input0.value = input0_value_value = ctx[8];
        input0.required = true;
        attr(input1, "type", "text");
        attr(input1, "class", "value svelte-1v6bu4l");
        attr(input1, "placeholder", input1_placeholder_value = _("Value"));
        attr(div, "class", "flex-row svelte-1v6bu4l");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, button);
        append(div, t13);
        append(div, input0);
        append(div, t22);
        append(div, input1);
        set_input_value(input1, ctx[0][ctx[8]]);
        append(div, t32);
        if (if_block)
          if_block.m(div, null);
        append(div, t4);
        if (!mounted) {
          dispose = [
            listen(button, "click", click_handler),
            listen(input0, "change", change_handler),
            listen(input1, "input", input1_input_handler)
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 2 && input0_value_value !== (input0_value_value = ctx[8]) && input0.value !== input0_value_value) {
          input0.value = input0_value_value;
        }
        if (dirty & 3 && input1.value !== ctx[0][ctx[8]]) {
          set_input_value(input1, ctx[0][ctx[8]]);
        }
        if (ctx[10] === ctx[1].length - 1) {
          if (if_block) {
            if_block.p(ctx, dirty);
          } else {
            if_block = create_if_block9(ctx);
            if_block.c();
            if_block.m(div, t4);
          }
        } else if (if_block) {
          if_block.d(1);
          if_block = null;
        }
      },
      d(detaching) {
        if (detaching)
          detach(div);
        if (if_block)
          if_block.d();
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_fragment24(ctx) {
    let each_1_anchor;
    let each_value = ctx[1];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block15(get_each_context15(ctx, each_value, i));
    }
    return {
      c() {
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        each_1_anchor = empty();
      },
      m(target, anchor) {
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(target, anchor);
        }
        insert(target, each_1_anchor, anchor);
      },
      p(ctx2, [dirty]) {
        if (dirty & 31) {
          each_value = ctx2[1];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context15(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block15(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        destroy_each(each_blocks, detaching);
        if (detaching)
          detach(each_1_anchor);
      }
    };
  }
  function instance24($$self, $$props, $$invalidate) {
    let metakeys;
    let {meta} = $$props;
    function removeMetadata(metakey) {
      delete meta[metakey];
      $$invalidate(0, meta);
    }
    function updateMetakey(currentKey, newKey) {
      $$invalidate(0, meta = Object.keys(meta).reduce((m, key) => {
        if (key === currentKey) {
          m[newKey] = meta[currentKey];
        } else {
          m[key] = meta[key];
        }
        return m;
      }, {}));
    }
    function addMetadata() {
      $$invalidate(0, meta[""] = "", meta);
      $$invalidate(0, meta);
    }
    const click_handler = (metakey) => removeMetadata(metakey);
    const change_handler = (metakey, event) => {
      updateMetakey(metakey, event.target.value);
    };
    function input1_input_handler(metakey) {
      meta[metakey] = this.value;
      $$invalidate(0, meta);
      $$invalidate(1, metakeys), $$invalidate(0, meta);
    }
    $$self.$$set = ($$props2) => {
      if ("meta" in $$props2)
        $$invalidate(0, meta = $$props2.meta);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(1, metakeys = Object.keys(meta).filter((key) => !key.startsWith("_") && key !== "filename" && key !== "lineno"));
      }
    };
    return [
      meta,
      metakeys,
      removeMetadata,
      updateMetakey,
      addMetadata,
      click_handler,
      change_handler,
      input1_input_handler
    ];
  }
  var EntryMetadata = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance24, create_fragment24, safe_not_equal, {meta: 0});
    }
  };
  var EntryMetadata_default = EntryMetadata;

  // src/entry-forms/Balance.svelte
  function create_fragment25(ctx) {
    let div1;
    let div0;
    let input0;
    let t03;
    let h4;
    let t22;
    let accountinput;
    let updating_value;
    let t32;
    let input1;
    let input1_placeholder_value;
    let input1_size_value;
    let t4;
    let autocompleteinput;
    let updating_value_1;
    let t5;
    let addmetadatabutton;
    let updating_meta;
    let t6;
    let entrymetadata;
    let updating_meta_1;
    let current;
    let mounted;
    let dispose;
    function accountinput_value_binding(value) {
      ctx[3].call(null, value);
    }
    let accountinput_props = {className: "grow"};
    if (ctx[0].account !== void 0) {
      accountinput_props.value = ctx[0].account;
    }
    accountinput = new AccountInput_default({props: accountinput_props});
    binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
    function autocompleteinput_value_binding(value) {
      ctx[5].call(null, value);
    }
    let autocompleteinput_props = {
      className: "currency",
      placeholder: _("Currency"),
      suggestions: ctx[1]
    };
    if (ctx[0].amount.currency !== void 0) {
      autocompleteinput_props.value = ctx[0].amount.currency;
    }
    autocompleteinput = new AutocompleteInput_default({props: autocompleteinput_props});
    binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
    function addmetadatabutton_meta_binding(value) {
      ctx[6].call(null, value);
    }
    let addmetadatabutton_props = {};
    if (ctx[0].meta !== void 0) {
      addmetadatabutton_props.meta = ctx[0].meta;
    }
    addmetadatabutton = new AddMetadataButton_default({props: addmetadatabutton_props});
    binding_callbacks.push(() => bind(addmetadatabutton, "meta", addmetadatabutton_meta_binding));
    function entrymetadata_meta_binding(value) {
      ctx[7].call(null, value);
    }
    let entrymetadata_props = {};
    if (ctx[0].meta !== void 0) {
      entrymetadata_props.meta = ctx[0].meta;
    }
    entrymetadata = new EntryMetadata_default({props: entrymetadata_props});
    binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
    return {
      c() {
        div1 = element("div");
        div0 = element("div");
        input0 = element("input");
        t03 = space();
        h4 = element("h4");
        h4.textContent = `${_("Balance")}`;
        t22 = space();
        create_component(accountinput.$$.fragment);
        t32 = space();
        input1 = element("input");
        t4 = space();
        create_component(autocompleteinput.$$.fragment);
        t5 = space();
        create_component(addmetadatabutton.$$.fragment);
        t6 = space();
        create_component(entrymetadata.$$.fragment);
        attr(input0, "type", "date");
        input0.required = true;
        attr(input1, "type", "tel");
        attr(input1, "pattern", "-?[0-9.,]*");
        attr(input1, "placeholder", input1_placeholder_value = _("Number"));
        attr(input1, "size", input1_size_value = 10);
        attr(div0, "class", "flex-row svelte-unorr4");
        attr(div1, "class", "svelte-unorr4");
      },
      m(target, anchor) {
        insert(target, div1, anchor);
        append(div1, div0);
        append(div0, input0);
        set_input_value(input0, ctx[0].date);
        append(div0, t03);
        append(div0, h4);
        append(div0, t22);
        mount_component(accountinput, div0, null);
        append(div0, t32);
        append(div0, input1);
        set_input_value(input1, ctx[0].amount.number);
        append(div0, t4);
        mount_component(autocompleteinput, div0, null);
        append(div0, t5);
        mount_component(addmetadatabutton, div0, null);
        append(div1, t6);
        mount_component(entrymetadata, div1, null);
        current = true;
        if (!mounted) {
          dispose = [
            listen(input0, "input", ctx[2]),
            listen(input1, "input", ctx[4])
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 1) {
          set_input_value(input0, ctx2[0].date);
        }
        const accountinput_changes = {};
        if (!updating_value && dirty & 1) {
          updating_value = true;
          accountinput_changes.value = ctx2[0].account;
          add_flush_callback(() => updating_value = false);
        }
        accountinput.$set(accountinput_changes);
        if (dirty & 1) {
          set_input_value(input1, ctx2[0].amount.number);
        }
        const autocompleteinput_changes = {};
        if (dirty & 2)
          autocompleteinput_changes.suggestions = ctx2[1];
        if (!updating_value_1 && dirty & 1) {
          updating_value_1 = true;
          autocompleteinput_changes.value = ctx2[0].amount.currency;
          add_flush_callback(() => updating_value_1 = false);
        }
        autocompleteinput.$set(autocompleteinput_changes);
        const addmetadatabutton_changes = {};
        if (!updating_meta && dirty & 1) {
          updating_meta = true;
          addmetadatabutton_changes.meta = ctx2[0].meta;
          add_flush_callback(() => updating_meta = false);
        }
        addmetadatabutton.$set(addmetadatabutton_changes);
        const entrymetadata_changes = {};
        if (!updating_meta_1 && dirty & 1) {
          updating_meta_1 = true;
          entrymetadata_changes.meta = ctx2[0].meta;
          add_flush_callback(() => updating_meta_1 = false);
        }
        entrymetadata.$set(entrymetadata_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(accountinput.$$.fragment, local);
        transition_in(autocompleteinput.$$.fragment, local);
        transition_in(addmetadatabutton.$$.fragment, local);
        transition_in(entrymetadata.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accountinput.$$.fragment, local);
        transition_out(autocompleteinput.$$.fragment, local);
        transition_out(addmetadatabutton.$$.fragment, local);
        transition_out(entrymetadata.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div1);
        destroy_component(accountinput);
        destroy_component(autocompleteinput);
        destroy_component(addmetadatabutton);
        destroy_component(entrymetadata);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance25($$self, $$props, $$invalidate) {
    let $currencies;
    component_subscribe($$self, currencies, ($$value) => $$invalidate(1, $currencies = $$value));
    let {entry} = $$props;
    function input0_input_handler() {
      entry.date = this.value;
      $$invalidate(0, entry);
    }
    function accountinput_value_binding(value) {
      entry.account = value;
      $$invalidate(0, entry);
    }
    function input1_input_handler() {
      entry.amount.number = this.value;
      $$invalidate(0, entry);
    }
    function autocompleteinput_value_binding(value) {
      entry.amount.currency = value;
      $$invalidate(0, entry);
    }
    function addmetadatabutton_meta_binding(value) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
    function entrymetadata_meta_binding(value) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
    $$self.$$set = ($$props2) => {
      if ("entry" in $$props2)
        $$invalidate(0, entry = $$props2.entry);
    };
    return [
      entry,
      $currencies,
      input0_input_handler,
      accountinput_value_binding,
      input1_input_handler,
      autocompleteinput_value_binding,
      addmetadatabutton_meta_binding,
      entrymetadata_meta_binding
    ];
  }
  var Balance2 = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance25, create_fragment25, safe_not_equal, {entry: 0});
    }
  };
  var Balance_default = Balance2;

  // src/entry-forms/Note.svelte
  function create_fragment26(ctx) {
    let div1;
    let div0;
    let input;
    let t03;
    let h4;
    let t22;
    let accountinput;
    let updating_value;
    let t32;
    let addmetadatabutton;
    let updating_meta;
    let t4;
    let textarea;
    let textarea_rows_value;
    let t5;
    let entrymetadata;
    let updating_meta_1;
    let current;
    let mounted;
    let dispose;
    function accountinput_value_binding(value) {
      ctx[2].call(null, value);
    }
    let accountinput_props = {className: "grow"};
    if (ctx[0].account !== void 0) {
      accountinput_props.value = ctx[0].account;
    }
    accountinput = new AccountInput_default({props: accountinput_props});
    binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
    function addmetadatabutton_meta_binding(value) {
      ctx[3].call(null, value);
    }
    let addmetadatabutton_props = {};
    if (ctx[0].meta !== void 0) {
      addmetadatabutton_props.meta = ctx[0].meta;
    }
    addmetadatabutton = new AddMetadataButton_default({props: addmetadatabutton_props});
    binding_callbacks.push(() => bind(addmetadatabutton, "meta", addmetadatabutton_meta_binding));
    function entrymetadata_meta_binding(value) {
      ctx[5].call(null, value);
    }
    let entrymetadata_props = {};
    if (ctx[0].meta !== void 0) {
      entrymetadata_props.meta = ctx[0].meta;
    }
    entrymetadata = new EntryMetadata_default({props: entrymetadata_props});
    binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
    return {
      c() {
        div1 = element("div");
        div0 = element("div");
        input = element("input");
        t03 = space();
        h4 = element("h4");
        h4.textContent = `${_("Note")}`;
        t22 = space();
        create_component(accountinput.$$.fragment);
        t32 = space();
        create_component(addmetadatabutton.$$.fragment);
        t4 = space();
        textarea = element("textarea");
        t5 = space();
        create_component(entrymetadata.$$.fragment);
        attr(input, "type", "date");
        attr(input, "name", "date");
        input.required = true;
        attr(div0, "class", "flex-row");
        attr(textarea, "name", "comment");
        attr(textarea, "rows", textarea_rows_value = 2);
        attr(textarea, "class", "svelte-s9o1z4");
      },
      m(target, anchor) {
        insert(target, div1, anchor);
        append(div1, div0);
        append(div0, input);
        set_input_value(input, ctx[0].date);
        append(div0, t03);
        append(div0, h4);
        append(div0, t22);
        mount_component(accountinput, div0, null);
        append(div0, t32);
        mount_component(addmetadatabutton, div0, null);
        append(div1, t4);
        append(div1, textarea);
        set_input_value(textarea, ctx[0].comment);
        append(div1, t5);
        mount_component(entrymetadata, div1, null);
        current = true;
        if (!mounted) {
          dispose = [
            listen(input, "input", ctx[1]),
            listen(textarea, "input", ctx[4])
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 1) {
          set_input_value(input, ctx2[0].date);
        }
        const accountinput_changes = {};
        if (!updating_value && dirty & 1) {
          updating_value = true;
          accountinput_changes.value = ctx2[0].account;
          add_flush_callback(() => updating_value = false);
        }
        accountinput.$set(accountinput_changes);
        const addmetadatabutton_changes = {};
        if (!updating_meta && dirty & 1) {
          updating_meta = true;
          addmetadatabutton_changes.meta = ctx2[0].meta;
          add_flush_callback(() => updating_meta = false);
        }
        addmetadatabutton.$set(addmetadatabutton_changes);
        if (dirty & 1) {
          set_input_value(textarea, ctx2[0].comment);
        }
        const entrymetadata_changes = {};
        if (!updating_meta_1 && dirty & 1) {
          updating_meta_1 = true;
          entrymetadata_changes.meta = ctx2[0].meta;
          add_flush_callback(() => updating_meta_1 = false);
        }
        entrymetadata.$set(entrymetadata_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(accountinput.$$.fragment, local);
        transition_in(addmetadatabutton.$$.fragment, local);
        transition_in(entrymetadata.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accountinput.$$.fragment, local);
        transition_out(addmetadatabutton.$$.fragment, local);
        transition_out(entrymetadata.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div1);
        destroy_component(accountinput);
        destroy_component(addmetadatabutton);
        destroy_component(entrymetadata);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance26($$self, $$props, $$invalidate) {
    let {entry} = $$props;
    function input_input_handler() {
      entry.date = this.value;
      $$invalidate(0, entry);
    }
    function accountinput_value_binding(value) {
      entry.account = value;
      $$invalidate(0, entry);
    }
    function addmetadatabutton_meta_binding(value) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
    function textarea_input_handler() {
      entry.comment = this.value;
      $$invalidate(0, entry);
    }
    function entrymetadata_meta_binding(value) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
    $$self.$$set = ($$props2) => {
      if ("entry" in $$props2)
        $$invalidate(0, entry = $$props2.entry);
    };
    return [
      entry,
      input_input_handler,
      accountinput_value_binding,
      addmetadatabutton_meta_binding,
      textarea_input_handler,
      entrymetadata_meta_binding
    ];
  }
  var Note2 = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance26, create_fragment26, safe_not_equal, {entry: 0});
    }
  };
  var Note_default = Note2;

  // src/entry-forms/Posting.svelte
  function create_fragment27(ctx) {
    let div;
    let button0;
    let button0_tabindex_value;
    let t13;
    let accountinput;
    let updating_value;
    let t22;
    let autocompleteinput;
    let updating_value_1;
    let t32;
    let button1;
    let t4;
    let button1_title_value;
    let current;
    let mounted;
    let dispose;
    function accountinput_value_binding(value) {
      ctx[15].call(null, value);
    }
    let accountinput_props = {
      className: "grow",
      suggestions: ctx[1]
    };
    if (ctx[0].account !== void 0) {
      accountinput_props.value = ctx[0].account;
    }
    accountinput = new AccountInput_default({props: accountinput_props});
    binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
    function autocompleteinput_value_binding(value) {
      ctx[16].call(null, value);
    }
    let autocompleteinput_props = {
      className: "amount",
      placeholder: _("Amount"),
      suggestions: ctx[4]
    };
    if (ctx[0].amount !== void 0) {
      autocompleteinput_props.value = ctx[0].amount;
    }
    autocompleteinput = new AutocompleteInput_default({props: autocompleteinput_props});
    binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
    return {
      c() {
        div = element("div");
        button0 = element("button");
        button0.textContent = "\xD7";
        t13 = space();
        create_component(accountinput.$$.fragment);
        t22 = space();
        create_component(autocompleteinput.$$.fragment);
        t32 = space();
        button1 = element("button");
        t4 = text("+");
        attr(button0, "class", "muted round remove-row svelte-164exxa");
        attr(button0, "type", "button");
        attr(button0, "tabindex", button0_tabindex_value = -1);
        attr(button1, "class", "muted round add-row svelte-164exxa");
        attr(button1, "type", "button");
        attr(button1, "title", button1_title_value = _("Add posting"));
        attr(div, "class", "flex-row svelte-164exxa");
        attr(div, "draggable", ctx[3]);
        toggle_class(div, "drag", ctx[2]);
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, button0);
        append(div, t13);
        mount_component(accountinput, div, null);
        append(div, t22);
        mount_component(autocompleteinput, div, null);
        append(div, t32);
        append(div, button1);
        append(button1, t4);
        current = true;
        if (!mounted) {
          dispose = [
            listen(button0, "click", ctx[14]),
            listen(button1, "click", ctx[17]),
            listen(div, "mousemove", ctx[6]),
            listen(div, "dragstart", ctx[7]),
            listen(div, "dragenter", ctx[8]),
            listen(div, "dragover", ctx[8]),
            listen(div, "dragleave", ctx[9]),
            listen(div, "drop", prevent_default(ctx[10]))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        const accountinput_changes = {};
        if (dirty & 2)
          accountinput_changes.suggestions = ctx2[1];
        if (!updating_value && dirty & 1) {
          updating_value = true;
          accountinput_changes.value = ctx2[0].account;
          add_flush_callback(() => updating_value = false);
        }
        accountinput.$set(accountinput_changes);
        const autocompleteinput_changes = {};
        if (dirty & 16)
          autocompleteinput_changes.suggestions = ctx2[4];
        if (!updating_value_1 && dirty & 1) {
          updating_value_1 = true;
          autocompleteinput_changes.value = ctx2[0].amount;
          add_flush_callback(() => updating_value_1 = false);
        }
        autocompleteinput.$set(autocompleteinput_changes);
        if (!current || dirty & 8) {
          attr(div, "draggable", ctx2[3]);
        }
        if (dirty & 4) {
          toggle_class(div, "drag", ctx2[2]);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(accountinput.$$.fragment, local);
        transition_in(autocompleteinput.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accountinput.$$.fragment, local);
        transition_out(autocompleteinput.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        destroy_component(accountinput);
        destroy_component(autocompleteinput);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance27($$self, $$props, $$invalidate) {
    let amount_number;
    let amountSuggestions;
    let $currencies;
    component_subscribe($$self, currencies, ($$value) => $$invalidate(13, $currencies = $$value));
    let {posting} = $$props;
    let {index} = $$props;
    let {suggestions} = $$props;
    const dispatch = createEventDispatcher();
    let drag = false;
    let draggable = true;
    function mousemove(event) {
      $$invalidate(3, draggable = !(event.target instanceof HTMLInputElement));
    }
    function dragstart(event) {
      event.dataTransfer?.setData("fava/posting", `${index}`);
    }
    function dragenter(event) {
      if (event.dataTransfer?.types.includes("fava/posting")) {
        event.preventDefault();
        $$invalidate(2, drag = true);
      }
    }
    function dragleave2() {
      $$invalidate(2, drag = false);
    }
    function drop2(event) {
      const from = event.dataTransfer?.getData("fava/posting");
      if (from) {
        dispatch("move", {from: +from, to: index});
        $$invalidate(2, drag = false);
      }
    }
    const click_handler = () => dispatch("remove");
    function accountinput_value_binding(value) {
      posting.account = value;
      $$invalidate(0, posting);
    }
    function autocompleteinput_value_binding(value) {
      posting.amount = value;
      $$invalidate(0, posting);
    }
    const click_handler_1 = () => dispatch("add");
    $$self.$$set = ($$props2) => {
      if ("posting" in $$props2)
        $$invalidate(0, posting = $$props2.posting);
      if ("index" in $$props2)
        $$invalidate(11, index = $$props2.index);
      if ("suggestions" in $$props2)
        $$invalidate(1, suggestions = $$props2.suggestions);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(12, amount_number = posting.amount.replace(/[^\-?0-9.]/g, ""));
      }
      if ($$self.$$.dirty & 12288) {
        $:
          $$invalidate(4, amountSuggestions = $currencies.map((c) => `${amount_number} ${c}`));
      }
    };
    return [
      posting,
      suggestions,
      drag,
      draggable,
      amountSuggestions,
      dispatch,
      mousemove,
      dragstart,
      dragenter,
      dragleave2,
      drop2,
      index,
      amount_number,
      $currencies,
      click_handler,
      accountinput_value_binding,
      autocompleteinput_value_binding,
      click_handler_1
    ];
  }
  var Posting = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance27, create_fragment27, safe_not_equal, {posting: 0, index: 11, suggestions: 1});
    }
  };
  var Posting_default = Posting;

  // src/entry-forms/Transaction.svelte
  function get_each_context16(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[16] = list[i];
    child_ctx[17] = list;
    child_ctx[18] = i;
    return child_ctx;
  }
  function create_each_block16(ctx) {
    let postingsvelte;
    let updating_posting;
    let current;
    function postingsvelte_posting_binding(value) {
      ctx[14].call(null, value, ctx[16], ctx[17], ctx[18]);
    }
    function remove_handler() {
      return ctx[15](ctx[16]);
    }
    let postingsvelte_props = {
      index: ctx[18],
      suggestions: ctx[2]
    };
    if (ctx[16] !== void 0) {
      postingsvelte_props.posting = ctx[16];
    }
    postingsvelte = new Posting_default({props: postingsvelte_props});
    binding_callbacks.push(() => bind(postingsvelte, "posting", postingsvelte_posting_binding));
    postingsvelte.$on("add", ctx[4]);
    postingsvelte.$on("move", ctx[6]);
    postingsvelte.$on("remove", remove_handler);
    return {
      c() {
        create_component(postingsvelte.$$.fragment);
      },
      m(target, anchor) {
        mount_component(postingsvelte, target, anchor);
        current = true;
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        const postingsvelte_changes = {};
        if (dirty & 4)
          postingsvelte_changes.suggestions = ctx[2];
        if (!updating_posting && dirty & 1) {
          updating_posting = true;
          postingsvelte_changes.posting = ctx[16];
          add_flush_callback(() => updating_posting = false);
        }
        postingsvelte.$set(postingsvelte_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(postingsvelte.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(postingsvelte.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(postingsvelte, detaching);
      }
    };
  }
  function create_fragment28(ctx) {
    let div2;
    let div0;
    let input0;
    let t03;
    let input1;
    let t13;
    let label0;
    let span0;
    let t4;
    let autocompleteinput;
    let updating_value;
    let t5;
    let label1;
    let span1;
    let t8;
    let input2;
    let input2_placeholder_value;
    let t9;
    let addmetadatabutton;
    let updating_meta;
    let t10;
    let button;
    let t11;
    let button_title_value;
    let button_tabindex_value;
    let t122;
    let entrymetadata;
    let updating_meta_1;
    let t132;
    let div1;
    let span3;
    let span2;
    let t16;
    let current;
    let mounted;
    let dispose;
    function autocompleteinput_value_binding(value) {
      ctx[10].call(null, value);
    }
    let autocompleteinput_props = {
      className: "payee",
      placeholder: _("Payee"),
      suggestions: ctx[1]
    };
    if (ctx[0].payee !== void 0) {
      autocompleteinput_props.value = ctx[0].payee;
    }
    autocompleteinput = new AutocompleteInput_default({props: autocompleteinput_props});
    binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
    autocompleteinput.$on("select", ctx[5]);
    function addmetadatabutton_meta_binding(value) {
      ctx[12].call(null, value);
    }
    let addmetadatabutton_props = {};
    if (ctx[0].meta !== void 0) {
      addmetadatabutton_props.meta = ctx[0].meta;
    }
    addmetadatabutton = new AddMetadataButton_default({props: addmetadatabutton_props});
    binding_callbacks.push(() => bind(addmetadatabutton, "meta", addmetadatabutton_meta_binding));
    function entrymetadata_meta_binding(value) {
      ctx[13].call(null, value);
    }
    let entrymetadata_props = {};
    if (ctx[0].meta !== void 0) {
      entrymetadata_props.meta = ctx[0].meta;
    }
    entrymetadata = new EntryMetadata_default({props: entrymetadata_props});
    binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
    let each_value = ctx[0].postings;
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block16(get_each_context16(ctx, each_value, i));
    }
    const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
      each_blocks[i] = null;
    });
    return {
      c() {
        div2 = element("div");
        div0 = element("div");
        input0 = element("input");
        t03 = space();
        input1 = element("input");
        t13 = space();
        label0 = element("label");
        span0 = element("span");
        span0.textContent = `${_("Payee")}:`;
        t4 = space();
        create_component(autocompleteinput.$$.fragment);
        t5 = space();
        label1 = element("label");
        span1 = element("span");
        span1.textContent = `${_("Narration")}:`;
        t8 = space();
        input2 = element("input");
        t9 = space();
        create_component(addmetadatabutton.$$.fragment);
        t10 = space();
        button = element("button");
        t11 = text("p");
        t122 = space();
        create_component(entrymetadata.$$.fragment);
        t132 = space();
        div1 = element("div");
        span3 = element("span");
        span2 = element("span");
        span2.textContent = `${_("Postings")}:`;
        t16 = space();
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(input0, "type", "date");
        input0.required = true;
        attr(input1, "type", "text");
        attr(input1, "name", "flag");
        input1.required = true;
        attr(input1, "class", "svelte-12mv83z");
        attr(span0, "class", "svelte-12mv83z");
        attr(label0, "class", "svelte-12mv83z");
        attr(span1, "class", "svelte-12mv83z");
        attr(input2, "type", "text");
        attr(input2, "name", "narration");
        attr(input2, "placeholder", input2_placeholder_value = _("Narration"));
        attr(input2, "class", "svelte-12mv83z");
        attr(label1, "class", "svelte-12mv83z");
        attr(button, "class", "muted round");
        attr(button, "type", "button");
        attr(button, "title", button_title_value = _("Add posting"));
        attr(button, "tabindex", button_tabindex_value = -1);
        attr(div0, "class", "flex-row svelte-12mv83z");
        attr(span2, "class", "svelte-12mv83z");
        attr(span3, "class", "label svelte-12mv83z");
        attr(div1, "class", "flex-row svelte-12mv83z");
        attr(div2, "class", "svelte-12mv83z");
      },
      m(target, anchor) {
        insert(target, div2, anchor);
        append(div2, div0);
        append(div0, input0);
        set_input_value(input0, ctx[0].date);
        append(div0, t03);
        append(div0, input1);
        set_input_value(input1, ctx[0].flag);
        append(div0, t13);
        append(div0, label0);
        append(label0, span0);
        append(label0, t4);
        mount_component(autocompleteinput, label0, null);
        append(div0, t5);
        append(div0, label1);
        append(label1, span1);
        append(label1, t8);
        append(label1, input2);
        set_input_value(input2, ctx[0].narration);
        append(label1, t9);
        mount_component(addmetadatabutton, label1, null);
        append(div0, t10);
        append(div0, button);
        append(button, t11);
        append(div2, t122);
        mount_component(entrymetadata, div2, null);
        append(div2, t132);
        append(div2, div1);
        append(div1, span3);
        append(span3, span2);
        append(div2, t16);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(div2, null);
        }
        current = true;
        if (!mounted) {
          dispose = [
            listen(input0, "input", ctx[8]),
            listen(input1, "input", ctx[9]),
            listen(input2, "input", ctx[11]),
            listen(button, "click", ctx[4])
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        if (dirty & 1) {
          set_input_value(input0, ctx2[0].date);
        }
        if (dirty & 1 && input1.value !== ctx2[0].flag) {
          set_input_value(input1, ctx2[0].flag);
        }
        const autocompleteinput_changes = {};
        if (dirty & 2)
          autocompleteinput_changes.suggestions = ctx2[1];
        if (!updating_value && dirty & 1) {
          updating_value = true;
          autocompleteinput_changes.value = ctx2[0].payee;
          add_flush_callback(() => updating_value = false);
        }
        autocompleteinput.$set(autocompleteinput_changes);
        if (dirty & 1 && input2.value !== ctx2[0].narration) {
          set_input_value(input2, ctx2[0].narration);
        }
        const addmetadatabutton_changes = {};
        if (!updating_meta && dirty & 1) {
          updating_meta = true;
          addmetadatabutton_changes.meta = ctx2[0].meta;
          add_flush_callback(() => updating_meta = false);
        }
        addmetadatabutton.$set(addmetadatabutton_changes);
        const entrymetadata_changes = {};
        if (!updating_meta_1 && dirty & 1) {
          updating_meta_1 = true;
          entrymetadata_changes.meta = ctx2[0].meta;
          add_flush_callback(() => updating_meta_1 = false);
        }
        entrymetadata.$set(entrymetadata_changes);
        if (dirty & 93) {
          each_value = ctx2[0].postings;
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context16(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
              transition_in(each_blocks[i], 1);
            } else {
              each_blocks[i] = create_each_block16(child_ctx);
              each_blocks[i].c();
              transition_in(each_blocks[i], 1);
              each_blocks[i].m(div2, null);
            }
          }
          group_outros();
          for (i = each_value.length; i < each_blocks.length; i += 1) {
            out(i);
          }
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(autocompleteinput.$$.fragment, local);
        transition_in(addmetadatabutton.$$.fragment, local);
        transition_in(entrymetadata.$$.fragment, local);
        for (let i = 0; i < each_value.length; i += 1) {
          transition_in(each_blocks[i]);
        }
        current = true;
      },
      o(local) {
        transition_out(autocompleteinput.$$.fragment, local);
        transition_out(addmetadatabutton.$$.fragment, local);
        transition_out(entrymetadata.$$.fragment, local);
        each_blocks = each_blocks.filter(Boolean);
        for (let i = 0; i < each_blocks.length; i += 1) {
          transition_out(each_blocks[i]);
        }
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div2);
        destroy_component(autocompleteinput);
        destroy_component(addmetadatabutton);
        destroy_component(entrymetadata);
        destroy_each(each_blocks, detaching);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance28($$self, $$props, $$invalidate) {
    let payee;
    let $payees;
    component_subscribe($$self, payees, ($$value) => $$invalidate(1, $payees = $$value));
    let {entry} = $$props;
    let suggestions;
    function removePosting(posting) {
      $$invalidate(0, entry.postings = entry.postings.filter((p) => p !== posting), entry);
    }
    function addPosting() {
      $$invalidate(0, entry.postings = entry.postings.concat(emptyPosting()), entry);
    }
    async function autocompleteSelectPayee() {
      if (entry.narration || !entry.postings.every((p) => !p.account)) {
        return;
      }
      const data = await get("payee_transaction", {payee: entry.payee});
      $$invalidate(0, entry = Object.assign(new Transaction(), data, {date: entry.date}));
    }
    function movePosting(ev) {
      const {from, to} = ev.detail;
      const moved = entry.postings[from];
      entry.postings.splice(from, 1);
      entry.postings.splice(to, 0, moved);
      $$invalidate(0, entry);
    }
    function input0_input_handler() {
      entry.date = this.value;
      $$invalidate(0, entry);
    }
    function input1_input_handler() {
      entry.flag = this.value;
      $$invalidate(0, entry);
    }
    function autocompleteinput_value_binding(value) {
      entry.payee = value;
      $$invalidate(0, entry);
    }
    function input2_input_handler() {
      entry.narration = this.value;
      $$invalidate(0, entry);
    }
    function addmetadatabutton_meta_binding(value) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
    function entrymetadata_meta_binding(value) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
    function postingsvelte_posting_binding(value, posting, each_value, index) {
      each_value[index] = value;
      $$invalidate(0, entry);
    }
    const remove_handler = (posting) => removePosting(posting);
    $$self.$$set = ($$props2) => {
      if ("entry" in $$props2)
        $$invalidate(0, entry = $$props2.entry);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(7, payee = entry.payee);
      }
      if ($$self.$$.dirty & 130) {
        $:
          if (payee) {
            $$invalidate(2, suggestions = void 0);
            if ($payees.includes(payee)) {
              get("payee_accounts", {payee}).then((s) => {
                $$invalidate(2, suggestions = s);
              });
            }
          }
      }
    };
    return [
      entry,
      $payees,
      suggestions,
      removePosting,
      addPosting,
      autocompleteSelectPayee,
      movePosting,
      payee,
      input0_input_handler,
      input1_input_handler,
      autocompleteinput_value_binding,
      input2_input_handler,
      addmetadatabutton_meta_binding,
      entrymetadata_meta_binding,
      postingsvelte_posting_binding,
      remove_handler
    ];
  }
  var Transaction_1 = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance28, create_fragment28, safe_not_equal, {entry: 0});
    }
  };
  var Transaction_default = Transaction_1;

  // src/entry-forms/Entry.svelte
  function create_fragment29(ctx) {
    let switch_instance;
    let updating_entry;
    let switch_instance_anchor;
    let current;
    function switch_instance_entry_binding(value) {
      ctx[2].call(null, value);
    }
    var switch_value = ctx[1];
    function switch_props(ctx2) {
      let switch_instance_props = {};
      if (ctx2[0] !== void 0) {
        switch_instance_props.entry = ctx2[0];
      }
      return {props: switch_instance_props};
    }
    if (switch_value) {
      switch_instance = new switch_value(switch_props(ctx));
      binding_callbacks.push(() => bind(switch_instance, "entry", switch_instance_entry_binding));
    }
    return {
      c() {
        if (switch_instance)
          create_component(switch_instance.$$.fragment);
        switch_instance_anchor = empty();
      },
      m(target, anchor) {
        if (switch_instance) {
          mount_component(switch_instance, target, anchor);
        }
        insert(target, switch_instance_anchor, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const switch_instance_changes = {};
        if (!updating_entry && dirty & 1) {
          updating_entry = true;
          switch_instance_changes.entry = ctx2[0];
          add_flush_callback(() => updating_entry = false);
        }
        if (switch_value !== (switch_value = ctx2[1])) {
          if (switch_instance) {
            group_outros();
            const old_component = switch_instance;
            transition_out(old_component.$$.fragment, 1, 0, () => {
              destroy_component(old_component, 1);
            });
            check_outros();
          }
          if (switch_value) {
            switch_instance = new switch_value(switch_props(ctx2));
            binding_callbacks.push(() => bind(switch_instance, "entry", switch_instance_entry_binding));
            create_component(switch_instance.$$.fragment);
            transition_in(switch_instance.$$.fragment, 1);
            mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
          } else {
            switch_instance = null;
          }
        } else if (switch_value) {
          switch_instance.$set(switch_instance_changes);
        }
      },
      i(local) {
        if (current)
          return;
        if (switch_instance)
          transition_in(switch_instance.$$.fragment, local);
        current = true;
      },
      o(local) {
        if (switch_instance)
          transition_out(switch_instance.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(switch_instance_anchor);
        if (switch_instance)
          destroy_component(switch_instance, detaching);
      }
    };
  }
  function instance29($$self, $$props, $$invalidate) {
    let component;
    let {entry} = $$props;
    const components2 = {Balance: Balance_default, Note: Note_default, Transaction: Transaction_default};
    function switch_instance_entry_binding(value) {
      entry = value;
      $$invalidate(0, entry);
    }
    $$self.$$set = ($$props2) => {
      if ("entry" in $$props2)
        $$invalidate(0, entry = $$props2.entry);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(1, component = components2[entry.type]);
      }
    };
    return [entry, component, switch_instance_entry_binding];
  }
  var Entry2 = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance29, create_fragment29, safe_not_equal, {entry: 0});
    }
  };
  var Entry_default = Entry2;

  // src/import/Extract.svelte
  function create_if_block10(ctx) {
    let div0;
    let h3;
    let t03;
    let t1_value = ctx[1] + 1 + "";
    let t13;
    let t22;
    let t3_value = ctx[0].length + "";
    let t32;
    let t4;
    let t5_value = ctx[0].length - ctx[5] + "";
    let t5;
    let t6;
    let t7;
    let span0;
    let t8;
    let label;
    let input;
    let t9;
    let t10;
    let div1;
    let entry_1;
    let updating_entry;
    let t11;
    let div2;
    let t122;
    let span1;
    let t132;
    let t14;
    let hr;
    let t15;
    let if_block2_anchor;
    let current;
    let mounted;
    let dispose;
    function entry_1_entry_binding(value) {
      ctx[10].call(null, value);
    }
    let entry_1_props = {};
    if (ctx[2] !== void 0) {
      entry_1_props.entry = ctx[2];
    }
    entry_1 = new Entry_default({props: entry_1_props});
    binding_callbacks.push(() => bind(entry_1, "entry", entry_1_entry_binding));
    let if_block0 = ctx[1] > 0 && create_if_block_42(ctx);
    function select_block_type(ctx2, dirty) {
      if (ctx2[1] < ctx2[0].length - 1)
        return create_if_block_32;
      return create_else_block4;
    }
    let current_block_type = select_block_type(ctx, -1);
    let if_block1 = current_block_type(ctx);
    let if_block2 = ctx[2].meta.__source__ && create_if_block_18(ctx);
    return {
      c() {
        div0 = element("div");
        h3 = element("h3");
        t03 = text("Entry\n          ");
        t13 = text(t1_value);
        t22 = text("\n          of\n          ");
        t32 = text(t3_value);
        t4 = text("\n          (");
        t5 = text(t5_value);
        t6 = text("\n          to import):");
        t7 = space();
        span0 = element("span");
        t8 = space();
        label = element("label");
        input = element("input");
        t9 = text("\n          ignore duplicate");
        t10 = space();
        div1 = element("div");
        create_component(entry_1.$$.fragment);
        t11 = space();
        div2 = element("div");
        if (if_block0)
          if_block0.c();
        t122 = space();
        span1 = element("span");
        t132 = space();
        if_block1.c();
        t14 = space();
        hr = element("hr");
        t15 = space();
        if (if_block2)
          if_block2.c();
        if_block2_anchor = empty();
        attr(span0, "class", "spacer");
        attr(input, "type", "checkbox");
        input.checked = ctx[4];
        attr(label, "class", "button muted");
        attr(div0, "class", "flex-row");
        attr(div1, "class", "svelte-kordbm");
        toggle_class(div1, "duplicate", ctx[4]);
        attr(span1, "class", "spacer");
        attr(div2, "class", "flex-row");
      },
      m(target, anchor) {
        insert(target, div0, anchor);
        append(div0, h3);
        append(h3, t03);
        append(h3, t13);
        append(h3, t22);
        append(h3, t32);
        append(h3, t4);
        append(h3, t5);
        append(h3, t6);
        append(div0, t7);
        append(div0, span0);
        append(div0, t8);
        append(div0, label);
        append(label, input);
        append(label, t9);
        insert(target, t10, anchor);
        insert(target, div1, anchor);
        mount_component(entry_1, div1, null);
        insert(target, t11, anchor);
        insert(target, div2, anchor);
        if (if_block0)
          if_block0.m(div2, null);
        append(div2, t122);
        append(div2, span1);
        append(div2, t132);
        if_block1.m(div2, null);
        insert(target, t14, anchor);
        insert(target, hr, anchor);
        insert(target, t15, anchor);
        if (if_block2)
          if_block2.m(target, anchor);
        insert(target, if_block2_anchor, anchor);
        current = true;
        if (!mounted) {
          dispose = listen(input, "click", ctx[9]);
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if ((!current || dirty & 2) && t1_value !== (t1_value = ctx2[1] + 1 + ""))
          set_data(t13, t1_value);
        if ((!current || dirty & 1) && t3_value !== (t3_value = ctx2[0].length + ""))
          set_data(t32, t3_value);
        if ((!current || dirty & 33) && t5_value !== (t5_value = ctx2[0].length - ctx2[5] + ""))
          set_data(t5, t5_value);
        if (!current || dirty & 16) {
          input.checked = ctx2[4];
        }
        const entry_1_changes = {};
        if (!updating_entry && dirty & 4) {
          updating_entry = true;
          entry_1_changes.entry = ctx2[2];
          add_flush_callback(() => updating_entry = false);
        }
        entry_1.$set(entry_1_changes);
        if (dirty & 16) {
          toggle_class(div1, "duplicate", ctx2[4]);
        }
        if (ctx2[1] > 0) {
          if (if_block0) {
            if_block0.p(ctx2, dirty);
          } else {
            if_block0 = create_if_block_42(ctx2);
            if_block0.c();
            if_block0.m(div2, t122);
          }
        } else if (if_block0) {
          if_block0.d(1);
          if_block0 = null;
        }
        if (current_block_type === (current_block_type = select_block_type(ctx2, dirty)) && if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1.d(1);
          if_block1 = current_block_type(ctx2);
          if (if_block1) {
            if_block1.c();
            if_block1.m(div2, null);
          }
        }
        if (ctx2[2].meta.__source__) {
          if (if_block2) {
            if_block2.p(ctx2, dirty);
          } else {
            if_block2 = create_if_block_18(ctx2);
            if_block2.c();
            if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
          }
        } else if (if_block2) {
          if_block2.d(1);
          if_block2 = null;
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(entry_1.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(entry_1.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div0);
        if (detaching)
          detach(t10);
        if (detaching)
          detach(div1);
        destroy_component(entry_1);
        if (detaching)
          detach(t11);
        if (detaching)
          detach(div2);
        if (if_block0)
          if_block0.d();
        if_block1.d();
        if (detaching)
          detach(t14);
        if (detaching)
          detach(hr);
        if (detaching)
          detach(t15);
        if (if_block2)
          if_block2.d(detaching);
        if (detaching)
          detach(if_block2_anchor);
        mounted = false;
        dispose();
      }
    };
  }
  function create_if_block_42(ctx) {
    let button0;
    let t13;
    let button1;
    let mounted;
    let dispose;
    return {
      c() {
        button0 = element("button");
        button0.textContent = "\u23EE";
        t13 = space();
        button1 = element("button");
        button1.textContent = `${_("Previous")}`;
        attr(button0, "type", "button");
        attr(button0, "class", "muted");
        attr(button1, "type", "button");
        attr(button1, "class", "muted");
      },
      m(target, anchor) {
        insert(target, button0, anchor);
        insert(target, t13, anchor);
        insert(target, button1, anchor);
        if (!mounted) {
          dispose = [
            listen(button0, "click", ctx[11]),
            listen(button1, "click", ctx[8])
          ];
          mounted = true;
        }
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(button0);
        if (detaching)
          detach(t13);
        if (detaching)
          detach(button1);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_else_block4(ctx) {
    let button;
    return {
      c() {
        button = element("button");
        button.textContent = `${_("Save")}`;
        attr(button, "type", "submit");
      },
      m(target, anchor) {
        insert(target, button, anchor);
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(button);
      }
    };
  }
  function create_if_block_32(ctx) {
    let button0;
    let t13;
    let button1;
    let mounted;
    let dispose;
    return {
      c() {
        button0 = element("button");
        button0.textContent = `${_("Next")}`;
        t13 = space();
        button1 = element("button");
        button1.textContent = "\u23ED";
        attr(button0, "type", "submit");
        attr(button1, "type", "button");
        attr(button1, "class", "muted");
      },
      m(target, anchor) {
        insert(target, button0, anchor);
        insert(target, t13, anchor);
        insert(target, button1, anchor);
        if (!mounted) {
          dispose = listen(button1, "click", ctx[12]);
          mounted = true;
        }
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(button0);
        if (detaching)
          detach(t13);
        if (detaching)
          detach(button1);
        mounted = false;
        dispose();
      }
    };
  }
  function create_if_block_18(ctx) {
    let h3;
    let t0_value = _("Source") + "";
    let t03;
    let t13;
    let t22;
    let pre;
    let t3_value = ctx[2].meta.__source__ + "";
    let t32;
    let if_block = ctx[2].meta.lineno && create_if_block_24(ctx);
    return {
      c() {
        h3 = element("h3");
        t03 = text(t0_value);
        t13 = space();
        if (if_block)
          if_block.c();
        t22 = space();
        pre = element("pre");
        t32 = text(t3_value);
        attr(pre, "class", "svelte-kordbm");
      },
      m(target, anchor) {
        insert(target, h3, anchor);
        append(h3, t03);
        append(h3, t13);
        if (if_block)
          if_block.m(h3, null);
        insert(target, t22, anchor);
        insert(target, pre, anchor);
        append(pre, t32);
      },
      p(ctx2, dirty) {
        if (ctx2[2].meta.lineno) {
          if (if_block) {
            if_block.p(ctx2, dirty);
          } else {
            if_block = create_if_block_24(ctx2);
            if_block.c();
            if_block.m(h3, null);
          }
        } else if (if_block) {
          if_block.d(1);
          if_block = null;
        }
        if (dirty & 4 && t3_value !== (t3_value = ctx2[2].meta.__source__ + ""))
          set_data(t32, t3_value);
      },
      d(detaching) {
        if (detaching)
          detach(h3);
        if (if_block)
          if_block.d();
        if (detaching)
          detach(t22);
        if (detaching)
          detach(pre);
      }
    };
  }
  function create_if_block_24(ctx) {
    let t03;
    let t1_value = _("Line") + "";
    let t13;
    let t22;
    let t3_value = ctx[2].meta.lineno + "";
    let t32;
    let t4;
    return {
      c() {
        t03 = text("(");
        t13 = text(t1_value);
        t22 = text(": ");
        t32 = text(t3_value);
        t4 = text(")");
      },
      m(target, anchor) {
        insert(target, t03, anchor);
        insert(target, t13, anchor);
        insert(target, t22, anchor);
        insert(target, t32, anchor);
        insert(target, t4, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 4 && t3_value !== (t3_value = ctx2[2].meta.lineno + ""))
          set_data(t32, t3_value);
      },
      d(detaching) {
        if (detaching)
          detach(t03);
        if (detaching)
          detach(t13);
        if (detaching)
          detach(t22);
        if (detaching)
          detach(t32);
        if (detaching)
          detach(t4);
      }
    };
  }
  function create_default_slot4(ctx) {
    let form;
    let h3;
    let t13;
    let current;
    let mounted;
    let dispose;
    let if_block = ctx[2] && create_if_block10(ctx);
    return {
      c() {
        form = element("form");
        h3 = element("h3");
        h3.textContent = `${_("Import")}`;
        t13 = space();
        if (if_block)
          if_block.c();
        form.noValidate = ctx[4];
      },
      m(target, anchor) {
        insert(target, form, anchor);
        append(form, h3);
        append(form, t13);
        if (if_block)
          if_block.m(form, null);
        current = true;
        if (!mounted) {
          dispose = listen(form, "submit", prevent_default(ctx[7]));
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (ctx2[2]) {
          if (if_block) {
            if_block.p(ctx2, dirty);
            if (dirty & 4) {
              transition_in(if_block, 1);
            }
          } else {
            if_block = create_if_block10(ctx2);
            if_block.c();
            transition_in(if_block, 1);
            if_block.m(form, null);
          }
        } else if (if_block) {
          group_outros();
          transition_out(if_block, 1, 1, () => {
            if_block = null;
          });
          check_outros();
        }
        if (!current || dirty & 16) {
          form.noValidate = ctx2[4];
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(form);
        if (if_block)
          if_block.d();
        mounted = false;
        dispose();
      }
    };
  }
  function create_fragment30(ctx) {
    let modalbase;
    let current;
    modalbase = new ModalBase_default({
      props: {
        shown: ctx[3],
        closeHandler: ctx[6],
        $$slots: {default: [create_default_slot4]},
        $$scope: {ctx}
      }
    });
    return {
      c() {
        create_component(modalbase.$$.fragment);
      },
      m(target, anchor) {
        mount_component(modalbase, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const modalbase_changes = {};
        if (dirty & 8)
          modalbase_changes.shown = ctx2[3];
        if (dirty & 16439) {
          modalbase_changes.$$scope = {dirty, ctx: ctx2};
        }
        modalbase.$set(modalbase_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(modalbase.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(modalbase.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(modalbase, detaching);
      }
    };
  }
  function instance30($$self, $$props, $$invalidate) {
    let shown;
    let entry;
    let duplicate;
    let duplicates;
    let {entries} = $$props;
    let currentIndex = 0;
    const dispatch = createEventDispatcher();
    const closeHandler = () => dispatch("close");
    async function submitOrNext() {
      if (currentIndex < entries.length - 1) {
        $$invalidate(1, currentIndex += 1);
      } else {
        dispatch("save");
      }
    }
    function previousEntry() {
      $$invalidate(1, currentIndex = Math.max(currentIndex - 1, 0));
    }
    function toggleDuplicate() {
      $$invalidate(2, entry.meta.__duplicate__ = !entry.meta.__duplicate__, entry);
    }
    function entry_1_entry_binding(value) {
      entry = value;
      $$invalidate(2, entry), $$invalidate(0, entries), $$invalidate(1, currentIndex);
    }
    const click_handler = () => {
      $$invalidate(1, currentIndex = 0);
    };
    const click_handler_1 = () => {
      $$invalidate(1, currentIndex = entries.length - 1);
    };
    $$self.$$set = ($$props2) => {
      if ("entries" in $$props2)
        $$invalidate(0, entries = $$props2.entries);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(3, shown = entries.length > 0);
      }
      if ($$self.$$.dirty & 3) {
        $:
          if (entries.length > 0 && currentIndex >= entries.length) {
            $$invalidate(1, currentIndex = 0);
          }
      }
      if ($$self.$$.dirty & 3) {
        $:
          $$invalidate(2, entry = entries[currentIndex]);
      }
      if ($$self.$$.dirty & 4) {
        $:
          $$invalidate(4, duplicate = entry && isDuplicate(entry));
      }
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(5, duplicates = entries.filter((e) => isDuplicate(e)).length);
      }
    };
    return [
      entries,
      currentIndex,
      entry,
      shown,
      duplicate,
      duplicates,
      closeHandler,
      submitOrNext,
      previousEntry,
      toggleDuplicate,
      entry_1_entry_binding,
      click_handler,
      click_handler_1
    ];
  }
  var Extract = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance30, create_fragment30, safe_not_equal, {entries: 0});
    }
  };
  var Extract_default = Extract;

  // src/import/Import.svelte
  function get_each_context17(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[18] = list[i];
    return child_ctx;
  }
  function get_each_context_15(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[21] = list[i];
    child_ctx[22] = list;
    child_ctx[23] = i;
    return child_ctx;
  }
  function create_else_block5(ctx) {
    let t_value = _("No importer matched this file.") + "";
    let t;
    return {
      c() {
        t = text(t_value);
      },
      m(target, anchor) {
        insert(target, t, anchor);
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(t);
      }
    };
  }
  function create_if_block_19(ctx) {
    let button;
    let t0_value = (ctx[3].get(`${ctx[18].name}:${ctx[21].importer_name}`) ? _("Continue") : _("Extract")) + "";
    let t03;
    let button_title_value;
    let t13;
    let show_if = ctx[3].get(`${ctx[18].name}:${ctx[21].importer_name}`);
    let t22;
    let t3_value = ctx[21].importer_name + "";
    let t32;
    let mounted;
    let dispose;
    function click_handler_3() {
      return ctx[15](ctx[18], ctx[21]);
    }
    let if_block = show_if && create_if_block_25(ctx);
    return {
      c() {
        button = element("button");
        t03 = text(t0_value);
        t13 = space();
        if (if_block)
          if_block.c();
        t22 = space();
        t32 = text(t3_value);
        attr(button, "type", "button");
        attr(button, "title", button_title_value = "" + (_("Extract") + " with importer " + ctx[21].importer_name));
      },
      m(target, anchor) {
        insert(target, button, anchor);
        append(button, t03);
        insert(target, t13, anchor);
        if (if_block)
          if_block.m(target, anchor);
        insert(target, t22, anchor);
        insert(target, t32, anchor);
        if (!mounted) {
          dispose = listen(button, "click", click_handler_3);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 12 && t0_value !== (t0_value = (ctx[3].get(`${ctx[18].name}:${ctx[21].importer_name}`) ? _("Continue") : _("Extract")) + ""))
          set_data(t03, t0_value);
        if (dirty & 4 && button_title_value !== (button_title_value = "" + (_("Extract") + " with importer " + ctx[21].importer_name))) {
          attr(button, "title", button_title_value);
        }
        if (dirty & 12)
          show_if = ctx[3].get(`${ctx[18].name}:${ctx[21].importer_name}`);
        if (show_if) {
          if (if_block) {
            if_block.p(ctx, dirty);
          } else {
            if_block = create_if_block_25(ctx);
            if_block.c();
            if_block.m(t22.parentNode, t22);
          }
        } else if (if_block) {
          if_block.d(1);
          if_block = null;
        }
        if (dirty & 4 && t3_value !== (t3_value = ctx[21].importer_name + ""))
          set_data(t32, t3_value);
      },
      d(detaching) {
        if (detaching)
          detach(button);
        if (detaching)
          detach(t13);
        if (if_block)
          if_block.d(detaching);
        if (detaching)
          detach(t22);
        if (detaching)
          detach(t32);
        mounted = false;
        dispose();
      }
    };
  }
  function create_if_block_25(ctx) {
    let button;
    let mounted;
    let dispose;
    function click_handler_4() {
      return ctx[16](ctx[18], ctx[21]);
    }
    return {
      c() {
        button = element("button");
        button.textContent = `${_("Clear")}`;
        attr(button, "type", "button");
      },
      m(target, anchor) {
        insert(target, button, anchor);
        if (!mounted) {
          dispose = listen(button, "click", click_handler_4);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
      },
      d(detaching) {
        if (detaching)
          detach(button);
        mounted = false;
        dispose();
      }
    };
  }
  function create_each_block_15(ctx) {
    let div;
    let accountinput;
    let updating_value;
    let t03;
    let input;
    let input_size_value;
    let t13;
    let button;
    let t32;
    let t4;
    let current;
    let mounted;
    let dispose;
    function accountinput_value_binding(value) {
      ctx[12].call(null, value, ctx[21]);
    }
    let accountinput_props = {};
    if (ctx[21].account !== void 0) {
      accountinput_props.value = ctx[21].account;
    }
    accountinput = new AccountInput_default({props: accountinput_props});
    binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
    function input_input_handler() {
      ctx[13].call(input, ctx[22], ctx[23]);
    }
    function click_handler_2() {
      return ctx[14](ctx[18], ctx[21]);
    }
    function select_block_type(ctx2, dirty) {
      if (ctx2[21].importer_name)
        return create_if_block_19;
      return create_else_block5;
    }
    let current_block_type = select_block_type(ctx, -1);
    let if_block = current_block_type(ctx);
    return {
      c() {
        div = element("div");
        create_component(accountinput.$$.fragment);
        t03 = space();
        input = element("input");
        t13 = space();
        button = element("button");
        button.textContent = `${"Move"}`;
        t32 = space();
        if_block.c();
        t4 = space();
        attr(input, "size", input_size_value = 40);
        attr(button, "type", "button");
        attr(div, "class", "flex-row");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        mount_component(accountinput, div, null);
        append(div, t03);
        append(div, input);
        set_input_value(input, ctx[21].newName);
        append(div, t13);
        append(div, button);
        append(div, t32);
        if_block.m(div, null);
        append(div, t4);
        current = true;
        if (!mounted) {
          dispose = [
            listen(input, "input", input_input_handler),
            listen(button, "click", click_handler_2)
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        const accountinput_changes = {};
        if (!updating_value && dirty & 4) {
          updating_value = true;
          accountinput_changes.value = ctx[21].account;
          add_flush_callback(() => updating_value = false);
        }
        accountinput.$set(accountinput_changes);
        if (dirty & 4 && input.value !== ctx[21].newName) {
          set_input_value(input, ctx[21].newName);
        }
        if (current_block_type === (current_block_type = select_block_type(ctx, dirty)) && if_block) {
          if_block.p(ctx, dirty);
        } else {
          if_block.d(1);
          if_block = current_block_type(ctx);
          if (if_block) {
            if_block.c();
            if_block.m(div, t4);
          }
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(accountinput.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accountinput.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        destroy_component(accountinput);
        if_block.d();
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_each_block17(ctx) {
    let div;
    let t0_value = ctx[18].basename + "";
    let t03;
    let t13;
    let button;
    let t22;
    let button_title_value;
    let button_tabindex_value;
    let div_title_value;
    let t32;
    let each_1_anchor;
    let current;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[10](ctx[18]);
    }
    function click_handler_1() {
      return ctx[11](ctx[18]);
    }
    let each_value_1 = ctx[18].importers;
    let each_blocks = [];
    for (let i = 0; i < each_value_1.length; i += 1) {
      each_blocks[i] = create_each_block_15(get_each_context_15(ctx, each_value_1, i));
    }
    const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
      each_blocks[i] = null;
    });
    return {
      c() {
        div = element("div");
        t03 = text(t0_value);
        t13 = space();
        button = element("button");
        t22 = text("\xD7");
        t32 = space();
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        each_1_anchor = empty();
        attr(button, "class", "round svelte-1a2aigf");
        attr(button, "type", "button");
        attr(button, "title", button_title_value = _("Delete"));
        attr(button, "tabindex", button_tabindex_value = -1);
        attr(div, "class", "header svelte-1a2aigf");
        attr(div, "title", div_title_value = ctx[18].name);
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, t03);
        append(div, t13);
        append(div, button);
        append(button, t22);
        insert(target, t32, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(target, anchor);
        }
        insert(target, each_1_anchor, anchor);
        current = true;
        if (!mounted) {
          dispose = [
            listen(button, "click", click_handler),
            listen(div, "click", self2(click_handler_1))
          ];
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if ((!current || dirty & 4) && t0_value !== (t0_value = ctx[18].basename + ""))
          set_data(t03, t0_value);
        if (!current || dirty & 4 && div_title_value !== (div_title_value = ctx[18].name)) {
          attr(div, "title", div_title_value);
        }
        if (dirty & 92) {
          each_value_1 = ctx[18].importers;
          let i;
          for (i = 0; i < each_value_1.length; i += 1) {
            const child_ctx = get_each_context_15(ctx, each_value_1, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
              transition_in(each_blocks[i], 1);
            } else {
              each_blocks[i] = create_each_block_15(child_ctx);
              each_blocks[i].c();
              transition_in(each_blocks[i], 1);
              each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
            }
          }
          group_outros();
          for (i = each_value_1.length; i < each_blocks.length; i += 1) {
            out(i);
          }
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        for (let i = 0; i < each_value_1.length; i += 1) {
          transition_in(each_blocks[i]);
        }
        current = true;
      },
      o(local) {
        each_blocks = each_blocks.filter(Boolean);
        for (let i = 0; i < each_blocks.length; i += 1) {
          transition_out(each_blocks[i]);
        }
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        if (detaching)
          detach(t32);
        destroy_each(each_blocks, detaching);
        if (detaching)
          detach(each_1_anchor);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_if_block11(ctx) {
    let div;
    let documentpreview;
    let current;
    documentpreview = new DocumentPreview_default({props: {filename: ctx[1]}});
    return {
      c() {
        div = element("div");
        create_component(documentpreview.$$.fragment);
        attr(div, "class", "svelte-1a2aigf");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        mount_component(documentpreview, div, null);
        current = true;
      },
      p(ctx2, dirty) {
        const documentpreview_changes = {};
        if (dirty & 2)
          documentpreview_changes.filename = ctx2[1];
        documentpreview.$set(documentpreview_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(documentpreview.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(documentpreview.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        destroy_component(documentpreview);
      }
    };
  }
  function create_fragment31(ctx) {
    let extract_1;
    let t03;
    let div1;
    let div0;
    let t13;
    let current;
    extract_1 = new Extract_default({props: {entries: ctx[0]}});
    extract_1.$on("close", ctx[9]);
    extract_1.$on("save", ctx[7]);
    let each_value = ctx[2];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block17(get_each_context17(ctx, each_value, i));
    }
    const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
      each_blocks[i] = null;
    });
    let if_block = ctx[1] && create_if_block11(ctx);
    return {
      c() {
        create_component(extract_1.$$.fragment);
        t03 = space();
        div1 = element("div");
        div0 = element("div");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        t13 = space();
        if (if_block)
          if_block.c();
        attr(div0, "class", "filelist svelte-1a2aigf");
        attr(div1, "class", "fixed-fullsize-container svelte-1a2aigf");
      },
      m(target, anchor) {
        mount_component(extract_1, target, anchor);
        insert(target, t03, anchor);
        insert(target, div1, anchor);
        append(div1, div0);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(div0, null);
        }
        append(div1, t13);
        if (if_block)
          if_block.m(div1, null);
        current = true;
      },
      p(ctx2, [dirty]) {
        const extract_1_changes = {};
        if (dirty & 1)
          extract_1_changes.entries = ctx2[0];
        extract_1.$set(extract_1_changes);
        if (dirty & 126) {
          each_value = ctx2[2];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context17(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
              transition_in(each_blocks[i], 1);
            } else {
              each_blocks[i] = create_each_block17(child_ctx);
              each_blocks[i].c();
              transition_in(each_blocks[i], 1);
              each_blocks[i].m(div0, null);
            }
          }
          group_outros();
          for (i = each_value.length; i < each_blocks.length; i += 1) {
            out(i);
          }
          check_outros();
        }
        if (ctx2[1]) {
          if (if_block) {
            if_block.p(ctx2, dirty);
            if (dirty & 2) {
              transition_in(if_block, 1);
            }
          } else {
            if_block = create_if_block11(ctx2);
            if_block.c();
            transition_in(if_block, 1);
            if_block.m(div1, null);
          }
        } else if (if_block) {
          group_outros();
          transition_out(if_block, 1, 1, () => {
            if_block = null;
          });
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(extract_1.$$.fragment, local);
        for (let i = 0; i < each_value.length; i += 1) {
          transition_in(each_blocks[i]);
        }
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(extract_1.$$.fragment, local);
        each_blocks = each_blocks.filter(Boolean);
        for (let i = 0; i < each_blocks.length; i += 1) {
          transition_out(each_blocks[i]);
        }
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        destroy_component(extract_1, detaching);
        if (detaching)
          detach(t03);
        if (detaching)
          detach(div1);
        destroy_each(each_blocks, detaching);
        if (if_block)
          if_block.d();
      }
    };
  }
  function instance31($$self, $$props, $$invalidate) {
    let {data} = $$props;
    let entries = [];
    let selected = null;
    let preprocessedData = [];
    let extractCache = new Map();
    function preventNavigation() {
      return extractCache.size > 0 ? "There are unfinished imports, are you sure you want to continue?" : null;
    }
    onMount(() => {
      $$invalidate(2, preprocessedData = preprocessData(data));
      router_default.interruptHandlers.add(preventNavigation);
      return () => {
        router_default.interruptHandlers.delete(preventNavigation);
      };
    });
    async function move(filename, account2, newName) {
      const moved = await moveDocument(filename, account2, newName);
      if (moved) {
        $$invalidate(2, preprocessedData = preprocessedData.filter((item) => item.name !== filename));
      }
    }
    async function remove2(filename) {
      const removed = await deleteDocument(filename);
      if (removed) {
        $$invalidate(2, preprocessedData = preprocessedData.filter((item) => item.name !== filename));
      }
    }
    async function extract(filename, importer) {
      const extractCacheKey = `${filename}:${importer}`;
      let cached = extractCache.get(extractCacheKey);
      if (!cached) {
        cached = await get("extract", {filename, importer});
        if (!cached.length) {
          notify("No entries to import from this file.", "warning");
          return;
        }
        extractCache.set(extractCacheKey, cached);
        $$invalidate(3, extractCache);
      }
      $$invalidate(0, entries = cached);
    }
    async function save() {
      const withoutDuplicates = entries.filter((e) => !isDuplicate(e));
      const key = [...extractCache].find(([, e]) => e === entries)?.[0];
      if (key) {
        extractCache.delete(key);
        $$invalidate(3, extractCache);
      }
      $$invalidate(0, entries = []);
      await saveEntries(withoutDuplicates);
    }
    const close_handler = () => {
      $$invalidate(0, entries = []);
    };
    const click_handler = (file) => remove2(file.name);
    const click_handler_1 = (file) => {
      $$invalidate(1, selected = selected === file.name ? null : file.name);
    };
    function accountinput_value_binding(value, info) {
      info.account = value;
      $$invalidate(2, preprocessedData);
    }
    function input_input_handler(each_value_1, info_index) {
      each_value_1[info_index].newName = this.value;
      $$invalidate(2, preprocessedData);
    }
    const click_handler_2 = (file, info) => move(file.name, info.account, info.newName);
    const click_handler_3 = (file, info) => extract(file.name, info.importer_name);
    const click_handler_4 = (file, info) => {
      extractCache.delete(`${file.name}:${info.importer_name}`);
      $$invalidate(3, extractCache);
    };
    $$self.$$set = ($$props2) => {
      if ("data" in $$props2)
        $$invalidate(8, data = $$props2.data);
    };
    return [
      entries,
      selected,
      preprocessedData,
      extractCache,
      move,
      remove2,
      extract,
      save,
      data,
      close_handler,
      click_handler,
      click_handler_1,
      accountinput_value_binding,
      input_input_handler,
      click_handler_2,
      click_handler_3,
      click_handler_4
    ];
  }
  var Import = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance31, create_fragment31, safe_not_equal, {data: 8});
    }
  };
  var Import_default = Import;

  // src/modals/AddEntry.svelte
  function get_each_context18(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[8] = list[i][0];
    child_ctx[9] = list[i][1];
    return child_ctx;
  }
  function create_each_block18(ctx) {
    let button;
    let t0_value = ctx[9] + "";
    let t03;
    let t13;
    let t2_value = " ";
    let t22;
    let mounted;
    let dispose;
    function click_handler() {
      return ctx[6](ctx[8]);
    }
    return {
      c() {
        button = element("button");
        t03 = text(t0_value);
        t13 = space();
        t22 = text(t2_value);
        attr(button, "type", "button");
        toggle_class(button, "muted", ctx[0].type !== ctx[8]);
      },
      m(target, anchor) {
        insert(target, button, anchor);
        append(button, t03);
        insert(target, t13, anchor);
        insert(target, t22, anchor);
        if (!mounted) {
          dispose = listen(button, "click", click_handler);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 5) {
          toggle_class(button, "muted", ctx[0].type !== ctx[8]);
        }
      },
      d(detaching) {
        if (detaching)
          detach(button);
        if (detaching)
          detach(t13);
        if (detaching)
          detach(t22);
        mounted = false;
        dispose();
      }
    };
  }
  function create_default_slot5(ctx) {
    let form;
    let h3;
    let t0_value = _("Add") + "";
    let t03;
    let t13;
    let t22;
    let entry_1;
    let updating_entry;
    let t32;
    let div;
    let span;
    let t4;
    let button0;
    let t6;
    let button1;
    let current;
    let mounted;
    let dispose;
    let each_value = ctx[2];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block18(get_each_context18(ctx, each_value, i));
    }
    function entry_1_entry_binding(value) {
      ctx[7].call(null, value);
    }
    let entry_1_props = {};
    if (ctx[0] !== void 0) {
      entry_1_props.entry = ctx[0];
    }
    entry_1 = new Entry_default({props: entry_1_props});
    binding_callbacks.push(() => bind(entry_1, "entry", entry_1_entry_binding));
    return {
      c() {
        form = element("form");
        h3 = element("h3");
        t03 = text(t0_value);
        t13 = space();
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        t22 = space();
        create_component(entry_1.$$.fragment);
        t32 = space();
        div = element("div");
        span = element("span");
        t4 = space();
        button0 = element("button");
        button0.textContent = `${_("Save and add new")}`;
        t6 = space();
        button1 = element("button");
        button1.textContent = `${_("Save")}`;
        attr(span, "class", "spacer");
        attr(button0, "type", "submit");
        attr(button0, "class", "muted");
        attr(button1, "type", "submit");
        attr(div, "class", "flex-row");
      },
      m(target, anchor) {
        insert(target, form, anchor);
        append(form, h3);
        append(h3, t03);
        append(h3, t13);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(h3, null);
        }
        append(form, t22);
        mount_component(entry_1, form, null);
        append(form, t32);
        append(form, div);
        append(div, span);
        append(div, t4);
        append(div, button0);
        append(div, t6);
        append(div, button1);
        current = true;
        if (!mounted) {
          dispose = [
            listen(button0, "click", prevent_default(ctx[3])),
            listen(form, "submit", prevent_default(ctx[4]))
          ];
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (dirty & 5) {
          each_value = ctx2[2];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context18(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block18(child_ctx);
              each_blocks[i].c();
              each_blocks[i].m(h3, null);
            }
          }
          for (; i < each_blocks.length; i += 1) {
            each_blocks[i].d(1);
          }
          each_blocks.length = each_value.length;
        }
        const entry_1_changes = {};
        if (!updating_entry && dirty & 1) {
          updating_entry = true;
          entry_1_changes.entry = ctx2[0];
          add_flush_callback(() => updating_entry = false);
        }
        entry_1.$set(entry_1_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(entry_1.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(entry_1.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(form);
        destroy_each(each_blocks, detaching);
        destroy_component(entry_1);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function create_fragment32(ctx) {
    let modalbase;
    let current;
    modalbase = new ModalBase_default({
      props: {
        shown: ctx[1],
        $$slots: {default: [create_default_slot5]},
        $$scope: {ctx}
      }
    });
    return {
      c() {
        create_component(modalbase.$$.fragment);
      },
      m(target, anchor) {
        mount_component(modalbase, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const modalbase_changes = {};
        if (dirty & 2)
          modalbase_changes.shown = ctx2[1];
        if (dirty & 4097) {
          modalbase_changes.$$scope = {dirty, ctx: ctx2};
        }
        modalbase.$set(modalbase_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(modalbase.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(modalbase.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(modalbase, detaching);
      }
    };
  }
  function instance32($$self, $$props, $$invalidate) {
    let shown;
    let $urlHash;
    component_subscribe($$self, urlHash, ($$value) => $$invalidate(5, $urlHash = $$value));
    const entryTypes = [
      ["Transaction", _("Transaction")],
      ["Balance", _("Balance")],
      ["Note", _("Note")]
    ];
    let entry = create("Transaction");
    async function submitAndNew(event) {
      if (event.target instanceof HTMLButtonElement && event.target.form?.reportValidity()) {
        await saveEntries([entry]);
        $$invalidate(0, entry = create(entry.type));
      }
    }
    async function submit() {
      await saveEntries([entry]);
      $$invalidate(0, entry = create(entry.type));
      closeOverlay();
    }
    const click_handler = (type) => {
      $$invalidate(0, entry = create(type));
    };
    function entry_1_entry_binding(value) {
      entry = value;
      $$invalidate(0, entry);
    }
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 32) {
        $:
          $$invalidate(1, shown = $urlHash === "add-transaction");
      }
    };
    return [
      entry,
      shown,
      entryTypes,
      submitAndNew,
      submit,
      $urlHash,
      click_handler,
      entry_1_entry_binding
    ];
  }
  var AddEntry = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance32, create_fragment32, safe_not_equal, {});
    }
  };
  var AddEntry_default = AddEntry;

  // src/editor/SliceEditor.svelte
  function create_fragment33(ctx) {
    let form;
    let div;
    let sourceSliceEditor_action;
    let t;
    let savebutton;
    let current;
    let mounted;
    let dispose;
    savebutton = new SaveButton_default({
      props: {
        changed: ctx[0],
        saving: ctx[1]
      }
    });
    return {
      c() {
        form = element("form");
        div = element("div");
        t = space();
        create_component(savebutton.$$.fragment);
        attr(div, "class", "svelte-1lgp5rh");
      },
      m(target, anchor) {
        insert(target, form, anchor);
        append(form, div);
        append(form, t);
        mount_component(savebutton, form, null);
        current = true;
        if (!mounted) {
          dispose = [
            action_destroyer(sourceSliceEditor_action = ctx[3].call(null, div)),
            listen(form, "submit", prevent_default(ctx[2]))
          ];
          mounted = true;
        }
      },
      p(ctx2, [dirty]) {
        const savebutton_changes = {};
        if (dirty & 1)
          savebutton_changes.changed = ctx2[0];
        if (dirty & 2)
          savebutton_changes.saving = ctx2[1];
        savebutton.$set(savebutton_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(savebutton.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(savebutton.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(form);
        destroy_component(savebutton);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance33($$self, $$props, $$invalidate) {
    let {slice: slice3} = $$props;
    let {entry_hash} = $$props;
    let {sha256sum} = $$props;
    let editor;
    let changed = false;
    let saving = false;
    async function save() {
      $$invalidate(1, saving = true);
      try {
        $$invalidate(5, sha256sum = await put("source_slice", {entry_hash, source: slice3, sha256sum}));
        $$invalidate(0, changed = false);
        editor.getDoc().markClean();
        router_default.reload();
        closeOverlay();
      } catch (error) {
        notify(error, "error");
      } finally {
        $$invalidate(1, saving = false);
      }
    }
    function sourceSliceEditor(div) {
      const options = {
        ...sourceEditorOptions(save),
        value: slice3
      };
      editor = import_codemirror7.default(div, options);
      enableAutomaticCompletions(editor);
      editor.on("changes", (cm) => {
        $$invalidate(4, slice3 = cm.getValue());
        $$invalidate(0, changed = !cm.getDoc().isClean());
      });
    }
    $$self.$$set = ($$props2) => {
      if ("slice" in $$props2)
        $$invalidate(4, slice3 = $$props2.slice);
      if ("entry_hash" in $$props2)
        $$invalidate(6, entry_hash = $$props2.entry_hash);
      if ("sha256sum" in $$props2)
        $$invalidate(5, sha256sum = $$props2.sha256sum);
    };
    return [changed, saving, save, sourceSliceEditor, slice3, sha256sum, entry_hash];
  }
  var SliceEditor = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance33, create_fragment33, safe_not_equal, {slice: 4, entry_hash: 6, sha256sum: 5});
    }
  };
  var SliceEditor_default = SliceEditor;

  // src/modals/Context.svelte
  function create_catch_block2(ctx) {
    let t;
    return {
      c() {
        t = text("Loading entry context failed...");
      },
      m(target, anchor) {
        insert(target, t, anchor);
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(t);
      }
    };
  }
  function create_then_block2(ctx) {
    let if_block_anchor;
    let current;
    let if_block = ctx[4] && create_if_block12(ctx);
    return {
      c() {
        if (if_block)
          if_block.c();
        if_block_anchor = empty();
      },
      m(target, anchor) {
        if (if_block)
          if_block.m(target, anchor);
        insert(target, if_block_anchor, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        if (ctx2[4]) {
          if (if_block) {
            if_block.p(ctx2, dirty);
            if (dirty & 4) {
              transition_in(if_block, 1);
            }
          } else {
            if_block = create_if_block12(ctx2);
            if_block.c();
            transition_in(if_block, 1);
            if_block.m(if_block_anchor.parentNode, if_block_anchor);
          }
        } else if (if_block) {
          group_outros();
          transition_out(if_block, 1, 1, () => {
            if_block = null;
          });
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if (if_block)
          if_block.d(detaching);
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function create_if_block12(ctx) {
    let html_tag;
    let raw_value = ctx[4].content + "";
    let t;
    let sliceeditor;
    let current;
    sliceeditor = new SliceEditor_default({
      props: {
        entry_hash: ctx[1],
        slice: ctx[4].slice,
        sha256sum: ctx[4].sha256sum
      }
    });
    return {
      c() {
        t = space();
        create_component(sliceeditor.$$.fragment);
        html_tag = new HtmlTag(t);
      },
      m(target, anchor) {
        html_tag.m(raw_value, target, anchor);
        insert(target, t, anchor);
        mount_component(sliceeditor, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        if ((!current || dirty & 4) && raw_value !== (raw_value = ctx2[4].content + ""))
          html_tag.p(raw_value);
        const sliceeditor_changes = {};
        if (dirty & 2)
          sliceeditor_changes.entry_hash = ctx2[1];
        if (dirty & 4)
          sliceeditor_changes.slice = ctx2[4].slice;
        if (dirty & 4)
          sliceeditor_changes.sha256sum = ctx2[4].sha256sum;
        sliceeditor.$set(sliceeditor_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(sliceeditor.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(sliceeditor.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          html_tag.d();
        if (detaching)
          detach(t);
        destroy_component(sliceeditor, detaching);
      }
    };
  }
  function create_pending_block2(ctx) {
    let t;
    return {
      c() {
        t = text("Loading entry context...");
      },
      m(target, anchor) {
        insert(target, t, anchor);
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(t);
      }
    };
  }
  function create_default_slot6(ctx) {
    let div;
    let promise;
    let current;
    let info = {
      ctx,
      current: null,
      token: null,
      hasCatch: true,
      pending: create_pending_block2,
      then: create_then_block2,
      catch: create_catch_block2,
      value: 4,
      blocks: [, , ,]
    };
    handle_promise(promise = ctx[2], info);
    return {
      c() {
        div = element("div");
        info.block.c();
        attr(div, "class", "content");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        info.block.m(div, info.anchor = null);
        info.mount = () => div;
        info.anchor = null;
        current = true;
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        info.ctx = ctx;
        if (dirty & 4 && promise !== (promise = ctx[2]) && handle_promise(promise, info)) {
        } else {
          const child_ctx = ctx.slice();
          child_ctx[4] = info.resolved;
          info.block.p(child_ctx, dirty);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(info.block);
        current = true;
      },
      o(local) {
        for (let i = 0; i < 3; i += 1) {
          const block = info.blocks[i];
          transition_out(block);
        }
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(div);
        info.block.d();
        info.token = null;
        info = null;
      }
    };
  }
  function create_fragment34(ctx) {
    let modalbase;
    let current;
    modalbase = new ModalBase_default({
      props: {
        shown: ctx[0],
        $$slots: {default: [create_default_slot6]},
        $$scope: {ctx}
      }
    });
    return {
      c() {
        create_component(modalbase.$$.fragment);
      },
      m(target, anchor) {
        mount_component(modalbase, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const modalbase_changes = {};
        if (dirty & 1)
          modalbase_changes.shown = ctx2[0];
        if (dirty & 38) {
          modalbase_changes.$$scope = {dirty, ctx: ctx2};
        }
        modalbase.$set(modalbase_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(modalbase.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(modalbase.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(modalbase, detaching);
      }
    };
  }
  function instance34($$self, $$props, $$invalidate) {
    let shown;
    let entry_hash;
    let content;
    let $urlHash;
    component_subscribe($$self, urlHash, ($$value) => $$invalidate(3, $urlHash = $$value));
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 8) {
        $:
          $$invalidate(0, shown = $urlHash.startsWith("context"));
      }
      if ($$self.$$.dirty & 9) {
        $:
          $$invalidate(1, entry_hash = shown ? $urlHash.slice(8) : "");
      }
      if ($$self.$$.dirty & 3) {
        $:
          $$invalidate(2, content = shown ? get("context", {entry_hash}) : null);
      }
    };
    return [shown, entry_hash, content, $urlHash];
  }
  var Context = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance34, create_fragment34, safe_not_equal, {});
    }
  };
  var Context_default = Context;

  // src/document-upload.ts
  function dragover(event, closestTarget) {
    if (event.dataTransfer && (event.dataTransfer.types.includes("Files") || event.dataTransfer.types.includes("text/uri-list"))) {
      closestTarget.classList.add("dragover");
      event.preventDefault();
    }
  }
  delegate(document, "dragenter", ".droptarget", dragover);
  delegate(document, "dragover", ".droptarget", dragover);
  function dragleave(event, closestTarget) {
    closestTarget.classList.remove("dragover");
    event.preventDefault();
  }
  delegate(document, "dragleave", ".droptarget", dragleave);
  var account = writable("");
  var hash = writable("");
  var files = writable([]);
  function drop(event, target) {
    target.classList.remove("dragover");
    event.preventDefault();
    event.stopPropagation();
    if (!event.dataTransfer) {
      return;
    }
    const url = event.dataTransfer.getData("URL");
    if (url) {
      let filename = new URL(url).searchParams.get("filename");
      const acc = target.getAttribute("data-account-name");
      if (acc && filename && documentHasAccount(filename, acc)) {
        filename = basename(filename);
      }
      const entry_hash = target.getAttribute("data-entry");
      if (filename && entry_hash) {
        put("attach_document", {filename, entry_hash}).then((response) => {
          notify(response);
        }, (error) => {
          notify(error, "error");
        });
      }
      return;
    }
    const dateAttribute = target.getAttribute("data-entry-date");
    const entryDate = dateAttribute || todayAsString();
    account.set(target.getAttribute("data-account-name") || "");
    hash.set(target.getAttribute("data-entry") || "");
    const uploadedFiles = [];
    for (const dataTransferFile of event.dataTransfer.files) {
      let {name} = dataTransferFile;
      if (!/^\d{4}-\d{2}-\d{2}/.test(name)) {
        name = `${entryDate} ${name}`;
      }
      uploadedFiles.push({
        dataTransferFile,
        name
      });
    }
    files.set(uploadedFiles);
  }
  delegate(document, "drop", ".droptarget", drop);

  // src/modals/DocumentUpload.svelte
  function get_each_context19(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[12] = list[i];
    return child_ctx;
  }
  function get_each_context_16(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[15] = list[i];
    child_ctx[16] = list;
    child_ctx[17] = i;
    return child_ctx;
  }
  function create_each_block_16(ctx) {
    let div;
    let input;
    let mounted;
    let dispose;
    function input_input_handler() {
      ctx[9].call(input, ctx[16], ctx[17]);
    }
    return {
      c() {
        div = element("div");
        input = element("input");
        attr(div, "class", "fieldset");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, input);
        set_input_value(input, ctx[15].name);
        if (!mounted) {
          dispose = listen(input, "input", input_input_handler);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if (dirty & 1 && input.value !== ctx[15].name) {
          set_input_value(input, ctx[15].name);
        }
      },
      d(detaching) {
        if (detaching)
          detach(div);
        mounted = false;
        dispose();
      }
    };
  }
  function create_each_block19(ctx) {
    let option;
    let t_value = ctx[12] + "";
    let t;
    let option_value_value;
    return {
      c() {
        option = element("option");
        t = text(t_value);
        option.__value = option_value_value = ctx[12];
        option.value = option.__value;
      },
      m(target, anchor) {
        insert(target, option, anchor);
        append(option, t);
      },
      p(ctx2, dirty) {
        if (dirty & 8 && t_value !== (t_value = ctx2[12] + ""))
          set_data(t, t_value);
        if (dirty & 8 && option_value_value !== (option_value_value = ctx2[12])) {
          option.__value = option_value_value;
          option.value = option.__value;
        }
      },
      d(detaching) {
        if (detaching)
          detach(option);
      }
    };
  }
  function create_default_slot7(ctx) {
    let form_1;
    let h3;
    let t22;
    let t32;
    let div0;
    let label0;
    let t4_value = _("Documents folder") + "";
    let t4;
    let t5;
    let select;
    let t6;
    let div1;
    let label1;
    let t7_value = _("Account") + "";
    let t7;
    let t8;
    let accountinput;
    let updating_value;
    let t9;
    let input;
    let t10;
    let button;
    let current;
    let mounted;
    let dispose;
    let each_value_1 = ctx[0];
    let each_blocks_1 = [];
    for (let i = 0; i < each_value_1.length; i += 1) {
      each_blocks_1[i] = create_each_block_16(get_each_context_16(ctx, each_value_1, i));
    }
    let each_value = ctx[3];
    let each_blocks = [];
    for (let i = 0; i < each_value.length; i += 1) {
      each_blocks[i] = create_each_block19(get_each_context19(ctx, each_value, i));
    }
    function accountinput_value_binding(value) {
      ctx[10].call(null, value);
    }
    let accountinput_props = {};
    if (ctx[4] !== void 0) {
      accountinput_props.value = ctx[4];
    }
    accountinput = new AccountInput_default({props: accountinput_props});
    binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
    return {
      c() {
        form_1 = element("form");
        h3 = element("h3");
        h3.textContent = `${_("Upload file(s)")}:`;
        t22 = space();
        for (let i = 0; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].c();
        }
        t32 = space();
        div0 = element("div");
        label0 = element("label");
        t4 = text(t4_value);
        t5 = text(":\n        ");
        select = element("select");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        t6 = space();
        div1 = element("div");
        label1 = element("label");
        t7 = text(t7_value);
        t8 = text(":\n\n        ");
        create_component(accountinput.$$.fragment);
        t9 = space();
        input = element("input");
        t10 = space();
        button = element("button");
        button.textContent = `${_("Upload")}`;
        attr(select, "name", "folder");
        attr(div0, "class", "fieldset");
        attr(input, "type", "hidden");
        attr(input, "name", "hash");
        input.value = ctx[5];
        attr(div1, "class", "fieldset");
        attr(button, "type", "submit");
      },
      m(target, anchor) {
        insert(target, form_1, anchor);
        append(form_1, h3);
        append(form_1, t22);
        for (let i = 0; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].m(form_1, null);
        }
        append(form_1, t32);
        append(form_1, div0);
        append(div0, label0);
        append(label0, t4);
        append(label0, t5);
        append(label0, select);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(select, null);
        }
        append(form_1, t6);
        append(form_1, div1);
        append(div1, label1);
        append(label1, t7);
        append(label1, t8);
        mount_component(accountinput, label1, null);
        append(div1, t9);
        append(div1, input);
        append(form_1, t10);
        append(form_1, button);
        ctx[11](form_1);
        current = true;
        if (!mounted) {
          dispose = listen(form_1, "submit", prevent_default(ctx[6]));
          mounted = true;
        }
      },
      p(ctx2, dirty) {
        if (dirty & 1) {
          each_value_1 = ctx2[0];
          let i;
          for (i = 0; i < each_value_1.length; i += 1) {
            const child_ctx = get_each_context_16(ctx2, each_value_1, i);
            if (each_blocks_1[i]) {
              each_blocks_1[i].p(child_ctx, dirty);
            } else {
              each_blocks_1[i] = create_each_block_16(child_ctx);
              each_blocks_1[i].c();
              each_blocks_1[i].m(form_1, t32);
            }
          }
          for (; i < each_blocks_1.length; i += 1) {
            each_blocks_1[i].d(1);
          }
          each_blocks_1.length = each_value_1.length;
        }
        if (dirty & 8) {
          each_value = ctx2[3];
          let i;
          for (i = 0; i < each_value.length; i += 1) {
            const child_ctx = get_each_context19(ctx2, each_value, i);
            if (each_blocks[i]) {
              each_blocks[i].p(child_ctx, dirty);
            } else {
              each_blocks[i] = create_each_block19(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;
        }
        const accountinput_changes = {};
        if (!updating_value && dirty & 16) {
          updating_value = true;
          accountinput_changes.value = ctx2[4];
          add_flush_callback(() => updating_value = false);
        }
        accountinput.$set(accountinput_changes);
        if (!current || dirty & 32) {
          input.value = ctx2[5];
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(accountinput.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(accountinput.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(form_1);
        destroy_each(each_blocks_1, detaching);
        destroy_each(each_blocks, detaching);
        destroy_component(accountinput);
        ctx[11](null);
        mounted = false;
        dispose();
      }
    };
  }
  function create_fragment35(ctx) {
    let modalbase;
    let current;
    modalbase = new ModalBase_default({
      props: {
        shown: ctx[2],
        closeHandler: ctx[7],
        $$slots: {default: [create_default_slot7]},
        $$scope: {ctx}
      }
    });
    return {
      c() {
        create_component(modalbase.$$.fragment);
      },
      m(target, anchor) {
        mount_component(modalbase, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const modalbase_changes = {};
        if (dirty & 4)
          modalbase_changes.shown = ctx2[2];
        if (dirty & 262203) {
          modalbase_changes.$$scope = {dirty, ctx: ctx2};
        }
        modalbase.$set(modalbase_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(modalbase.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(modalbase.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(modalbase, detaching);
      }
    };
  }
  function instance35($$self, $$props, $$invalidate) {
    let shown;
    let documents;
    let $files;
    let $favaAPIStore;
    let $account;
    let $hash;
    component_subscribe($$self, files, ($$value) => $$invalidate(0, $files = $$value));
    component_subscribe($$self, favaAPIStore, ($$value) => $$invalidate(8, $favaAPIStore = $$value));
    component_subscribe($$self, account, ($$value) => $$invalidate(4, $account = $$value));
    component_subscribe($$self, hash, ($$value) => $$invalidate(5, $hash = $$value));
    let form;
    async function submit() {
      await Promise.all($files.map(({dataTransferFile, name}) => {
        const formData = new FormData(form);
        formData.append("account", $account);
        formData.append("file", dataTransferFile, name);
        return put("add_document", formData).then((response) => {
          notify(response);
        }, (error) => {
          notify(`Upload error: ${error}`, "error");
        });
      }));
      set_store_value(files, $files = [], $files);
      set_store_value(account, $account = "", $account);
      set_store_value(hash, $hash = "", $hash);
      router_default.reload();
    }
    function closeHandler() {
      $$invalidate(2, shown = false);
      set_store_value(files, $files = [], $files);
    }
    function input_input_handler(each_value_1, file_index) {
      each_value_1[file_index].name = this.value;
      files.set($files);
    }
    function accountinput_value_binding(value) {
      $account = value;
      account.set($account);
    }
    function form_1_binding($$value) {
      binding_callbacks[$$value ? "unshift" : "push"](() => {
        form = $$value;
        $$invalidate(1, form);
      });
    }
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 1) {
        $:
          $$invalidate(2, shown = !!$files.length);
      }
      if ($$self.$$.dirty & 256) {
        $:
          $$invalidate(3, documents = $favaAPIStore.options.documents);
      }
    };
    return [
      $files,
      form,
      shown,
      documents,
      $account,
      $hash,
      submit,
      closeHandler,
      $favaAPIStore,
      input_input_handler,
      accountinput_value_binding,
      form_1_binding
    ];
  }
  var DocumentUpload = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance35, create_fragment35, safe_not_equal, {});
    }
  };
  var DocumentUpload_default = DocumentUpload;

  // src/modals/Export.svelte
  function create_if_block13(ctx) {
    let div;
    let h3;
    let t22;
    let a;
    let t3_value = _("Download currently filtered entries as a Beancount file") + "";
    let t32;
    let a_href_value;
    return {
      c() {
        div = element("div");
        h3 = element("h3");
        h3.textContent = `${_("Export")}:`;
        t22 = space();
        a = element("a");
        t32 = text(t3_value);
        attr(a, "href", a_href_value = urlFor("download-journal"));
        attr(a, "data-remote", "");
      },
      m(target, anchor) {
        insert(target, div, anchor);
        append(div, h3);
        append(div, t22);
        append(div, a);
        append(a, t32);
      },
      p: noop,
      d(detaching) {
        if (detaching)
          detach(div);
      }
    };
  }
  function create_default_slot8(ctx) {
    let if_block_anchor;
    let if_block = ctx[0] && create_if_block13(ctx);
    return {
      c() {
        if (if_block)
          if_block.c();
        if_block_anchor = empty();
      },
      m(target, anchor) {
        if (if_block)
          if_block.m(target, anchor);
        insert(target, if_block_anchor, anchor);
      },
      p(ctx2, dirty) {
        if (ctx2[0]) {
          if (if_block) {
            if_block.p(ctx2, dirty);
          } else {
            if_block = create_if_block13(ctx2);
            if_block.c();
            if_block.m(if_block_anchor.parentNode, if_block_anchor);
          }
        } else if (if_block) {
          if_block.d(1);
          if_block = null;
        }
      },
      d(detaching) {
        if (if_block)
          if_block.d(detaching);
        if (detaching)
          detach(if_block_anchor);
      }
    };
  }
  function create_fragment36(ctx) {
    let modalbase;
    let current;
    modalbase = new ModalBase_default({
      props: {
        shown: ctx[0],
        $$slots: {default: [create_default_slot8]},
        $$scope: {ctx}
      }
    });
    return {
      c() {
        create_component(modalbase.$$.fragment);
      },
      m(target, anchor) {
        mount_component(modalbase, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const modalbase_changes = {};
        if (dirty & 1)
          modalbase_changes.shown = ctx2[0];
        if (dirty & 5) {
          modalbase_changes.$$scope = {dirty, ctx: ctx2};
        }
        modalbase.$set(modalbase_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(modalbase.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(modalbase.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(modalbase, detaching);
      }
    };
  }
  function instance36($$self, $$props, $$invalidate) {
    let shown;
    let $urlHash;
    component_subscribe($$self, urlHash, ($$value) => $$invalidate(1, $urlHash = $$value));
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 2) {
        $:
          $$invalidate(0, shown = $urlHash === "export");
      }
    };
    return [shown, $urlHash];
  }
  var Export = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance36, create_fragment36, safe_not_equal, {});
    }
  };
  var Export_default = Export;

  // src/modals/Modals.svelte
  function create_fragment37(ctx) {
    let addentry;
    let t03;
    let context;
    let t13;
    let documentupload;
    let t22;
    let export_1;
    let current;
    addentry = new AddEntry_default({});
    context = new Context_default({});
    documentupload = new DocumentUpload_default({});
    export_1 = new Export_default({});
    return {
      c() {
        create_component(addentry.$$.fragment);
        t03 = space();
        create_component(context.$$.fragment);
        t13 = space();
        create_component(documentupload.$$.fragment);
        t22 = space();
        create_component(export_1.$$.fragment);
      },
      m(target, anchor) {
        mount_component(addentry, target, anchor);
        insert(target, t03, anchor);
        mount_component(context, target, anchor);
        insert(target, t13, anchor);
        mount_component(documentupload, target, anchor);
        insert(target, t22, anchor);
        mount_component(export_1, target, anchor);
        current = true;
      },
      p: noop,
      i(local) {
        if (current)
          return;
        transition_in(addentry.$$.fragment, local);
        transition_in(context.$$.fragment, local);
        transition_in(documentupload.$$.fragment, local);
        transition_in(export_1.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(addentry.$$.fragment, local);
        transition_out(context.$$.fragment, local);
        transition_out(documentupload.$$.fragment, local);
        transition_out(export_1.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(addentry, detaching);
        if (detaching)
          detach(t03);
        destroy_component(context, detaching);
        if (detaching)
          detach(t13);
        destroy_component(documentupload, detaching);
        if (detaching)
          detach(t22);
        destroy_component(export_1, detaching);
      }
    };
  }
  var Modals = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, null, create_fragment37, safe_not_equal, {});
    }
  };
  var Modals_default = Modals;

  // src/stores/query.ts
  var query_shell_history = localStorageSyncedStore("fava-query-history", array(string), () => []);
  function addToHistory(query) {
    if (query) {
      query_shell_history.update((hist) => {
        hist.unshift(query);
        return [...new Set(hist)];
      });
    }
  }

  // src/query/QueryEditor.svelte
  var import_codemirror8 = __toModule(require_codemirror());
  function create_fragment38(ctx) {
    let form;
    let button;
    let keyboardShortcut_action;
    let queryEditor_action;
    let mounted;
    let dispose;
    return {
      c() {
        form = element("form");
        button = element("button");
        button.textContent = `${_("Submit")}`;
        attr(button, "type", "submit");
        attr(button, "class", "svelte-1xc24s1");
        attr(form, "class", "svelte-1xc24s1");
      },
      m(target, anchor) {
        insert(target, form, anchor);
        append(form, button);
        if (!mounted) {
          dispose = [
            action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, "Control+Enter")),
            action_destroyer(queryEditor_action = ctx[1].call(null, form)),
            listen(form, "submit", prevent_default(ctx[4]))
          ];
          mounted = true;
        }
      },
      p: noop,
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(form);
        mounted = false;
        run_all(dispose);
      }
    };
  }
  function instance37($$self, $$props, $$invalidate) {
    let {value} = $$props;
    let editor;
    const dispatch = createEventDispatcher();
    function queryEditor(form) {
      const queryOptions = {
        value,
        mode: "beancount-query",
        extraKeys: {
          "Ctrl-Enter": () => dispatch("submit"),
          "Cmd-Enter": () => dispatch("submit")
        },
        placeholder: _("...enter a BQL query. 'help' to list available commands.")
      };
      $$invalidate(3, editor = import_codemirror8.default((cm) => {
        form.insertBefore(cm, form.firstChild);
      }, queryOptions));
      editor.on("change", (cm) => {
        $$invalidate(2, value = cm.getValue());
      });
      enableAutomaticCompletions(editor);
    }
    const submit_handler = () => dispatch("submit");
    $$self.$$set = ($$props2) => {
      if ("value" in $$props2)
        $$invalidate(2, value = $$props2.value);
    };
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 12) {
        $:
          if (editor && value !== editor.getValue()) {
            editor.setValue(value);
          }
      }
    };
    return [dispatch, queryEditor, value, editor, submit_handler];
  }
  var QueryEditor = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance37, create_fragment38, safe_not_equal, {value: 2});
    }
  };
  var QueryEditor_default = QueryEditor;

  // src/query/QueryLinks.svelte
  function create_if_block14(ctx) {
    let t03;
    let a0;
    let t13;
    let a0_href_value;
    let t22;
    let a1;
    let t32;
    let a1_href_value;
    let t4;
    let a2;
    let t5;
    let a2_href_value;
    return {
      c() {
        t03 = text(",\n    ");
        a0 = element("a");
        t13 = text("XLS");
        t22 = text("\n    ,\n    ");
        a1 = element("a");
        t32 = text("XLSX");
        t4 = text("\n    , or\n    ");
        a2 = element("a");
        t5 = text("ODS");
        attr(a0, "href", a0_href_value = ctx[2](ctx[0], "xls"));
        attr(a0, "data-remote", "");
        attr(a1, "href", a1_href_value = ctx[2](ctx[0], "xlsx"));
        attr(a1, "data-remote", "");
        attr(a2, "href", a2_href_value = ctx[2](ctx[0], "ods"));
        attr(a2, "data-remote", "");
      },
      m(target, anchor) {
        insert(target, t03, anchor);
        insert(target, a0, anchor);
        append(a0, t13);
        insert(target, t22, anchor);
        insert(target, a1, anchor);
        append(a1, t32);
        insert(target, t4, anchor);
        insert(target, a2, anchor);
        append(a2, t5);
      },
      p(ctx2, dirty) {
        if (dirty & 1 && a0_href_value !== (a0_href_value = ctx2[2](ctx2[0], "xls"))) {
          attr(a0, "href", a0_href_value);
        }
        if (dirty & 1 && a1_href_value !== (a1_href_value = ctx2[2](ctx2[0], "xlsx"))) {
          attr(a1, "href", a1_href_value);
        }
        if (dirty & 1 && a2_href_value !== (a2_href_value = ctx2[2](ctx2[0], "ods"))) {
          attr(a2, "href", a2_href_value);
        }
      },
      d(detaching) {
        if (detaching)
          detach(t03);
        if (detaching)
          detach(a0);
        if (detaching)
          detach(t22);
        if (detaching)
          detach(a1);
        if (detaching)
          detach(t4);
        if (detaching)
          detach(a2);
      }
    };
  }
  function create_fragment39(ctx) {
    let span;
    let t03;
    let t1_value = _("Download as") + "";
    let t13;
    let t22;
    let a;
    let t32;
    let a_href_value;
    let t4;
    let t5;
    let if_block = ctx[1] && create_if_block14(ctx);
    return {
      c() {
        span = element("span");
        t03 = text("(");
        t13 = text(t1_value);
        t22 = space();
        a = element("a");
        t32 = text("CSV");
        t4 = space();
        if (if_block)
          if_block.c();
        t5 = text("\n  )");
        attr(a, "href", a_href_value = ctx[2](ctx[0], "csv"));
        attr(a, "data-remote", "");
        attr(span, "class", "svelte-1j4mih2");
      },
      m(target, anchor) {
        insert(target, span, anchor);
        append(span, t03);
        append(span, t13);
        append(span, t22);
        append(span, a);
        append(a, t32);
        append(span, t4);
        if (if_block)
          if_block.m(span, null);
        append(span, t5);
      },
      p(ctx2, [dirty]) {
        if (dirty & 1 && a_href_value !== (a_href_value = ctx2[2](ctx2[0], "csv"))) {
          attr(a, "href", a_href_value);
        }
        if (ctx2[1]) {
          if (if_block) {
            if_block.p(ctx2, dirty);
          } else {
            if_block = create_if_block14(ctx2);
            if_block.c();
            if_block.m(span, t5);
          }
        } else if (if_block) {
          if_block.d(1);
          if_block = null;
        }
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(span);
        if (if_block)
          if_block.d();
      }
    };
  }
  function instance38($$self, $$props, $$invalidate) {
    let $HAVE_EXCEL;
    component_subscribe($$self, HAVE_EXCEL, ($$value) => $$invalidate(1, $HAVE_EXCEL = $$value));
    let {query} = $$props;
    function queryUrl(query_string, format2) {
      return urlFor(`download-query/query_result.${format2}`, {query_string});
    }
    $$self.$$set = ($$props2) => {
      if ("query" in $$props2)
        $$invalidate(0, query = $$props2.query);
    };
    return [query, $HAVE_EXCEL, queryUrl];
  }
  var QueryLinks = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance38, create_fragment39, safe_not_equal, {query: 0});
    }
  };
  var QueryLinks_default = QueryLinks;

  // src/query/Query.svelte
  function get_each_context20(ctx, list, i) {
    const child_ctx = ctx.slice();
    child_ctx[11] = list[i][0];
    child_ctx[12] = list[i][1].result;
    child_ctx[13] = list[i][1].error;
    child_ctx[14] = list;
    child_ctx[15] = i;
    return child_ctx;
  }
  function create_if_block_33(ctx) {
    let span;
    let t;
    let querylinks;
    let current;
    querylinks = new QueryLinks_default({
      props: {query: ctx[11]}
    });
    return {
      c() {
        span = element("span");
        t = space();
        create_component(querylinks.$$.fragment);
        attr(span, "class", "spacer");
      },
      m(target, anchor) {
        insert(target, span, anchor);
        insert(target, t, anchor);
        mount_component(querylinks, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const querylinks_changes = {};
        if (dirty & 4)
          querylinks_changes.query = ctx2[11];
        querylinks.$set(querylinks_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(querylinks.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(querylinks.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(span);
        if (detaching)
          detach(t);
        destroy_component(querylinks, detaching);
      }
    };
  }
  function create_if_block_26(ctx) {
    let html_tag;
    let raw_value = ctx[13] + "";
    let html_anchor;
    return {
      c() {
        html_anchor = empty();
        html_tag = new HtmlTag(html_anchor);
      },
      m(target, anchor) {
        html_tag.m(raw_value, target, anchor);
        insert(target, html_anchor, anchor);
      },
      p(ctx2, dirty) {
        if (dirty & 4 && raw_value !== (raw_value = ctx2[13] + ""))
          html_tag.p(raw_value);
      },
      i: noop,
      o: noop,
      d(detaching) {
        if (detaching)
          detach(html_anchor);
        if (detaching)
          html_tag.d();
      }
    };
  }
  function create_if_block15(ctx) {
    let t;
    let html_tag;
    let raw_value = ctx[12].table + "";
    let html_anchor;
    let current;
    let if_block = ctx[12].chart && create_if_block_110(ctx);
    return {
      c() {
        if (if_block)
          if_block.c();
        t = space();
        html_anchor = empty();
        html_tag = new HtmlTag(html_anchor);
      },
      m(target, anchor) {
        if (if_block)
          if_block.m(target, anchor);
        insert(target, t, anchor);
        html_tag.m(raw_value, target, anchor);
        insert(target, html_anchor, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        if (ctx2[12].chart) {
          if (if_block) {
            if_block.p(ctx2, dirty);
            if (dirty & 4) {
              transition_in(if_block, 1);
            }
          } else {
            if_block = create_if_block_110(ctx2);
            if_block.c();
            transition_in(if_block, 1);
            if_block.m(t.parentNode, t);
          }
        } else if (if_block) {
          group_outros();
          transition_out(if_block, 1, 1, () => {
            if_block = null;
          });
          check_outros();
        }
        if ((!current || dirty & 4) && raw_value !== (raw_value = ctx2[12].table + ""))
          html_tag.p(raw_value);
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block);
        current = true;
      },
      o(local) {
        transition_out(if_block);
        current = false;
      },
      d(detaching) {
        if (if_block)
          if_block.d(detaching);
        if (detaching)
          detach(t);
        if (detaching)
          detach(html_anchor);
        if (detaching)
          html_tag.d();
      }
    };
  }
  function create_if_block_110(ctx) {
    let chart;
    let current;
    chart = new Chart_default({
      props: {chart: ctx[12].chart}
    });
    return {
      c() {
        create_component(chart.$$.fragment);
      },
      m(target, anchor) {
        mount_component(chart, target, anchor);
        current = true;
      },
      p(ctx2, dirty) {
        const chart_changes = {};
        if (dirty & 4)
          chart_changes.chart = ctx2[12].chart;
        chart.$set(chart_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(chart.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(chart.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(chart, detaching);
      }
    };
  }
  function create_each_block20(key_1, ctx) {
    let details;
    let summary;
    let pre;
    let code;
    let t0_value = ctx[11] + "";
    let t03;
    let t13;
    let t22;
    let div;
    let current_block_type_index;
    let if_block1;
    let t32;
    let history_item = ctx[11];
    let current;
    let mounted;
    let dispose;
    let if_block0 = ctx[12] && create_if_block_33(ctx);
    function click_handler() {
      return ctx[8](ctx[11]);
    }
    const if_block_creators = [create_if_block15, create_if_block_26];
    const if_blocks = [];
    function select_block_type(ctx2, dirty) {
      if (ctx2[12])
        return 0;
      if (ctx2[13])
        return 1;
      return -1;
    }
    if (~(current_block_type_index = select_block_type(ctx, -1))) {
      if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
    }
    const assign_details = () => ctx[9](details, history_item);
    const unassign_details = () => ctx[9](null, history_item);
    return {
      key: key_1,
      first: null,
      c() {
        details = element("details");
        summary = element("summary");
        pre = element("pre");
        code = element("code");
        t03 = text(t0_value);
        t13 = space();
        if (if_block0)
          if_block0.c();
        t22 = space();
        div = element("div");
        if (if_block1)
          if_block1.c();
        t32 = space();
        attr(div, "class", "svelte-yulyqv");
        attr(details, "class", "svelte-yulyqv");
        toggle_class(details, "error", ctx[13]);
        this.first = details;
      },
      m(target, anchor) {
        insert(target, details, anchor);
        append(details, summary);
        append(summary, pre);
        append(pre, code);
        append(code, t03);
        append(summary, t13);
        if (if_block0)
          if_block0.m(summary, null);
        append(details, t22);
        append(details, div);
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].m(div, null);
        }
        append(details, t32);
        assign_details();
        current = true;
        if (!mounted) {
          dispose = listen(summary, "click", click_handler);
          mounted = true;
        }
      },
      p(new_ctx, dirty) {
        ctx = new_ctx;
        if ((!current || dirty & 4) && t0_value !== (t0_value = ctx[11] + ""))
          set_data(t03, t0_value);
        if (ctx[12]) {
          if (if_block0) {
            if_block0.p(ctx, dirty);
            if (dirty & 4) {
              transition_in(if_block0, 1);
            }
          } else {
            if_block0 = create_if_block_33(ctx);
            if_block0.c();
            transition_in(if_block0, 1);
            if_block0.m(summary, null);
          }
        } else if (if_block0) {
          group_outros();
          transition_out(if_block0, 1, 1, () => {
            if_block0 = null;
          });
          check_outros();
        }
        let previous_block_index = current_block_type_index;
        current_block_type_index = select_block_type(ctx, dirty);
        if (current_block_type_index === previous_block_index) {
          if (~current_block_type_index) {
            if_blocks[current_block_type_index].p(ctx, dirty);
          }
        } else {
          if (if_block1) {
            group_outros();
            transition_out(if_blocks[previous_block_index], 1, 1, () => {
              if_blocks[previous_block_index] = null;
            });
            check_outros();
          }
          if (~current_block_type_index) {
            if_block1 = if_blocks[current_block_type_index];
            if (!if_block1) {
              if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
              if_block1.c();
            } else {
              if_block1.p(ctx, dirty);
            }
            transition_in(if_block1, 1);
            if_block1.m(div, null);
          } else {
            if_block1 = null;
          }
        }
        if (history_item !== ctx[11]) {
          unassign_details();
          history_item = ctx[11];
          assign_details();
        }
        if (dirty & 4) {
          toggle_class(details, "error", ctx[13]);
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(if_block0);
        transition_in(if_block1);
        current = true;
      },
      o(local) {
        transition_out(if_block0);
        transition_out(if_block1);
        current = false;
      },
      d(detaching) {
        if (detaching)
          detach(details);
        if (if_block0)
          if_block0.d();
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].d();
        }
        unassign_details();
        mounted = false;
        dispose();
      }
    };
  }
  function create_fragment40(ctx) {
    let queryeditor;
    let updating_value;
    let t;
    let div;
    let each_blocks = [];
    let each_1_lookup = new Map();
    let current;
    function queryeditor_value_binding(value) {
      ctx[7].call(null, value);
    }
    let queryeditor_props = {};
    if (ctx[0] !== void 0) {
      queryeditor_props.value = ctx[0];
    }
    queryeditor = new QueryEditor_default({props: queryeditor_props});
    binding_callbacks.push(() => bind(queryeditor, "value", queryeditor_value_binding));
    queryeditor.$on("submit", ctx[3]);
    let each_value = ctx[2];
    const get_key = (ctx2) => ctx2[11];
    for (let i = 0; i < each_value.length; i += 1) {
      let child_ctx = get_each_context20(ctx, each_value, i);
      let key = get_key(child_ctx);
      each_1_lookup.set(key, each_blocks[i] = create_each_block20(key, child_ctx));
    }
    return {
      c() {
        create_component(queryeditor.$$.fragment);
        t = space();
        div = element("div");
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].c();
        }
        attr(div, "class", "svelte-yulyqv");
      },
      m(target, anchor) {
        mount_component(queryeditor, target, anchor);
        insert(target, t, anchor);
        insert(target, div, anchor);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].m(div, null);
        }
        current = true;
      },
      p(ctx2, [dirty]) {
        const queryeditor_changes = {};
        if (!updating_value && dirty & 1) {
          updating_value = true;
          queryeditor_changes.value = ctx2[0];
          add_flush_callback(() => updating_value = false);
        }
        queryeditor.$set(queryeditor_changes);
        if (dirty & 22) {
          each_value = ctx2[2];
          group_outros();
          each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div, outro_and_destroy_block, create_each_block20, null, get_each_context20);
          check_outros();
        }
      },
      i(local) {
        if (current)
          return;
        transition_in(queryeditor.$$.fragment, local);
        for (let i = 0; i < each_value.length; i += 1) {
          transition_in(each_blocks[i]);
        }
        current = true;
      },
      o(local) {
        transition_out(queryeditor.$$.fragment, local);
        for (let i = 0; i < each_blocks.length; i += 1) {
          transition_out(each_blocks[i]);
        }
        current = false;
      },
      d(detaching) {
        destroy_component(queryeditor, detaching);
        if (detaching)
          detach(t);
        if (detaching)
          detach(div);
        for (let i = 0; i < each_blocks.length; i += 1) {
          each_blocks[i].d();
        }
      }
    };
  }
  function instance39($$self, $$props, $$invalidate) {
    let query_result_array;
    let $query_shell_history;
    component_subscribe($$self, query_shell_history, ($$value) => $$invalidate(6, $query_shell_history = $$value));
    let query_string = "";
    const resultElems = {};
    const query_results = {};
    async function setResult(query, res) {
      addToHistory(query);
      $$invalidate(5, query_results[query] = res, query_results);
      await tick();
      const url = new URL(window.location.href);
      url.searchParams.set("query_string", query);
      window.history.replaceState(null, "", url.toString());
      resultElems[query].setAttribute("open", "true");
    }
    function submit() {
      const query = query_string;
      if (!query) {
        return;
      }
      get("query_result", {
        query_string: query,
        ...getFilterParams()
      }).then((res) => {
        const chart = parseQueryChart(res.chart);
        setResult(query, {result: {chart, table: res.table}});
      }, (error) => {
        setResult(query, {error});
      });
    }
    function click(query) {
      if (!query_results[query]) {
        $$invalidate(0, query_string = query);
        submit();
      }
    }
    onMount(() => {
      const url = new URL(window.location.href);
      $$invalidate(0, query_string = url.searchParams.get("query_string") || "");
      if (query_string) {
        submit();
      }
    });
    function queryeditor_value_binding(value) {
      query_string = value;
      $$invalidate(0, query_string);
    }
    const click_handler = (history_item) => click(history_item);
    function details_binding($$value, history_item) {
      binding_callbacks[$$value ? "unshift" : "push"](() => {
        resultElems[history_item] = $$value;
        $$invalidate(1, resultElems);
        $$invalidate(2, query_result_array), $$invalidate(6, $query_shell_history), $$invalidate(5, query_results);
      });
    }
    $$self.$$.update = () => {
      if ($$self.$$.dirty & 96) {
        $:
          $$invalidate(2, query_result_array = $query_shell_history.map((item) => [item, query_results[item] || {}]));
      }
    };
    return [
      query_string,
      resultElems,
      query_result_array,
      submit,
      click,
      query_results,
      $query_shell_history,
      queryeditor_value_binding,
      click_handler,
      details_binding
    ];
  }
  var Query = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance39, create_fragment40, safe_not_equal, {});
    }
  };
  var Query_default = Query;

  // src/sidebar/AccountSelector.svelte
  function create_fragment41(ctx) {
    let autocompleteinput;
    let updating_value;
    let current;
    function autocompleteinput_value_binding(value) {
      ctx[3].call(null, value);
    }
    let autocompleteinput_props = {
      placeholder: _("Go to account"),
      selectFirst: true,
      suggestions: ctx[1],
      key: "g a"
    };
    if (ctx[0] !== void 0) {
      autocompleteinput_props.value = ctx[0];
    }
    autocompleteinput = new AutocompleteInput_default({props: autocompleteinput_props});
    binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
    autocompleteinput.$on("select", ctx[2]);
    return {
      c() {
        create_component(autocompleteinput.$$.fragment);
      },
      m(target, anchor) {
        mount_component(autocompleteinput, target, anchor);
        current = true;
      },
      p(ctx2, [dirty]) {
        const autocompleteinput_changes = {};
        if (dirty & 2)
          autocompleteinput_changes.suggestions = ctx2[1];
        if (!updating_value && dirty & 1) {
          updating_value = true;
          autocompleteinput_changes.value = ctx2[0];
          add_flush_callback(() => updating_value = false);
        }
        autocompleteinput.$set(autocompleteinput_changes);
      },
      i(local) {
        if (current)
          return;
        transition_in(autocompleteinput.$$.fragment, local);
        current = true;
      },
      o(local) {
        transition_out(autocompleteinput.$$.fragment, local);
        current = false;
      },
      d(detaching) {
        destroy_component(autocompleteinput, detaching);
      }
    };
  }
  function instance40($$self, $$props, $$invalidate) {
    let $accounts;
    component_subscribe($$self, accounts, ($$value) => $$invalidate(1, $accounts = $$value));
    let value = "";
    function select(ev) {
      if (value) {
        router_default.navigate(accountUrl(value));
        ev.detail.blur();
        $$invalidate(0, value = "");
      }
    }
    function autocompleteinput_value_binding(value$1) {
      value = value$1;
      $$invalidate(0, value);
    }
    return [value, $accounts, select, autocompleteinput_value_binding];
  }
  var AccountSelector = class extends SvelteComponent {
    constructor(options) {
      super();
      init(this, options, instance40, create_fragment41, safe_not_equal, {});
    }
  };
  var AccountSelector_default = AccountSelector;

  // src/svelte-custom-elements.ts
  var components = new Map([
    ["charts", ChartSwitcher_default],
    ["documents", Documents_default],
    ["editor", SourceEditor_default],
    ["import", Import_default],
    ["query", Query_default],
    ["account-selector", AccountSelector_default],
    ["filter-form", FilterForm_default],
    ["modals", Modals_default]
  ]);
  var SvelteCustomElement = class extends HTMLElement {
    connectedCallback() {
      if (this.component) {
        return;
      }
      const type = this.getAttribute("type");
      if (!type) {
        throw new Error("Component is missing type");
      }
      const Cls = components.get(type);
      if (!Cls) {
        throw new Error("Invalid component");
      }
      const props = {};
      const script = this.querySelector("script");
      if (script && script.type === "application/json") {
        props.data = JSON.parse(script.innerHTML);
      }
      this.component = new Cls({target: this, props});
    }
    disconnectedCallback() {
      this.component?.$destroy();
      this.component = void 0;
    }
  };

  // src/tree-table.ts
  var TreeTable = class extends HTMLElement {
    constructor() {
      super();
      const expandAllLink = this.querySelector(".expand-all");
      expandAllLink?.addEventListener("click", () => {
        expandAllLink.classList.add("hidden");
        this.querySelectorAll(".toggled").forEach((el) => {
          el.classList.remove("toggled");
        });
      });
      delegate(this, "click", "span.has-children", (event) => {
        const {target} = event;
        if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
          return;
        }
        const row = target.closest("li");
        if (!row) {
          return;
        }
        const willShow = row.classList.contains("toggled");
        if (event.shiftKey) {
          this.querySelectorAll("li").forEach((el) => {
            el.classList.toggle("toggled", !willShow);
          });
        }
        if (event.ctrlKey || event.metaKey) {
          this.querySelectorAll("li").forEach((el) => {
            el.classList.toggle("toggled", willShow);
          });
        }
        row.classList.toggle("toggled");
        expandAllLink?.classList.toggle("hidden", !this.querySelectorAll(".toggled").length);
      });
    }
  };

  // src/main.ts
  function defineCustomElements() {
    customElements.define("beancount-textarea", BeancountTextarea, {
      extends: "textarea"
    });
    customElements.define("copyable-text", CopyableText);
    customElements.define("fava-journal", FavaJournal);
    customElements.define("sortable-table", SortableTable, {extends: "table"});
    customElements.define("tree-table", TreeTable);
    customElements.define("svelte-component", SvelteCustomElement);
  }
  var pageTitle = document.querySelector("h1 strong");
  var reloadButton = document.querySelector("#reload-page");
  router_default.on("page-loaded", () => {
    favaAPIStore.set(favaAPIValidator(getScriptTagJSON("#ledger-data")));
    initCurrentKeyboardShortcuts();
    document.title = favaAPI.documentTitle;
    if (pageTitle) {
      pageTitle.innerHTML = favaAPI.pageTitle;
    }
    reloadButton?.classList.add("hidden");
    updateSidebar();
  });
  async function doPoll() {
    const changed = await get("changed");
    if (changed) {
      if (favaAPI.favaOptions["auto-reload"]) {
        router_default.reload();
      } else {
        reloadButton?.classList.remove("hidden");
        errorCount.set(await get("errors"));
        notify(_("File change detected. Click to reload."), "warning", () => {
          router_default.reload();
        });
      }
    }
  }
  function init2() {
    favaAPIStore.set(favaAPIValidator(getScriptTagJSON("#ledger-data")));
    router_default.init();
    initSyncedStoreValues();
    initSidebar();
    initGlobalKeyboardShortcuts();
    defineCustomElements();
    setInterval(doPoll, 5e3);
    reloadButton?.addEventListener("click", () => {
      router_default.reload();
    });
    router_default.trigger("page-loaded");
  }
  init2();
})();
