"use strict";var e=require("obsidian"),t=require("@codemirror/view"),n=require("@codemirror/state"),r=require("@codemirror/language");class i{static get version(){return"1.4.0"}static toString(){return"JavaScript Expression Parser (JSEP) v"+i.version}static addUnaryOp(e){return i.max_unop_len=Math.max(e.length,i.max_unop_len),i.unary_ops[e]=1,i}static addBinaryOp(e,t,n){return i.max_binop_len=Math.max(e.length,i.max_binop_len),i.binary_ops[e]=t,n?i.right_associative.add(e):i.right_associative.delete(e),i}static addIdentifierChar(e){return i.additional_identifier_chars.add(e),i}static addLiteral(e,t){return i.literals[e]=t,i}static removeUnaryOp(e){return delete i.unary_ops[e],e.length===i.max_unop_len&&(i.max_unop_len=i.getMaxKeyLen(i.unary_ops)),i}static removeAllUnaryOps(){return i.unary_ops={},i.max_unop_len=0,i}static removeIdentifierChar(e){return i.additional_identifier_chars.delete(e),i}static removeBinaryOp(e){return delete i.binary_ops[e],e.length===i.max_binop_len&&(i.max_binop_len=i.getMaxKeyLen(i.binary_ops)),i.right_associative.delete(e),i}static removeAllBinaryOps(){return i.binary_ops={},i.max_binop_len=0,i}static removeLiteral(e){return delete i.literals[e],i}static removeAllLiterals(){return i.literals={},i}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new i(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map(e=>e.length))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return i.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!i.binary_ops[String.fromCharCode(e)]||i.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return i.isIdentifierStart(e)||i.isDecimalDigit(e)}throwError(e){const t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(i.hooks[e]){const n={context:this,node:t};return i.hooks.run(e,n),n.node}return t}searchHook(e){if(i.hooks[e]){const t={context:this};return i.hooks[e].find(function(e){return e.call(t.context,t),t.node}),t.node}}gobbleSpaces(){let e=this.code;for(;e===i.SPACE_CODE||e===i.TAB_CODE||e===i.LF_CODE||e===i.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");const e=this.gobbleExpressions(),t=1===e.length?e[0]:{type:i.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t,n,r=[];for(;this.index0;){if(i.binary_ops.hasOwnProperty(e)&&(!i.isIdentifierStart(this.code)||this.index+e.lengtho.right_a&&e.right_a?n>e.prec:n<=e.prec;for(;r.length>2&&c(r[r.length-2]);)a=r.pop(),t=r.pop().value,s=r.pop(),e={type:i.BINARY_EXP,operator:t,left:s,right:a},r.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+l),r.push(o,e)}for(c=r.length-1,e=r[c];c>1;)e={type:i.BINARY_EXP,operator:r[c-1].value,left:r[c-2],right:e},c-=2;return e}gobbleToken(){let e,t,n,r;if(this.gobbleSpaces(),r=this.searchHook("gobble-token"),r)return this.runHook("after-token",r);if(e=this.code,i.isDecimalDigit(e)||e===i.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===i.SQUOTE_CODE||e===i.DQUOTE_CODE)r=this.gobbleStringLiteral();else if(e===i.OBRACK_CODE)r=this.gobbleArray();else{for(t=this.expr.substr(this.index,i.max_unop_len),n=t.length;n>0;){if(i.unary_ops.hasOwnProperty(t)&&(!i.isIdentifierStart(this.code)||this.index+t.length=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}if(o===i.COMMA_CODE){if(this.index++,r++,r!==t.length)if(e===i.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===i.CBRACK_CODE)for(let e=t.length;e{if("object"!=typeof e||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}}(i),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"??":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10,"**":11},right_associative:new Set(["**"]),additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"}),i.max_unop_len=i.getMaxKeyLen(i.unary_ops),i.max_binop_len=i.getMaxKeyLen(i.binary_ops);const s=e=>new i(e).parse(),a=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(i).filter(e=>!a.includes(e)&&void 0===s[e]).forEach(e=>{s[e]=i[e]}),s.Jsep=i;var c={name:"ternary",init(e){e.hooks.add("after-expression",function(t){if(t.node&&this.code===e.QUMARK_CODE){this.index++;const n=t.node,r=this.gobbleExpression();if(r||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===e.COLON_CODE){this.index++;const i=this.gobbleExpression();if(i||this.throwError("Expected expression"),t.node={type:"ConditionalExpression",test:n,consequent:r,alternate:i},n.operator&&e.binary_ops[n.operator]<=.9){let r=n;for(;r.right.operator&&e.binary_ops[r.right.operator]<=.9;)r=r.right;t.node.test=r.right,r.right=t.node,t.node=n}}else this.throwError("Expected :")}})}};s.plugins.register(c);var l={name:"regex",init(e){e.hooks.add("gobble-token",function(t){if(47===this.code){const n=++this.index;let r=!1;for(;this.index=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57))break;o+=this.char}try{i=new RegExp(r,o)}catch(e){this.throwError(e.message)}return t.node={type:e.LITERAL,value:i,raw:this.expr.slice(n-1,this.index)},t.node=this.gobbleTokenProperty(t.node),t.node}this.code===e.OBRACK_CODE?r=!0:r&&this.code===e.CBRACK_CODE&&(r=!1),this.index+=92===this.code?2:1}this.throwError("Unclosed Regex")}})}};const u={name:"assignment",assignmentOperators:new Set(["=","*=","**=","/=","%=","+=","-=","<<=",">>=",">>>=","&=","^=","|=","||=","&&=","??="]),updateOperators:[43,45],assignmentPrecedence:.9,init(e){const t=[e.IDENTIFIER,e.MEMBER_EXP];function n(e){u.assignmentOperators.has(e.operator)?(e.type="AssignmentExpression",n(e.left),n(e.right)):e.operator||Object.values(e).forEach(e=>{e&&"object"==typeof e&&n(e)})}u.assignmentOperators.forEach(t=>e.addBinaryOp(t,u.assignmentPrecedence,!0)),e.hooks.add("gobble-token",function(e){const n=this.code;u.updateOperators.some(e=>e===n&&e===this.expr.charCodeAt(this.index+1))&&(this.index+=2,e.node={type:"UpdateExpression",operator:43===n?"++":"--",argument:this.gobbleTokenProperty(this.gobbleIdentifier()),prefix:!0},e.node.argument&&t.includes(e.node.argument.type)||this.throwError(`Unexpected ${e.node.operator}`))}),e.hooks.add("after-token",function(e){if(e.node){const n=this.code;u.updateOperators.some(e=>e===n&&e===this.expr.charCodeAt(this.index+1))&&(t.includes(e.node.type)||this.throwError(`Unexpected ${e.node.operator}`),this.index+=2,e.node={type:"UpdateExpression",operator:43===n?"++":"--",argument:e.node,prefix:!1})}}),e.hooks.add("after-expression",function(e){e.node&&n(e.node)})}};s.plugins.register(l,u),s.addUnaryOp("typeof"),s.addLiteral("null",null),s.addLiteral("undefined",void 0);const h=new Set(["constructor","__proto__","__defineGetter__","__defineSetter__"]),f={evalAst(e,t){switch(e.type){case"BinaryExpression":case"LogicalExpression":return f.evalBinaryExpression(e,t);case"Compound":return f.evalCompound(e,t);case"ConditionalExpression":return f.evalConditionalExpression(e,t);case"Identifier":return f.evalIdentifier(e,t);case"Literal":return f.evalLiteral(e,t);case"MemberExpression":return f.evalMemberExpression(e,t);case"UnaryExpression":return f.evalUnaryExpression(e,t);case"ArrayExpression":return f.evalArrayExpression(e,t);case"CallExpression":return f.evalCallExpression(e,t);case"AssignmentExpression":return f.evalAssignmentExpression(e,t);default:throw SyntaxError("Unexpected expression",e)}},evalBinaryExpression:(e,t)=>({"||":(e,t)=>e||t(),"&&":(e,t)=>e&&t(),"|":(e,t)=>e|t(),"^":(e,t)=>e^t(),"&":(e,t)=>e&t(),"==":(e,t)=>e==t(),"!=":(e,t)=>e!=t(),"===":(e,t)=>e===t(),"!==":(e,t)=>e!==t(),"<":(e,t)=>e":(e,t)=>e>t(),"<=":(e,t)=>e<=t(),">=":(e,t)=>e>=t(),"<<":(e,t)=>e<>":(e,t)=>e>>t(),">>>":(e,t)=>e>>>t(),"+":(e,t)=>e+t(),"-":(e,t)=>e-t(),"*":(e,t)=>e*t(),"/":(e,t)=>e/t(),"%":(e,t)=>e%t()}[e.operator](f.evalAst(e.left,t),()=>f.evalAst(e.right,t))),evalCompound(e,t){let n;for(let r=0;rf.evalAst(e.test,t)?f.evalAst(e.consequent,t):f.evalAst(e.alternate,t),evalIdentifier(e,t){if(Object.hasOwn(t,e.name))return t[e.name];throw ReferenceError(`${e.name} is not defined`)},evalLiteral:e=>e.value,evalMemberExpression(e,t){const n=String(e.computed?f.evalAst(e.property):e.property.name),r=f.evalAst(e.object,t);if(null==r)throw TypeError(`Cannot read properties of ${r} (reading '${n}')`);if(!Object.hasOwn(r,n)&&h.has(n))throw TypeError(`Cannot read properties of ${r} (reading '${n}')`);const i=r[n];return"function"==typeof i?i.bind(r):i},evalUnaryExpression:(e,t)=>({"-":e=>-f.evalAst(e,t),"!":e=>!f.evalAst(e,t),"~":e=>~f.evalAst(e,t),"+":e=>+f.evalAst(e,t),typeof:e=>typeof f.evalAst(e,t)}[e.operator](e.argument)),evalArrayExpression:(e,t)=>e.elements.map(e=>f.evalAst(e,t)),evalCallExpression(e,t){const n=e.arguments.map(e=>f.evalAst(e,t));return f.evalAst(e.callee,t)(...n)},evalAssignmentExpression(e,t){if("Identifier"!==e.left.type)throw SyntaxError("Invalid left-hand side in assignment");const n=e.left.name,r=f.evalAst(e.right,t);return t[n]=r,t[n]}};function p(e,t){return(e=e.slice()).push(t),e}function d(e,t){return(t=t.slice()).unshift(e),t}class g extends Error{constructor(e){super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'),this.avoidNew=!0,this.value=e,this.name="NewError"}}function m(e,t,n,r,i){if(!(this instanceof m))try{return new m(e,t,n,r,i)}catch(e){if(!e.avoidNew)throw e;return e.value}"string"==typeof e&&(i=r,r=n,n=t,t=e,e=null);const o=e&&"object"==typeof e;if(e=e||{},this.json=e.json||n,this.path=e.path||t,this.resultType=e.resultType||"value",this.flatten=e.flatten||!1,this.wrap=!Object.hasOwn(e,"wrap")||e.wrap,this.sandbox=e.sandbox||{},this.eval=void 0===e.eval?"safe":e.eval,this.ignoreEvalErrors=void 0!==e.ignoreEvalErrors&&e.ignoreEvalErrors,this.parent=e.parent||null,this.parentProperty=e.parentProperty||null,this.callback=e.callback||r||null,this.otherTypeCallback=e.otherTypeCallback||i||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==e.autostart){const r={path:o?e.path:t};o?"json"in e&&(r.json=e.json):r.json=n;const i=this.evaluate(r);if(!i||"object"!=typeof i)throw new g(i);return i}}m.prototype.evaluate=function(e,t,n,r){let i=this.parent,o=this.parentProperty,{flatten:s,wrap:a}=this;if(this.currResultType=this.resultType,this.currEval=this.eval,this.currSandbox=this.sandbox,n=n||this.callback,this.currOtherTypeCallback=r||this.otherTypeCallback,t=t||this.json,(e=e||this.path)&&"object"==typeof e&&!Array.isArray(e)){if(!e.path&&""!==e.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!Object.hasOwn(e,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');({json:t}=e),s=Object.hasOwn(e,"flatten")?e.flatten:s,this.currResultType=Object.hasOwn(e,"resultType")?e.resultType:this.currResultType,this.currSandbox=Object.hasOwn(e,"sandbox")?e.sandbox:this.currSandbox,a=Object.hasOwn(e,"wrap")?e.wrap:a,this.currEval=Object.hasOwn(e,"eval")?e.eval:this.currEval,n=Object.hasOwn(e,"callback")?e.callback:n,this.currOtherTypeCallback=Object.hasOwn(e,"otherTypeCallback")?e.otherTypeCallback:this.currOtherTypeCallback,i=Object.hasOwn(e,"parent")?e.parent:i,o=Object.hasOwn(e,"parentProperty")?e.parentProperty:o,e=e.path}if(i=i||null,o=o||null,Array.isArray(e)&&(e=m.toPathString(e)),!e&&""!==e||!t)return;const c=m.toPathArray(e);"$"===c[0]&&c.length>1&&c.shift(),this._hasParentSelector=null;const l=this._trace(c,t,["$"],i,o,n).filter(function(e){return e&&!e.isParentSelector});return l.length?a||1!==l.length||l[0].hasArrExpr?l.reduce((e,t)=>{const n=this._getPreferredOutput(t);return s&&Array.isArray(n)?e=e.concat(n):e.push(n),e},[]):this._getPreferredOutput(l[0]):a?[]:void 0},m.prototype._getPreferredOutput=function(e){const t=this.currResultType;switch(t){case"all":{const t=Array.isArray(e.path)?e.path:m.toPathArray(e.path);return e.pointer=m.toPointer(t),e.path="string"==typeof e.path?e.path:m.toPathString(e.path),e}case"value":case"parent":case"parentProperty":return e[t];case"path":return m.toPathString(e[t]);case"pointer":return m.toPointer(e.path);default:throw new TypeError("Unknown result type")}},m.prototype._handleCallback=function(e,t,n){if(t){const r=this._getPreferredOutput(e);e.path="string"==typeof e.path?e.path:m.toPathString(e.path),t(r,n,e)}},m.prototype._trace=function(e,t,n,r,i,o,s,a){let c;if(!e.length)return c={path:n,value:t,parent:r,parentProperty:i,hasArrExpr:s},this._handleCallback(c,o,"value"),c;const l=e[0],u=e.slice(1),h=[];function f(e){Array.isArray(e)?e.forEach(e=>{h.push(e)}):h.push(e)}if(("string"!=typeof l||a)&&t&&Object.hasOwn(t,l))f(this._trace(u,t[l],p(n,l),t,l,o,s));else if("*"===l)this._walk(t,e=>{f(this._trace(u,t[e],p(n,e),t,e,o,!0,!0))});else if(".."===l)f(this._trace(u,t,n,r,i,o,s)),this._walk(t,r=>{"object"==typeof t[r]&&f(this._trace(e.slice(),t[r],p(n,r),t,r,o,!0))});else{if("^"===l)return this._hasParentSelector=!0,{path:n.slice(0,-1),expr:u,isParentSelector:!0};if("~"===l)return c={path:p(n,l),value:i,parent:r,parentProperty:null},this._handleCallback(c,o,"property"),c;if("$"===l)f(this._trace(u,t,n,null,null,o,s));else if(/^(-?\d*):(-?\d*):?(\d*)$/u.test(l))f(this._slice(l,u,t,n,r,i,o));else if(0===l.indexOf("?(")){if(!1===this.currEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");const e=l.replace(/^\?\((.*?)\)$/u,"$1"),s=/@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(e);s?this._walk(t,e=>{const a=[s[2]],c=s[1]?t[e][s[1]]:t[e];this._trace(a,c,n,r,i,o,!0).length>0&&f(this._trace(u,t[e],p(n,e),t,e,o,!0))}):this._walk(t,s=>{this._eval(e,t[s],s,n,r,i)&&f(this._trace(u,t[s],p(n,s),t,s,o,!0))})}else if("("===l[0]){if(!1===this.currEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");f(this._trace(d(this._eval(l,t,n.at(-1),n.slice(0,-1),r,i),u),t,n,r,i,o,s))}else if("@"===l[0]){let e=!1;const s=l.slice(1,-2);switch(s){case"scalar":t&&["object","function"].includes(typeof t)||(e=!0);break;case"boolean":case"string":case"undefined":case"function":typeof t===s&&(e=!0);break;case"integer":!Number.isFinite(t)||t%1||(e=!0);break;case"number":Number.isFinite(t)&&(e=!0);break;case"nonFinite":"number"!=typeof t||Number.isFinite(t)||(e=!0);break;case"object":t&&typeof t===s&&(e=!0);break;case"array":Array.isArray(t)&&(e=!0);break;case"other":e=this.currOtherTypeCallback(t,n,r,i);break;case"null":null===t&&(e=!0);break;default:throw new TypeError("Unknown value type "+s)}if(e)return c={path:n,value:t,parent:r,parentProperty:i},this._handleCallback(c,o,"value"),c}else if("`"===l[0]&&t&&Object.hasOwn(t,l.slice(1))){const e=l.slice(1);f(this._trace(u,t[e],p(n,e),t,e,o,s,!0))}else if(l.includes(",")){const e=l.split(",");for(const s of e)f(this._trace(d(s,u),t,n,r,i,o,!0))}else!a&&t&&Object.hasOwn(t,l)&&f(this._trace(u,t[l],p(n,l),t,l,o,s,!0))}if(this._hasParentSelector)for(let e=0;e{t(e)})},m.prototype._slice=function(e,t,n,r,i,o,s){if(!Array.isArray(n))return;const a=n.length,c=e.split(":"),l=c[2]&&Number.parseInt(c[2])||1;let u=c[0]&&Number.parseInt(c[0])||0,h=c[1]&&Number.parseInt(c[1])||a;u=u<0?Math.max(0,u+a):Math.min(a,u),h=h<0?Math.max(0,h+a):Math.min(a,h);const f=[];for(let e=u;e{f.push(e)})}return f},m.prototype._eval=function(e,t,n,r,i,o){this.currSandbox._$_parentProperty=o,this.currSandbox._$_parent=i,this.currSandbox._$_property=n,this.currSandbox._$_root=this.json,this.currSandbox._$_v=t;const s=e.includes("@path");s&&(this.currSandbox._$_path=m.toPathString(r.concat([n])));const a=this.currEval+"Script:"+e;if(!m.cache[a]){let t=e.replaceAll("@parentProperty","_$_parentProperty").replaceAll("@parent","_$_parent").replaceAll("@property","_$_property").replaceAll("@root","_$_root").replaceAll(/@([.\s)[])/gu,"_$_v$1");if(s&&(t=t.replaceAll("@path","_$_path")),"safe"===this.currEval||!0===this.currEval||void 0===this.currEval)m.cache[a]=new this.safeVm.Script(t);else if("native"===this.currEval)m.cache[a]=new this.vm.Script(t);else if("function"==typeof this.currEval&&this.currEval.prototype&&Object.hasOwn(this.currEval.prototype,"runInNewContext")){const e=this.currEval;m.cache[a]=new e(t)}else{if("function"!=typeof this.currEval)throw new TypeError(`Unknown "eval" property "${this.currEval}"`);m.cache[a]={runInNewContext:e=>this.currEval(t,e)}}}try{return m.cache[a].runInNewContext(this.currSandbox)}catch(t){if(this.ignoreEvalErrors)return!1;throw new Error("jsonPath: "+t.message+": "+e)}},m.cache={},m.toPathString=function(e){const t=e,n=t.length;let r="$";for(let e=1;e"function"==typeof e[t]);const i=n.map(t=>e[t]);t=r.reduce((t,n)=>{let r=e[n].toString();return/function/u.test(r)||(r="function "+r),"var "+n+"="+r+";"+t},"")+t,/(['"])use strict\1/u.test(t)||n.includes("arguments")||(t="var arguments = undefined;"+t),t=t.replace(/;\s*$/u,"");const o=t.lastIndexOf(";"),s=-1!==o?t.slice(0,o+1)+" return "+t.slice(o+1):" return "+t;return new Function(...n,s)(...i)}}};const x={en:new class{url="https://qb-grammar-en.languagetool.org/phrasal-paraphraser/subscribe";async query(e,t){const n={message:{indices:[e.slice(0,t.from).split(/\s+/).length],mode:0,phrases:[e.slice(t.from,t.to)],text:e},meta:{clientStatus:"string",product:"string",traceID:"string",userID:"string"},response_queue:"string"};try{return v("$.data.suggestions[*][*]@string()",(await b({url:this.url,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json)}catch(e){throw new Error(`Requesting synonyms failed\n${e}`)}}},de:new class{url="https://synonyms.languagetool.org/synonyms/de";async query(e,t){const n=e.slice(t.from,t.to).trim(),r=e.slice(0,t.from).split(/\s+/).join("+"),i=e.slice(t.to).split(/\s+/).join("+");try{return v("$.synsets[*].terms[*].term@string()",(await b({url:E(`${this.url}/${n}`,{before:r,after:i}).href,method:"GET"})).json)}catch(e){throw new Error(`Requesting synonyms failed\n${e}`)}}}};async function b(t){let n;try{n=await e.requestUrl({...t,throw:!1})}catch(e){throw new Error(`Request to LanguageTool failed: Please check your connection and server URL.\n${e}`)}if(504===n.status||503===n.status)throw new Error("Request to LanguageTool timed out. Please try again later.");if(200!==n.status){let e=n.text;throw e.length>310&&(e=e.substring(0,300)+"..."),new Error(`Request to LanguageTool failed ${n.status}:\n${e}`)}return n}function w(e,t){const n=m({path:e,json:t,wrap:!1,eval:!1});if(null==n)throw new Error("Error parsing response.");return n}function v(e,t){const n=m({path:e,json:t,wrap:!0,eval:!1});if(null==n||!(n instanceof Array))throw new Error("Error parsing response.");return n}function E(e,t){const n=new URL(e);return n.search=new URLSearchParams(t).toString(),n}function C(e){switch(e){case"COLLOQUIALISMS":case"REDUNDANCY":case"STYLE":case"SYNONYMS":return"lt-style";case"TYPOS":return"lt-major";default:return"lt-minor"}}function S(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n}function _(e,t){return(e=e.toLowerCase())>(t=t.toLowerCase())?1:ee.code===t).filter(e=>e.longCode!==e.code),Object.fromEntries(e.map(e=>[e.longCode,e.name]))}class P extends e.PluginSettingTab{plugin;endpointListeners=[];languageListeners=[];languages=[];constructor(e,t){super(e,t),this.plugin=t}async configureCheckDelay(e,t){const n=I[t].minDelay;await this.plugin.settings.update({autoCheckDelay:Math.clamp(this.plugin.settings.options.autoCheckDelay,n,5e3)}),e.setLimits(n,5e3,250)}async notifyEndpointChange(e){for(const t of this.endpointListeners)await t(e.serverUrl)}async configureLanguageVariants(e,t){const n=this.plugin.settings.options.languageVariety,r=L(this.languages,t);n[t]=n[t]??Object.keys(r)[0],e.addOptions(r).setValue(n[t]).onChange(async e=>{n[t]=e,await this.plugin.settings.update({languageVariety:n})}),this.languageListeners.push(async r=>{for(;e.selectEl.options.length>0;)e.selectEl.remove(0);const i=L(r,t);n[t]=n[t]??Object.keys(i)[0],e.addOptions(i).setValue(n[t])})}async display(){const{containerEl:t}=this;t.empty();const n=this.plugin.settings;this.endpointListeners=[],this.endpointListeners.push(async t=>{let n=[];t&&(n=await async function(t){const n=await e.requestUrl({url:`${t}/v2/languages`}).json;if(null==n||!(n instanceof Array))throw new Error("Error processing response from LanguageTool.");return n}(t)),this.languages=n;for(const e of this.languageListeners)await e(n)}),this.endpointListeners.push(async e=>{await this.plugin.syncDictionary()}),this.languageListeners=[],new e.Setting(t).setName("Error logs").setDesc(`${this.plugin.logs.length} messages`).addButton(t=>{t.setButtonText("Copy to clipboard").onClick(async()=>{await window.navigator.clipboard.writeText(this.plugin.logs.join("\n")),new e.Notice("Logs copied to clipboard")})});let r=T(n.options.serverUrl),i=null;function o(e){if(e.appendText("Enables the context menu for synonyms fetched from"),e.createEl("br"),null!=n.options.synonyms){const t=x[n.options.synonyms];if(!t)return void e.appendText(" (unknown API)");e.createEl("a",{text:t.url,href:t.url,attr:{target:"_blank"}})}else e.appendText("(none)")}new e.Setting(t).setName("Endpoint").setDesc("Choose the LanguageTool server url").then(e=>{e.controlEl.classList.add("lt-settings-grid");let t=null,o=null;e.addDropdown(e=>{t=e,e.addOptions({standard:"(Standard) api.languagetool.org",premium:"(Premium) api.languagetoolplus.com",custom:"Custom URL"}).setValue(r).onChange(async e=>{r=e,await n.update({serverUrl:I[r].url}),o&&o.setValue(n.options.serverUrl).setDisabled("custom"!==e),i&&this.configureCheckDelay(i,r),await this.notifyEndpointChange(n.options)})}),e.addText(e=>{o=e,e.setPlaceholder("https://your-custom-url.com").setValue(n.options.serverUrl).setDisabled("custom"!==r).onChange(async e=>{await n.update({serverUrl:e.replace(/\/v2\/check\/$/,"").replace(/\/$/,"")}),r=T(n.options.serverUrl),"custom"!==r&&(t?.setValue(r),o?.setDisabled(!0)),await this.notifyEndpointChange(n.options)})})}),new e.Setting(t).setName("API username").setDesc("Enter a username/mail for API access").addText(e=>e.setPlaceholder("peterlustig@example.com").setValue(n.options.username||"").onChange(async e=>{await n.update({username:e.replace(/\s+/g,"")})})),new e.Setting(t).setName("API key").setDesc(createFragment(e=>{e.createEl("a",{text:"Click here for information about Premium Access",href:"https://github.com/wrenger/obsidian-languagetool#premium-accounts",attr:{target:"_blank"}})})).addText(t=>t.setValue(n.options.apikey||"").onChange(async t=>{await n.update({apikey:t.replace(/\s+/g,"")}),n.options.apikey&&"premium"!==r&&new e.Notice("You have entered an API Key but you are not using the Premium Endpoint")})),new e.Setting(t).setName("Auto check text").setDesc("Check text as you type").addToggle(e=>{e.setValue(n.options.shouldAutoCheck).onChange(async e=>{await n.update({shouldAutoCheck:e})})}),new e.Setting(t).setName("Auto check delay (ms)").setDesc("Time to wait for autocheck after the last key press").addSlider(e=>{i=e,this.configureCheckDelay(e,r),e.setValue(n.options.autoCheckDelay).onChange(async e=>{await n.update({autoCheckDelay:e})}).setDynamicTooltip()});const s=new e.Setting(t).setName("Find synonyms").setDesc(createFragment(o));s.addDropdown(e=>{e.addOption("none","---");for(const t of Object.keys(x))e.addOption(t,t);e.setValue(n.options.synonyms??"none").onChange(async e=>{await n.update({synonyms:"none"!==e?e:void 0}),s.setDesc(createFragment(o))})}),new e.Setting(t).setName("Language settings").setHeading(),new e.Setting(t).setName("Mother tongue").setDesc("Set mother tongue if you want to be warned about false friends when writing in other languages. This setting will also be used for automatic language detection.").addDropdown(e=>{this.languageListeners.push(async t=>{for(;e.selectEl.options.length>0;)e.selectEl.remove(0);e.addOption("none","---").addOptions(Object.fromEntries(t.filter(e=>e.longCode==e.code).map(e=>[e.longCode,e.name]))).setValue(n.options.motherTongue??"none").onChange(async e=>{await n.update({motherTongue:"none"!==e?e:void 0})})})}),new e.Setting(t).setName("Static language").setDesc("Set a static language that will always be used (LanguageTool tries to auto detect the language, this is usually not necessary)").addDropdown(e=>{this.languageListeners.push(async t=>{const r=t.filter(e=>e.longCode.length>2||e.longCode!==e.code||t.filter(t=>t.code==e.code).length<=1);for(;e.selectEl.options.length>0;)e.selectEl.remove(0);e.addOption("auto","Auto Detect").addOptions(Object.fromEntries(r.map(e=>[e.longCode,e.name]))).setValue(n.options.staticLanguage??"auto").onChange(async e=>{await n.update({staticLanguage:"auto"!==e?e:void 0})})})}),new e.Setting(t).setName("Language varieties").setHeading().setDesc("Some languages have varieties depending on the country they are spoken in.");const a={en:"English",de:"German",pt:"Portuguese",ca:"Catalan"};for(const[n,r]of Object.entries(a))new e.Setting(t).setName(`Interpret ${r} as`).addDropdown(async e=>{this.configureLanguageVariants(e,n)});new e.Setting(t).setName("Spellcheck Dictionary").setHeading(),new e.Setting(t).setName("Ignored Words").setDesc("Words that should not be highlighted as spelling mistakes.").addButton(e=>{e.setIcon("settings").setTooltip("Edit dictionary").onClick(()=>{new M(this.app,this.plugin).open()})}),new e.Setting(t).setName("Sync with LanguageTool").setDesc("This is only supported for premium users.").addToggle(e=>{e.setDisabled("premium"!==r).setValue(n.options.syncDictionary).onChange(async e=>{await n.update({syncDictionary:e}),e&&await this.plugin.syncDictionary()}),this.endpointListeners.push(async t=>{e.setDisabled("premium"!==T(t))})}),new e.Setting(t).setName("Rule categories").setHeading().setDesc(createFragment(e=>{e.appendText("The picky mode enables a lot of extra categories and rules. Additionally, you can enable or disable specific rules down below."),e.createEl("br"),e.createEl("a",{text:"Click here for a list of rules and categories",href:"https://community.languagetool.org/rule/list",attr:{target:"_blank"}})})),new e.Setting(t).setName("Picky mode").setDesc("Provides more style and tonality suggestions, detects long or complex sentences, recognizes colloquialism and redundancies, proactively suggests synonyms for commonly overused words").addToggle(e=>{e.setValue(n.options.pickyMode).onChange(async e=>{await n.update({pickyMode:e})})}),new e.Setting(t).setName("Enabled categories").setDesc("Comma-separated list of categories").addText(e=>e.setPlaceholder("CATEGORY_1,CATEGORY_2").setValue(n.options.enabledCategories??"").onChange(async e=>{await n.update({enabledCategories:e.replace(/\s+/g,"")})})),new e.Setting(t).setName("Disabled categories").setDesc("Comma-separated list of categories").addText(e=>e.setPlaceholder("CATEGORY_1,CATEGORY_2").setValue(n.options.disabledCategories??"").onChange(async e=>{await n.update({disabledCategories:e.replace(/\s+/g,"")})})),new e.Setting(t).setName("Enabled rules").setDesc("Comma-separated list of rules").addText(e=>e.setPlaceholder("RULE_1,RULE_2").setValue(n.options.enabledRules??"").onChange(async e=>{await n.update({enabledRules:e.replace(/\s+/g,"")})})),new e.Setting(t).setName("Disabled rules").setDesc("Comma-separated list of rules").addText(e=>e.setPlaceholder("RULE_1,RULE_2").setValue(n.options.disabledRules??"").onChange(async e=>{await n.update({disabledRules:e.replace(/\s+/g,"")})})),await this.notifyEndpointChange(n.options)}}class M extends e.Modal{plugin;words;constructor(e,t){super(e),this.setTitle("Spellcheck dictionary"),this.plugin=t,this.words=t.settings.options.dictionary}async onOpen(){this.words=this.plugin.settings.options.dictionary;const{contentEl:t}=this,n=t=>{t.replaceChildren(...this.words.map(r=>t.createDiv({cls:"multi-select-pill"},i=>{i.createDiv({cls:"multi-select-pill-content"},e=>e.createSpan({text:r})),i.createDiv({cls:"multi-select-pill-remove-button"},i=>{i.appendChild(e.getIcon("x")),i.onClickEvent(()=>{this.words.remove(r),n(t)})})})))};let r=null;t.createDiv({cls:["multi-select-container","lt-dictionary-words"]},e=>{r=e,n(e)}),this.plugin.syncDictionary().then(()=>{this.words=this.plugin.settings.options.dictionary,r&&n(r)});let i="",o=null;const s=()=>{i&&(this.words=[...new Set([...this.words,i])].sort(_),r&&n(r),o&&o.setValue(""),i="")};new e.Setting(t).setName("Add").addText(e=>{o=e.setValue(i).onChange(e=>i=e.trim()),e.inputEl.addEventListener("keypress",e=>{"Enter"===e.key&&s()})}).addExtraButton(e=>{e.setIcon("plus").setTooltip("Add").onClick(()=>{s()})})}async onClose(){this.contentEl.empty(),await this.plugin.settings.update({dictionary:this.words}),await this.plugin.syncDictionary()}}function R(e){let n=-1,r=1/0,i=-1/0;return t.EditorView.updateListener.of(t=>{let o=e.getActiveFileSettings();if(!t.docChanged||!o.shouldAutoCheck)return;t.changes.iterChangedRanges((e,t,n,o)=>{r=Math.min(r,n,o),i=Math.max(i,n,o)});const s=t.view;clearTimeout(n),n=window.setTimeout(()=>{e.runDetection(s,{from:r,to:i}).catch(e=>{console.error(e)}),r=1/0,i=-1/0},e.settings.options.autoCheckDelay)})}const F=/(frontmatter|code|math|templater|blockid|hashtag)/,N=n.StateEffect.define(),z=n.StateEffect.define(),j=n.StateEffect.define(),B=n.StateEffect.define();function $(e,t){return e.from<=t.from&&t.from<=e.to||e.from<=t.to&&t.to<=e.to||t.from<=e.from&&e.from<=t.to||t.from<=e.to&&e.to<=t.to}const U=n.StateField.define({create:()=>t.Decoration.none,update(e,n){e=e.map(n.changes);const i=new Set,o={};let s=null;const a=e=>{if(null==o[e]){s||(s=r.syntaxTree(n.state));const t=s.resolveInner(e,1).type.prop(r.tokenClassNodeProp);o[e]=!(t&&F.test(t))}return o[e]},c=(e,t)=>{s||(s=r.syntaxTree(n.state));const i=s.resolve(n.newDoc.lineAt(t.from).from,1).type.prop(r.tokenClassNodeProp);return!i?.includes("table")||"WHITESPACE_RULE"!==e.ruleId};n.docChanged&&n.selection&&e.size&&(e=e.update({filter:(e,t)=>!$({from:e,to:t},n.selection.main)}));for(const r of n.effects)if(r.is(N)){const n=r.value,o=n.range,s=`${o.from},${o.to}`;!i.has(s)&&a(o.from)&&a(o.to)&&c(n,o)&&(i.add(s),e=e.update({add:[t.Decoration.mark({class:`lt-underline ${C(n.categoryId)}`,underline:n}).range(o.from,o.to)]}))}else r.is(z)?e=t.Decoration.none:r.is(j)?e=e.update({filterFrom:r.value.from,filterTo:r.value.to,filter:(e,t)=>!$({from:e,to:t},r.value)}):r.is(B)&&(e=e.update({filter:(e,t,n)=>!r.value(n.spec.underline)}));return e},provide:e=>t.EditorView.decorations.from(e)});function V(t,n,r,i){const o=r.replacements.slice(0,4),s=r.categoryId,a=r.ruleId;return createDiv({cls:["lt-tooltip",C(s)]},c=>{r.title&&c.createSpan({cls:"lt-title",text:r.title}),r.message&&c.createSpan({cls:"lt-message",text:r.message}),c.createDiv({cls:"lt-bottom"},t=>{t.createDiv({cls:"lt-buttoncontainer"},t=>{for(const r of o){const o=new e.ButtonComponent(t);o.setButtonText(r||"(delete)"),o.onClick(()=>{n.dispatch({changes:[{...i,insert:r}],effects:[j.of(i)]})})}})}),c.createDiv({cls:"lt-ignore-container"},o=>{"TYPOS"===s?o.createEl("button",{cls:"lt-ignore-btn"},i=>{e.setIcon(i.createSpan(),"plus-with-circle"),i.createSpan({text:"Add to dictionary"}),i.onclick=async()=>{let e=[...t.settings.options.dictionary,r.text.trim()];await t.settings.update({dictionary:e}),n.dispatch({effects:[B.of(e=>e.text==e.text)]})}}):(o.createDiv({cls:"lt-ignore-btn"},t=>{e.setIcon(t.createSpan(),"cross"),t.createSpan({text:"Ignore"}),t.onclick=()=>n.dispatch({effects:[j.of(i)]})}),"SYNONYMS"!==s&&o.createDiv({cls:"lt-ignore-btn"},r=>{e.setIcon(r.createSpan(),"circle-off"),r.createSpan({text:"Disable rule"}),r.onclick=async()=>{let e=t.settings.options.disabledRules;e?e+=","+a:e=a,await t.settings.update({disabledRules:e}),n.dispatch({effects:[B.of(e=>e.ruleId===a)]})}})),o.createDiv({cls:"lt-info-container"},t=>{t.createDiv({cls:"lt-info-button clickable-icon"},t=>{e.setIcon(t,"info"),t.onclick=()=>{const e=document.getElementsByClassName("lt-info-box").item(0);e&&e.toggleAttribute("hidden")}})})}),c.createDiv({cls:"lt-info-box",attr:{hidden:!0}},e=>{e.createDiv({cls:"lt-info",text:`Category: ${s}`}),e.createDiv({cls:"lt-info",text:`Rule: ${a}`}),e.createDiv({cls:"lt-info",text:`Text: ${r.text} (${i.from}-${i.to})`})})})}function H(e,t,n,r){const i=t.state,o=i.field(U);if(0===o.size||i.selection.ranges.length>1)return null;let s=o.iter(n);if(null!=s.value&&s.from<=n&&s.to>=n){let t=s.value.spec.underline;return{pos:s.from,end:s.to,above:!0,strictSide:!1,arrow:!1,clip:!1,create:n=>({dom:V(e,n,t,s)})}}return null}function q(e){return t.hoverTooltip(H.bind(null,e),{hideOnChange:!0})}const Y=t.EditorView.baseTheme({".cm-tooltip.cm-tooltip-hover":{padding:"var(--size-2-3)",border:"1px solid var(--background-modifier-border-hover)",backgroundColor:"var(--background-secondary)",borderRadius:"var(--radius-m)",boxShadow:"var(--shadow-s)",zIndex:"var(--layer-menu)",userSelect:"none",overflow:"hidden","& > .lt-tooltip":{fontFamily:"var(--default-font)",fontSize:"var(--font-ui-small)",width:"300px",lineHeight:1.5,"& > .lt-title":{display:"block",fontWeight:600,marginBottom:"6px",padding:"0 12px",textDecoration:"underline 2px var(--lt-highlight)","-webkit-text-decoration":"underline 2px var(--lt-highlight)"},"& > .lt-message":{display:"block",padding:"0 12px"},"& > .lt-bottom":{minHeight:"10px",padding:"0 12px",position:"relative","& > .lt-buttoncontainer":{"&:not(:empty)":{paddingTop:"10px"},"& > button":{marginRight:"4px",marginBottom:"4px",padding:"4px 6px"}}},"& > .lt-ignore-container":{display:"flex","& > .lt-ignore-btn":{fontSize:"var(--font-ui-small)",padding:"4px",display:"flex",flex:1,width:"100%",textAlign:"left",alignItems:"center",lineHeight:1,color:"var(--text-muted)","& > span":{display:"flex","&:last-child":{marginLeft:"5px"}},"&:hover":{color:"var(--text-normal)"}},"& > .lt-info-container":{display:"flex",flex:0,"& > .lt-info-button":{color:"var(--text-faint)",height:"100%"}}},"& > .lt-info-box":{padding:"5px 0px 0px 0px",overflowX:"scroll",color:"var(--text-muted)"}}},".lt-underline":{cursor:"pointer",transition:"background-color 100ms ease-out",textDecoration:"wavy underline var(--lt-highlight)","-webkit-text-decoration":"wavy underline var(--lt-highlight)","&:hover":{backgroundColor:"color-mix(in srgb, var(--lt-highlight), transparent 80%)"}}});const Q={};function K(e,t,n){if(function(e){return Boolean(e&&"object"==typeof e)}(e)){if("value"in e)return"html"!==e.type||n?e.value:"";if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return W(e.children,t,n)}return Array.isArray(e)?W(e,t,n):""}function W(e,t,n){const r=[];let i=-1;for(;++ii?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);s0?(G(e,e.length,0,t),e):t}const ee={}.hasOwnProperty;function te(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||!(65535&~n)||65534==(65535&n)||n>1114111?"�":String.fromCodePoint(n)}function oe(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const se=ke(/[A-Za-z]/),ae=ke(/[\dA-Za-z]/),ce=ke(/[#-'*+\--9=?A-Z^-~]/);function le(e){return null!==e&&(e<32||127===e)}const ue=ke(/\d/),he=ke(/[\dA-Fa-f]/),fe=ke(/[!-/:-@[-`{-~]/);function pe(e){return null!==e&&e<-2}function de(e){return null!==e&&(e<0||32===e)}function ge(e){return-2===e||-1===e||32===e}const me=ke(/\p{P}|\p{S}/u),ye=ke(/\s/);function ke(e){return function(t){return null!==t&&t>-1&&e.test(String.fromCharCode(t))}}function xe(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let o=0;return function(r){if(ge(r))return e.enter(n),s(r);return t(r)};function s(r){return ge(r)&&o++o))return;const n=t.events.length;let i,a,c=n;for(;c--;)if("exit"===t.events[c][0]&&"chunkFlow"===t.events[c][1].type){if(i){a=t.events[c][1].end;break}i=!0}for(y(s),e=n;er;){const r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function k(){r.write([null]),i=void 0,r=void 0,t.containerState._closeFlow=void 0}}},ve={tokenize:function(e,t,n){return xe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function Ee(e){return null===e||de(e)||ye(e)?1:me(e)?2:void 0}function Ce(e,t,n){const r=[];let i=-1;for(;++i1&&e[u][1].end.offset-e[u][1].start.offset>1?2:1;const h={...e[n][1].end},f={...e[u][1].start};_e(h,-a),_e(f,a),o={type:a>1?"strongSequence":"emphasisSequence",start:h,end:{...e[n][1].end}},s={type:a>1?"strongSequence":"emphasisSequence",start:{...e[u][1].start},end:f},i={type:a>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[u][1].start}},r={type:a>1?"strong":"emphasis",start:{...o.start},end:{...s.end}},e[n][1].end={...o.start},e[u][1].start={...s.end},c=[],e[n][1].end.offset-e[n][1].start.offset&&(c=Z(c,[["enter",e[n][1],t],["exit",e[n][1],t]])),c=Z(c,[["enter",r,t],["enter",o,t],["exit",o,t],["enter",i,t]]),c=Z(c,Ce(t.parser.constructs.insideSpan.null,e.slice(n+1,u),t)),c=Z(c,[["exit",i,t],["enter",s,t],["exit",s,t],["exit",r,t]]),e[u][1].end.offset-e[u][1].start.offset?(l=2,c=Z(c,[["enter",e[u][1],t],["exit",e[u][1],t]])):l=0,G(e,n-1,u-n+3,c),u=n+c.length-l-2;break}u=-1;for(;++u=a?(e.exit("codeFencedFenceSequence"),ge(t)?xe(e,h,"whitespace")(t):h(t)):n(t)}function h(r){return null===r||pe(r)?(e.exit("codeFencedFence"),t(r)):n(r)}}};let o,s=0,a=0;return function(t){return function(t){const n=r.events[r.events.length-1];return s=n&&"linePrefix"===n[1].type?n[2].sliceSerialize(n[1],!0).length:0,o=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(t)}(t)};function c(t){return t===o?(a++,e.consume(t),c):a<3?n(t):(e.exit("codeFencedFenceSequence"),ge(t)?xe(e,l,"whitespace")(t):l(t))}function l(n){return null===n||pe(n)?(e.exit("codeFencedFence"),r.interrupt?t(n):e.check(Le,p,k)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),u(n))}function u(t){return null===t||pe(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),l(t)):ge(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),xe(e,h,"whitespace")(t)):96===t&&t===o?n(t):(e.consume(t),u)}function h(t){return null===t||pe(t)?l(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(t))}function f(t){return null===t||pe(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),l(t)):96===t&&t===o?n(t):(e.consume(t),f)}function p(t){return e.attempt(i,k,d)(t)}function d(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),g}function g(t){return s>0&&ge(t)?xe(e,m,"linePrefix",s+1)(t):m(t)}function m(t){return null===t||pe(t)?e.check(Le,p,k)(t):(e.enter("codeFlowValue"),y(t))}function y(t){return null===t||pe(t)?(e.exit("codeFlowValue"),m(t)):(e.consume(t),y)}function k(n){return e.exit("codeFenced"),t(n)}}};const Me={name:"codeIndented",tokenize:function(e,t,n){const r=this;return function(t){return e.enter("codeIndented"),xe(e,i,"linePrefix",5)(t)};function i(e){const t=r.events[r.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return null===t?a(t):pe(t)?e.attempt(Re,o,a)(t):(e.enter("codeFlowValue"),s(t))}function s(t){return null===t||pe(t)?(e.exit("codeFlowValue"),o(t)):(e.consume(t),s)}function a(n){return e.exit("codeIndented"),t(n)}}},Re={partial:!0,tokenize:function(e,t,n){const r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):pe(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i):xe(e,o,"linePrefix",5)(t)}function o(e){const o=r.events[r.events.length-1];return o&&"linePrefix"===o[1].type&&o[2].sliceSerialize(o[1],!0).length>=4?t(e):pe(e)?i(e):n(e)}}};const Fe={name:"codeText",previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type},resolve:function(e){let t,n,r=e.length-4,i=3;if(!("lineEnding"!==e[i][1].type&&"space"!==e[i][1].type||"lineEnding"!==e[r][1].type&&"space"!==e[r][1].type))for(t=i;++t=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){const r=t||0;this.setCursor(Math.trunc(e));const i=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return n&&ze(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),ze(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),ze(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&0===this.right.length||e<0&&0===this.left.length))if(e=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}};function Ve(e,t,n,r,i,o,s,a,c){const l=c||Number.POSITIVE_INFINITY;let u=0;return function(t){if(60===t)return e.enter(r),e.enter(i),e.enter(o),e.consume(t),e.exit(o),h;if(null===t||32===t||41===t||le(t))return n(t);return e.enter(r),e.enter(s),e.enter(a),e.enter("chunkString",{contentType:"string"}),d(t)};function h(n){return 62===n?(e.enter(o),e.consume(n),e.exit(o),e.exit(i),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),f(n))}function f(t){return 62===t?(e.exit("chunkString"),e.exit(a),h(t)):null===t||60===t||pe(t)?n(t):(e.consume(t),92===t?p:f)}function p(t){return 60===t||62===t||92===t?(e.consume(t),f):f(t)}function d(i){return u||null!==i&&41!==i&&!de(i)?u999||null===h||91===h||93===h&&!a||94===h&&!c&&"_hiddenFootnoteSupport"in s.parser.constructs?n(h):93===h?(e.exit(o),e.enter(i),e.consume(h),e.exit(i),e.exit(r),t):pe(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),l):(e.enter("chunkString",{contentType:"string"}),u(h))}function u(t){return null===t||91===t||93===t||pe(t)||c++>999?(e.exit("chunkString"),l(t)):(e.consume(t),a||(a=!ge(t)),92===t?h:u)}function h(t){return 91===t||92===t||93===t?(e.consume(t),c++,u):u(t)}}function qe(e,t,n,r,i,o){let s;return function(t){if(34===t||39===t||40===t)return e.enter(r),e.enter(i),e.consume(t),e.exit(i),s=40===t?41:t,a;return n(t)};function a(n){return n===s?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(o),c(n))}function c(t){return t===s?(e.exit(o),a(s)):null===t?n(t):pe(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),xe(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),l(t))}function l(t){return t===s||null===t||pe(t)?(e.exit("chunkString"),c(t)):(e.consume(t),92===t?u:l)}function u(t){return t===s||92===t?(e.consume(t),l):l(t)}}function Ye(e,t){let n;return function r(i){if(pe(i))return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r;if(ge(i))return xe(e,r,n?"linePrefix":"lineSuffix")(i);return t(i)}}const Qe={name:"definition",tokenize:function(e,t,n){const r=this;let i;return function(t){return e.enter("definition"),function(t){return He.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function o(t){return i=oe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),s):n(t)}function s(t){return de(t)?Ye(e,a)(t):a(t)}function a(t){return Ve(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function c(t){return e.attempt(Ke,l,l)(t)}function l(t){return ge(t)?xe(e,u,"whitespace")(t):u(t)}function u(o){return null===o||pe(o)?(e.exit("definition"),r.parser.defined.push(i),t(o)):n(o)}}},Ke={partial:!0,tokenize:function(e,t,n){return function(t){return de(t)?Ye(e,r)(t):n(t)};function r(t){return qe(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function i(t){return ge(t)?xe(e,o,"whitespace")(t):o(t)}function o(e){return null===e||pe(e)?t(e):n(e)}}};const We={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),r};function r(r){return pe(r)?(e.exit("hardBreakEscape"),t(r)):n(r)}}};const Je={name:"headingAtx",resolve:function(e,t){let n,r,i=e.length-2,o=3;"whitespace"===e[o][1].type&&(o+=2);i-2>o&&"whitespace"===e[i][1].type&&(i-=2);"atxHeadingSequence"===e[i][1].type&&(o===i-1||i-4>o&&"whitespace"===e[i-2][1].type)&&(i-=o+1===i?2:4);i>o&&(n={type:"atxHeadingText",start:e[o][1].start,end:e[i][1].end},r={type:"chunkText",start:e[o][1].start,end:e[i][1].end,contentType:"text"},G(e,o,i-o+1,[["enter",n,t],["enter",r,t],["exit",r,t],["exit",n,t]]));return e},tokenize:function(e,t,n){let r=0;return function(t){return e.enter("atxHeading"),function(t){return e.enter("atxHeadingSequence"),i(t)}(t)};function i(t){return 35===t&&r++<6?(e.consume(t),i):null===t||de(t)?(e.exit("atxHeadingSequence"),o(t)):n(t)}function o(n){return 35===n?(e.enter("atxHeadingSequence"),s(n)):null===n||pe(n)?(e.exit("atxHeading"),t(n)):ge(n)?xe(e,o,"whitespace")(n):(e.enter("atxHeadingText"),a(n))}function s(t){return 35===t?(e.consume(t),s):(e.exit("atxHeadingSequence"),o(t))}function a(t){return null===t||35===t||de(t)?(e.exit("atxHeadingText"),o(t)):(e.consume(t),a)}}};const Xe=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ge=["pre","script","style","textarea"],Ze={concrete:!0,name:"htmlFlow",resolveTo:function(e){let t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2));return e},tokenize:function(e,t,n){const r=this;let i,o,s,a,c;return function(t){return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),l}(t)};function l(a){return 33===a?(e.consume(a),u):47===a?(e.consume(a),o=!0,p):63===a?(e.consume(a),i=3,r.interrupt?t:M):se(a)?(e.consume(a),s=String.fromCharCode(a),d):n(a)}function u(o){return 45===o?(e.consume(o),i=2,h):91===o?(e.consume(o),i=5,a=0,f):se(o)?(e.consume(o),i=4,r.interrupt?t:M):n(o)}function h(i){return 45===i?(e.consume(i),r.interrupt?t:M):n(i)}function f(i){const o="CDATA[";return i===o.charCodeAt(a++)?(e.consume(i),6===a?r.interrupt?t:_:f):n(i)}function p(t){return se(t)?(e.consume(t),s=String.fromCharCode(t),d):n(t)}function d(a){if(null===a||47===a||62===a||de(a)){const c=47===a,l=s.toLowerCase();return c||o||!Ge.includes(l)?Xe.includes(s.toLowerCase())?(i=6,c?(e.consume(a),g):r.interrupt?t(a):_(a)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(a):o?m(a):y(a)):(i=1,r.interrupt?t(a):_(a))}return 45===a||ae(a)?(e.consume(a),s+=String.fromCharCode(a),d):n(a)}function g(i){return 62===i?(e.consume(i),r.interrupt?t:_):n(i)}function m(t){return ge(t)?(e.consume(t),m):C(t)}function y(t){return 47===t?(e.consume(t),C):58===t||95===t||se(t)?(e.consume(t),k):ge(t)?(e.consume(t),y):C(t)}function k(t){return 45===t||46===t||58===t||95===t||ae(t)?(e.consume(t),k):x(t)}function x(t){return 61===t?(e.consume(t),b):ge(t)?(e.consume(t),x):y(t)}function b(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),c=t,w):ge(t)?(e.consume(t),b):v(t)}function w(t){return t===c?(e.consume(t),c=null,E):null===t||pe(t)?n(t):(e.consume(t),w)}function v(t){return null===t||34===t||39===t||47===t||60===t||61===t||62===t||96===t||de(t)?x(t):(e.consume(t),v)}function E(e){return 47===e||62===e||ge(e)?y(e):n(e)}function C(t){return 62===t?(e.consume(t),S):n(t)}function S(t){return null===t||pe(t)?_(t):ge(t)?(e.consume(t),S):n(t)}function _(t){return 45===t&&2===i?(e.consume(t),O):60===t&&1===i?(e.consume(t),D):62===t&&4===i?(e.consume(t),R):63===t&&3===i?(e.consume(t),M):93===t&&5===i?(e.consume(t),P):!pe(t)||6!==i&&7!==i?null===t||pe(t)?(e.exit("htmlFlowData"),A(t)):(e.consume(t),_):(e.exit("htmlFlowData"),e.check(et,F,A)(t))}function A(t){return e.check(tt,I,F)(t)}function I(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),T}function T(t){return null===t||pe(t)?A(t):(e.enter("htmlFlowData"),_(t))}function O(t){return 45===t?(e.consume(t),M):_(t)}function D(t){return 47===t?(e.consume(t),s="",L):_(t)}function L(t){if(62===t){const n=s.toLowerCase();return Ge.includes(n)?(e.consume(t),R):_(t)}return se(t)&&s.length<8?(e.consume(t),s+=String.fromCharCode(t),L):_(t)}function P(t){return 93===t?(e.consume(t),M):_(t)}function M(t){return 62===t?(e.consume(t),R):45===t&&2===i?(e.consume(t),M):_(t)}function R(t){return null===t||pe(t)?(e.exit("htmlFlowData"),F(t)):(e.consume(t),R)}function F(n){return e.exit("htmlFlow"),t(n)}}},et={partial:!0,tokenize:function(e,t,n){return function(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Ie,t,n)}}},tt={partial:!0,tokenize:function(e,t,n){const r=this;return function(t){if(pe(t))return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i;return n(t)};function i(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}};const nt={name:"htmlText",tokenize:function(e,t,n){const r=this;let i,o,s;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),a};function a(t){return 33===t?(e.consume(t),c):47===t?(e.consume(t),b):63===t?(e.consume(t),k):se(t)?(e.consume(t),E):n(t)}function c(t){return 45===t?(e.consume(t),l):91===t?(e.consume(t),o=0,p):se(t)?(e.consume(t),y):n(t)}function l(t){return 45===t?(e.consume(t),f):n(t)}function u(t){return null===t?n(t):45===t?(e.consume(t),h):pe(t)?(s=u,L(t)):(e.consume(t),u)}function h(t){return 45===t?(e.consume(t),f):u(t)}function f(e){return 62===e?D(e):45===e?h(e):u(e)}function p(t){const r="CDATA[";return t===r.charCodeAt(o++)?(e.consume(t),6===o?d:p):n(t)}function d(t){return null===t?n(t):93===t?(e.consume(t),g):pe(t)?(s=d,L(t)):(e.consume(t),d)}function g(t){return 93===t?(e.consume(t),m):d(t)}function m(t){return 62===t?D(t):93===t?(e.consume(t),m):d(t)}function y(t){return null===t||62===t?D(t):pe(t)?(s=y,L(t)):(e.consume(t),y)}function k(t){return null===t?n(t):63===t?(e.consume(t),x):pe(t)?(s=k,L(t)):(e.consume(t),k)}function x(e){return 62===e?D(e):k(e)}function b(t){return se(t)?(e.consume(t),w):n(t)}function w(t){return 45===t||ae(t)?(e.consume(t),w):v(t)}function v(t){return pe(t)?(s=v,L(t)):ge(t)?(e.consume(t),v):D(t)}function E(t){return 45===t||ae(t)?(e.consume(t),E):47===t||62===t||de(t)?C(t):n(t)}function C(t){return 47===t?(e.consume(t),D):58===t||95===t||se(t)?(e.consume(t),S):pe(t)?(s=C,L(t)):ge(t)?(e.consume(t),C):D(t)}function S(t){return 45===t||46===t||58===t||95===t||ae(t)?(e.consume(t),S):_(t)}function _(t){return 61===t?(e.consume(t),A):pe(t)?(s=_,L(t)):ge(t)?(e.consume(t),_):C(t)}function A(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),i=t,I):pe(t)?(s=A,L(t)):ge(t)?(e.consume(t),A):(e.consume(t),T)}function I(t){return t===i?(e.consume(t),i=void 0,O):null===t?n(t):pe(t)?(s=I,L(t)):(e.consume(t),I)}function T(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||de(t)?C(t):(e.consume(t),T)}function O(e){return 47===e||62===e||de(e)?C(e):n(e)}function D(r){return 62===r?(e.consume(r),e.exit("htmlTextData"),e.exit("htmlText"),t):n(r)}function L(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),P}function P(t){return ge(t)?xe(e,M,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):M(t)}function M(t){return e.enter("htmlTextData"),s(t)}}};const rt={name:"labelEnd",resolveAll:function(e){let t=-1;const n=[];for(;++t=3&&(null===o||pe(o))?(e.exit("thematicBreak"),t(o)):n(o)}function s(t){return t===r?(e.consume(t),i++,s):(e.exit("thematicBreakSequence"),ge(t)?xe(e,o,"whitespace")(t):o(t))}}};const ht={continuation:{tokenize:function(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Ie,i,o);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,xe(e,t,"listItemIndent",r.containerState.size+1)(n)}function o(n){return r.containerState.furtherBlankLines||!ge(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(pt,t,s)(n))}function s(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,xe(e,e.attempt(ht,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(i)}}},exit:function(e){e.exit(this.containerState.type)},name:"list",tokenize:function(e,t,n){const r=this,i=r.events[r.events.length-1];let o=i&&"linePrefix"===i[1].type?i[2].sliceSerialize(i[1],!0).length:0,s=0;return function(t){const i=r.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===i?!r.containerState.marker||t===r.containerState.marker:ue(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),"listUnordered"===i)return e.enter("listItemPrefix"),42===t||45===t?e.check(ut,n,c)(t):c(t);if(!r.interrupt||49===t)return e.enter("listItemPrefix"),e.enter("listItemValue"),a(t)}return n(t)};function a(t){return ue(t)&&++s<10?(e.consume(t),a):(!r.interrupt||s<2)&&(r.containerState.marker?t===r.containerState.marker:41===t||46===t)?(e.exit("listItemValue"),c(t)):n(t)}function c(t){return e.enter("listItemMarker"),e.consume(t),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||t,e.check(Ie,r.interrupt?n:l,e.attempt(ft,h,u))}function l(e){return r.containerState.initialBlankLine=!0,o++,h(e)}function u(t){return ge(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),h):n(t)}function h(n){return r.containerState.size=o+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}}},ft={partial:!0,tokenize:function(e,t,n){const r=this;return xe(e,function(e){const i=r.events[r.events.length-1];return!ge(e)&&i&&"listItemPrefixWhitespace"===i[1].type?t(e):n(e)},"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5)}},pt={partial:!0,tokenize:function(e,t,n){const r=this;return xe(e,function(e){const i=r.events[r.events.length-1];return i&&"listItemIndent"===i[1].type&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)},"listItemIndent",r.containerState.size+1)}};const dt={name:"setextUnderline",resolveTo:function(e,t){let n,r,i,o=e.length;for(;o--;)if("enter"===e[o][0]){if("content"===e[o][1].type){n=o;break}"paragraph"===e[o][1].type&&(r=o)}else"content"===e[o][1].type&&e.splice(o,1),i||"definition"!==e[o][1].type||(i=o);const s={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};e[r][1].type="setextHeadingText",i?(e.splice(r,0,["enter",s,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end={...e[i][1].end}):e[n][1]=s;return e.push(["exit",s,t]),e},tokenize:function(e,t,n){const r=this;let i;return function(t){let s,a=r.events.length;for(;a--;)if("lineEnding"!==r.events[a][1].type&&"linePrefix"!==r.events[a][1].type&&"content"!==r.events[a][1].type){s="paragraph"===r.events[a][1].type;break}if(!r.parser.lazy[r.now().line]&&(r.interrupt||s))return e.enter("setextHeadingLine"),i=t,function(t){return e.enter("setextHeadingLineSequence"),o(t)}(t);return n(t)};function o(t){return t===i?(e.consume(t),o):(e.exit("setextHeadingLineSequence"),ge(t)?xe(e,s,"lineSuffix")(t):s(t))}function s(r){return null===r||pe(r)?(e.exit("setextHeadingLine"),t(r)):n(r)}}};const gt={tokenize:function(e){const t=this,n=e.attempt(Ie,function(r){if(null===r)return void e.consume(r);return e.enter("lineEndingBlank"),e.consume(r),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n},e.attempt(this.parser.constructs.flowInitial,r,xe(e,e.attempt(this.parser.constructs.flow,r,e.attempt($e,r)),"linePrefix")));return n;function r(r){if(null!==r)return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),t.currentConstruct=void 0,n;e.consume(r)}}};const mt={resolveAll:bt()},yt=xt("string"),kt=xt("text");function xt(e){return{resolveAll:bt("text"===e?wt:void 0),tokenize:function(t){const n=this,r=this.parser.constructs[e],i=t.attempt(r,o,s);return o;function o(e){return c(e)?i(e):s(e)}function s(e){if(null!==e)return t.enter("data"),t.consume(e),a;t.consume(e)}function a(e){return c(e)?(t.exit("data"),i(e)):(t.consume(e),a)}function c(e){if(null===e)return!0;const t=r[e];let i=-1;if(t)for(;++i-1){const e=s[0];"string"==typeof e?s[0]=e.slice(r):s.shift()}o>0&&s.push(e[i].slice(0,o))}return s}(s,e)}function f(){const{_bufferIndex:e,_index:t,line:n,column:i,offset:o}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:o}}function p(){let e;for(;r._index0){const e=o.tokenStack[o.tokenStack.length-1];(e[1]||Vt).call(o,void 0,e[0])}for(r.position={start:Bt(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:Bt(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},h=-1;++h0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}Gt[43]=Xt,Gt[45]=Xt,Gt[46]=Xt,Gt[95]=Xt,Gt[72]=[Xt,Jt],Gt[104]=[Xt,Jt],Gt[87]=[Xt,Wt],Gt[119]=[Xt,Wt];const sn={tokenize:function(e,t,n){const r=this;return xe(e,function(e){const i=r.events[r.events.length-1];return i&&"gfmFootnoteDefinitionIndent"===i[1].type&&4===i[2].sliceSerialize(i[1],!0).length?t(e):n(e)},"gfmFootnoteDefinitionIndent",5)},partial:!0};function an(e,t,n){const r=this;let i=r.events.length;const o=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s;for(;i--;){const e=r.events[i][1];if("labelImage"===e.type){s=e;break}if("gfmFootnoteCall"===e.type||"labelLink"===e.type||"label"===e.type||"image"===e.type||"link"===e.type)break}return function(i){if(!s||!s._balanced)return n(i);const a=oe(r.sliceSerialize({start:s.end,end:r.now()}));if(94!==a.codePointAt(0)||!o.includes(a.slice(1)))return n(i);return e.enter("gfmFootnoteCallLabelMarker"),e.consume(i),e.exit("gfmFootnoteCallLabelMarker"),t(i)}}function cn(e,t){let n=e.length;for(;n--;)if("labelImage"===e[n][1].type&&"enter"===e[n][0]){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",o,t],["enter",s,t],["exit",s,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function ln(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o,s=0;return function(t){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(t),e.exit("gfmFootnoteCallLabelMarker"),a};function a(t){return 94!==t?n(t):(e.enter("gfmFootnoteCallMarker"),e.consume(t),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",c)}function c(a){if(s>999||93===a&&!o||null===a||91===a||de(a))return n(a);if(93===a){e.exit("chunkString");const o=e.exit("gfmFootnoteCallString");return i.includes(oe(r.sliceSerialize(o)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(a),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(a)}return de(a)||(o=!0),s++,e.consume(a),92===a?l:c}function l(t){return 91===t||92===t||93===t?(e.consume(t),s++,c):c(t)}}function un(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o,s,a=0;return function(t){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionLabelMarker"),c};function c(t){return 94===t?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",l):n(t)}function l(t){if(a>999||93===t&&!s||null===t||91===t||de(t))return n(t);if(93===t){e.exit("chunkString");const n=e.exit("gfmFootnoteDefinitionLabelString");return o=oe(r.sliceSerialize(n)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return de(t)||(s=!0),a++,e.consume(t),92===t?u:l}function u(t){return 91===t||92===t||93===t?(e.consume(t),a++,l):l(t)}function h(t){return 58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),i.includes(o)||i.push(o),xe(e,f,"gfmFootnoteDefinitionWhitespace")):n(t)}function f(e){return t(e)}}function hn(e,t,n){return e.check(Ie,t,e.attempt(sn,t,n))}function fn(e){e.exit("gfmFootnoteDefinition")}function pn(e){let t={}.singleTilde;const n={name:"strikethrough",tokenize:function(e,n,r){const i=this.previous,o=this.events;let s=0;return function(t){if(126===i&&"characterEscape"!==o[o.length-1][1].type)return r(t);return e.enter("strikethroughSequenceTemporary"),a(t)};function a(o){const c=Ee(i);if(126===o)return s>1?r(o):(e.consume(o),s++,a);if(s<2&&!t)return r(o);const l=e.exit("strikethroughSequenceTemporary"),u=Ee(o);return l._open=!u||2===u&&Boolean(c),l._close=!c||2===c&&Boolean(u),n(o)}},resolveAll:function(e,t){let n=-1;for(;++n0;)t-=1,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(const t of r)e.push(t);r=n.pop()}this.map.length=0}}function gn(e,t){let n=!1;const r=[];for(;t-1;){const e=r.events[t][1].type;if("lineEnding"!==e&&"linePrefix"!==e)break;t--}const i=t>-1?r.events[t][1].type:null,o="tableHead"===i||"tableRow"===i?b:a;if(o===b&&r.parser.lazy[r.now().line])return n(e);return o(e)};function a(t){return e.enter("tableHead"),e.enter("tableRow"),function(e){if(124===e)return c(e);return i=!0,s+=1,c(e)}(t)}function c(t){return null===t?n(t):pe(t)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),h):n(t):ge(t)?xe(e,c,"whitespace")(t):(s+=1,i&&(i=!1,o+=1),124===t?(e.enter("tableCellDivider"),e.consume(t),e.exit("tableCellDivider"),i=!0,c):(e.enter("data"),l(t)))}function l(t){return null===t||124===t||de(t)?(e.exit("data"),c(t)):(e.consume(t),92===t?u:l)}function u(t){return 92===t||124===t?(e.consume(t),l):l(t)}function h(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter("tableDelimiterRow"),i=!1,ge(t)?xe(e,f,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):f(t))}function f(t){return 45===t||58===t?d(t):124===t?(i=!0,e.enter("tableCellDivider"),e.consume(t),e.exit("tableCellDivider"),p):x(t)}function p(t){return ge(t)?xe(e,d,"whitespace")(t):d(t)}function d(t){return 58===t?(s+=1,i=!0,e.enter("tableDelimiterMarker"),e.consume(t),e.exit("tableDelimiterMarker"),g):45===t?(s+=1,g(t)):null===t||pe(t)?k(t):x(t)}function g(t){return 45===t?(e.enter("tableDelimiterFiller"),m(t)):x(t)}function m(t){return 45===t?(e.consume(t),m):58===t?(i=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(t),e.exit("tableDelimiterMarker"),y):(e.exit("tableDelimiterFiller"),y(t))}function y(t){return ge(t)?xe(e,k,"whitespace")(t):k(t)}function k(n){return 124===n?f(n):(null===n||pe(n))&&i&&o===s?(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(n)):x(n)}function x(e){return n(e)}function b(t){return e.enter("tableRow"),w(t)}function w(n){return 124===n?(e.enter("tableCellDivider"),e.consume(n),e.exit("tableCellDivider"),w):null===n||pe(n)?(e.exit("tableRow"),t(n)):ge(n)?xe(e,w,"whitespace")(n):(e.enter("data"),v(n))}function v(t){return null===t||124===t||de(t)?(e.exit("data"),w(t)):(e.consume(t),92===t?E:v)}function E(t){return 92===t||124===t?(e.consume(t),v):v(t)}}function yn(e,t){let n,r,i,o=-1,s=!0,a=0,c=[0,0,0,0],l=[0,0,0,0],u=!1,h=0;const f=new dn;for(;++on[2]+1){const t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[["exit",s,t]])}return void 0!==i&&(o.end=Object.assign({},bn(t.events,i)),e.add(i,0,[["exit",o,t]]),o=void 0),o}function xn(e,t,n,r,i){const o=[],s=bn(t.events,n);i&&(i.end=Object.assign({},s),o.push(["exit",i,t])),r.end=Object.assign({},s),o.push(["exit",r,t]),e.add(n+1,0,o)}function bn(e,t){const n=e[t],r="enter"===n[0]?"start":"end";return n[1][r]}const wn={name:"tasklistCheck",tokenize:function(e,t,n){const r=this;return function(t){if(null!==r.previous||!r._gfmTasklistFirstContentOfListItem)return n(t);return e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(t),e.exit("taskListCheckMarker"),i};function i(t){return de(t)?(e.enter("taskListCheckValueUnchecked"),e.consume(t),e.exit("taskListCheckValueUnchecked"),o):88===t||120===t?(e.enter("taskListCheckValueChecked"),e.consume(t),e.exit("taskListCheckValueChecked"),o):n(t)}function o(t){return 93===t?(e.enter("taskListCheckMarker"),e.consume(t),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),s):n(t)}function s(r){return pe(r)?t(r):ge(r)?e.check({tokenize:vn},t,n)(r):n(r)}}};function vn(e,t,n){return xe(e,function(e){return null===e?n(e):t(e)},"whitespace")}function En(e){return te([{text:Gt},{document:{91:{name:"gfmFootnoteDefinition",tokenize:un,continuation:{tokenize:hn},exit:fn}},text:{91:{name:"gfmFootnoteCall",tokenize:ln},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:an,resolveTo:cn}}},pn(),{flow:{null:{name:"table",tokenize:mn,resolveAll:yn}}},{text:{91:wn}}])}function Cn(e,t){const n=String(e);if("string"!=typeof t)throw new TypeError("Expected character");let r=0,i=n.indexOf(t);for(;-1!==i;)r++,i=n.indexOf(t,i+t.length);return r}const Sn=function(e){if(null==e)return An;if("function"==typeof e)return _n(e);if("object"==typeof e)return Array.isArray(e)?function(e){const t=[];let n=-1;for(;++n":"")+")"})}return a;function a(){let s,a,c,l=In;if(o(t,r,i[i.length-1]||void 0)&&(l=function(e){if(Array.isArray(e))return e;if("number"==typeof e)return[Tn,e];return null==e?In:[e]}(n(t,i)),l[0]===On))return l;if("children"in t&&t.children){const n=t;if(n.children&&"skip"!==l[0])for(a=0,c=i.concat(n);a>-1&&a0?{type:"text",value:o}:void 0),!1===o?r.lastIndex=n+1:(a!==n&&u.push({type:"text",value:e.value.slice(a,n)}),Array.isArray(o)?u.push(...o):o&&u.push(o),a=n+h[0].length,l=!0),!r.global)break;h=r.exec(e.value)}l?(a?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=Cn(e,"(");let o=Cn(e,")");for(;-1!==r&&i>o;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),o++;return[e,n]}(n+r);if(!s[0])return!1;const a={type:"link",title:null,url:o+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[a,{type:"text",value:s[1]}]:a}function Vn(e,t,n,r){return!(!Hn(r,!0)||/[-\d_]$/.test(n))&&{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function Hn(e,t){const n=e.input.charCodeAt(e.index-1);return(0===e.index||ye(n)||me(n))&&(!t||47!==n)}function qn(){this.buffer()}function Yn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Qn(){this.buffer()}function Kn(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Wn(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=oe(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Jn(e){this.exit(e)}function Xn(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=oe(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Gn(e){this.exit(e)}function Zn(e){this.enter({type:"delete",children:[]},e)}function er(e){this.exit(e)}function tr(e){const t=e._align;this.enter({type:"table",align:t.map(function(e){return"none"===e?null:e}),children:[]},e),this.data.inTable=!0}function nr(e){this.exit(e),this.data.inTable=void 0}function rr(e){this.enter({type:"tableRow",children:[]},e)}function ir(e){this.exit(e)}function or(e){this.enter({type:"tableCell",children:[]},e)}function sr(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,ar));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function ar(e,t){return"|"===t?t:e}function cr(e){const t=this.stack[this.stack.length-2];t.type,t.checked="taskListCheckValueChecked"===e.type}function lr(e){const t=this.stack[this.stack.length-2];if(t&&"listItem"===t.type&&"boolean"==typeof t.checked){const e=this.stack[this.stack.length-1];e.type;const n=e.children[0];if(n&&"text"===n.type){const r=t.children;let i,o=-1;for(;++o0?parseInt(n):null};a0&&this.annotations.push({text:e})}pushMarkup(e,t){this.annotations.push({markup:e,interpretAs:t})}extend(e){for(const t of e.annotations)"text"in t?this.pushText(t.text):this.pushMarkup(t.markup,t.interpretAs)}optimize(){const e=[];for(const t of this.annotations){if("text"in t&&0===t.text.length||"markup"in t&&0===t.markup.length&&!t.interpretAs)continue;const n=e.at(-1);void 0===n?e.push(t):"text"in n&&"text"in t?n.text+=t.text:"markup"in n&&"markup"in t?(n.markup+=t.markup,n.interpretAs&&t.interpretAs?n.interpretAs+=t.interpretAs:t.interpretAs&&(n.interpretAs=t.interpretAs)):e.push(t)}for(const t of e)"markup"in t&&t.interpretAs&&(t.interpretAs=t.interpretAs.replace(/\n{3,}/g,"\n\n"));for(let t=e.at(-1);t&&"markup"in t;t=e.at(-1))e.pop();let t=0;for(let n=e.at(0);n&&"markup"in n;n=e.at(0))t+=n.markup.length,e.shift();return this.annotations=e,t}extractSlice(e,t){let n=0;for(;n=t)return r.slice(e,t).trim()}return null}length(){return this.annotations.reduce((e,t)=>"text"in t?e+t.text.length:"markup"in t?e+t.markup.length:e,0)}stringify(){return JSON.stringify({annotation:this.annotations})}}const Or=-2,Dr=0,Lr=null,Pr=32,Mr=91;function Rr(e){return null!=e&&(e?@\[\\\]^_`{|}~]/g;class Br{raw;output;output_start;output_end;offset;range;constructor(e,t){this.raw=e,this.output=new Tr,this.offset=0,this.range=t}visitText(e){const t=e?.position?.start.offset,n=e?.position?.end.offset;if(null==t||null==n)throw Error("Markdown parsing: unknown position for text node");if(function(e,t,n){const[r,...i]=e.replace(/\n$/,"").split("\n"),[o,...s]=t.replace(/\n$/,"").split("\n");if(i.length!==s.length)throw console.error("Invalid number of lines",i.length,s.length,e,t),Error("Markdown parsing: invalid number of lines");$r(r,n);for(let e=0;e=this.range.to+1)return;t<=this.range.from&&this.range.from<=n&&(this.output=new Tr,this.offset=t,this.output_start=this.offset,console.debug("Start from",this.output_start)),t<=this.range.to&&this.range.to<=n&&(this.output_end=n,console.debug("End at",this.output_end))}switch(this.offsetthis.visitRoot(e));break;case"list":case"heading":case"tableRow":e.children.forEach(e=>this.visitRoot(e)),this.output.pushMarkup("","\n\n");break;case"inlineCode":this.output.pushMarkup(Ur(t,n),e.value),this.offset=n;break;case"break":this.output.pushMarkup(Ur(t,n),"\n"),this.offset=n;break;case"blockquote":case"paragraph":e.children.length>0&&(e.children.forEach(e=>this.visitRoot(e)),this.output.pushMarkup("","\n\n"));break;case"listItem":e.children.length>0&&(this.output.pushMarkup("","• "),e.children.forEach(e=>this.visitRoot(e)));break;case"link":case"wikiLink":e.children?e.children.forEach(e=>this.visitRoot(e)):(this.output.pushMarkup(Ur(t,n),"DUMMY"),this.offset=n);break;case"table":this.output.pushMarkup("","\n"),e.children.forEach(e=>this.visitRoot(e));break;case"tableCell":e.children.forEach(e=>this.visitRoot(e)),this.output.pushMarkup("","\n");break;case"thematicBreak":this.output.pushMarkup(Ur(t,n),"\n\n"),this.offset=n}this.offsetthis.handleStatusBarClick(),this.setStatusBarReady(),this.registerEditorExtension(function(e){return[U,R(e),q(e),Y]}(this)),this.registerCommands(),this.registerMenuItems();try{let e=this.app.metadataTypeManager;e.setType("lt-language","text"),e.setType("lt-picky","checkbox"),e.setType("lt-autoCheck","checkbox"),e.setType("lt-dictionary","multitext"),e.setType("lt-disabledRules","multitext"),e.setType("lt-disabledCategories","multitext")}catch{console.error("Failed to set metadata types")}const e=new Set(this.settings.options.dictionary.map(e=>e.trim()));e.delete(""),await this.settings.update({dictionary:[...e].sort(_)}),await this.syncDictionary()}onunload(){this.logs=[],this.isLoading=!1}registerCommands(){this.addCommand({id:"check",name:"Check text",icon:"spell-check",editorCallback:(t,n)=>{const r=t.cm;this.runDetection(r).catch(e=>console.error(e)).then(t=>{t||new e.Notice("No suggestions found.")})}}),this.addCommand({id:"toggle-auto-check",name:"Toggle automatic checking",icon:"uppercase-lowercase-a",callback:async()=>{await this.settings.update({shouldAutoCheck:!this.settings.options.shouldAutoCheck})}}),this.addCommand({id:"clear",name:"Clear suggestions",icon:"cross",editorCallback:e=>{e.cm.dispatch({effects:[z.of(null)]})}}),this.addCommand({id:"accept-all",name:"Accept all suggestions",icon:"circle-check-big",editorCallback:e=>{const t=e.cm,n=[],r=[];t.state.field(U).between(0,1/0,(e,t,i)=>{i.spec?.underline?.replacements?.length&&(n.push({from:e,to:t,insert:i.spec.underline.replacements[0]}),r.push(j.of({from:e,to:t})))}),t.dispatch({changes:n,effects:r})}}),this.addCommand({id:"next",name:"Jump to next suggestion",icon:"chevron-right",editorCheckCallback:(e,t)=>{const n=t.cm,r=t.posToOffset(t.getCursor());let i=null;if(n.state.field(U).between(r+1,1/0,(e,t)=>{(!i||i.from>e)&&(i={from:e,to:t})}),e)return null!=i;null!=i&&n.dispatch({selection:{anchor:i.from,head:i.to}})}});for(let e=1;e<=8;e++)this.addCommand(this.applySuggestionCommand(e));this.addCommand({id:"synonyms",name:"Show synonyms",icon:"square-stack",editorCheckCallback:(e,t)=>this.showSynonyms(t,e)})}applySuggestionCommand(e){return{id:`accept-${e}`,name:`Accept suggestion ${e}`,icon:"circle-check",editorCheckCallback(t,n){const r=n.cm,i=n.posToOffset(n.getCursor()),o=[];r.state.field(U).between(i,i,(e,t,n)=>{o.push({from:e,to:t,value:n})});const s=1===o.length&&o[0].value.spec?.underline?.replacements?.length>=e;if(t)return s;if(!s)return;const{from:a,to:c,value:l}=o[0],u={from:a,to:c,insert:l.spec.underline.replacements[e-1]};r.dispatch({changes:[u],effects:[j.of({from:a,to:c})]})}}}registerMenuItems(){this.registerEvent(this.app.workspace.on("editor-menu",(e,t,n)=>{console.debug(e);const r=t.cm;this.populateSuggestionMenu(e,r),this.showSynonyms(t,!0)&&e.addItem(e=>{e.setTitle("Synonyms"),e.setIcon("square-stack"),e.setSection("spellcheck"),e.onClick(()=>this.showSynonyms(t))})}))}populateSuggestionMenu(e,t){const n=t.state.field(U),r=t.state.selection.main;let i=!1;const o=n.iter(r.from);for(;null!=o.value&&o.from<=r.to;){i=!0;const n=o.value.spec.underline;e.addItem(e=>{e.setTitle(`LanguageTool (${n.text})`),e.setIcon("spell-check"),e.setSection("spellcheck");const r=e.setSubmenu();this.populateSuggestionSubmenu(r,n,o,t)}),o.next()}return i}populateSuggestionSubmenu(t,n,r,i){(n.message||n.title)&&(t.addItem(e=>{let t=new DocumentFragment;t.appendChild(createDiv({cls:"lt-menu-info"},e=>{n.title&&e.createDiv({text:n.title,cls:"lt-menu-title"}),n.message&&e.createDiv({text:n.message,cls:"lt-menu-message"})})),e.setIsLabel(!0),e.setTitle(t)}),t.addSeparator());for(const e of n.replacements.slice(0,8))t.addItem(t=>{t.setTitle(e?JSON.stringify(e):"(delete)"),t.onClick(()=>{i.dispatch({changes:{...r,insert:e},effects:[j.of(r)]})})});t.addSeparator(),"TYPOS"===n.categoryId?t.addItem(e=>{e.setTitle("Add to dictionary"),e.setIcon("plus-with-circle"),e.onClick(async()=>{let e=[...this.settings.options.dictionary,n.text.trim()];e.sort(_),await this.settings.update({dictionary:e}),await this.syncDictionary(),i.dispatch({effects:[B.of(e=>e.text===n.text)]})})}):(t.addItem(e=>{e.setTitle("Ignore suggestion"),e.setIcon("cross"),e.onClick(()=>{i.dispatch({effects:[j.of(r)]})})}),n.ruleId&&"SYNONYMS"!==n.ruleId&&t.addItem(t=>{t.setTitle("Disable rule"),t.setIcon("circle-off"),t.onClick(async()=>{let e=this.settings.options.disabledRules;e?e+=","+n.ruleId:e=n.ruleId,await this.settings.update({disabledRules:e}),i.dispatch({effects:[B.of(e=>e.ruleId===n.ruleId)]})});const r=t.dom;e.setTooltip(r,`${n.categoryId} > ${n.ruleId}`)}))}showSynonyms(t,n=!1){if(!this.settings.options.synonyms||!(this.settings.options.synonyms in x))return!1;const r=x[this.settings.options.synonyms];if(!r)return!1;const i=t.cm,o=i.state.selection.main;if(o.empty)return!1;const s=i.state.sliceDoc(i.state.selection.main.from,i.state.selection.main.to);if(s.match(/[\s\.]/))return!1;if(n)return!0;const a=i.state.doc.lineAt(o.from),c=a.text.slice(0,o.from-a.from).lastIndexOf(".")+1,l=a.text.slice(c);let u=l.trimStart();const h=a.from+c+l.length-u.length,f={from:o.from-h,to:o.to-h};u=u.trimEnd();const p=u.indexOf(".");return-1!==p&&(u=u.slice(0,p+1)),r.query(u,f).then(e=>i.dispatch({effects:[N.of({text:s,range:o,title:"Synonyms",message:"",categoryId:"SYNONYMS",ruleId:"SYNONYMS",replacements:e})]})).catch(t=>{console.error(t),this.pushLogs(t),new e.Notice(t.message,3e4)}),!0}setStatusBarReady(){this.isLoading=!1,e.setIcon(this.statusBarItem,"spell-check")}setStatusBarWorking(){this.isLoading||(this.isLoading=!0,e.setIcon(this.statusBarItem,"sync-small"))}handleStatusBarClick(){const t=this.statusBarItem.getBoundingClientRect(),n=this.statusBarItem.getBoundingClientRect();(new e.Menu).addItem(t=>{t.setTitle("Check text"),t.setIcon("spell-check"),t.onClick(async()=>{const t=this.app.workspace.getActiveViewOfType(e.MarkdownView);if(t&&"source"===t.getMode()){const n=t.editor.cm;await this.runDetection(n)||new e.Notice("No suggestions found.")}})}).addItem(e=>{e.setTitle(this.settings.options.shouldAutoCheck?"Disable automatic checking":"Enable automatic checking"),e.setIcon("uppercase-lowercase-a"),e.onClick(async()=>{await this.settings.update({shouldAutoCheck:!this.settings.options.shouldAutoCheck})})}).addItem(t=>{t.setTitle("Clear suggestions"),t.setIcon("cross"),t.onClick(()=>{const t=this.app.workspace.getActiveViewOfType(e.MarkdownView);if(!t)return;t.editor.cm.dispatch({effects:[z.of(null)]})})}).showAtPosition({x:n.right+5,y:(t?.top||0)-5})}getActiveFileSettings(){const e=this.app.workspace.getActiveFile(),t=e&&this.app.metadataCache.getFileCache(e);if(null!=t?.frontmatter){const e=t.frontmatter["lt-language"]??t.frontmatter.lt_language,n=t.frontmatter["lt-picky"],r=t.frontmatter["lt-autoCheck"],i=t.frontmatter["lt-dictionary"],o=t.frontmatter["lt-disabledRules"],s=t.frontmatter["lt-disabledCategories"];let a={...this.settings.options};return"string"==typeof e&&(a.staticLanguage=e),"boolean"==typeof r&&(a.shouldAutoCheck=r),"boolean"==typeof n&&(a.pickyMode=n),Array.isArray(i)&&(a.dictionary=i),Array.isArray(o)&&o.length&&(a.disabledRules+=","+o.join(",")),Array.isArray(s)&&s.length&&(a.disabledCategories+=","+s.join(",")),a}return this.settings.options}async runDetection(t,n){let r=this.getActiveFileSettings();const i=t.state.selection.main;n||i.empty||(n={...i});const o=t.state.sliceDoc();if(!o.trim())return!1;let s,a;try{this.setStatusBarWorking();let{offset:t,annotations:i}=await async function(e,t){const n=jt(e,{extensions:[En(),wr(["yaml"]),Nr({aliasDivider:"|"})],mdastExtensions:[[{transforms:[$n],enter:{literalAutolink:Rn,literalAutolinkEmail:Fn,literalAutolinkHttp:Fn,literalAutolinkWww:Fn},exit:{literalAutolink:Bn,literalAutolinkEmail:jn,literalAutolinkHttp:Nn,literalAutolinkWww:zn}},{enter:{gfmFootnoteCallString:qn,gfmFootnoteCall:Yn,gfmFootnoteDefinitionLabelString:Qn,gfmFootnoteDefinition:Kn},exit:{gfmFootnoteCallString:Wn,gfmFootnoteCall:Jn,gfmFootnoteDefinitionLabelString:Xn,gfmFootnoteDefinition:Gn}},{canContainEols:["delete"],enter:{strikethrough:Zn},exit:{strikethrough:er}},{enter:{table:tr,tableData:or,tableHeader:or,tableRow:rr},exit:{codeText:sr,table:nr,tableData:ir,tableHeader:ir,tableRow:ir}},{exit:{taskListCheckValueChecked:cr,taskListCheckValueUnchecked:cr,paragraph:lr}}],Sr(["yaml"]),zr()]}),r=new Br(e,t);try{n.children.forEach(e=>r.visitRoot(e))}catch(e){throw console.error("Error while parsing markdown:\n",JSON.stringify(n,void 0," ")),e}return{offset:r.output_start??0,annotations:r.output}}(o,n);if(t+=i.optimize(),0===i.length())return!1;i.length()>500&&(a=new e.Notice("Checking spelling...",3e4)),console.info(`Checking ${i.length()} characters...`),console.debug("Text",JSON.stringify(i,void 0," ")),s=await async function(e,t,n){const r=n.stringify(),i=e.staticLanguage??"auto",o={data:r,language:i,enabledOnly:"false",level:e.pickyMode?"picky":"default"};e.motherTongue&&(o.motherTongue=e.motherTongue),e.enabledCategories&&(o.enabledCategories=e.enabledCategories),e.disabledCategories&&(o.disabledCategories=e.disabledCategories),e.enabledRules&&(o.enabledRules=e.enabledRules),e.disabledRules&&(o.disabledRules=e.disabledRules),"auto"==i&&(o.preferredVariants=Object.values(e.languageVariety).join(",")),"standard"!==T(e.serverUrl)&&e.apikey&&e.username&&(o.username=e.username,o.apiKey=e.apikey);const s=await b({url:`${e.serverUrl}/v2/check`,method:"POST",body:new URLSearchParams(o).toString(),headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}});if(null==s.json)throw new Error("Error processing response from LanguageTool.");return v("$.matches[*]",s.json).map(e=>{const r=w("$.offset@number()",e),i=r+w("$.length@number()",e);return{range:{from:t+r,to:t+i},text:n.extractSlice(r,i)||"",title:w("$.shortMessage@string()",e),message:w("$.message@string()",e),replacements:v("$.replacements[*].value@string()",e),categoryId:w("$.rule.category.id@string()",e),ruleId:w("$.rule.id@string()",e)}})}(r,t,i),n&&(n={from:t,to:t+i.length()})}catch(t){return console.error(t),t instanceof Error&&(this.pushLogs(t),new e.Notice(t.message,3e4)),!0}finally{this.setStatusBarReady(),a&&a.hide()}const c=[];if(n?c.push(j.of(n)):c.push(z.of(null)),s){const e=r.dictionary;for(const n of s)n.range.to>t.state.doc.length||"TYPOS"===n.categoryId&&e.includes(n.text)||c.push(N.of(n))}return c.length&&t.dispatch({effects:c}),console.info(`Found ${c.length-1} suggestions.`),c.length>1}async pushLogs(e){const t=`${(new Date).toLocaleString()}:\nError: '${e.message}'\nSettings: ${JSON.stringify({...this.settings,username:"REDACTED",apikey:"REDACTED"})}\n`;this.logs.push(t),this.logs.length>10&&this.logs.shift()}async onExternalSettingsChange(){await this.settings.load(),await this.settingTab.notifyEndpointChange(this.settings.options)}async syncDictionary(){if(this.settings.options.syncDictionary&&"premium"===T(this.settings.options.serverUrl))try{const e=new Set(this.settings.options.remoteDictionary);let t=new Set(this.settings.options.dictionary),n=new Set(await async function(e){if(null==e.username||null==e.apikey)throw Error("Syncing words is only supported for premium users");try{return v("$.words[*]@string()",(await b({url:E(`${e.serverUrl}/v2/words`,{username:e.username,apiKey:e.apikey,limit:"1000"}).href})).json)}catch(e){throw new Error(`Requesting words failed\n${e}`)}}(this.settings.options)),r=S(e,t);r=function(e,t){const n=new Set;for(const r of t)e.has(r)&&n.add(r);return n}(r,n);for(const e of r)await k(this.settings.options,e);const i=S(e,n);n=S(n,r),t=S(t,i);const o=S(t,n);for(const e of o)await y(this.settings.options,e);let s=[...function(e,t){const n=new Set(e);for(const e of t)n.add(e);return n}(n,t)].sort(_);await this.settings.update({dictionary:s,remoteDictionary:s})}catch(t){this.pushLogs(t),new e.Notice(t.message,3e4),console.error("Failed sync spellcheck with LanguageTool",t)}}}module.exports=Hr; /* nosourcemap */