// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("javascript", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var statementIndent = parserConfig.statementIndent;
  var jsonldMode = parserConfig.jsonld;
  var jsonMode = parserConfig.json || jsonldMode;
  var isTS = parserConfig.typescript;
  var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;

  // Tokenizer

  var keywords = function(){
    function kw(type) {return {type: type, style: "keyword"};}
    var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
    var operator = kw("operator"), atom = {type: "atom", style: "atom"},atom1 = {type: "atom1", style: "atom1"},atom2 = {type: "atom2", style: "atom2"},atom3 = {type: "atom3", style: "atom3"},atom4 = {type: "atom4", style: "atom4"};
    return {
       "finally": B,"abstract":B,"byte":B,"case":B,"catch":B,"char":B,"class":B,"const":B,"continue":B,"default":B,"delete":B,"do":B,"double":B,"else":B,"extends":B,"false":B,"final":B,"finally":B,"float":B,"function":B,"goto":B,"if":B,"implements":B,"import":B,"in":B,"instanceof":B,"int":B,"interface":B,"long":B,"native":B,"new":B,"null":B,"package":B,"private":B,"protected":B,"public":B,"return":B,"short":B,"static":B,"super":B,"switch":B,"synchronized":B,"this":B,"throw":B,"transient":B,"true":B,"try":B,"void":B,"while":B,"with":B,"break":B,
      "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
      "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
      "function": kw("function"), "catch": kw("catch"),
      "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
      "in": operator, "typeof": operator, "instanceof": operator,
      "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
      "$n":atom1,"above":atom1,"abs":atom1,"acos":atom1,"activeelement":atom1,"alert":atom1,"alinkcolor":atom1,"asin":atom1,"assign":atom1,"atan":atom1,"atan2":atom1,"atob":atom1,"availheight":atom1,"availleft":atom1,"availtop":atom1,"availwidth":atom1,"back":atom1,"background":atom1,"below":atom1,"bgcolor":atom1,"big":atom1,"blink":atom1,"blur":atom1,"bold":atom1,"btoa":atom1,"callee":atom1,"caller":atom1,"cancelbubble":atom1,"captureevents":atom1,"ceil":atom1,"charat":atom1,"charcodeat":atom1,"charset":atom1,"checked":atom1,"children":atom1,"classes":atom1,"click":atom1,"clientinformation":atom1,"clientx":atom1,"clienty":atom1,"close":atom1,"closed":atom1,"colordepth":atom1,"compile":atom1,"complete":atom1,"concat":atom1,"confirm":atom1,"constructir":atom1,"contains":atom1,"contextual":atom1,"cookie":atom1,"cos":atom1,"crypto":atom1,"ctrlkey":atom1,"current":atom1,"data":atom1,"defaultcharset":atom1,"defaultchecked":atom1,"defaultselected":atom1,"defaultstatus":atom1,"defaultvalue":atom1,"description":atom1,"disableexternalcapture":atom1,"disableprivilege":atom1,"document":atom1,"domain":atom1,"frompoint":atom1,"elements":atom1,"embeds":atom1,"enabledplugin":atom1,"enableexternalcapture":atom1,"enableprivilege":atom1,"encoding":atom1,"escape":atom1,"eval":atom1,"event":atom1,"exec":atom1,"exp":atom1,"expando":atom1,"getclass":atom1,"getdate":atom1,"getday":atom1,"getfullyear":atom1,"gethours":atom1,"getmember":atom1,"getmilliseconds":atom1,"getminutes":atom1,"getmonth":atom1,"getseconds":atom1,"getselection":atom1,"getslot":atom1,"gettime":atom1,"gettimezoneoffset":atom1,"getutcdate":atom1,"getutcday":atom1,"getutcfullyear":atom1,"getutchours":atom1,"getutcmilliseconds":atom1,"getutcminutes":atom1,"getutcmonth":atom1,"getutcseconds":atom1,"getwindow":atom1,"getyear":atom1,"go":atom1,"handleevent":atom1,"hash":atom1,"ignorecase":atom1,"index":atom1,"indexof":atom1,"inner":atom1,"height":atom1,"innerhtml":atom1,"innertext":atom1,"innerwidth":atom1,"insertadjacenthtml":atom1,"insertadjacenttext":atom1,"isfinite":atom1,"isnan":atom1,"italics":atom1,"java":atom1,"javaenabled":atom1,"join":atom1,"keycode":atom1,"lang":atom1,"language":atom1,"lastindex":atom1,"lastindexof":atom1,"lastmatch":atom1,"lastmodified":atom1,"lastparen":atom1,"layers":atom1,"layerx":atom1,"layery":atom1,"left":atom1,"leftcontext":atom1,"length":atom1,"link":atom1,"linkcolor":atom1,"links":atom1,"ln10":atom1,"ln2":atom1,"load":atom1,"location":atom1,"locationbar":atom1,"log":atom1,"log10e":atom1,"log2e":atom1,"lowsrc":atom1,"margins":atom1,"match":atom1,"max":atom1,"max_value":atom1,"menubar":atom1,"method":atom1,"mimetypes":atom1,"min":atom1,"min_value":atom1,"modifiers":atom1,"moveabove":atom1,"movebelow":atom1,"moveby":atom1,"moveto":atom1,"movetoabsolute":atom1,"multiline":atom1,"nan":atom1,"navigate":atom1,"navigator":atom1,"negative_infinity":atom1,"netscape":atom1,"next":atom1,"offscreenbuffering":atom1,"offset":atom1,"offsetheight":atom1,"offsetleft":atom1,"offsetparent":atom1,"offsettop":atom1,"offsetwidth":atom1,"offsetx":atom1,"offsety":atom1,"onabort":atom1,"onblur":atom1,"onchange":atom1,"onclick":atom1,"ondblclick":atom1,"ondragdrop":atom1,"onerror":atom1,"onfocus":atom1,"onhelp":atom1,"onkeydown":atom1,"onkeypress":atom1,"onkeyup":atom1,"onload":atom1,"onmousedown":atom1,"onmousemove":atom1,"onmouseout":atom1,"onmouseover":atom1,"onmouseup":atom1,"onmove":atom1,"onreset":atom1,"onresize":atom1,"onsubmit":atom1,"onunload":atom1,"open":atom1,"opener":atom1,"options":atom1,"outerheight":atom1,"outerhtml":atom1,"outertext":atom1,"outerwidth":atom1,"paddings":atom1,"pagex":atom1,"pagexoffset":atom1,"pagey":atom1,"pageyoffset":atom1,"parent":atom1,"parentelement":atom1,"parentlayer":atom1,"parentwindow":atom1,"parse":atom1,"parsefloat":atom1,"parseint":atom1,"pathname":atom1,"personalbar":atom1,"pi":atom1,"pixeldepth":atom1,"platform":atom1,"plugins":atom1,"pop":atom1,"port":atom1,"positive_infinity":atom1,"pow":atom1,"preference":atom1,"previous":atom1,"print":atom1,"println":atom1,"prompt":atom1,"protocol":atom1,"prototype":atom1,"push":atom1,"random":atom1,"readystate":atom1,"reason":atom1,"referrer":atom1,"refresh":atom1,"releaseevents":atom1,"reload":atom1,"removeattribute":atom1,"removemember":atom1,"replace":atom1,"resizeby":atom1,"resizeto":atom1,"returnvalue":atom1,"reverse":atom1,"right":atom1,"rightcontext":atom1,"screenx":atom1,"screeny":atom1,"scroll":atom1,"scrollbars":atom1,"scrollby":atom1,"scrollintoview":atom1,"scrollto":atom1,"search":atom1,"select":atom1,"selected":atom1,"selectedindex":atom1,"self":atom1,"setattribute":atom1,"setday":atom1,"setfullyear":atom1,"sethotkeys":atom1,"sethours":atom1,"setinterval":atom1,"setmember":atom1,"setmilliseconds":atom1,"setminutes":atom1,"setmonth":atom1,"setresizable":atom1,"setseconds":atom1,"setslot":atom1,"settime":atom1,"settimeout":atom1,"setutcdate":atom1,"setutcfullyear":atom1,"setutchours":atom1,"setutcmillseconds":atom1,"setutcminutes":atom1,"setutcmonth":atom1,"setutcseconds":atom1,"setyear":atom1,"setzoptions":atom1,"shift":atom1,"shiftkey":atom1,"siblingabove":atom1,"siblingbelow":atom1,"signtext":atom1,"sin":atom1,"slice":atom1,"smallsort":atom1,"source":atom1,"sourceindex":atom1,"splice":atom1,"split":atom1,"sqrt":atom1,"sqrt1_2":atom1,"sqrt2":atom1,"src":atom1,"srcelement":atom1,"srcfilter":atom1,"status":atom1,"statusbar":atom1,"stop":atom1,"strike":atom1,"style":atom1,"sub":atom1,"submit":atom1,"substr":atom1,"substring":atom1,"suffixes":atom1,"sun":atom1,"sup":atom1,"systemlanguage":atom1,"tagname":atom1,"tags":atom1,"taint":atom1,"taintenabled":atom1,"tan":atom1,"target":atom1,"test":atom1,"text":atom1,"title":atom1,"toelement":atom1,"togmtstring":atom1,"tolocalestring":atom1,"tolowercase":atom1,"toolbar":atom1,"tostring":atom1,"touppercase":atom1,"toutcstring":atom1,"type":atom1,"type":atom1,"typeof":atom1,"unescape":atom1,"unshift":atom1,"untaint":atom1,"unwatch":atom1,"useragent":atom1,"userlanguage":atom1,"utc":atom1,"value":atom1,"valueof":atom1,"visibility":atom1,"vlinkcolor":atom1,"vspace":atom1,"watch":atom1,"which":atom1,"width":atom1,"window":atom1,"write":atom1,"writeln":atom1,"x":atom1,"y":atom1,"zindex":atom1,
      "anchor":atom2,"area":atom2,"array":atom2,"boolean":atom2,"crypto":atom2,"date":atom2,"function":atom2,"math":atom2,"mimetype":atom2,"navigator":atom2,"number":atom2,"packages":atom2,"random":atom2,"regexp":atom2,"string":atom2,
      "getId":atom3,"getItemValue":atom3,"getItemValueAsString":atom3,"getItemValueAsDate":atom3,"getItemValueAsDouble":atom3,"getItemValueAsInt":atom3,"countSubDocument":atom3,"sumSubDocument":atom3,"getCurrentDocument":atom3,"getDomainid":atom3,"getParentDocument":atom3,"getRelateDocument":atom3,"getDocItemValue":atom3,"getDocItemValueAsString":atom3,"getDocItemValueAsDouble":atom3,"getDocItemValueAsDate":atom3,"getDocItemValueAsInt":atom3,"findDocument":atom3,"queryByDQL":atom3,"queryByDQLWithCache":atom3,"findByDQL":atom3,"findBySQL":atom3,"queryByDQLDomain":atom3,"countByDQL":atom3,"countBySQL":atom3,"sumByDQL":atom3,"sumBySQL":atom3,"isNumberText":atom3,"isDateText":atom3,"splitText":atom3,"splitString":atom3,"joinText":atom3,"getToday":atom3,"getDay":atom3,"getMonth":atom3,"getYear":atom3,"parseDate":atom3,"diffYears":atom3,"diffMonths":atom3,"diffDays":atom3,"adjustYear":atom3,"adjustMonth":atom3,"adjustDay":atom3,"countNext":atom3,"countNext2":atom3,"getLastCount":atom3,"getLastCount2":atom3,"resetCounter":atom3,"getApplication":atom3,"getWebUser":atom3,"isPositive":atom3,"isNegative":atom3,"round":atom3,"getOptionsByDQL":atom3,"toCeil":atom3,"toFloor":atom3,"isMailAddressText":atom3,"format":atom3,"getCurDate":atom3,"diffHours":atom3,"getWorkingDayCount":atom3,"getWorkingTimesCount":atom3,"createObject":atom3,"createProcess":atom3,"getDocProcess":atom3,"getUploadProcess":atom3,"getDocumentProcess":atom3,"getDataSourceProcess":atom3,"getUserProcess":atom3,"getDepartmentProcess":atom3,"getRoleProcess":atom3,"getFormProcess":atom3,"getViewProcess":atom3,"getDomainProcess":atom3,"println":atom3,"parseInt":atom3,"parseLong":atom3,"parseDouble":atom3,"getLastRelationHis":atom3,"getLastApprover":atom3,"getLastApproverId":atom3,"getLastApproverName":atom3,"getLastApprovedTime":atom3,"getRoleByRoleNo":atom3,"doUpdateDocumentWithoutVersions":atom3,"closeSessionAndConnection":atom3,"getParamsTable":atom3,"createParamsTable":atom3,"getParameter":atom3,"getParameterAsText":atom3,"getParameterAsDouble":atom3,"getParameterAsArray":atom3,"getContextPath":atom3,"isNotNull":atom3,"queryBySQL":atom3,"queryBySQLWithCache":atom3,"createAlert":atom3,"createConfirm":atom3,"createOptions":atom3,"sendMessage":atom3,"sendMessageByDept":atom3,"sendMessageByRole":atom3,"sendSMS":atom3,"listReplyByDocid":atom3,"checkFieldUnique":atom3,"getSession":atom3,"getDepartmentByLevel":atom3,"getDeptIdByNameAndLevel":atom3,"getRoleIdByName":atom3,"getUserIdByLoginno":atom3,"getDepartmentsByParent":atom3,"getUsersByDptId":atom3,"getUsersByRoleId":atom3,"getUsersByDptIdAndRoleId":atom3,"getAllUsers":atom3,"sendMail":atom3,"sendMailtoAllUser":atom3,"sendEmailBySystemUser":atom3,"getAllRoles":atom3,"getStateLabel":atom3,"isComplete":atom3,"isCompleteByDocId":atom3,"isFirtNode":atom3,"isFirtNodeByDocId":atom3,"getParentFlowDoc":atom3,"getSubFlowDocList":atom3,"queryByDSName":atom3,"insertByDSName":atom3,"updateByDSName":atom3,"deleteByDSName":atom3,"getUserById":atom3,"getUserByLoginno":atom3,"getRoleByName":atom3,"isWorkingTime":atom3,"isWorkingTimeByCalendar":atom3,"isEditAble":atom3,"getLastFlowOperation":atom3,"setLastFlowOperation":atom3,"getFlowid":atom3,"setFlowid":atom3,"getVersions":atom3,"setVersions":atom3,"getChilds":atom3,"getChilds":atom3,"setId":atom3,"is_new":atom3,"set_new":atom3,"getLastmodified":atom3,"setLastmodified":atom3,"findItem":atom3,"addItems":atom3,"getFormShortName":atom3,"getFormname":atom3,"setFormname":atom3,"getAuditdate":atom3,"setAuditdate":atom3,"getAudituser":atom3,"getAuditusers":atom3,"setAuditusers":atom3,"setAudituser":atom3,"getCreated":atom3,"getItems":atom3,"toJSON":atom3,"get_params":atom3,"set_params":atom3,"getItemValueAsInt":atom3,"getItemValueAsString":atom3,"getItemValueAsString":atom3,"getBlobItemValueAsString":atom3,"getImgItemUrlAsString":atom3,"getItemValueAsFloat":atom3,"getItemValueAsDouble":atom3,"getItemValueAsLong":atom3,"getItemValueAsDate":atom3,"formatFieldNameByPageDiv":atom3,"get_issubdoc":atom3,"set_issubdoc":atom3,"getFormid":atom3,"setFormid":atom3,"getAuthor":atom3,"setAuthor":atom3,"setAuthor":atom3,"getStateid":atom3,"addStringItem":atom3,"addTextItem":atom3,"addDateItem":atom3,"addDoubleItem":atom3,"addLongItem":atom3,"addIntItem":atom3,"addFloatItem":atom3,"getValueByPropertyName":atom3,"getFirstNodeList":atom3,"getIstmp":atom3,"setIstmp":atom3,"deepClone":atom3,"setItems":atom3,"getStateLabel":atom3,"getStateLableList":atom3,"setStateLabel":atom3,"getParentid":atom3,"getAudituserid":atom3,"setAudituserid":atom3,"setEditAble":atom3,"getFieldPermList":atom3,"getFlowVO":atom3,"getFieldPermListInJSON":atom3,"getAuditorNames":atom3,"setAuditorNames":atom3,"getLastmodifier":atom3,"setLastmodifier":atom3,"compareFieldValue":atom3,"compareWith":atom3,"getAuditorList":atom3,"setAuditorList":atom3,"setFlowVO":atom3,"getMappingId":atom3,"setMappingId":atom3,"getForm":atom3,"getValueByField":atom3,"getParentFlowDocument":atom3,"getSubFlowDocuments":atom3,"getStateInt":atom3,"setStateInt":atom3,"clone":atom3,"compareTo":atom3,"toString":atom3,"getParent":atom3,"getId":atom3,"getState":atom3,"setParent":atom3,"setParent":atom3,"setState":atom3,"setState":atom3,"toMap":atom3,"addItem":atom3,"setCreated":atom3,"removeItem":atom3,"removeItem":atom3,"queryByParentID":atom3,"queryByParentID":atom3,"doView":atom3,"doUpdate":atom3,"doUpdate":atom3,"doUpdate":atom3,"doUpdate":atom3,"doCreate":atom3,"doCreate":atom3,"doCreate":atom3,"doCreate":atom3,"doRemove":atom3,"doRemove":atom3,"doRemove":atom3,"doQuery":atom3,"doCreateOrUpdate":atom3,"doStartFlow":atom3,"doFlow":atom3,"queryByDQL":atom3,"queryByDQL":atom3,"queryByDQLDomainName":atom3,"queryByDQLPage":atom3,"queryByDQLPage":atom3,"queryBySQL":atom3,"queryBySQL":atom3,"queryBySQL":atom3,"queryByDQLWithCache":atom3,"queryByDQLWithCache":atom3,"queryBySQLPage":atom3,"queryBySQLPage":atom3,"queryByDQLPageWithCache":atom3,"queryByDQLAndDocumentLastModifyDate":atom3,"getNeedExportDocumentTotal":atom3,"queryLimitByDQL":atom3,"sumByDQL":atom3,"sumBySQL":atom3,"countByDQL":atom3,"iteratorLimitByDQL":atom3,"mergePO":atom3,"doBatchApprove":atom3,"doBatchApprove":atom3,"doValidate":atom3,"isDocSaveUser":atom3,"countBySQL":atom3,"isNotStart":atom3,"queryModifiedDocuments":atom3,"doStartFlowOrUpdate":atom3,"doRemoveWithChildren":atom3,"doNewWithOutItems":atom3,"doNew":atom3,"doNewWithChildren":atom3,"findByDQL":atom3,"findBySQL":atom3,"doRemoveByFormName":atom3,"doRemoveDocByFields":atom3,"doApprove":atom3,"doApprove":atom3,"doViewByCondition":atom3,"createDocumentHead":atom3,"doSimpleQuery":atom3,"doSimpleQuery":atom3,"getDAO":atom3,"updateActorRTList":atom3,"isInNextNodeList":atom3,"isImpropriated":atom3,"getPendingDAO":atom3,"createMonitoProcess":atom3,"recursiveCreate":atom3,"recursiveRemove":atom3,"setId":atom3,"getVarcharvalue":atom3,"setVarcharvalue":atom3,"getNumbervalue":atom3,"setNumbervalue":atom3,"getDatevalue":atom3,"setDatevalue":atom3,"getTextvalue":atom3,"setTextvalue":atom3,"getFormname":atom3,"setFormname":atom3,"isChanged":atom3,"setChanged":atom3,"getIsbrief":atom3,"setIsbrief":atom3,"getIssubformvalue":atom3,"setIssubformvalue":atom3,"getOrderno":atom3,"setOrderno":atom3,"getValueArray":atom3,"toString":atom3,"getName":atom3,"getValue":atom3,"getId":atom3,"setName":atom3,"getType":atom3,"setValue":atom3,"setLastModified":atom3,"getLastModified":atom3,"getDocument":atom3,"setDocument":atom3,"setType":atom3,
      "$EMAIL":atom4,"$MESSAGE":atom4,"$FTP":atom4,"$CURRDOC":atom4,"$PRINTER":atom4,"$WEB":atom4,"$TOOLS":atom4,"$BEANFACTORY":atom4,"$PROCESSFACTORY":atom4,"$WEB":atom4,"$WEB":atom4,"#include":atom4,
      "this": kw("this"), "class": kw("class"), "super": kw("atom"),
      "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
      "await": C
    };
  }();

  var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
  var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;

  function readRegexp(stream) {
    var escaped = false, next, inSet = false;
    while ((next = stream.next()) != null) {
      if (!escaped) {
        if (next == "/" && !inSet) return;
        if (next == "[") inSet = true;
        else if (inSet && next == "]") inSet = false;
      }
      escaped = !escaped && next == "\\";
    }
  }

  // Used as scratch variables to communicate multiple values without
  // consing up tons of objects.
  var type, content;
  function ret(tp, style, cont) {
    type = tp; content = cont;
    return style;
  }
  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
      return ret("number", "number");
    } else if (ch == "." && stream.match("..")) {
      return ret("spread", "meta");
    } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      return ret(ch);
    } else if (ch == "=" && stream.eat(">")) {
      return ret("=>", "operator");
    } else if (ch == "0" && stream.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i)) {
      return ret("number", "number");
    } else if (/\d/.test(ch)) {
      stream.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/);
      return ret("number", "number");
    } else if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      } else if (stream.eat("/")) {
        stream.skipToEnd();
        return ret("comment", "comment");
      } else if (expressionAllowed(stream, state, 1)) {
        readRegexp(stream);
        stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
        return ret("regexp", "string-2");
      } else {
        stream.eat("=");
        return ret("operator", "operator", stream.current());
      }
    } else if (ch == "`") {
      state.tokenize = tokenQuasi;
      return tokenQuasi(stream, state);
    } else if (ch == "#") {
      stream.skipToEnd();
      return ret("error", "error");
    } else if (isOperatorChar.test(ch)) {
      if (ch != ">" || !state.lexical || state.lexical.type != ">") {
        if (stream.eat("=")) {
          if (ch == "!" || ch == "=") stream.eat("=")
        } else if (/[<>*+\-]/.test(ch)) {
          stream.eat(ch)
          if (ch == ">") stream.eat(ch)
        }
      }
      return ret("operator", "operator", stream.current());
    } else if (wordRE.test(ch)) {
      stream.eatWhile(wordRE);
      var word = stream.current()
      if (state.lastType != ".") {
        if (keywords.propertyIsEnumerable(word)) {
          var kw = keywords[word]
          return ret(kw.type, kw.style, word)
        }
        if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
          return ret("async", "keyword", word)
      }
      return ret("variable", "variable", word)
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next;
      if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
        state.tokenize = tokenBase;
        return ret("jsonld-keyword", "meta");
      }
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) break;
        escaped = !escaped && next == "\\";
      }
      if (!escaped) state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function tokenQuasi(stream, state) {
    var escaped = false, next;
    while ((next = stream.next()) != null) {
      if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
        state.tokenize = tokenBase;
        break;
      }
      escaped = !escaped && next == "\\";
    }
    return ret("quasi", "string-2", stream.current());
  }

  var brackets = "([{}])";
  // This is a crude lookahead trick to try and notice that we're
  // parsing the argument patterns for a fat-arrow function before we
  // actually hit the arrow token. It only works if the arrow is on
  // the same line as the arguments and there's no strange noise
  // (comments) in between. Fallback is to only notice when we hit the
  // arrow, and not declare the arguments as locals for the arrow
  // body.
  function findFatArrow(stream, state) {
    if (state.fatArrowAt) state.fatArrowAt = null;
    var arrow = stream.string.indexOf("=>", stream.start);
    if (arrow < 0) return;

    if (isTS) { // Try to skip TypeScript return type declarations after the arguments
      var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
      if (m) arrow = m.index
    }

    var depth = 0, sawSomething = false;
    for (var pos = arrow - 1; pos >= 0; --pos) {
      var ch = stream.string.charAt(pos);
      var bracket = brackets.indexOf(ch);
      if (bracket >= 0 && bracket < 3) {
        if (!depth) { ++pos; break; }
        if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
      } else if (bracket >= 3 && bracket < 6) {
        ++depth;
      } else if (wordRE.test(ch)) {
        sawSomething = true;
      } else if (/["'\/]/.test(ch)) {
        return;
      } else if (sawSomething && !depth) {
        ++pos;
        break;
      }
    }
    if (sawSomething && !depth) state.fatArrowAt = pos;
  }

  // Parser

  var atomicTypes = {"atom": true,"atom1": true,"atom2": true,"atom3": true,"atom4": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};

  function JSLexical(indented, column, type, align, prev, info) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.prev = prev;
    this.info = info;
    if (align != null) this.align = align;
  }

  function inScope(state, varname) {
    for (var v = state.localVars; v; v = v.next)
      if (v.name == varname) return true;
    for (var cx = state.context; cx; cx = cx.prev) {
      for (var v = cx.vars; v; v = v.next)
        if (v.name == varname) return true;
    }
  }

  function parseJS(state, style, type, content, stream) {
    var cc = state.cc;
    // Communicate our context to the combinators.
    // (Less wasteful than consing up a hundred closures on every call.)
    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;

    if (!state.lexical.hasOwnProperty("align"))
      state.lexical.align = true;

    while(true) {
      var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
      if (combinator(type, content)) {
        while(cc.length && cc[cc.length - 1].lex)
          cc.pop()();
        if (cx.marked) return cx.marked;
        if (type == "variable" && inScope(state, content)) return "variable-2";
        return style;
      }
    }
  }

  // Combinator utils

  var cx = {state: null, column: null, marked: null, cc: null};
  function pass() {
    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
  }
  function cont() {
    pass.apply(null, arguments);
    return true;
  }
  function inList(name, list) {
    for (var v = list; v; v = v.next) if (v.name == name) return true
    return false;
  }
  function register(varname) {
    var state = cx.state;
    cx.marked = "def";
    if (state.context) {
      if (state.lexical.info == "var" && state.context && state.context.block) {
        // FIXME function decls are also not block scoped
        var newContext = registerVarScoped(varname, state.context)
        if (newContext != null) {
          state.context = newContext
          return
        }
      } else if (!inList(varname, state.localVars)) {
        state.localVars = new Var(varname, state.localVars)
        return
      }
    }
    // Fall through means this is global
    if (parserConfig.globalVars && !inList(varname, state.globalVars))
      state.globalVars = new Var(varname, state.globalVars)
  }
  function registerVarScoped(varname, context) {
    if (!context) {
      return null
    } else if (context.block) {
      var inner = registerVarScoped(varname, context.prev)
      if (!inner) return null
      if (inner == context.prev) return context
      return new Context(inner, context.vars, true)
    } else if (inList(varname, context.vars)) {
      return context
    } else {
      return new Context(context.prev, new Var(varname, context.vars), false)
    }
  }

  function isModifier(name) {
    return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
  }

  // Combinators

  function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
  function Var(name, next) { this.name = name; this.next = next }

  var defaultVars = new Var("this", new Var("arguments", null))
  function pushcontext() {
    cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
    cx.state.localVars = defaultVars
  }
  function pushblockcontext() {
    cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
    cx.state.localVars = null
  }
  function popcontext() {
    cx.state.localVars = cx.state.context.vars
    cx.state.context = cx.state.context.prev
  }
  popcontext.lex = true
  function pushlex(type, info) {
    var result = function() {
      var state = cx.state, indent = state.indented;
      if (state.lexical.type == "stat") indent = state.lexical.indented;
      else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
        indent = outer.indented;
      state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
    };
    result.lex = true;
    return result;
  }
  function poplex() {
    var state = cx.state;
    if (state.lexical.prev) {
      if (state.lexical.type == ")")
        state.indented = state.lexical.indented;
      state.lexical = state.lexical.prev;
    }
  }
  poplex.lex = true;

  function expect(wanted) {
    function exp(type) {
      if (type == wanted) return cont();
      else if (wanted == ";") return pass();
      else return cont(exp);
    };
    return exp;
  }

  function statement(type, value) {
    if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
    if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
    if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
    if (type == "debugger") return cont(expect(";"));
    if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
    if (type == ";") return cont();
    if (type == "if") {
      if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
        cx.state.cc.pop()();
      return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
    }
    if (type == "function") return cont(functiondef);
    if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
    if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), className, poplex); }
    if (type == "variable") {
      if (isTS && value == "declare") {
        cx.marked = "keyword"
        return cont(statement)
      } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
        cx.marked = "keyword"
        if (value == "enum") return cont(enumdef);
        else if (value == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";"));
        else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
      } else if (isTS && value == "namespace") {
        cx.marked = "keyword"
        return cont(pushlex("form"), expression, block, poplex)
      } else if (isTS && value == "abstract") {
        cx.marked = "keyword"
        return cont(statement)
      } else {
        return cont(pushlex("stat"), maybelabel);
      }
    }
    if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
                                      block, poplex, poplex, popcontext);
    if (type == "case") return cont(expression, expect(":"));
    if (type == "default") return cont(expect(":"));
    if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
    if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
    if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
    if (type == "async") return cont(statement)
    if (value == "@") return cont(expression, statement)
    return pass(pushlex("stat"), expression, expect(";"), poplex);
  }
  function maybeCatchBinding(type) {
    if (type == "(") return cont(funarg, expect(")"))
  }
  function expression(type, value) {
    return expressionInner(type, value, false);
  }
  function expressionNoComma(type, value) {
    return expressionInner(type, value, true);
  }
  function parenExpr(type) {
    if (type != "(") return pass()
    return cont(pushlex(")"), expression, expect(")"), poplex)
  }
  function expressionInner(type, value, noComma) {
    if (cx.state.fatArrowAt == cx.stream.start) {
      var body = noComma ? arrowBodyNoComma : arrowBody;
      if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
      else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
    }

    var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
    if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
    if (type == "function") return cont(functiondef, maybeop);
    if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
    if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
    if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
    if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
    if (type == "{") return contCommasep(objprop, "}", null, maybeop);
    if (type == "quasi") return pass(quasi, maybeop);
    if (type == "new") return cont(maybeTarget(noComma));
    if (type == "import") return cont(expression);
    return cont();
  }
  function maybeexpression(type) {
    if (type.match(/[;\}\)\],]/)) return pass();
    return pass(expression);
  }

  function maybeoperatorComma(type, value) {
    if (type == ",") return cont(expression);
    return maybeoperatorNoComma(type, value, false);
  }
  function maybeoperatorNoComma(type, value, noComma) {
    var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
    var expr = noComma == false ? expression : expressionNoComma;
    if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
    if (type == "operator") {
      if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
      if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
        return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
      if (value == "?") return cont(expression, expect(":"), expr);
      return cont(expr);
    }
    if (type == "quasi") { return pass(quasi, me); }
    if (type == ";") return;
    if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
    if (type == ".") return cont(property, me);
    if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
    if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
    if (type == "regexp") {
      cx.state.lastType = cx.marked = "operator"
      cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
      return cont(expr)
    }
  }
  function quasi(type, value) {
    if (type != "quasi") return pass();
    if (value.slice(value.length - 2) != "${") return cont(quasi);
    return cont(expression, continueQuasi);
  }
  function continueQuasi(type) {
    if (type == "}") {
      cx.marked = "string-2";
      cx.state.tokenize = tokenQuasi;
      return cont(quasi);
    }
  }
  function arrowBody(type) {
    findFatArrow(cx.stream, cx.state);
    return pass(type == "{" ? statement : expression);
  }
  function arrowBodyNoComma(type) {
    findFatArrow(cx.stream, cx.state);
    return pass(type == "{" ? statement : expressionNoComma);
  }
  function maybeTarget(noComma) {
    return function(type) {
      if (type == ".") return cont(noComma ? targetNoComma : target);
      else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
      else return pass(noComma ? expressionNoComma : expression);
    };
  }
  function target(_, value) {
    if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
  }
  function targetNoComma(_, value) {
    if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
  }
  function maybelabel(type) {
    if (type == ":") return cont(poplex, statement);
    return pass(maybeoperatorComma, expect(";"), poplex);
  }
  function property(type) {
    if (type == "variable") {cx.marked = "property"; return cont();}
  }
  function objprop(type, value) {
    if (type == "async") {
      cx.marked = "property";
      return cont(objprop);
    } else if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property";
      if (value == "get" || value == "set") return cont(getterSetter);
      var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
      if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
        cx.state.fatArrowAt = cx.stream.pos + m[0].length
      return cont(afterprop);
    } else if (type == "number" || type == "string") {
      cx.marked = jsonldMode ? "property" : (cx.style + " property");
      return cont(afterprop);
    } else if (type == "jsonld-keyword") {
      return cont(afterprop);
    } else if (isTS && isModifier(value)) {
      cx.marked = "keyword"
      return cont(objprop)
    } else if (type == "[") {
      return cont(expression, maybetype, expect("]"), afterprop);
    } else if (type == "spread") {
      return cont(expressionNoComma, afterprop);
    } else if (value == "*") {
      cx.marked = "keyword";
      return cont(objprop);
    } else if (type == ":") {
      return pass(afterprop)
    }
  }
  function getterSetter(type) {
    if (type != "variable") return pass(afterprop);
    cx.marked = "property";
    return cont(functiondef);
  }
  function afterprop(type) {
    if (type == ":") return cont(expressionNoComma);
    if (type == "(") return pass(functiondef);
  }
  function commasep(what, end, sep) {
    function proceed(type, value) {
      if (sep ? sep.indexOf(type) > -1 : type == ",") {
        var lex = cx.state.lexical;
        if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
        return cont(function(type, value) {
          if (type == end || value == end) return pass()
          return pass(what)
        }, proceed);
      }
      if (type == end || value == end) return cont();
      return cont(expect(end));
    }
    return function(type, value) {
      if (type == end || value == end) return cont();
      return pass(what, proceed);
    };
  }
  function contCommasep(what, end, info) {
    for (var i = 3; i < arguments.length; i++)
      cx.cc.push(arguments[i]);
    return cont(pushlex(end, info), commasep(what, end), poplex);
  }
  function block(type) {
    if (type == "}") return cont();
    return pass(statement, block);
  }
  function maybetype(type, value) {
    if (isTS) {
      if (type == ":") return cont(typeexpr);
      if (value == "?") return cont(maybetype);
    }
  }
  function mayberettype(type) {
    if (isTS && type == ":") {
      if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
      else return cont(typeexpr)
    }
  }
  function isKW(_, value) {
    if (value == "is") {
      cx.marked = "keyword"
      return cont()
    }
  }
  function typeexpr(type, value) {
    if (value == "keyof" || value == "typeof") {
      cx.marked = "keyword"
      return cont(value == "keyof" ? typeexpr : expressionNoComma)
    }
    if (type == "variable" || value == "void") {
      cx.marked = "type"
      return cont(afterType)
    }
    if (type == "string" || type == "number" || type == "atom"|| type == "atom1"|| type == "atom2"|| type == "atom3"|| type == "atom4") return cont(afterType);
    if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
    if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
    if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType)
    if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
  }
  function maybeReturnType(type) {
    if (type == "=>") return cont(typeexpr)
  }
  function typeprop(type, value) {
    if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property"
      return cont(typeprop)
    } else if (value == "?") {
      return cont(typeprop)
    } else if (type == ":") {
      return cont(typeexpr)
    } else if (type == "[") {
      return cont(expression, maybetype, expect("]"), typeprop)
    }
  }
  function typearg(type, value) {
    if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
    if (type == ":") return cont(typeexpr)
    return pass(typeexpr)
  }
  function afterType(type, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
    if (value == "|" || type == "." || value == "&") return cont(typeexpr)
    if (type == "[") return cont(expect("]"), afterType)
    if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
  }
  function maybeTypeArgs(_, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
  }
  function typeparam() {
    return pass(typeexpr, maybeTypeDefault)
  }
  function maybeTypeDefault(_, value) {
    if (value == "=") return cont(typeexpr)
  }
  function vardef(_, value) {
    if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
    return pass(pattern, maybetype, maybeAssign, vardefCont);
  }
  function pattern(type, value) {
    if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
    if (type == "variable") { register(value); return cont(); }
    if (type == "spread") return cont(pattern);
    if (type == "[") return contCommasep(pattern, "]");
    if (type == "{") return contCommasep(proppattern, "}");
  }
  function proppattern(type, value) {
    if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
      register(value);
      return cont(maybeAssign);
    }
    if (type == "variable") cx.marked = "property";
    if (type == "spread") return cont(pattern);
    if (type == "}") return pass();
    return cont(expect(":"), pattern, maybeAssign);
  }
  function maybeAssign(_type, value) {
    if (value == "=") return cont(expressionNoComma);
  }
  function vardefCont(type) {
    if (type == ",") return cont(vardef);
  }
  function maybeelse(type, value) {
    if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
  }
  function forspec(type, value) {
    if (value == "await") return cont(forspec);
    if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
  }
  function forspec1(type) {
    if (type == "var") return cont(vardef, expect(";"), forspec2);
    if (type == ";") return cont(forspec2);
    if (type == "variable") return cont(formaybeinof);
    return pass(expression, expect(";"), forspec2);
  }
  function formaybeinof(_type, value) {
    if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
    return cont(maybeoperatorComma, forspec2);
  }
  function forspec2(type, value) {
    if (type == ";") return cont(forspec3);
    if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
    return pass(expression, expect(";"), forspec3);
  }
  function forspec3(type) {
    if (type != ")") cont(expression);
  }
  function functiondef(type, value) {
    if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
    if (type == "variable") {register(value); return cont(functiondef);}
    if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
    if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
  }
  function funarg(type, value) {
    if (value == "@") cont(expression, funarg)
    if (type == "spread") return cont(funarg);
    if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
    return pass(pattern, maybetype, maybeAssign);
  }
  function classExpression(type, value) {
    // Class expressions may have an optional name.
    if (type == "variable") return className(type, value);
    return classNameAfter(type, value);
  }
  function className(type, value) {
    if (type == "variable") {register(value); return cont(classNameAfter);}
  }
  function classNameAfter(type, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
    if (value == "extends" || value == "implements" || (isTS && type == ",")) {
      if (value == "implements") cx.marked = "keyword";
      return cont(isTS ? typeexpr : expression, classNameAfter);
    }
    if (type == "{") return cont(pushlex("}"), classBody, poplex);
  }
  function classBody(type, value) {
    if (type == "async" ||
        (type == "variable" &&
         (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
         cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
      cx.marked = "keyword";
      return cont(classBody);
    }
    if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property";
      return cont(isTS ? classfield : functiondef, classBody);
    }
    if (type == "[")
      return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
    if (value == "*") {
      cx.marked = "keyword";
      return cont(classBody);
    }
    if (type == ";") return cont(classBody);
    if (type == "}") return cont();
    if (value == "@") return cont(expression, classBody)
  }
  function classfield(type, value) {
    if (value == "?") return cont(classfield)
    if (type == ":") return cont(typeexpr, maybeAssign)
    if (value == "=") return cont(expressionNoComma)
    return pass(functiondef)
  }
  function afterExport(type, value) {
    if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
    if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
    if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
    return pass(statement);
  }
  function exportField(type, value) {
    if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
    if (type == "variable") return pass(expressionNoComma, exportField);
  }
  function afterImport(type) {
    if (type == "string") return cont();
    if (type == "(") return pass(expression);
    return pass(importSpec, maybeMoreImports, maybeFrom);
  }
  function importSpec(type, value) {
    if (type == "{") return contCommasep(importSpec, "}");
    if (type == "variable") register(value);
    if (value == "*") cx.marked = "keyword";
    return cont(maybeAs);
  }
  function maybeMoreImports(type) {
    if (type == ",") return cont(importSpec, maybeMoreImports)
  }
  function maybeAs(_type, value) {
    if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
  }
  function maybeFrom(_type, value) {
    if (value == "from") { cx.marked = "keyword"; return cont(expression); }
  }
  function arrayLiteral(type) {
    if (type == "]") return cont();
    return pass(commasep(expressionNoComma, "]"));
  }
  function enumdef() {
    return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
  }
  function enummember() {
    return pass(pattern, maybeAssign);
  }

  function isContinuedStatement(state, textAfter) {
    return state.lastType == "operator" || state.lastType == "," ||
      isOperatorChar.test(textAfter.charAt(0)) ||
      /[,.]/.test(textAfter.charAt(0));
  }

  function expressionAllowed(stream, state, backUp) {
    return state.tokenize == tokenBase &&
      /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
      (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
  }

  // Interface

  return {
    startState: function(basecolumn) {
      var state = {
        tokenize: tokenBase,
        lastType: "sof",
        cc: [],
        lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
        localVars: parserConfig.localVars,
        context: parserConfig.localVars && new Context(null, null, false),
        indented: basecolumn || 0
      };
      if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
        state.globalVars = parserConfig.globalVars;
      return state;
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if (!state.lexical.hasOwnProperty("align"))
          state.lexical.align = false;
        state.indented = stream.indentation();
        findFatArrow(stream, state);
      }
      if (state.tokenize != tokenComment && stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);
      if (type == "comment") return style;
      state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
      return parseJS(state, style, type, content, stream);
    },

    indent: function(state, textAfter) {
      if (state.tokenize == tokenComment) return CodeMirror.Pass;
      if (state.tokenize != tokenBase) return 0;
      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
      // Kludge to prevent 'maybelse' from blocking lexical scope pops
      if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
        var c = state.cc[i];
        if (c == poplex) lexical = lexical.prev;
        else if (c != maybeelse) break;
      }
      while ((lexical.type == "stat" || lexical.type == "form") &&
             (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
                                   (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
                                   !/^[,\.=+\-*:?[\(]/.test(textAfter))))
        lexical = lexical.prev;
      if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
        lexical = lexical.prev;
      var type = lexical.type, closing = firstChar == type;

      if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
      else if (type == "form" && firstChar == "{") return lexical.indented;
      else if (type == "form") return lexical.indented + indentUnit;
      else if (type == "stat")
        return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
      else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
        return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
      else if (lexical.align) return lexical.column + (closing ? 0 : 1);
      else return lexical.indented + (closing ? 0 : indentUnit);
    },

    electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
    blockCommentStart: jsonMode ? null : "/*",
    blockCommentEnd: jsonMode ? null : "*/",
    blockCommentContinue: jsonMode ? null : " * ",
    lineComment: jsonMode ? null : "//",
    fold: "brace",
    closeBrackets: "()[]{}''\"\"``",

    helperType: jsonMode ? "json" : "javascript",
    jsonldMode: jsonldMode,
    jsonMode: jsonMode,

    expressionAllowed: expressionAllowed,

    skipExpression: function(state) {
      var top = state.cc[state.cc.length - 1]
      if (top == expression || top == expressionNoComma) state.cc.pop()
    }
  };
});

CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);

CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });

});
