Skip to content

Instantly share code, notes, and snippets.

@TamerRizk
Last active February 11, 2019 21:45
Show Gist options
  • Save TamerRizk/f65ace8ff89a5c136f09ee18290350c0 to your computer and use it in GitHub Desktop.
Save TamerRizk/f65ace8ff89a5c136f09ee18290350c0 to your computer and use it in GitHub Desktop.
mathKey
/*
mathKey.js: Copyright (c) 2018-2028 TR (tr[at]mathkey.org)
By exercising any rights granted by this license (the "License"), You agree and accept to be bound by the terms and conditions herein. To the extent that the License may be interpreted as a contract, You are granted consideration of Your agreement with these terms and conditions by consideration for your utility of (the "Software", "mathKey.js"), and the Copyright (the "Licensor", "TR") specified in the notice above is granted consideration for utilitizing the software from acceptance of the Software through its utilization.
Subject to Your agreement to be bound by the terms and conditions herein the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable License that shall permit You to deal in the Software and permit those upon whom You furnish the Software to use the Software, without limitation to Your rights to use, link to, copy, and/or sell copies of the Software, subject to the following terms and conditions:
Any alteration, arrangement, transformation, or other modification of the Software is an Adapted Work. Any process of publication to alter, arrange, transform, or otherwise modify the Software to an Adapted Work is disclosure of Adapted Work.
You may exercise rights to alter, arrange, transform, or otherwise modify the Software subject to the former and following terms and conditions:
Except in disclosure and distribution as part of the Software through express consent of the Licensor, Adapted Work shall not be disclosed or distributed to any recipient without such recipient of express prior agreement to not publish such Adapted Work. The Text of the License must be included in such Adapted Work.
Rights are hereby granted, free of charge, for You to publish and distribute the Software subject to the former and following terms and conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
The full text of the License, from the above Copyright notice to this license notice, (the "Text") must be included in all copies or substantial portions of the Software.
This is MathKey version 0.33
With special thanks to ASCIIMathML.js:
Peter Jipsen http://www.chapman.edu/~jipsen
Douglas Woodall
Paulo Soares
*/
var __hashSum = function(){
/******************************************************************************************/
/* hashSum */
/******************************************************************************************/
/*
The object of return by this function, and following this notice, is made available under:
The MIT License (MIT)
Copyright (c) 2014 Nicolas Bevacqua
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/
var hs = {};
hs.pad = function(hash, len) {
while (hash.length < len) {
hash = '0' + hash;
}
return hash;
};
hs.fold = function(hash, text) {
var i, chr, len;
if ((len=text.length) === 0) {
return hash;
}
for(i=-1; len>++i;) {
chr = text.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash < 0 ? hash * -2 : hash;
};
hs.foldObject = function(hash, o, seen) {
var foldKey = function(hash, key) {
return hs.foldValue(hash, o[key], key, seen);
};
return Object.keys(o).sort().reduce(foldKey, hash);
};
hs.foldValue = function (input, value, key, seen) {
var hash = hs.fold(hs.fold(hs.fold(input, key), Object.prototype.toString.call(hs.normalize(value))), typeof value);
if (value === null) {
return hs.fold(hash, 'null');
}
if (value === undefined) {
return hs.fold(hash, 'undefined');
}
if (typeof value === 'object') {
if (seen.indexOf(value) !== -1) {
return hs.fold(hash, '[Circular]' + key);
}
seen.push(value);
return hs.foldObject(hash, value, seen);
}
return hs.fold(hash, hs.normalize(value).toString());
};
hs.normalize = !!String.prototype.normalize ? function(s){
return 'string'==typeof s? s.normalize() : s;
} : function(s){ return s; }; //see unorm polyfill
hs.hash = function(o) {
return hs.pad(hs.normalize(hs.foldValue(0, o, '', [])).toString(16), 8);
};
return hs;
};
/******************************************************************************************/
var __levenshtein = function(value='', other='', insensitive=false){
/******************************************************************************************/
/* levenshtein-edit-distance */
/******************************************************************************************/
/*
This function is made available under:
The MIT License (MIT)
Copyright (c) 2018 Titus Wormer
(License text incorporated by reference)
*/
var cache = [], codes = [], length, lengthOther, code, result, distance, distanceOther, index, indexOther;
if (value === other) {
return 0
}
length = value.length;
lengthOther = other.length;
if (length === 0) {
return lengthOther;
}
if (lengthOther === 0) {
return length;
}
if (!!insensitive) {
value = value.toLowerCase();
other = other.toLowerCase();
}
index = 0;
while (index < length) {
codes[index] = value.charCodeAt(index);
cache[index] = ++index;
}
indexOther = 0;
while (indexOther < lengthOther) {
code = other.charCodeAt(indexOther);
result = distance = indexOther++;
index = -1;
while (++index < length) {
distanceOther = code === codes[index] ? distance : distance + 1;
distance = cache[index];
cache[index] = result =
distance > result ?
distanceOther > result ? result + 1 : distanceOther
:
distanceOther > distance ? distance + 1 : distanceOther;
}
}
return result;
};
/******************************************************************************************/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if ((typeof module === 'object' || typeof exports === 'object') && module.exports) {
module.exports = factory();
} else {
root.mathKey = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
var conf = {
checkformathml: true,
notifyifnomathml: false,
notifywarnings: true,
notifywarningscallback: null,
translateonstart: true,
document: null,
autostart: true,
translateclass: '_MK_',
fallbackcssurl: '/mathml-mozilla.css', // or mathml-w3c.css ... see: https://developer.mozilla.org/en-US/docs/Mozilla/MathML_Project/test-mathml-css and https://www.w3.org/TR/MathML2/appendixg.html
fallbackliburl: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js', //if available, ex: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js or http://www.wiris.com/quizzes/demo/generic/quizzes/resources/quizzes.js
mstyle:{displaystyle:'true', scriptsizemultiplier:'0.8', scriptminsize:'6px', mathcolor:'', fontfamily:'serif'},
manage:'`',
managementinterface: null
}, mk = null;
// token types
var mkDef = {VAR:0, UNARY:1, BINARY:2, INFIX:3, LEFTBRACKET:4, RIGHTBRACKET:5, LEFTRIGHT:6, SHAPE:7, SPACE:8, UNDEROVER:9, DIFFERENTIAL:10, TEXT:11, PHANTOM: 12, NONE: 13, MULTI:14, CONST:15, STYLE:16}, mkRdef ={};
for(mk in mkDef){
eval('var '+mk+'='+mkDef[mk]+';');
mkRdef[mkDef[mk]]=mk;
}
mk = {init:null};
var mkDebug = false, errorBuf = [], userAgent = '', mkMathns = 'http://www.w3.org/1998/Math/MathML', mkDoc, mkHasMathML = false, mkConfigured = false, mkReady = false, mkTranslated = 0, mkTsp={mo:0.7}, mkCk = false, mkFallback = '', mkFallbackCSS = '', mkLineHeight = 5, mkFields = {},
mkMng = {html:['<div style="background-color: #ffffff;display:inline-block;width:700px;box-shadow: 3px 3px 3px #000; padding:5px 0 15px 0; position:relative;"><div style="text-align:right;height:10px;width:100%;"><div style="height:10px;color:#aaaaaa;font-weight: 600;user-select: none;cursor: pointer;width:20px;font-size:14px;display:inline-block;margin-right:7px;line-height:14px" onclick="this.parentNode.parentNode.parentNode.style.display=\'none\'" aria-label="close this panel" tabIndex="0">X</div></div><table border="0" cellspacing="0" cellpadding="0" width="100%" style="width: 620px; max-width: 620px; display:inline-block;"><tr><td style="text-align:right;height:10px;"><span class="mathKeyFex" style="font-size: 9px;font-family: times;float: left;white-space: nowrap;text-align: left;max-width:500px;overflow:hidden;"></span><span style="position:relative;top:38px;cursor:pointer;font-size:9px;color:#666666;text-decoration:underline;" onclick="mathKey.manageReset();">reset definitions</span></td><td></td><td rowspan="3" style="vertical-align:middle;text-align:center;width:225px" class="mathKeyOutput"></td></tr><tr><td style="text-align:left;vertical-align:bottom;height:25px;width:410px;"><input type="text" class="mathKeyInput" onkeyup="mathKey.manageInput()" placeholder="New symbol entry" style="width:400px;height:20px;border:1px solid #ccc;font-size:10px;"></td><td style="text-align:left;vertical-align:bottom;text-align:left;"><button style="cursor:pointer;width:40px;height:24px;font-size:11px;" onclick="mathKey.manageAdd()">Add</button></td></tr><tr><td style="text-align:left;height:40px;"><select style="width:280px;height:20px;border:1px solid #ccc;font-size:10px;margin-right:5px;" class="mathKeyFields" onclick="mathKey.manageFieldData();"><option value="" style="color:#cccccc">--fields--</option></select><span style="cursor:pointer;font-size:12px;color:#444;background:#ccc;border:1px solid #999999;line-height:12px;padding:0 3px 0 3px;" onclick="mathKey.manageField();">&#9650;</span></td><td></td></tr></table><table border="0" cellspacing="0" cellpadding="0" width="100%" style="border: 1px solid #ddd; border-radius: 5px; width: 620px; max-width: 620px; display:inline-block;font-family: Times, serif;font-size:10px;">', '<tr>',
'<td style="cursor: pointer; text-align:center;vertical-align:middle;background:%MKROWCOLOR%;padding: 2px;height: 25px !important;overflow: hidden;border-bottom: 1px solid #ccc;outline:none;width:50px;max-width:50px;" onclick="mathKey.manageCopy(this.parentNode)"><span class="mathKeyTranslateDict">%MKDICT%</span></td><td style="cursor: pointer;font-family: monospace; text-align:left;vertical-align:middle;width:540px;max-width:540px;background:%MKROWCOLOR%;padding: 2px;height: 25px !important;overflow: hidden;border-bottom: 1px solid #ccc;outline:none;" onclick="mathKey.manageCopy(this.parentNode)">{%MKENTRY%}</td><td style="border-bottom: 1px solid #ccc;outline:none;font-size:10px;text-align:center;vertical-align:middle;;user-select: none;width:25px;background:%MKROWCOLOR%;cursor: pointer;color:#ff0000" onclick="mathKey.manageDelete(this.parentNode);">X</td>', '</tr>', '</table></div>'], rowcolors:['#ffffff','#fcfcfc'], style: {display:'none', position:'absolute', zIndex:'2147483636', width:'100%', height:'1000%', top:'0', left:'0', textAlign:'center', background:'rgba(0,0,0,0.8)'}},
mkLoading = new Image();
mkLoading.height=16;
mkLoading.width=16;
mkLoading.className = '__mkLoading';
mkLoading.src='data:image/gif;base64,R0lGODlhIAAgANUAAP////f///f39/f3/+/39+/v9+/v7+bv7+bm7+bm5t7e3t7e5tbW3s7O1sXOzsXO1sXF1sXFzr3Fxb3Fzr29xbW9vbW9xbW1xbW1va21ta21va2tva2ttaWttZylrZycrZScrZScpZSUpYyUpYyUnISMnP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCAAmACwAAAAAIAAgAAAG/0CTcEgkgkolUHHJLBaGBBKSRBgCmk2Bo9MQFpDIp6mAKFyxQ0Omw35+wVUAYo4IoIWCNVtiIoBLVWR0Z3cKbGwHAn8CcnQCaAKPQhaHGgYlIyMlBYIIBlaEeBERCEIIhxMGBpGrnZICc6EKoxENnxMYn0ywTwKdYiYCtLQMBZJNAACdg0IAC8O1och0dGZEAgy0x3cD1dJpDQx3TolLyeeR40Tn7CYJC/Dx32iN1Ajx+PNY9dT48upW7M1550/fNIEm2AFgBLCZwm+8Go5BsG1dpwEAu82xZmVZrHH8Np4JWSYZPWUCCXVaNbHikIgCDFRbN+eVN4Wu8HxcR8gevymQoCBRY0Rt4VB1/J78nMjsToCiCaHyswOSjJilEzkCJIQ1oUQm1AAGAQAh+QQFCAAmACwAAAAAGgATAAAGmkCTcEgkYjodTHG5FBCRSKKBSVREFkIBtOM0WUqWblEQKUecWqjQUGqPEExzhCHc1tulEYGJkBdMWwALeCUNRQBDDWYNBB0ZGR0mIXgfRIILfyYFZgwCXQIGHXhYQwYLpwhODIZUCSCRRKeyC6mIVCYCmaWzCwm3v0IIssDEAglwxMAAAclFCM/QyM1D0dDTRNXP19TZ21S220EAIfkEBQgAJgAsAAAAAB8ADgAABpZAk3BIJDYikUZxyWyakEin1AQwLAxDaGTY6Dimw4V4kYUOO+gMVgoYLxBCrVCC7mTApoJbAJAj6h0KTgBECWMJT1ACGnUWQwIHRQgIAkICY3BUhCYTdZkNIySVQ5MIBUIICaNLBhhbCx4lshdCAKWlp3gbsrwlaya3k3gCIb0lFKsABaV4qLwdmUsHuc0dIILNeAXJJkEAIfkEBQgAJgAsBgAAABoAFAAABp9Ak3AoTCwWCaJyKQQMAcejUyhgKhHP6GK6iCisAYQY4YRGnYKIOlJdjhEFk1lqYqwjVsFbqDUZ7lhWBnt9DWsNRAZuYgUAAU0CdmpxJgoaHUsFgVYNDCYIFh2iDkpTVnImEaKrmKenl6yIroKrE4qzpxIWm7inBgIEBQUEvZkjJcjIIMVEAiTJycxDztDI0kIGz9Ah1yYCw8HD3UKNSkEAIfkEBQgAJgAsDQAAABMAGgAABoxAE2KIMBmPyCSxmGwel0fDwgBwConHhXZhhQq3i2oTKgAXnIAlAJxACqxf7VsYicBNgkTR0KhHFHd4DH5+c1YAfYRhgQJ+DIaBDA0GgUkCc5eVeB2cnRiVGZ2doKKcjKGiGoGUVZmVHSBcmkIltRtMdwIhtbwUkE0FG7y8lIELHrwXsyYNIyS/jAdHQQAh+QQFCAAmACwSAAEADgAeAAAGi0CT0AQYGo8mBPIIQDgRgaWp8FRKq4Lr0zAsdqnOYWGx8A4RBZMAQV5wkew2eZmQu6VtqzYr7UsjgIENSACBhoSGgUuJEYNHAnx+EhUJfgYdmBNvRwEamJ+OQ1kRn59GCSAbSRafDkKXJbELQgqeoiOxJR9GmyYLuSWhSB25IwRSBsV6SBYlFpHIfUEAIfkEBQgAJgAsDAAGABQAGgAABp1Ak3BILJoAxiRRgEAolYWm8zkERKVNJNWEbW6J0oL2ayoYyEUkYL0mAxbweIIcr9Pr8O8bP0ezx1QMDWdoJgIRiAwCaA2IjguASgyOjotKBhgTJgaNiApDAgYCoSYTHadTCBARQwUFJSMjJAYapx0VS1UCJbwlAge2HZ9JBL0lBKW2GUrFvQVCyoRFr85CDR0OTwQkvCTIaCG8IWhBACH5BAUIACYALAYADAAaABQAAAabQJNwSCwSD8akkghYOo2IqBTxVE6l1eQ1moVuu8RAE2xNCMjJhZqKHibUcEOxcF4CBAg4vNgBJZYNDCZ4cEhDCyWJHQZ1AgIMEZEFQgVqY0IfiSUhJh0ZGR0EDZERDUOXQg2aJQsAHa8dJgWkEWxFBCOasZ2wQpCkWrmJcryvZwK0dUUCFiUWQgKwHXULEQpPxELSRMpdGq8aXUEAIfkEBQgAJgAsAAASAB8ADgAABphAk3AoKAyPyKRyqAB1lssCYonolK5TKBLBLQCIlKs4JNAOueisySAWb8xDaRrxNV3EnoUpgjEsBQlZBmhGQgIkIw1CBx2NE0IAdQgLlGUmAlxIB5YmFY0dGgIRoxEmCZQLCUd1SgqfHVOkEQACqAuFZhmfj3ukQpOorEsGuo1DskO2cEIOHYpCyEIGCwbCy8e+13ANo89mQQAh+QQFCAAmACwAAAwAGgAUAAAGnECTUAgoDI/IpJBQKBAEBYFyOgSVrleSgUrFYklSrtKbDYuRIfLIeE4ynYJtm4uoSOZKw6TDl+OFDXyCGn9DgoIRJgBiAUgOghYIJgwNdGxHHRoKQgURngwCiyYBRQimSX4mDZ4RlQuvCyams1QIrBFbsLGys2ZItwyKuosFs5JJArdSAMOKxo1KChG7zLCismdm1a/X13MJrwlTQQAh+QQFCAAmACwAAAYAEwAaAAAGkkCT8CAQGo9IoYA0aiSfwktp6llAj4aptrQpXE0CyrYUKn5NiI0WcT4uQJ02uAgwGc6Yjl6fMV/3e31ngHxtGoSCbQJmi3JGBg0MjgIMEZZ+UAALlpwNdVcCnJwMmE8KnXcICaVIERBsYAuysE+YCbKyAAi7CJ9IBbgLRby0R5q4sMRQwUbKTwAGC3dCznLVbcpBACH5BAkIACYALAAAAAAgACAAAAaiQJNwSCwaj8iiIclkCiwlS3NKRIxK2CV1SrhiO1tqA4tdhI9a4Yc8EpyLHY1CuCB30m9HZ29BmDYgCW9we4URJm6DRA2FexoBikYGE4V4kUQJFRKXSQKJnA0RoqOcQ6OnAKUmp6OppaGsqrJUAgl+syYIC7uzBru/gqq/v7elB8RuBcWRALsFQwjRBa7M0NHRswLXy6Xbz7IB29Sz3LPjuKVBADs=';
var mkCref = [{'&gt;':'>','&lt;':'<','&amp;':'&','&quot;':'"','&GT;':'>','&LT;':'<','&AMP;':'&','&QUOT;':'"','(:':'\u2774',':)':'\u2775', '||':'\u2228', '^|^':'uparrow','.|.':'downarrow','___':'\uff3f\uff3f','__':'\uff3f','\uff3f_':'\uff3f\uff3f'},{':\\:':'\uff3c','\\_':'\uff0f','|--':'\u27cc ','+/-':'\u00B1','___':'\uff3f\uff3f','__':'\uff3f','\uff3f_':'\uff3f\uff3f'}],
mkParen = [{'\u2774':'\u2775','(':')','{':'}','[':']'}];
mkParen[1] = {};
mkParen[2] = {};
Object.keys(mkParen[0]).filter(function(k){ mkParen[1][mkParen[0][k]]=k; 255>k.charCodeAt(0)&&(mkParen[2][k]=mkParen[0][k])&&(mkParen[2][mkParen[0][k]]=k);});
var mkSync = {}, mkToParseSo={}, mkCopying=null, mkCCopy = 0, mkExt={sn:{},ref:{},id:{},img:{},cache:['','','','']}, mkOrigin={}, mkRorigin={}, mkFrames = {}, mkFrameUrl = {}, mkFromMathKey, mkUrl, mkTo = {pmInteractive:[100,50], fDoc:[500,5], fStart:[2000,1], wfpmInteractive:[5000,1], checkForId:[250,30]},
mkRand = [], mkHashSum = __hashSum(), mkSig = {'06e42274':true,'5e218b5f':true};
var mkNames = {}, mkRnames = {}, mkBak = [], mkBakNames={}, mkSym = [], mkRLength = 0,
mkElementPhantom = {symbol:{input:'', ptag:'mrow', output:'', type:PHANTOM}, pos:0, text:''},
mkSymbolNone = {input:'', ptag:'mi', output:'', type:NONE},
mkSymbolMulti = {input:'', ptag:'mrow', output:'', type:MULTI};
var mkSymbols = [
{input:'alpha', ptag:'mi', output:'\u03B1', type:VAR, sym:true},
{input:'beta', ptag:'mi', output:'\u03B2', type:VAR, sym:true},
{input:'chi', ptag:'mi', output:'\u03C7', type:VAR, sym:true},
{input:'delta', ptag:'mi', output:'\u03B4', type:VAR, sym:true},
{input:'Delta', ctag:'minus', csymbol: 'displacement', ptag:'mi', output:'\u0394', type:VAR, sym:true, functional: BINARY, isprefixop:true, paren:true},
{input:'epsilon', ptag:'mi', output:'\u03B5', type:VAR, sym:true},
{input:'varepsilon', ptag:'mi', output:'\u025B', type:VAR, sym:true},
{input:'eta', ptag:'mi', output:'\u03B7', type:VAR, sym:true},
{input:'gamma', ptag:'mi', output:'\u03B3', type:VAR, sym:true},
{input:'Gamma', ptag:'mi', output:'\u0393', type:VAR, functional: UNARY, paren:true},
{input:'iota', ptag:'mi', output:'\u03B9', type:VAR, sym:true},
{input:'kappa', ptag:'mi', output:'\u03BA', type:VAR, sym:true},
{input:'lambda', ctag:'lambda', ptag:'mi', output:'\u03BB', type:VAR, sym:true, functional: UNARY, paren:true},
{input:'Lambda', ptag:'mi', output:'\u039B', type:VAR, functional: UNARY, paren:true},
{input:'mu', ptag:'mi', output:'\u03BC', type:VAR, sym:true},
{input:'nu', ptag:'mi', output:'\u03BD', type:VAR, sym:true},
{input:'omega', ptag:'mi', output:'\u03C9', type:VAR, sym:true},
{input:'Omega', ptag:'mi', output:'\u03A9', type:VAR, sym:true, functional: UNARY, paren:true},
{input:'phi', ptag:'mi', output:'\u03C6', type:VAR, sym:true},
{input:'varphi', ptag:'mi', output:'\u03D5', type:VAR, sym:true},
{input:'Phi', ptag:'mi', output:'\u03A6', type:VAR, sym:true, functional: UNARY, paren:true},
{input:'pi', ctag:'pi', ptag:'mi', output:'\u03C0', type:CONST, sym:true},
{input:'Pi', ptag:'mi', ctag:'product', output:'\u220F', type:UNDEROVER, sym:true, functional: UNARY, sov:true},
{input:'prod', ptag:'mo', ctag:'product', output:'\u220F', type:UNDEROVER, sov:true},
{input:'Sigma', ptag:'mi', ctag:'sum', output:'\u2211', type:UNDEROVER, sov:true, functional:UNARY, separators:'+'},
{input:'sum', ptag:'mo', ctag:'sum', output:'\u2211', type:UNDEROVER, sov:true, separators:'+'},
{input:'stdev', ptag:'mo', ctag:'sdev', output:'\u03C3', type:UNARY, paren:true, sov:true},
{input:'sigma', ptag:'mi', ctag:'sdev', output:'\u03C3', type:VAR, sym:true, functional: UNARY, sov:true, separators:'',paren:true},
{input:'sigma2', ptag:'mi', ctag:'variance', output:'\u03C3\u00B2', type:VAR, sym:true, functional: UNARY, sov:true, paren:true},
{input:'vari', ptag:'mo', ctag:'variance', output:'\u03C3\u00B2', type:UNARY, paren:true, sov:true},
{input:'div', ptag:'mo', ctag:'divergence', output:'\u2207\u22C5', type:UNARY},
{input:'grad', ptag:'mo', ctag:'grad', output:'\u2207', type:UNARY, paren:true},
{input:'curl', ptag:'mo', ctag:'curl', output:'\u2207\u00D7', type:VAR, functional: UNARY},
{input:'nab2', ptag:'mi', ctag:'laplacian', output:'\u2207\u00B2', type:VAR, sym:true, functional: UNARY,paren:true},
{input:'Lap', ptag:'mi', ctag:'laplacian', output:'\u2112', type:VAR, paren:true, functional:UNARY, separators:'',sov:true},
{input:'psi', ptag:'mi', output:'\u03C8', type:VAR, sym:true},
{input:'Psi', ptag:'mi', output:'\u03A8', type:VAR, sym:true, functional: UNARY, paren:true},
{input:'rho', ptag:'mi', output:'\u03C1', type:VAR, sym:true},
{input:'tau', ptag:'mi', output:'\u03C4', type:VAR, sym:true},
{input:'theta', ptag:'mi', output:'\u03B8', type:VAR, sym:true},
{input:'vartheta', ptag:'mi', output:'\u03D1', type:VAR, sym:true},
{input:'Theta', ptag:'mi', output:'\u0398', type:VAR, sym:true, functional: UNARY, paren:true},
{input:'upsilon', ptag:'mi', output:'\u03C5', type:VAR, sym:true},
{input:'xi', ptag:'mi', output:'\u03BE', type:VAR, sym:true},
{input:'Xi', ptag:'mi', output:'\u039E', type:VAR, sym:true, functional: UNARY, paren:true},
{input:'zeta', ptag:'mi', output:'\u03B6', type:VAR, sym:true},
{input:'euler', ctag:'eulergamma', ptag:'mi', output:'\u03B3', type:CONST, sym:true},
{input:'+', ptag:'mo', ctag:'plus', output:'+', type:CONST, arith:true, pri:true},
{input:'-', ptag:'mo', ctag:'minus', output:'-', type:CONST, arith:true, pri:true},
{input:'**', ptag:'mo', ctag:'times', output:'\u00D7', type:CONST, arith: true},
{input:'*', ptag:'mo', ctag:'times', output:'*', type:CONST, arith: true},
{input:'/', ptag:'mfrac', ctag:'divide', output:'/', type:INFIX, arith:true},
{input:'-:', ptag:'mo', ctag:'divide', output:'\u00F7', type:CONST, arith:true},
{input:'\u27cc', vinput:'|--', ptag:'mlongdiv', ctag:'divide', output:'\u27cc', type:INFIX, infixop:true, arith:true, infixswap:1},
{input:'.*', ptag:'mo', ctag:'scalarproduct', output:'\u22C5', type:CONST, arith:true},
{input:'~*', ptag:'mo', ctag:'vectorproduct', output:'\u00D7', type:CONST, arith:true},
{input:'@*', ptag:'mo', ctag:'outerproduct', output:'\u2297', type:CONST, arith:true},
{input:'@', ptag:'mi', ctag:'compose' , output:'\u26AC', type:CONST, arith:true},
{input:'_', ptag:'msub', output:'_', type:INFIX},
{input:'^', ptag:'msup', output:'^', type:INFIX},
{input:'!', ptag:'mo', ctag:'factorial', output:'!', type:CONST, issuffixop:true},
{input:'\u00B1', vinput:'+/-', ctag:'plusminus', ptag:'mo', output:'\u00B1', type:CONST, arith:true, pri:true},
{input:'%', ctag:'rem', ptag:'mo', output:'mod', type:INFIX, infixop:true},
{input:'\uff0f', vinput:'\\_', ctag:'ci', ptag:'mo', output:'\u2220', type:INFIX, infixop:true, ctype:'complex-polar'},
{input:'imgi', ctag:'imaginaryi', ptag:'mi', output:'\u2170', type:CONST, sym:true},
{input:'Real', ctag:'real', ptag:'mo', output:'\u211b', type:UNARY, paren:true},
{input:'Imag', ctag:'imaginary', ptag:'mo', output:'\u2111', type:UNARY, paren:true},
{input:'Argu', ctag:'arg', ptag:'mo', output:'Arg', type:UNARY, paren:true},
{input:'Conj', ctag:'conjugate', ptag:'mover', output:'\u00AF', type:UNARY, acc:true, functional:true},
{input:'bar', ptag:'mover', ctag:'conjugate', output:'\u00AF', type:CONST, acc:true, functional:true},
{input:'=', ptag:'mo', ctag:'eq', output:'=', type:CONST, eq:true},
{input:'==', ptag:'mo', ctag:'equivalent', output:'\u2261', type:CONST, eq:true},
{input:'~=', ptag:'mo', ctag:'equivalent', output:'\u2245', type:CONST, eq:true},
{input:'~~', ptag:'mo', ctag:'approx', output:'\u2248', type:CONST, eq:true},
{input:'=~', ptag:'mo', ctag:'factorof', output:'\u221D', type:CONST, eq:true}, //not entirely accurate
{input:'!=', ptag:'mo', ctag:'neq', output:'\u2260', type:CONST, eq:true},
{input:':=', ptag:'mo', ctag:'eq', output:':=', type:CONST, eq:true},
{input:'<', ptag:'mo', ctag:'lt', output:'<', type:CONST, eq:true},
{input:'>', ptag:'mo', ctag:'gt', output:'>', type:CONST, eq:true},
{input:'<=', ptag:'mo', ctag:'leq', output:'\u2264', type:CONST, eq:true},
{input:'>=', ptag:'mo', ctag:'geq', output:'\u2265', type:CONST, eq:true},
{input:'->', ptag:'mo', ctag:'tendsto', output:'\u2192', type:CONST, rel:true},
{input:'=>', ptag:'mo', ctag:'implies', output:'\u21D2', type:CONST, rel:true},
{input:'if:', ptag:'mo', output:'if', ctag:'if', type:CONST, fi:true }, ///////////
{input:'\u01c0', vinput:'|', ptag:'mo', ctag:'condition' , output:'|', type:CONST, cond:true,arith:true,ipop:true},
{input:'...', ptag:'mo', output:'...', type:SHAPE},
{input:':.', ptag:'mo', output:'\u2234', type:SHAPE},
{input:'&&', ptag:'mo', ctag:'and', output:'\u2227', type:CONST, logic:true, pri:true},
{input:'\u2228', vinput:'||', ptag:'mo', ctag:'or', output:'\u2228', type:CONST, logic:true, pri:true},
{input:'`', ptag:'mo', ctag:'not', output:'\'', type:CONST, issuffixop:true},
{input:'true', ctag:'true', ptag:'mi', output:'true', type:CONST, sym:true},
{input:'false', ctag:'false', ptag:'mi', output:'false', type:CONST, sym:true},
{input:':n:', ptag:'mo', ctag:'intersect', output:'\u2229', type:CONST, setop:true, pri:true},
{input:':u:', ptag:'mo', ctag:'union', output:'\u222A', type:CONST, setop:true, pri:true},
{input:':in:', ptag:'mo', ctag:'in', output:'\u2208', type:CONST, setop:true},
{input:'!in:', ptag:'mo', ctag:'notin', output:'\u2209', type:CONST, setop:true},
{input:':c:', ptag:'mo', ctag:'prsubset', output:'\u2282', type:CONST, setop:true},
{input:'!c:', ptag:'mo', ctag:'notprsubset', output:'\u2282', type:CONST, setop:true},
{input:':c::', ptag:'mo', ctag:'subset', output:'\u2286', type:CONST, setop:true},
{input:'!c::', ptag:'mo', ctag:'notsubset', output:'\u2288', type:CONST, setop:true},
{input:'\uff3c', vinput:':\\:', ptag:'mo', ctag:'setdiff', output:'\\', type:CONST, setop:true, ipop:true},
{input:':*:', ptag:'mo', ctag:'cartesianproduct', output:'\u00D7', type:CONST, setop:true, ipop:true},
{input:'O/', ctag:'emptyset', ptag:'mi', output:'\u2205', type:CONST, sym:true},
{input:'#_', ptag:'mo', ctag:'floor', output:'\u230A', append:'\u230B', type:CONST, isprefixop:true},
{input:'#^', ptag:'mo', ctag:'ceiling', output:'\u2308', append:'\u2309', type:CONST, isprefixop:true},
{input:'gcd', ptag:'mo', ctag:'gcd', output:'gcd', type:UNARY, sov:true, paren:true},
{input:'lcm', ptag:'mo', ctag:'lcm', output:'lcm', type:UNARY, sov:true, paren:true},
{input:'mean', ptag:'mo', ctag:'mean', output:'mean', type:UNARY, sov:true, paren:true},
{input:'mode', ptag:'mo', ctag:'mode', output:'glb', type:UNARY, sov:true, paren:true},
{input:'min', ptag:'mo', ctag:'min', output:'min', type:UNARY,sov:true, paren:true},
{input:'max', ptag:'mo', ctag:'max', output:'max', type:UNARY, sov:true, paren:true},
//grouping brackets
{input:'&#x200b;', ptag:'mo', output:'\u200B', type:SPACE, invisible:true},
{input:',', ptag:'mo', output:',', type:CONST, sep:true},
{input:'(', ptag:'mo', output:'(', type:LEFTBRACKET},
{input:')', ptag:'mo', output:')', type:RIGHTBRACKET},
{input:'[', ptag:'mo', output:'[', type:LEFTBRACKET},
{input:']', ptag:'mo', output:']', type:RIGHTBRACKET},
{input:'{', ptag:'mo', output:'{', type:LEFTBRACKET},
{input:'}', ptag:'mo', output:'}', type:RIGHTBRACKET},
{input:'|', ptag:'mo', output:'|', type:LEFTRIGHT},
{input:'\\', ptag:'mo', output:'(', type:LEFTBRACKET},
{input:'\u2774', vinput:'(:', ptag:'mo', output:'\u2774', type:LEFTBRACKET},
{input:'\u2775', vinput:':)', ptag:'mo', output:'\u2775', type:RIGHTBRACKET},
{input:'\'', ptag:'mo', ctag:'diff', output:'\'', type:CONST, issuffixop:true},
{input:'int', ctag:'int', ptag:'mo', output:'\u222B', type:UNARY, integral:true},
{input:'d', ctag:'diff', ptag:'mo', output:'d', iscalcop:true, type:DIFFERENTIAL, carry:true},
{input:'dd', ctag:'partialdiff', ptag:'mo', output:'\u2202', iscalcop:true, type:DIFFERENTIAL, carry:true},
{input:'oint', ctag:'int', ptag:'mo', output:'\u222E', type:UNARY, integral:true},
{input:'oo', ctag:'infinity', ptag:'mi', output:'\u221E', type:CONST, sym:true},
{input:'NaN', ctag:'notanumber', ptag:'mi', output:'NaN', type:CONST, sym:true},
{input:'CC', ctag:'complexes', ptag:'mi', output:'\u2102', type:CONST, sym:true},
{input:'NN', ctag:'naturalnumbers', ptag:'mi', output:'\u2115', type:CONST, sym:true},
{input:'QQ', ctag:'rationals', ptag:'mi', output:'\u211A', type:CONST, sym:true},
{input:'RR', ctag:'reals', ptag:'mi', output:'\u211D', type:CONST, sym:true},
{input:'ZZ', ctag:'integers', ptag:'mi', output:'\u2124', type:CONST, sym:true},
{input:'F', ptag:'mi', output:'F', type:VAR, functional:true, ctype:'function',paren:true},
{input:'f', ptag:'mi', output:'f', type:VAR, functional:true, ctype:'function',paren:true},
{input:'g', ptag:'mi', output:'g', type:VAR, functional:true, ctype:'function',paren:true},
{input:'\uff45', ctag:'exp', ptag:'mi', output:'\uff45', type:CONST, eop:true},
{input:'exp', ctag:'exp', ptag:'mi', output:'\uff45', type:VAR, functional:UNARY, paren:true},
{input:'lim', ctag:'limit', ptag:'mo', output:'lim', type:UNDEROVER},
{input:'Lim', ctag:'limit', ptag:'mo', output:'Lim', type:UNDEROVER},
{input:'sin', ctag:'sin', ptag:'mo', output:'sin', type:UNARY, paren:true},
{input:'cos', ctag:'cos', ptag:'mo', output:'cos', type:UNARY, paren:true},
{input:'tan', ctag:'tan', ptag:'mo', output:'tan', type:UNARY, paren:true},
{input:'sinh', ctag:'sinh', ptag:'mo', output:'sinh', type:UNARY, paren:true},
{input:'cosh', ctag:'cosh', ptag:'mo', output:'cosh', type:UNARY, paren:true},
{input:'tanh', ctag:'tanh', ptag:'mo', output:'tanh', type:UNARY, paren:true},
{input:'cot', ctag:'cot', ptag:'mo', output:'cot', type:UNARY, paren:true},
{input:'sec', ctag:'sec', ptag:'mo', output:'sec', type:UNARY, paren:true},
{input:'csc', ctag:'csc', ptag:'mo', output:'csc', type:UNARY, paren:true},
{input:'arcsin', ctag:'arcsin', ptag:'mo', output:'arcsin', type:UNARY, paren:true},
{input:'arccos', ctag:'arccos', ptag:'mo', output:'arccos', type:UNARY, paren:true},
{input:'arctan', ctag:'arctan', ptag:'mo', output:'arctan', type:UNARY, paren:true},
{input:'arccot', ctag:'arccot', ptag:'mo', output:'arccot', type:UNARY, paren:true},
{input:'arcsec', ctag:'arcsec', ptag:'mo', output:'arcsec', type:UNARY, paren:true},
{input:'arccsc', ctag:'arccsc', ptag:'mo', output:'arccsc', type:UNARY, paren:true},
{input:'arcsinh', ctag:'arcsinh', ptag:'mo', output:'arcsinh', type:UNARY, paren:true},
{input:'arccosh', ctag:'arccosh', ptag:'mo', output:'arccosh', type:UNARY, paren:true},
{input:'arctanh', ctag:'arctanh', ptag:'mo', output:'arctanh', type:UNARY, paren:true},
{input:'arccoth', ctag:'arccoth', ptag:'mo', output:'arccoth', type:UNARY, paren:true},
{input:'arcsech', ctag:'arcsech', ptag:'mo', output:'arcsech', type:UNARY, paren:true},
{input:'arccsch', ctag:'arccsch', ptag:'mo', output:'arccsch', type:UNARY, paren:true},
{input:'log', ctag:'log', barge:['_logbase',10], ptag:'mo', output:'log', type:UNARY, paren:true},
{input:'ln', ctag:'ln', ptag:'mo', output:'ln', type:UNARY, paren:true},
{input:'det', ctag:'determinant', ptag:'mo', output:'det', type:UNARY},
//shapes
{input:'---', ptag:'mi', output: '\u203e\u203e\u203e', type:SHAPE, shape:'line'},
{input:'\uff3f', vinput:'__', ptag:'mi', output: '\uff3f', type:SHAPE},
{input:'uparrow', vinput:'^|^', ptag:'mi', output:'\u2191', type:SHAPE},
{input:'downarrow', vinput:'.|.', ptag:'mi', output:'\u2193', type:SHAPE},
{input:'-->', ptag:'mi', output:'\u2192', type:SHAPE},
{input:'<--', ptag:'mi', output:'\u2190', type:SHAPE},
{input:'<->', ptag:'mi', output:'\u2194', type:SHAPE},
{input:'==>', ptag:'mi', output:'\u21D2', type:SHAPE},
{input:'<==', ptag:'mi', output:'\u21D0', type:SHAPE},
{input:'<=>', ptag:'mi', output:'\u21D4', type:SHAPE},
{input:'***', ptag:'mi', output:'\u22C6', type:VAR, sym:true},
{input:'diamond', ptag:'mi', output:'\u22C4', type:VAR, sym:true},
{input:'square', ptag:'mi', output:'\u25A1', type:VAR, sym:true},
{input:'sqrt', ctag:'root', barge:['degree',2], ptag:'msqrt', output:'msqrt', type:UNARY, paren:true},
{input:'root', ptag:'mroot', ctag:'root', barge:['degree',1], output:'mroot', type:BINARY, paren:true},
{input:'stackrel', ptag:'mrow', output:'mrow', type:BINARY},
{input:'hat', ptag:'mover', output:'\u005E', type:VAR, acc:true, ctype:'vector'},
//note: https://www.openmath.org/cd/linalg2.html#vector This symbol represents an n-ary function used to construct (or describe) vectors. Vectors in this CD are considered to be row vectors and must therefore be transposed to be considered as column vectors. vs https://www.w3.org/TR/MathML3/chapter4.html#contm.vector For purposes of interaction with matrices and matrix multiplication, vectors are regarded as equivalent to a matrix consisting of a single column, and the transpose of a vector as a matrix consisting of a single row.... Since the W3C spec references the linalg2 cd, treating them as row vectors herein
{input:'vec', ptag:'mover', output:'\u2192', type:VAR, acc:true, ctype:'vector'},
{input:'dot', ptag:'mover', output:'.', type:VAR, acc:true},
{input:'ddot', ptag:'mover', output:'..', type:VAR, acc:true},
{input:'ul', ptag:'munder', output:'\u0332', type:VAR, acc:true},
{input:'"', ptag:'mtext', output:'mbox', type:TEXT},
{input:'strike:', ptag:'mstyle', attr:{style:'text-decoration:line-through;'}, output:'strike:', type:STYLE},
{input:'large:', ptag:'mstyle', attr:{mathsize:'large', style:'font-size:150%'}, output:'large:', type:STYLE},
{input:'small:', ptag:'mstyle', attr:{mathsize:'small',style:'font-size:75%'}, output:'small:', type:STYLE},
{input:'light:', ptag:'mstyle', attr:{style:'opacity:0.35'}, output:'light:', type:STYLE},
{input:'hide:', ptag:'mstyle', attr:{style:'opacity:0'}, output:'hide:', type:STYLE},
{input:'bold:', ptag:'mstyle', attr:{fontweight:'bold',style:'font-weight:bold'}, output:'bold:', type:STYLE},
{input:'serif:', ptag:'mstyle', attr:{fontfamily:'sans-serif'}, output:'serif:', type:STYLE},
{input:'struck:', ptag:'mstyle', attr:{mathvariant:'double-struck'}, output:'struck:', type:STYLE},
{input:'script:', ptag:'mstyle', attr:{mathvariant:'script'}, output:'script:', type:STYLE},
{input:'mono:', ptag:'mstyle', attr:{fontfamily:'monospace'}, output:'mono:', type:STYLE}
];
mk.getUserAgent = function(){
var isedge, isie;
if(!!userAgent){
return userAgent;
}
isie = /*@cc_on!@*/false || !!mkDoc.documentMode;
if(!(isedge = !isie && !!window.StyleMedia) && !!(userAgent = -1!==navigator.userAgent.indexOf('Chrome') ? 'chrome' : (-1!==navigator.userAgent.indexOf('Safari') ? 'safari' : ''))){
return userAgent;
}
return userAgent = -1!==navigator.userAgent.indexOf('Firefox') ? 'firefox' : ( (-1!==navigator.userAgent.indexOf('MSIE')||!!mkDoc.documentMode) ? 'ie' : (isedge?'edge': ( (-1!==navigator.userAgent.indexOf('Opera') || -1!==navigator.userAgent.indexOf('OPR')) ? 'opera':'other' ) ) );
};
var mk_rand = (window.crypto && window.crypto.getRandomValues) ? function(){
if(0==mkRand.length){
var i=32, a = new Uint32Array(32);
window.crypto.getRandomValues(a);
while(-1<--i){mkRand.push(a[i]);}
}
return mkRand.pop();
} : function(){ return Math.floor(Math.random() * Math.floor(Number.MAX_SAFE_INTEGER>>1)); };
var mk_regSig = function(fn){
mkSig[mkHashSum.hash(fn)] = true;
if(2==mkDebug){
console.log(mkHashSum.hash(fn));
}
return fn;
};
var mk_idFromUrl = function(s=''){
var i = 0;
return -1!=(i = s.indexOf('#')) ? s.substring(i).replace(/^[\s#]+/ug,'').trim() : '';
};
var mk_isFromMathKey = function(url=null){
var v = 0;
return -1==(v=(url = url||location.href).lastIndexOf('?mathKeyCom'+Date.now().toString().slice(0,6))) ? false : url.substring(0, v);
};
var mk_mathKeyUrl = function(url,id=''){
var i = -1;
if(!!id){
id='#'+id
}
if(-1!=url.indexOf('?mathKeyCom')){
url=url.replace(/\?mathKeyCom=/ug,'?&mathKeyCom=').replace(/\?mathKeyCom/ug, '%3FmathKeyCom');
}
return (-1!=(i=url.indexOf('#')) ?
(url.substring(0,i)+'?mathKeyCom'+Date.now()+'mathKey='+url.substring(i).replace(/#+/g,'')):(url+'?mathKeyCom'+Date.now()))+id;
};
if(2==mkDebug){
console.log(document.location.href);
}
(function(){
if(false!==(mkUrl = mk_isFromMathKey())){
if(2==mkDebug){
console.log('c:'+mkUrl);
}
mkFromMathKey = mk_idFromUrl(document.location.href)||'#';
var fn=null, id = mkFromMathKey, to=mkTo.pmInteractive[0], tm = mkTo.pmInteractive[1], src = null;
(fn = function(){
if(0>--to || '|complete|interactive|'.indexOf(document.readyState)){
window.addEventListener('message', function(e){
if(!!src && src!==e.source){
console.log('source mismatch');
return;
}
var data = null, er = false, msg = null;
try{
data = JSON.parse(e.data);
msg = !!data.msg ? JSON.stringify(data.msg) : '';
}catch(err){
console.log(err);
er = true;
}
if(!er && !!data.msg.fn){
try{
data.msg.fn = (new Function('return '+data.msg.fn+';'))();
}catch(err){
console.log(err);
er = true;
}
}
if(!!er || !id || id!==data.to || !data.sig || !data.msg || !data.msg.sig || !data.msg.fn || !msg || !mkSig[mkHashSum.hash(data.msg.fn)] || data.sig!==mkHashSum.hash(e.origin+"\n"+id+"\n"+msg)){
console.log('pm '+id+' could not decode msg');
window.parent.postMessage({from:id, status:'error'},'*');
return false;
}
if(!src){
src = e.source;
}
data.msg.fn({args: (!!data.msg.args?data.msg.args:{}), doc:document, id:id, cb: function(res){if(!!res && !!res.status){res.from=id; src.postMessage(res,'*');}else{console.log('pm '+id+' invalid return');console.log(res);} window.stop();}, path:'pm', res: ''});
}, false);
window.parent.postMessage({from:id, status:'loaded'},'*');
return;
}
window.setTimeout(fn, tm);
})();
}else{
mkUrl = document.location.href;
if(2==mkDebug){
console.log('p:'+mkUrl);
}
window.addEventListener('message', function(e){
var f = null;
if(!e.data || !e.source || !e.data.from || !e.data.status || !(f=mkFrames[e.data.from]) || !!f.error.pm || (!!f.src && f.src !== e.source)){
return f.onerror('pm', 'child returned invalid data');
}
if(!f.src){
f.src = e.source;
}
f.active.pm=0;
if('error'===e.data.status){
return f.onerror('pm');
}
f.oncancel('pm');
if('loaded'===e.data.status){
f.onloaded('pm');
}else if('completed'===e.data.status){
f.oncompleted('pm', e.data);
}
});
}
})();
var mk_trimUrl = function(url=''){
return url.replace(/(?:\s+[0-9]+\.?[0-9]*\s*[whx])+\s*$/uig,' ').trim();
};
var mk_isValidUrl = function(url=''){
var er = false, pre = '', i=0;
url = mk_trimUrl(url);
if('about:blank'===url){
return {};
}
//todo:
if(!url || (-1==url.indexOf('/') && -1==url.indexOf('.') && -1==url.indexOf('#'))){
return false;
}
if(!url.match(/^[a-zA-Z0-9]+\:/)){
++i;
pre+=location.protocol;
}
if(!((pre+url).match(/^[a-zA-Z0-9]+\:\/\//))){
++i;
pre+='//';
}
if(!((pre+url).match(/^[a-zA-Z0-9]+\:\/\/(?:[a-zA-Z0-9][a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]+(?:\:[0-9]+)?(?:\?|\/|$)/))){
++i;
pre+=document.location.host;
if(0!=url.indexOf('/')){
pre+='/';
}
}
try {
er = new URL(pre+url);
} catch(err) {
console.log(err);
}
//todo: multilingual, only perform this check if the input url is substantially ascii
if(!!er){
if(0.5>(1-(0<i ? __levenshtein(url=pre+url,er.href) : __levenshtein(url,er.href))/url.length)){
return false;
}
}
return er;
};
var mk_frame = function(url, fn=null, ld=null, cb=null, ka=false){
var args = {}, k ='';
if('object' == typeof fn){
if(!!fn.args){
args = fn.args;
}
fn = !!fn.fn ? fn.fn : null;
}
if(!!fn && ('function' != typeof fn || !mkSig[k=mkHashSum.hash(fn)])){
console.log('could not frame '+url);
return false;
}
var id = mkHashSum.hash(Date.now()+mk_rand()), data=null;
if(!(data=mk_isValidUrl(url)) || !!mkFrameUrl[url]){
return false;
}
mkFrameUrl[url] = id;
var f, doc = (!!mkDoc&&!!mkDoc.body) ? mkDoc : document;
data = data.pathname;
mkFrames[id] = {
active: {},
cancelfrom: 'xhr',
cp:false,
cb: cb,
completed:false,
doc: doc,
data: null,
error:{},
file:data,
fn: fn,
id: id,
if:doc.createElement('iframe'),
ka:ka,
ld:ld,
loaded:false,
started:false,
fto:mkTo.fDoc[1],
res:'',
src:null,
url:[url]
};
f = mkFrames[id];
f.data = { to: id, msg: {sig: k, args: args, fn: !!fn ? fn.toString():null} }
f.data.sig = mkHashSum.hash(window.location.origin+"\n"+id+"\n"+JSON.stringify(f.data.msg));
if(2==mkDebug){
f.log = function(msg=''){
console.log((!!mkFromMathKey?'*':'')+'['+f.id+'] '+msg+' @'+Math.round(parseFloat((Date.now()-f.started)/1000),1)+'s');
};
}
f.if.style = 'display:none;';
f.oncompleted = function(path='',d=null){
if(2==mkDebug){
f.log('oncompleted '+path+': '+f.url[0]);
}
if('xhr'!=path){
var w = '';
if(!!(w=(f.if.contentDocument || f.if.contentWindow.document)) && !!(w.contentWindow)){
w.contentWindow.stop();
}
}
if(!f.oncancel(path)){
return;
}
if(!!f.completed){
console.log('already completed');
return;
}
if(!!d && !!d.msg && undefined!==d.msg.keepalive){
f.ka = !!d.msg.keepalive;
}
if(!!f.cb){
f.cb(d);
}
f.completed = Date.now();
if(!f.ka){
f.doc.body.removeChild(f.if);
delete mkFrameUrl[f.url.pop()];
delete mkFrames[f.id];
}
};
f.onloaded = function(path=''){
if(2==mkDebug){
f.log('onloaded '+path+': '+f.url[0]);
}
if(!f.oncancel(path)){
return;
}
for(var i in f.active){
window.clearTimeout(f.active[path]);
delete f.active[path];
}
if(!!f.ld && !f.loaded){
f.ld();
}
f.loaded = Date.now();
if('pm'==path){
if(!!f.src){
f.src.postMessage(JSON.stringify(f.data),'*');
}else{
console.log('no src for '+id);
}
}else if(!!f.fn){
fn({args:f.data.msg.args, cb:function(d){ f.oncompleted(path, d); }, doc: (f.if.contentDocument || !!f.if.contentWindow?f.if.contentWindow.document:null), id:id, path:path, res:f.res});
}
};
f.onerror = function(path='',msg=''){
f.error[path] = true;
if(undefined!==f.active[path]){
window.clearTimeout(f.active[path]);
delete f.active[path];
}
if(2==mkDebug){
f.log('error loading '+path);
}
if(!!msg){
console.log(msg);
}
if(!f.oncancel(path)){
return;
}
f.cancelfrom = 'xhr';
f.retry(path);
};
f.oncancel = function(path=''){
if(2==mkDebug){
f.log('cancel from '+path+' [current:'+f.cancelfrom+']');
}
if(undefined!==f.active[path]){
window.clearTimeout(f.active[path]);
delete f.active[path];
}
if('pm'==path){
return !f.error[path] ? f.cancelfrom = path : false;
}
if('pm'==f.cancelfrom){
return !f.error[path]&&path==f.cancelfrom;
}
if('frame'==path){
return !f.error[path] ? f.cancelfrom = path : false;
}
if('frame'==f.cancelfrom){
return !f.error[path]&&path==f.cancelfrom;
}
return !f.error[path]&&path==f.cancelfrom;
};
f.retry = function(path=''){
if(2==mkDebug){
f.log('retry from: '+path);
}
if(undefined!==f.active.xhr || !!f.res){
window.clearTimeout(f.active.xhr);
delete f.active.xhr;
if(!f.error.xhr){
if(2==mkDebug){
f.log('setup long xhr read');
}
f.active.xhr = window.setTimeout(function(){f.onloaded('xhr');},mkTo.wfpmInteractive[0]);
}
}
if(!f.error.frame){
if(2==mkDebug){
f.log('retrying frame');
}
if(undefined!==f.active.frame){
window.clearTimeout(f.active.frame);
delete f.active.frame;
}
var m = null;
if(!!(m=f.file.match(/\.((?:png)|(?:jpe?g)|(?:gif)|(?:svg)|(?:bmp)|(?:tiff))$/i))){
var img = new Image();
img.style='display:none;';
img.contentType='image/'+m[1].toLowerCase();
//TODO:
//img.crossOrigin = 'anonymous';
img.onload = function(){
if(undefined!==f.active.frame){
window.clearTimeout(f.active.frame);
delete f.active.frame;
}
f.res = this;
f.onloaded(f.cancelfrom='img');
};
img.src = f.url[f.url.length-1];
return;
}
f.fto = mkTo.fDoc[1]*4;
f.load();
}else if(!f.error.xhr&&!f.res){
if(2==mkDebug){
f.log('retrying xhr');
}
f.fto = -1;
f.load();
}
};
f.load = function(){
if(!f.started){
f.started = Date.now();
f.if.src = 'about:blank';
f.doc.body.appendChild(f.if);
(f.if.src = mk_mathKeyUrl(f.url[0], f.id)), (f.url.unshift(f.if.src));
if(undefined!==f.active.frame){
window.clearTimeout(f.active.frame);
}
return f.active.iframe=window.setTimeout(function(){f.load();},mkTo.fStart[0]);
}
//TODO: dns prefetch, parallel xhr/iframe responsive to errors in former, recursive requests via `grep -n mkFromMathKey | tail -n 1`
var d = null;
if(!!f && !!f.if && !!(d=(f.if.contentDocument || !!f.if.contentWindow?f.if.contentWindow.document:null)) && 'about:blank'!=d.location.href){
if(2==mkDebug){
f.log('frame contentDocument');
}
if(undefined!==f.active.frame){
window.clearTimeout(f.active.frame);
}
f.active.iframe = 0;
if(!d.location || !d.documentElement){
return f.onerror('frame');
}else if(!f.oncancel('frame')){
return;
}
if(2==mkDebug){
f.log('frame contentElement');
}
if(d.location.href.replace(/[#?].*$/g,'')!==f.url[0].replace(/[#?].*$/g,'')){
f.url.unshift(d.location.href);
}
f.onloaded('frame');
}else if(!!f && -1<--f.fto){
if(mkTo.fDoc[1]==f.fto){
return f.onerror('frame');
}
if(2==mkDebug){
if((mkTo.fDoc[1]-1)==f.fto){
f.log('frame sequence');
}
}
if(undefined!==f.active.frame){
window.clearTimeout(f.active.frame);
}
f.active.iframe=window.setTimeout(f.load(), mkTo.fDoc[0]);
}else{
if(2==mkDebug){
f.log('xhr request');
}
if(undefined!==f.active.xhr){
f.active.xhr = 0;
}
if(!f || !f.oncancel('xhr')){
return;
}
d = new XMLHttpRequest();
d.open('GET', f.url[0], true);
d.responseType = 'text';
d.onerror = function(e) {
f.onerror('xhr');
f.retry('xhr');
};
d.onload = function(e) {
if(2==mkDebug){
f.log('xhr loaded');
}
if(!f||!f.oncancel('xhr')||!!f.res){
return;
}
if(!e || !e.target){
if(!!f){
f.onerror('xhr','target undefined');
f.retry('xhr');
}
return;
}
var res = e.target.response || '';
if(!res || !!res.replace(/[\r\n]/ugm,' ').match(/src\s*=\s*['"][^'"]*mathKey.js/u) || (!!(d=(f.if.contentDocument || f.if.contentWindow?f.if.contentWindow.document:null)) && !!d.documentElement && !(f.error['frame']=false))){
if(2==mkDebug){
f.log('xhr response may be for pm');
}
f.res = res;
f.active.xhr=0;
f.retry('xhr');
return;
}
if(2==mkDebug){
f.log('xhr response');
}
f.res = res;
f.onloaded('xhr');
};
d.send();
}
};
f.load();
return true;
};
mk.reInit = function(){
mkRnames = {};
mkNames = {};
mkRLength = 0;
mkSymbols = mkSymbols.filter(function(v){ return v !== null; });
mkSymbols.filter(function(v,i){
var j = -1, k = -1;
k = v.input.length;
if(mkRLength<k){
mkRLength = k;
}
while(k>++j){
mkRnames[v.input.slice(-j)] = true;
}
mkNames[v.input] = i;
return false;
});
};
var mk_fallbackCss = function(){
if(!!conf.fallbackcssurl && !mkFromMathKey){
mk_frame(conf.fallbackcssurl, {args:{fallbackurl: conf.fallbackcssurl}, fn: mk_regSig(function(com){
var css = (!!com.doc && !!com.doc.body)? com.doc.body.innerText : (!!com.res? com.res : '');
com.cb({status:'completed',msg:{cssText:css}});
})}, function(){mkSync.mathKeyTranslate=true;}, function(data){if(!!data && !!data.msg &&!!data.msg.cssText && (!mkHasMathML || 1===mkHasMathML)){mkFallbackCSS=data.msg.cssText;} mkSync.mathKeyTranslate=false;});
}
};
mk_fallbackCss();
var mk_checkMathML = function(mj=false, mp=false){
mkHasMathML = false;
if ('firefox'==userAgent || 'safari'==userAgent){
mkHasMathML = true;
mkFallbackCSS='';
}else if ('opera'==userAgent && 9.5<=parseFloat(navigator.appVersion.slice(0,1))){
mkHasMathML = true;
mkFallbackCSS='';
}else if ('other'==userAgent && 'Netscape'==navigator.appName.slice(0,8) && 5<=parseFloat(navigator.appVersion.slice(0,1))){
mkHasMathML = true;
mkFallbackCSS='';
}
if (!mkHasMathML && !!mkDoc.createElementNS) {
var d = null, div = mkDoc.createElement('div'), mfrac = null;
div.style.position = 'absolute';
div.style.top = 0;
div.style.left = 0;
div.style.opacity = '0';
div.style.width = 'auto';
div.style.height = 'auto';
div.style.fontFamily = 'serif';
div.style.lineheight = 'normal';
div.appendChild(
mfrac = mkDoc.createElementNS(mkMathns,'math')
);
mfrac.appendChild(mkDoc.createElementNS(mkMathns,'mfrac'));
mfrac = mfrac.children[0];
mfrac.appendChild(
d = mkDoc.createElementNS(mkMathns,'mi')
);
d.appendChild(mkDoc.createTextNode('xx'));
mfrac.appendChild(
d = mkDoc.createElementNS(mkMathns,'mi')
);
d.appendChild(mkDoc.createTextNode('yy'));
mkDoc.body.appendChild(div);
mkHasMathML = div.offsetHeight > div.offsetWidth;
mkDoc.body.removeChild(div);
}
if (!mkHasMathML && !mp && 'ie'==userAgent){
if(!mj && !mkDoc.getElementById('mathplayer')){
var head = mkDoc.getElementsByTagName('head')[0], object = mkDoc.createElement('object'); //script = mkDoc.createElement('script');
object.id = 'mkmathplayer';
object.onload = function(){mk_checkMathML(true);};
object.classid = 'clsid:32F66A20-7614-11D4-BD11-00104BD3F987';
head.innerHTML+='<?import namespace="m" implementation="#mathplayer"?>';
//mkDoc.namespaces.add("m","http://www.w3.org/1998/Math/MathML");
// mkDoc.namespaces.m.doImport("#mathplayer");
head.appendChild(object);
return;
}else if (!!mkDoc.getElementById('mkmathplayer')){
var ActiveX = null;
try {
ActiveX = new ActiveXObject('MathPlayer.Factory.1');
mkHasMathML = true;
mkFallbackCSS='';
} catch (e) {
mkHasMathML = false;
mj = false;
}
}
}
if(!mkHasMathML && !mp && !conf.fallbackliburl && !!conf.fallbackcssurl){
var head = mkDoc.getElementsByTagName('head')[0],
link = mkDoc.createElement('link');
link.setAttribute('rel','stylesheet');
link.setAttribute('type','text/css');
head.appendChild(link);
link.href = conf.fallbackcssurl;
mkHasMathML = 1;
mkFallback = conf.fallbackcssurl.replace(/^.*\//g,'');
}
if (!!mj && !mkHasMathML && !!conf.fallbackliburl){
if(conf.fallbackliburl.match(/MathJax[^\/]*(?:\/|(?:\.js))/i) && undefined!=window['MathJax'] && !!window['MathJax'].Hub) {
mkHasMathML = 2;
mkFallbackCSS='';
}else if(conf.fallbackliburl.match(/(?:(?:wiris)|(?:quizzes))[^\/]*(?:\/|(?:\.js))/i) && !!window['com'] && !!window['com'].wiris){
mkHasMathML = 3;
mkFallbackCSS='';
}
}
if(!mj && !mkHasMathML){
var head = mkDoc.getElementsByTagName('head')[0];
if(conf.fallbackliburl.match(/MathJax[^\/]*(?:\/|(?:\.js))/i)){
var scripts = [ mkDoc.createElement('script'), mkDoc.createElement('script')],
xconfig = 'MathJax.Hub.Config({' +
'mml2jax: {preview: "mathml"},' +
'extensions: ["mml2jax.js"],' +
'jax: ["input/MathML","output/HTML-CSS"]' +
'});';
scripts[0].type = 'text/x-mathjax-config';
(userAgent !== 'opera') ? scripts[0].text = xconfig : scripts[0].innerHTML = xconfig;
head.appendChild(scripts[0]);
mkFallback = 'MathJax';
scripts[1].async = true;
scripts[1].type = 'text/javascript';
scripts[1].onload = function(){
var fn = function(){
(!window['MathJax']||!window['MathJax'].isReady)? window.setTimeout(fn,500):mk_checkMathML(true, userAgent==='ie');
};
fn();
};
scripts[1].src = conf.fallbackliburl+'?config=MML_HTMLorMML';
head.appendChild(scripts[1]);
return;
}else if(conf.fallbackliburl.match(/(?:(?:wiris)|(?:quizzes))[^\/]*(?:\/|(?:\.js))/i)){
var script = mkDoc.createElement('script');
script.type = 'text/javascript';
script.onload = function(){
var fn = function(){
(!window['com']||!window['com'].wiris)? window.setTimeout(fn,500):mk_checkMathML(true, userAgent==='ie');
};
fn();
};
mkFallback = 'WIRIS';
script.src = conf.fallbackliburl;
head.appendChild(script);
return;
}
}
if (!mkHasMathML) {
mkFallback = 'none';
if(!!conf.notifyifnomathml){
mk_warn('ASCIIMathML is unavailable. Please upgrade your browser.');
}
return false;
}
if(!!mj && !!conf.translateonstart){
mk_translateOnStart();
}
return (mkReady = true);
};
var mk_fallback = function(o=null,r=false){
var fn = (!!o&&!!r) ? function(){ var c,i,v=o.getElementsByTagName('mo');for(i in v){ if('*'==v[i].innerHTML && (!v[i].previousElementSibling || 'mspace'!=mk_nodeName(v[i].previousElementSibling)) && (!v[i].nextElementSibling || ('mspace'!=mk_nodeName(v[i].nextElementSibling)
&& (!(c=v[i].nextElementSibling.textContent.charAt(0).toLowerCase()) || '0'>c || c>'9' )
)) ){v[i].innerHTML='&#x2062;<!-- &InvisibleTimes; -->';} } } : function(){};
if(2===mkHasMathML && !!window['MathJax']){
fn();
window['MathJax'].Hub.Queue(['Typeset',window['MathJax'].Hub,o]);
}else if(3===mkHasMathML){
fn();
var builder, uibuilder, viewer, toFilter, tag, i, m;
builder = window['com'].wiris.quizzes.api.QuizzesBuilder.getInstance();
uibuilder = builder.getQuizzesUIBuilder();
viewer = uibuilder.getMathViewer();
viewer.setZoom(2.0);
toFilter = 'math'==mk_nodeName(o)? [o] : o.getElementsByTagName('math');
m=toFilter.length;
for(i=-1; m>++i;){
//todo: filter on class mathMLPresentation added to presentation nodes
if(!toFilter[i] || !toFilter[i].getAttribute('alttext')){
continue;
}
tag = document.createElement('span');
toFilter[i].insertAdjacentElement('beforebegin',tag);
tag.appendChild(toFilter[i]);
viewer.filter(tag);
}
}else{
window.setTimeout(fn,1000);
}
};
mk.usingFallback = function(){
return mkFallback;
};
mk.translate = function(translateclass=''){
if (mkTranslated<(Date.now()-1000)) {
mkTranslated = Date.now();
var i=-1, j = -1, m = null, obj = null;
if(!translateclass){
translateclass=conf.translateclass;
}
translateclass = translateclass.replace(/^\./g,'');
if(!mkDoc.querySelector('.'+translateclass)){
console.log('Could not find an element of class '+translateclass);
return;
}
mkSync.mathKeyTranslate=true;
obj = mkDoc.body.getElementsByClassName(translateclass);
for(i=-1;obj.length>++i;){
if(!obj[i].firstChild || 'math'==mk_nodeName(obj[i].firstChild)){
continue;
}
if(!!(m = mk.parseR(obj[i].innerHTML))){
if(!obj[i]){
console.log('no object:');
console.log(m);
continue;
}
if(-1<(j = obj[i].childNodes.length-1)){
while(-1<--j){
obj[i].removeChild(obj[i].childNodes[0]);
}
obj[i].replaceChild(m,obj[i].childNodes[0]);
}else{
obj[i].appendChild(m);
}
}
mkExt.cache[0]='';
mkExt.cache[1]='';
}
mkSync.mathKeyTranslate=false;
mkDoc.dispatchEvent(new CustomEvent('mktranslated'));
mk_fallback(mkDoc.body);
}
};
var mk_warn = function(warnings='') {
if(!warnings && 0==errorBuf.length){
return;
}
if(!Array.isArray(warnings)){
warnings = [warnings];
}
if(0==warnings.length){
warnings = errorBuf.map(mk_acopy);
}else if(errorBuf.length>0){
warnings = warnings.concat(errorBuf);
}
errorBuf.splice(0);
if(!!conf.notifywarnings){
(!!conf.notifywarningscallback && !!window[conf.notifywarningscallback])?
window[conf.notifywarningscallback](warnings) : alert(warnings.join('; '));
}
};
var mk_setCurrentSymbol = function(t,s,passive=false){
if(!t.par){
t.cs = s;
}
if(!passive){
t.par = false;
}
};
var mk_spaces = function(str,i,p,cs,ls){
var c = '', n=!!mkTsp[p]?mkTsp[p]:0.5, sp = '', sn='';
while(' '==(c=str.charAt(i)) || '\n'==c){
++i;
}
while(-1<--i && ((' '==(c=str.charAt(i))&&(sp+=c)) || ('\n'==c&&(sn+=c))));
if(!sp&&!!sn){
sp=' ';
}
return [Math.round(sp.length*n),(1>cs?Math.abs(cs):0),Math.round(sn.length*n),1>ls?Math.abs(ls):0];
};
var mk_isNeg = function(str,k){
var i = k, s = '', c='';
if('-'!=str.charAt(i)){
'-'==str.charAt(i-1) ? --i : ++i;
}
if(1>i){
return true;
}
k = i;
while((-1<--i || (k=0)) && (!!s || ((33>(c=str.charCodeAt(i)))&&10!=c&&0<--k) || (s=str.charAt(i))) && (!s || !!mkRnames[str.substring(i, k)] || -1==++i));
return (('A'<=s && s<='Z') || ('a'<=s && s<='z') || ('0'<=s && s<='9') || (i!=k && -1==',{(^_'.indexOf(s) && undefined!=(i=mkNames[str.substring(i, k)]) && !!(s=mkSymbols[i]) && !(INFIX==s.type || LEFTBRACKET==s.type || !!s.arith || !!s.setop || !!s.rel || !!s.eq || !!s.isprefixop) )) ? false : true;
};
var mk_isComma = function(s,str,i,n=0){
if(1>i||','!=s || 3!=n|| '0'>(s=str.charAt(--i)) || s>'9'){
return false;
}
var p = {};
while(-1<--i){
n = s;
s=str.charAt(i);
if(','==s && ('0'>n || n>'9' || (0<i && ('0'>(n=str.charAt(i-1)) || n>'9'))) ){
return false;
}else if(!!mkParen[0][s]){
if(!p[mkParen[0][s]]){
return false;
}
}else if(!!mkParen[1][s]){
!p[s]?p[s]=1:p[s]++;
}
}
return true;
};
var mk_continueSymbol = function(str='', hint=null, r=0){
var a = '', i = 0, sym = '', strl, def=false, mode = true;
if(null!=hint){
hint = hint.toLowerCase();
}else{
str=str.trimRight();
mode = false;
}
strl = str.length;
i = strl-1;
if(4096<r){
console.log('recursion');
return;
}
while((!!mkRnames[str.slice(i,strl)] || -1==++i) && (-1<--i || (i=0)));
sym = str.slice(i,strl);
a = str.charAt(--strl).toLowerCase();
if(!mode){
return '\u200c'==a ? null : (undefined!=mkNames[sym] ? -i : strl);
}
if(undefined==mkNames[sym]){
if(('a'>a||a>'z') && ('0'>a||a>'9')){
return null;
}else if((0<strl && -1!='\/_^'.indexOf(def=str.charAt(strl-1)))||(1<strl && '-'==def && -1!='\/_^'.indexOf(str.charAt(strl-2)))){
return 0;
}else{
def = true;
}
}
if(undefined==(sym=mkNames[sym]) || 1>i){
return (!!(sym = mkSymbols[sym]) && DIFFERENTIAL!=sym.type && !!sym.input&& 2>sym.input.length && (('a'<=a&&a<='z')|| ('0'<=a&&a<='9'))) ? true : (undefined==sym ? true : ((!!sym.sym&&VAR==sym.type) ? 0 : (!!sym.attr? '' : false)));
}
sym = mkSymbols[sym];
a = str.charAt(i-1).toLowerCase();
hint = hint.charAt(0);
if(DIFFERENTIAL==sym.type){
if((-1=='^({[\\/'.indexOf(hint) && ('a'>hint||hint>'z')) || -1!='^_'.indexOf(a) ){
return true;
}
if('a'<=a&&a<='z' || '0'<=a&&a<='9'){
while(-1<--i && !!(hint=(a=str.charAt(i))+hint) && (undefined==mkNames[hint] &&
('d'!=a || (
(-1=='^({[\\/'.indexOf(a=str.charAt(i+1).toLowerCase())&&('a'>a||a>'z'))
||
(0!=i && ('d'!=str.charAt(i-1)||(0!=--i&&(hint=a+hint))) && -1!='^_'.indexOf(str.charAt(i-1)))
))));
if(undefined==mkNames[hint] && 'd'!=a && -1==str.indexOf('int') ){
return true;
}
}
return false;
}
if(2>sym.input.length && 'a'<=sym.input.toLowerCase()<='z' && (('a'<=hint&&hint<='z')|| ('0'<=hint&&hint<='9')|| ('0'<=a&&a<='9') )){
if(!r){
return true;
}
def = true;
}
if(!!sym.attr){
return '';
}else if(!!sym.sym&&VAR==sym.type){
return 0;
}
if(!!r && (!!sym.arith || !!sym.sep || !!sym.eq || INFIX<= sym.type && sym.type<=SHAPE || !!sym.rel || !!sym.logic || !!sym.setop || !!sym.issuffixop || !!sym.isprefixop || -1!=sym.input.indexOf('\\')
)){
return 1===r ? false : undefined;
}
if(undefined==(a = mk_continueSymbol(str.slice(0,i),sym.input,++r)) && !sym.acc){
return def;
}
return true===a || (!!sym.acc?null:false);
};
var mk_cloneSymbol = function(sym={},s={}) {
if(undefined!=sym.charAt||undefined!=sym.toPrecision||true===sym||false===sym){
return sym;
}
for(var i in sym){
s[i] = (!sym[i] || undefined!=sym[i].charAt||undefined!=sym[i].toPrecision||true===sym[i]||false===sym[i])?sym[i]:mk_cloneSymbol(sym[i],!!sym[i].length?[]:{});
}
return s;
};
mkBak = mkSymbols.map(function(v,i){mkBakNames[v.input]=i; return mk_cloneSymbol(v);});
var mk_findStackOrigin = function(str=''){
var i, k=str.length, c =0, s='', r=-1;
i = k;
while(-1<--i && (!!s || ((33>(c=str.charCodeAt(i))||10==c)&&-1<--k) || !!(s=1)) && (!s || !!mkRorigin[str.slice(i,k)]));
r = (!!mkOrigin[str.slice(++i,k)]) ? i : -1;
if(-1<r){
if(!!mk_continueSymbol(str.slice(0,r), str.charAt(r),1)){
return -1;
}
i = k = r-1;
s = '';
while(-1<--i && (!!s || ((33>(c=str.charCodeAt(i))||10==c||'"'==c||'('==c)&&-1<--k) || !!(s=1)) && (!s || -1!='stackrel'.indexOf(str.slice(i,k)) ));
if('stackrel'==str.slice(++i,k)){
r = -1;
}
}
return r;
};
//return maximal final substring of str that appears in names
var mk_rgetSymbol = function(str,spa=[0,0,0,0],literal=false,t=null) {
var f=false,i=0, j=true, k=0, ptag='',b=null,c='', s='', strl = str.length, sl=spa[2], sp = spa[0], bb=[];
if(!t){
t = mk_t();
}
i = strl-1;
while(( ((' '==(s=str.charAt(i))&&(undefined!=--sp)) || ('\n'==s&&(undefined!=--sl))) || 33>s.charCodeAt(0) || '\u200b'==s) && -1<--i);
if(0>(strl=i) || ''===literal || '\u200c'==str || '\u200b'==str){
t.par = false;
return {symbol: mk_cloneSymbol(mkSymbolNone), pos:i, text:''};
}
++strl;
if(!t.par){
t.ps = t.cs;
}
if(!literal && -1!=(j=mk_findStackOrigin(str))){
s = str.slice(j,strl);
if(!!(b = mk_rgetSymbol(str.slice(0, j), sp)) && !!b.symbol.acc){
mk_setCurrentSymbol(t,b.symbol.type, true);
return {symbol: mk_cloneSymbol(b.symbol,{multi:true}), pos:b.pos, text:[{input:s, ptag:'mi', ctag:'ci', text:s}], sp:b.sp, origin:s};
}
return {symbol: {input:s, ptag:'mi', ctag:'ci', output:s, type:VAR, mys:true}, pos:j, text:s, sp:mk_spaces(str,j,ptag,sp,sl), origin:s};
}
j = true;
if( (null===(i = mk_continueSymbol(str)) || !!literal) ? (f=true) : (0<i || undefined==(k=mkNames[str.slice(i=-i,strl)]) || !(k = mkSymbols[k])|| (VAR==k.type && !!k.sym && 0!==literal) || (0!==literal && 0<(j=t.o.length-1) && RIGHTBRACKET==t.o[j].symbol.type && 2>k.input.length && 'a'<=k.input && 'z'>=k.input && (literal=true) ) ) ){
if(0===literal){
t.par = false;
return {symbol: mk_cloneSymbol(mkSymbolNone), pos:i, text:''};
}
if(null==i){--strl};
s = str.charAt(--strl);
mk_setCurrentSymbol(t,VAR, true);
t.par = t.par? false : true;
b = {};
i=strl;
if(!!k&&!literal){
++i;
ptag=k.ptag;
s = k.output;
bb[0] = mk_cloneSymbol(k);
bb[0].text='';
}else {
if('0'<=s && s<='9'){
ptag = 'mn';
j=true;
while(-1<--i && (s = str.charAt(i)) && ((('0'<=s && s<='9' && ++c)||(mk_isComma(s,str,i,c)?!(c=j=0):(c=0))) ? j||true : ((j && '.'==s && 0<i && '0'<=(s=str.charAt(i-1))&& s<='9') ? !(j=c) : false)));
j = false;
if('-'==s){
if(!!(j = !mk_isNeg(str,k=i))){
s='';
}
}
s = str.slice(('-'==s&&!j)?i:++i);
}else if((ptag = ((('A'>s || s>'Z') && ('a'>s || s>'z') && (!!mkRnames[s] || s.charCodeAt(0)<300)) ?'mo':'mi'))=='mi' && 0<(strl-1) && '-'==str.charAt(strl-1) && !!mk_isNeg(str,i-1)){
s='-'+s;
--i;
}
s = s.trim();
b.text = s;
}
j = false;
b.pos=i;
b.sp=mk_spaces(str,i,ptag,sp,sl);
c = ptag;
if(t.par && ('mo'!=ptag||!!literal) && 1>b.sp[0] && '-'!=s){
if(!k){
bb.unshift({ptag:c,text:s, sp: b.sp, output:s, pos:i});
}
k = false;
while(!!(b = mk_rgetSymbol(str.slice(0, b.pos), b.sp, (!!literal || mk_continueSymbol(str.slice(0,b.pos), str.charAt(b.pos),1)), t)) && -1<(b.pos=Math.abs(b.pos)) && !b.origin && NONE!=b.symbol.type && ( ((VAR==b.symbol.type && (!!b.symbol.sym || !!b.symbol.mys))||(CONST==b.symbol.type && !!b.symbol.sym)||!!b.symbol.acc)) && (t.par||!!b.symbol.par)&&(!bb[0].par||!!b.symbol.acc)){
if(!!b.symbol.par){
bb[0].par=true;
}
if(b.pos==bb[0].pos){
b.pos=bb[0].pos-=bb[0].input.length;
continue;
}
k = false;
j = true;
(b.symbol.ptag==c)? (bb[0].text=b.symbol.output.trim()+bb[0].text) : bb.unshift({ptag:b.symbol.ptag,text:b.symbol.output.trim()});
c=b.symbol.ptag;
bb[0].pos =b.pos;
bb[0].sp =b.sp;
if(0<b.sp[0]||0<b.sp[1]){
break;
}
}
if(0<bb.length){
if(!b.symbol){
b.symbol = bb[0];
b.pos=0;
}
bb[0].origin = !!mkOrigin[bb[0].text] ? bb[0].text : '';
if('-'==b.text){
++bb[0].pos;
bb[0].text='-'+bb[0].text;
}
}else if(!b.symbol){
b.symbol = mk_cloneSymbol(mkSymbolNone);
b.pos=0;
}
j = j || !!b.symbol.acc;
}
if(j){
t.par = false;
if(!!b.symbol.acc){
mk_setCurrentSymbol(t,b.symbol.type, true);
return {symbol: mk_cloneSymbol(b.symbol,{multi:true}), pos:b.pos, text:bb, sp:b.sp, origin:bb[0].origin};
}else if(!!bb[0].par){
return {symbol: mk_cloneSymbol(bb[0]), pos:bb[0].pos, text:'', sp:bb[0].sp, origin:bb[0].origin}
}
return {symbol: mk_cloneSymbol(mkSymbolMulti), pos:bb[0].pos, text:bb, sp:bb[0].sp, origin: bb[0].origin};
}else{
t.par = t.par? false : ptag!='mo';
}
return {symbol: {input:s, ptag:ptag, output:s, type:VAR, mys:true}, pos:i, text:'', sp:mk_spaces(str,i,ptag,sp,sl)};
}
if(0===literal){
k = mk_cloneSymbol(k);
k.par = true;
}
if(STYLE==k.type){
mk_setCurrentSymbol(t,STYLE);
f=strl;
j = null;
bb = [];
while((!!mkRnames[str.slice(i,f)] && ((undefined!=(j=mkNames[str.slice(i, f)])&&!!(k=mkSymbols[j]) && STYLE==k.type && (bb.push(k),1) && -1!=(f=i) ) || 1)) && (-1<--i || (i=0)));
if(0==bb.length){
t.par = false;
return {symbol: mk_cloneSymbol(mkSymbolNone), pos:i, text:''};
}
k = mk_cloneSymbol(bb.pop());
i = strl - k.input.length;
for(s in bb){
for(j in bb[s].attr){
if('style'==j){
if(!k.attr.style){
k.attr.style='';
}else if(';'!=k.attr.style.charAt(k.attr.style.length-1)){
k.attr.style+=';';
}
k.attr.style+=bb[s].attr.style;
}else{
k.attr[j]=bb[s].attr[j];
}
}
i-=bb[s].input.length;
}
}else if(TEXT==k.type){
--strl;
if((i=str.slice(0,strl).lastIndexOf(k.input))==-1){
t.par = false;
return {symbol: mk_cloneSymbol(mkSymbolNone), pos:0, text:''};
}
mk_setCurrentSymbol(t,TEXT);
return {symbol: mk_cloneSymbol(k), pos:i, text:str.slice(i+1,strl), sp:mk_spaces(str,i,'mtext',sp,sl)};
}
s = '';
if(i>0 && (!!k.paren||!!k.carry||!!k.sov||!!k.sym||!!k.acc) && str.charAt(i-1)=='-' && !!mk_isNeg(str,i-1)){
s='-'+s;
--i;
}
mk_setCurrentSymbol(t,k.type);
k = mk_cloneSymbol(k);
if(!!k.shape && 'line'==k.shape){
while('-'==str.charAt(i)){
k.output+=k.output.charAt(0);
--i;
}
++i;
}
return {symbol: k, pos:i, text:s, sp:mk_spaces(str,i,k.ptag,sp,sl), found:true};
};
mk.rgetSymbol = mk_rgetSymbol;
var mk_nodeName = function(n){
return (!!n&&!!n.nodeName) ? n.nodeName.toLowerCase(): '';
};
var mk_acopy = function(v){
return v;
};
var mk_tcopy = function(v){
return v.text;
};
var mk_anotneg1 = function(v){
return v!=-1;
};
var mk_dunwrap = function(node=null){
if(!node){
return;
}
if('declare' == mk_nodeName(node)){
while(!!node.children[0]){
node.parentNode.insertBefore(node.children[0],node);
}
node.parentNode.removeChild(node);
return;
}
if(0==node.children.length){
return;
}
var i = -1;
for(i=-1;node.children.length>++i;){
mk_dunwrap(node.children[i]);
}
};
var mk_funwrap = function(node=null){
if(!node){
return;
}
if(!!node.hasAttribute('class') && !node.className){
node.removeAttribute('class');
}
var c = mk_nodeName(node);
if(0==node.children.length){
if('mrow'==c){
node.parentNode.removeChild(node);
return 1;
}
return 0;
}
if('mrow' == c){
if(1==node.children.length && 'mrow'==mk_nodeName(node.children[0])){
c = node.children[0];
node.parentNode.insertBefore(c,node);
node.parentNode.removeChild(node);
node = c;
}
}
var i = -1;
for(i=-1;node.children.length>++i;){
mk_funwrap(node.children[i]);
}
return 0;
//todo: empty mrows @ end
};
var mk_tunwrap = function(t,node=null){
if(!node){
return t.pML('math');
}
mk_dunwrap(node);
var p=null,n=null,b=null,c=null,d=null,tbl=null,i,j,k;
n = node.getElementsByClassName('__mkFraction');
i = n.length;
while(-1<--i){
if(!!n[i].children[0] && 'mspace'==mk_nodeName(n[i].children[0]) && !!n[i].parentNode){
n[i].parentNode.insertAdjacentElement('beforebegin',n[i].children[0]);
}
mk_removeClass(n[i], '__mkFraction');
}
n = node.getElementsByClassName('__mkDeferOriginal');
i = n.length;
while(-1<--i){
if(!!(b = n[i].className.match(/__mkDeferID([0-9]+)(?:[^0-9]|$)/u))&&!!(d=t.o[b[1]])&&!!d.origin&&!!mkOrigin[d.origin]&&!!(c=mk_getExt(mkOrigin[d.origin]))&&!!c.original){
p = n[i].parentNode;
p.replaceChild(c.original.cloneNode(true),n[i]);
}else{
if(!!b[1]){
mk_removeClass(n[i],'__mkDeferID'+b[1]);
}
mk_removeClass(n[i],'__mkDeferOriginal');
}
}
n = node.getElementsByClassName('__mkmlongdiv');
for(i=-1;n.length>++i;){
b = !!n[i].previousElementSibling ? n[i].parentNode : n[i].parentNode.previousElementSibling;
if(!!b && !!(b=b.querySelector('.__mklinebreak'))){
p = b;
while(!p.previousElementSibling && !!(p=p.parentNode));
d = b.parentNode;
if(1<d.children.length && b==d.children[0]){
while(!d.previousElementSibling && !!(d=d.parentNode));
//d = !!d.previousElementSibling ? d.previousElementSibling : null;
}
b.parentNode.removeChild(b);
c = null;
if(!!d && !!(d=d.previousElementSibling)){
c = t.pML('mtd');
do{
b = d.previousElementSibling;
c.insertAdjacentElement('afterbegin', d);
}while(!!(d=b));
}
if(!!p && 'mtable'!=mk_nodeName(p) && !p.querySelector('mtable')){
// n[i].children[0].children[0].insertAdjacentElement('afterbegin',p);
}
b = mk_tcunwrap(t,null,n[i].children[0].children[1]);
b.replaceChild(n[i].children[0].children[0], b.children[0]);
n[i].replaceChild(b, n[i].children[0]);
if(!!n[i].children[0].children[2].textContent.trim()){
mk_setStyle(n[i].children[0].children[2], 'border-top:1px solid');
}
p = n[i].parentNode;
if(!!(p=p.nextElementSibling) && ((!p.className||-1==p.className.indexOf('__mklinebreak'))&&!p.querySelector('.__mklinebreak')) ){
do{
b = p.nextElementSibling;
mk_appendChild(n[i].children[0].children[2], p);
}while(!!(p=b) && ((!p.className||-1==p.className.indexOf('__mklinebreak'))&&!p.querySelector('.__mklinebreak')));
}
if(!!c){
n[i].insertAdjacentElement('afterbegin',mk_tcunwrap(t,null,c));
}
p = n[i].parentNode;
mk_trunwrap(t,tbl=n[i],c=p.parentNode,p);
tbl.setAttribute('displaystyle','true');
}
n[i].removeAttribute('class');
}
n = node.getElementsByClassName('__mkline');
for(i=-1;n.length>++i;){
if(!!(p=n[i].parentNode) && !!(b=p.querySelector('.__mklinebreak'))){
b.parentNode.removeChild(b);
while(!p.previousElementSibling && !!(p=p.parentNode));
if(!!p && !!(p = p.parentNode)){
p.appendChild(tbl=t.pML('mtable'));
mk_trunwrap(t,tbl,p,tbl,true);
tbl.setAttribute('displaystyle','true');
}
}
}
n = node.getElementsByClassName('__mkline');
i = n.length;
while(-1<--i){
n[i].removeAttribute('class');
}
n = node.getElementsByTagName('mstyle');
i = n.length;
while(-1<--i){
n[i].removeAttribute('class');
}
do{
c = node.getElementsByClassName('__mklinebreak');
if(!!(n = c[0])){
if(!n.hasAttribute('linebreak')){
n.removeAttribute('class');
c = node.getElementsByClassName('__mklinebreak');
n = c[0];
continue;
}
p = n.parentNode;
j = !!n.nextElementSibling?1:0;
i = (!(i = n.getAttribute('height'))) ? mkLineHeight : parseInt(i.replace(/[^0-9\-]/g,''),10)*mkLineHeight;
n.removeAttribute('linebreak');
n.removeAttribute('height');
while(!!(n=p) &&!(p=null)&& !!(p = n.parentNode) && -1=='|math|mstyle|mrow|mtd|mfenced|'.indexOf(b=mk_nodeName(p)) && !!b);
b = t.pML('mtable');
b.appendChild(t.pML('mtr'));
b.appendChild(t.pML('mtr'));
b.children[0].appendChild(t.pML('mtd'));
b.children[1].appendChild(t.pML('mtd'));
n.insertAdjacentElement(0==j?'afterend':'beforebegin', b);
d = null;
d = b.children[0].children[0];
while(!!p.children[1] && b!=p.children[0]){
d.appendChild(p.children[0]);
}
d = b.children[1].children[0];
while(!!p.children[1] && b==p.children[0]){
d.appendChild(p.children[1]);
}
d = null;
d = 1==j ? b.children[1].children[0] : b.children[0].children[0];
if(!d.children || !d.children[0] || 'mpadded'!=mk_nodeName(d.children[0])){
d.insertAdjacentElement('afterbegin', t.pML('mpadded'));
}
d = d.children[0];
d.setAttribute('height', i+'px');
}
}while(0<c.length);
n = node.getElementsByTagName('mspace');
i = n.length;
while(-1<--i){
if(!!n[i].className && -1!=n[i].className.indexOf('__mkSpaceMrow')){
continue;
}
b = n[i].parentNode;
for(j=-1;b.children.length>++j;){
if('mspace'==mk_nodeName(b.children[j])){
mk_addClass(b.children[j],'__mkSpaceMrow');
if(!!(d=b.children[j].previousElementSibling)){
b.children[j].insertAdjacentElement('beforebegin',mk_appendChild( t.pML('mrow'), d));
if(!!(d=b.children[j].previousElementSibling)){
mk_appendChild(d, b.children[j]);
--j;
}
}else if(!!(d=b.children[j].nextElementSibling)){
b.children[j].insertAdjacentElement('afterend',mk_appendChild( t.pML('mrow'), d));
if(!!(d=b.children[j].nextElementSibling)){
d.insertAdjacentElement('afterbegin', b.children[j]);
--j;
}
}
}
}
}
n = node.getElementsByClassName('__mkSpaceMrow');
i = n.length;
while(-1<--i){
mk_removeClass(n[i],'__mkSpaceMrow');
}
mk_funwrap(node);
return node;
};
var mk_trunwrap = function(t,tbl,c,p,nodelay=false){
var j = -1, b = null, n = null, h=false, k=1024, d;
if(!c.children){
return;
}
c = c.children;
for(j=-1;c.length>++j;){
if(0>--k){
break;
}
if(c[j]!==p&&!!nodelay){
if(!!nodelay && 42!==nodelay && !n){
n = t.pML('mtd');
//n.setAttribute('columnalign','right');
}
d = false;
if(!!(b=c[j].querySelector('.__mkline')) || (b=c[j]).className.match(/\b\_\_mkline\b/)){
if(!!(d=b.className.match(/\b\_\_mkID([0-9]+)\b/))){
t.i[d[1]]='thus';
}
b.parentNode.removeChild(b);
mk_tcunwrap(t,null,n,true);
d=true;
}
if(!!c[j]&&!!(b=c[j].querySelector('.__mklinebreak'))){
if(!!d && c.length>(j+1) && p!=c[j+1]){
++j;
}
b.parentNode.removeChild(b);
if(!!n){
mk_tcunwrap(t,tbl,n);
}
n = t.pML('mtd');
// n.setAttribute('columnalign','right');
}
if(!!n){
n = mk_appendChild(n, c[j]);
}
--j;
}else if(c[j]===p){
nodelay = 42;//nag lé hitchikers condition
}
if(!!tbl.lastChild&&!!tbl.lastChild.lastChild&&!!tbl.lastChild.lastChild.textContent){
h=true;
}
}
if(!!n){
if(!!(b=n.querySelector('.__mklinebreak'))){
b.parentNode.removeChild(b);
}
mk_tcunwrap(t,tbl,n);
}
for(k=-1;tbl.children.length>++k;){
if(!!h){
d = mk_setStyle(tbl.children[k].children[1]);
if(!!d['border-bottom']){
mk_setStyle(tbl.children[k].children[2], 'border-bottom:'+d['border-bottom']+';padding-right:5px;');
}
}
tbl.children[k].children[1].setAttribute('columnalign','right');
tbl.children[k].children[2].setAttribute('columnalign','left');
}
};
var mk_tsunwrap = function(t,n){
var b,i,j,k,m,q={};
if(!n || !(b=n.querySelector('mstyle')) || !(m=b.className.match(/\b\_\_mkID([0-9]+)\b/))){
return 0;
}
if(-1!=n.innerHTML.indexOf('mathsize="small"')){
c=n.getElementsByTagName('mstyle');
for(i=-1;c.length>++i;){
if(!!c[i].className && !!(m=c[i].className.match(/\b\_\_mkID([0-9]+)\b/))){
t.o[m[1]].symbol.supressmath = true;
}
}
}else {
c=n.getElementsByTagName('mstyle');
for(i=-1;c.length>++i;){
if(!!c[i].className && !!(m=c[i].className.match(/\b\_\_mkID([0-9]+)\b/)) && 'mn'==t.o[j=parseInt(m[1],10)].symbol.ptag){
m.splice(0);
--j;
while(t.o.length>++j && (('mn'==t.o[j].symbol.ptag||('.'==t.o[j].symbol.output && t.o.length>(j+1) && 'mn'==t.o[j+1].symbol.ptag)) ? ((undefined==q[j]&&(m.unshift(q[j]=j))),!t.o[j].sp[2]) : 'mstyle'==t.o[j].symbol.ptag) && !t.o[j].sp[3]);
while(-1<--j && !t.o[j].sp[2] && (('mn'==t.o[j].symbol.ptag||('.'==t.o[j].symbol.output && -1<(j-1) && ('mn'==t.o[j-1].symbol.ptag || (-1<(j-2) && 'mstyle'==t.o[j-1].symbol.ptag && 'mn'==t.o[j-2].symbol.ptag)))) ? ((undefined==q[j]&&(m.push(q[j]=j))),!t.o[j].sp[2]) : 'mstyle'==t.o[j].symbol.ptag));
if(0<m.length){
t.o[m[0]].text = t.o[m[0]].symbol.output;
for(j=0;m.length>++j;){
t.o[m[0]].text+=t.o[m[j]].symbol.output;
t.o[m[j]].symbol.supressmath = true;
}
t.o[m[0]].__text = t.o[m[0]].text;
}
k=c[i].textContent;
m.splice(0);
while(c[i].children[0]){
m.push(c[i].children[0].getAttribute('style')||'');
c[i].removeChild(c[i].children[0]);
}
if('-'==k.charAt(0)){
j=k.charAt(1);
mk_appendChild(c[i],t.pML((('0'<=j&&j<='9')?'mn':'mi'),k.substring(0,1)));
k=k.substring(2);
}else{
j=k.charAt(0);
mk_appendChild(c[i],t.pML((('0'<=j&&j<='9')?'mn':'mi'),j));
k=k.substring(1);
}
if('.'==(j=k.charAt(0))){
j=k.charAt(1);
}
j = ('0'<=j&&j<='9')?'mn':'mi';
c[i].insertAdjacentElement('afterend',t.pML(j,k));
for(j=-1;c[i].children.length<++j;){
if(!!m[j]){
c[i].children[j].setAttribute('style',m[j]);
}
}
}
}
}
return 1;
};
var mk_tpunwrap = function(h=''){
return h.replace(/<(m[roi][ow]*)><\/\1>/g,'').replace(/(<mstyle[^>]*:line-through[^>]*>)(.*?)(<\/mstyle>)/g,'$1<menclose notation="downdiagonalstrike">$2</menclose>$3');
};
var mk_tcunwrap = function(t,tbl=null,n=null,b=false){
var h = '', i = 0, k = '', m = null, o = null, r = null, s = null;
if(!!n && !b){
mk_tsunwrap(t,n);
s = n.getAttribute('style');
o = t.pML('mtd');
h = n.innerHTML.replace(/(<\/?mspace[^>]*>)/g, ' $1 ');
if(!!(m = !!(k=-1!=h.indexOf('mathsize="small"')) ? h.match(/^(.*<[^>]*>[^<>]*)\.([^<>]*<[^>]*>.*)$/):
(h.match(/^(.*<[^>]*>[^<>]*[0-9])([^0-9,<>][^<>]*<[^>]*>.*)$/)
||h.match(/^(.*<[^>]*>[^<>]*[0-9][^<>]*<[^>]*>)(.*?<[^>]*>[^<>]*[^0-9,<>].*)$/
)))){
m[1] = m[1].replace(/\s*(<\/?mspace[^>]*>)\s*/g, '$1').trim();
m[2] = m[2].replace(/\s*(<\/?mspace[^>]*>)\s*/g, '$1').trim();
r=m[1].match(/<(\/?\s*[^\s<>]+)[^>]*>/g);
i=r.length;
m[3]={};
while(-1<--i){
r[i] = r[i].slice(1, r[i].indexOf(' '));
if(1<r[i].length && r[i].length!=(r[i].indexOf('/')+1)){
if(0==r[i].indexOf('/')){
m[4]=r[i].substring(1);
undefined==m[3][m[4]]?m[3][m[4]]=1:m[3][m[4]]++;
}else if(!m[3][r[i]]){
m[1]+='</'+r[i]+'>';
}else{
--m[3][r[i]];
}
}
}
r=m[2].match(/<(\/?\s*[^\s<>]+)[^>]*>/g);
i=-1;
m[3]={};
while(r.length>++i){
r[i] = r[i].slice(1, r[i].indexOf(' '));
if(1<r[i].length && r[i].length!=(r[i].indexOf('/')+1)){
if(0!=r[i].indexOf('/')){
m[4]='/'+r[i];
undefined==m[3][m[4]]?m[3][m[4]]=1:m[3][m[4]]++;
}else if(!m[3][r[i]]){
m[2]='<'+r[i].substring(1)+'>'+m[2];
}else{
--m[3][r[i]];
}
}
}
n.innerHTML= mk_tpunwrap(m[1]);
o.innerHTML= mk_tpunwrap(m[2]).replace('<mo>.</mo>','<mi>.</mi>');
//n.setAttribute('columnalign','right');
//o.setAttribute('columnalign','left');
if(0<o.children.length){
if(0==o.textContent.indexOf('.')){
mk_setStyle(o.children[0], 'margin-left:-8px;margin-right:1px;');
}else if(0==o.textContent.indexOf('\u2193')){
mk_setStyle(o.children[0], 'margin-left:-5px');
}
}
if(!!s&&s.indexOf('border-top')){
mk_setStyle(o, s);
}
}else{
n.innerHTML= mk_tpunwrap(n.innerHTML);
}
}
if(!!n){
r = mk_appendChild(mk_appendChild(mk_appendChild(t.pML('mtr'),t.pML('mtd')),n),o);
if(r.innerHTML.match(/font-size:[0-9][0-9]?[^0-9]/i)){
m = r.getElementsByTagName('mtd');
for(i=-1;m.length>++i;){
mk_setStyle(m[i], 'margin:0;padding:0;height:5px;line-height:5px;');
}
}
m = r.getElementsByClassName('__mklinebreak');
for(i=-1;m.length>++i;){
m[i].removeAttribute('class');
}
if(!!tbl){
tbl.insertAdjacentElement('beforeend',r);
}
if(!b){
return r;
}
}
if(!!b && !!(b = (!!tbl && !!tbl.lastChild) ? tbl.lastChild.children[1] : n)){
mk_setStyle(b, 'border-bottom:1px solid');
}
};
//todo: getstyle
var mk_setStyle = function(o,s=null){
var ss = {}, a=null, b='';
(o.getAttribute('style')||'').split(';').filter(function(v){
a = v.split(':');
if(1<a.length && !!(b=(a.shift()).trim().toLowerCase()) && !!(a[0]=(a.join(':')).trim())){
ss[b] = a[0];
}
});
if(null==s){
return ss;
}
s.split(';').filter(function(v){
a = v.split(':');
if(0<a.length && !!(b=(a.shift()).trim().toLowerCase())){
if(!!(a[0]=(a.join(':')).trim())){
ss[b] = a[0];
}else{
delete ss[b];
}
}
});
s = '';
Object.keys(ss).map(function(k){
s+=k+':'+ss[k]+';';
});
o.setAttribute('style', s);
};
var mk_unwrap = function(node, t='declare'){
if(!node || !node.children || 1!=node.children.length){
return node;
}
if('declare' == mk_nodeName(node.children[0])){
while(!!node.children[0].children[0]){
node.appendChild(node.children[0].children[0]);
}
node.removeChild(node.children[0]);
}
return ((('apply'!=t || -1!='|ci|cn|set|vector|cs|apply|'.indexOf(mk_nodeName(node.children[0])))&& t == mk_nodeName(node) && 1==node.children.length )) ? node.children[0] : node;
};
var mk_appendChild = function(p, c=null, r=true){
var cc=null, i=-1, j=-1;
if(!c||!c.nodeName){
return p;
}
p.appendChild(c);
if(r){
cc = p.getElementsByTagName('declare');
i = cc.length;
while(-1<--i){
j = cc[i].children.length;
while(-1<--j){
cc[i].insertAdjacentElement('beforebegin', cc[i].children[0]);
}
cc[i].parentNode.removeChild(cc[i]);
}
}
return p;
};
var mk_cFirstClosedTag = function(content){
var c = -1;
return (!!content && !!content.outerHTML && (c=content.outerHTML.indexOf('/>'))!=-1 && c<content.outerHTML.indexOf('>'));
};
var mk_cMinus = function(t, p){
if(!!t.o[p].neg){
var content = mk_content(t,p,true);
if('cminus'!=mk_nodeName(content) && (1!=content.children.length||'cminus'!=mk_nodeName(content.children[0]))){
var node = t.cML('apply', t.cML('minus'));
mk_appendChild(node, content);
content = node;
}
t.o[p].content = content;
delete t.o[p].neg;
}
return t.o[p].content;
};
var mk_cAffix = (function(){
var ops = ['suffixop','prefixop'];
return function(t,p,n=null){
var o = t.o[p];
if(!n && !!o._cAffix){
return;
}
var i = -1, j=-1, node=null, op=null;
i = ops.length;
while(-1<--i){
if(!!(op = o[ops[i]]) && 0<op.length){
j = -1, node = null;
while(op.length>++j){
node = t.cML('apply', t.cML(op[j].ctag || op[j].csymbol));
if(null==n){
mk_appendChild(node, o.content);
o.content = node;
}else{
mk_appendChild(node, n);
n = node;
}
}
}
}
if(undefined != o.suffixof){
node = null;
node = t.cML('apply', {symbol: o.ofprefixop});
mk_appendChild(node,mk_content(t, o.suffixof));//t.o[o.suffixof].content);
if(null==n){
mk_appendChild(node,o.content);
o.content = node;
}else{
mk_appendChild(node,n);
n=node;
}
}
t.o[p]._cAffix=true;
};
})();
var mk_cBvar = function(t,p,content=null,node=null){
var c = null, i = -1, j = -1, k = null==content ? 1 : t.o[p].c.length;
while(k>++i){
if(!!content && !!t.o[t.o[p].c[i]].c){
node = mk_cBvar(t, t.o[p].c[i], content, node);
}else {
c = null;
if(!content) {
c = p;
}else if(0<i && (!!t.o[t.o[p].c[i]].symbol.eq || !!t.o[t.o[p].c[i]].symbol.rel)){
j=i;
while(k>++j && 'mi'!=t.o[t.o[p].c[j]].symbol.ptag);
if(j<k){
c = t.o[p].c[j];
}
}
if(null!=c){
if(undefined!=t.o[c].subscript){
node = t.cML('apply',t.cML('selector'));
mk_appendChild(node, t.cML(c));
mk_appendChild(node,!!t.o[t.o[c].subscript].content?t.o[t.o[c].subscript].content:t.cML(t.o[c].subscript));
node = t.cML('bvar',node);
}else{
node = t.cML('bvar',t.o[c]);
}
if(undefined!=t.o[c].calcop && (undefined!=(j=t.o[c].order) || undefined!=(j=t.o[t.o[c].calcop].order))){
mk_appendChild(node,t.cML('degree', mk_content(t, j)));
}else if(undefined!=t.o[c].power){
mk_appendChild(node,t.cML('degree',mk_content(t, t.o[c].power)));
}
if(!!content){
mk_appendChild(content,node);
}
}
}
}
return node;
};
var mk_cSubPow = function(t,p,r=false,pre=''){
var o = t.o[p], u = false, pow = pre+'power', sub = pre+'subscript', b = null;
if(!!o._cSubPow && (!pre || !!o._cemSubPow)){
if(!!pre || (undefined==o._upower && undefined==o._usubscript)){
return;
}
u = true;
o._opower = o.power;
o._osubscript = o.subscript;
o.power = o._upower;
o.subscript = o._usubscript;
delete o._upower;
delete o._usubscript;
}
var content=o.content, i=(undefined==o['_'+sub]?o[sub]:null), j=-1, k=(undefined==o['_'+pow]?o[pow]:null), node=null, v=-1;
if(!content){
return mk_content(t,p);
}
if(mk_cFirstClosedTag(content) && 0!=content.children.length){
content = t.cML('apply', content);
}
if(!!(node = v = 'apply'==mk_nodeName(content)? content : content.querySelector('apply')) ){
for(j=-1;v.children.length>++j;){
if('bvar'==mk_nodeName(v.children[j])){
node = v.children[j];
}
}
}
if('apply'==mk_nodeName(node)){
node = node.firstChild;
}
if( !pre && UNDEROVER == o.symbol.type && undefined!=(v = (undefined!=i && !!t.o[i].c) ? i : ((undefined!=k && !!t.o[k].c)? k : undefined))){
if(!u){
node = mk_cBvar(t,v,content,node);
}
}
v = ((undefined!=i && undefined!=t.o[i][pow] && undefined==t.o[i]['_'+pow]) ? t.o[i][pow] : (undefined!=k ? k : -1));
if(undefined!=i){
if(!u && (UNDEROVER==o.symbol.type||!!o.symbol.integral)){
!!node ?
(node.insertAdjacentElement(
('apply'==mk_nodeName(node)? 'afterbegin' : 'afterend'),
t.cML('lowlimit',mk_content(t,i))
),(node = node.nextElementSibling)) : (mk_appendChild(
content,
node=t.cML('lowlimit',mk_content(t,i))
), (node=content.lastChild));
}else{
node = t.cML('apply', t.cML('selector'));
mk_appendChild(node,content);
mk_appendChild(node, mk_content(t,i));
content = node;
}
t.o[p].content = content;
if(undefined != t.o[i][pow]){
t.x[t.o[i][pow]] = true;
}
}
if(v>-1 && (!o['is'+sub] || r)){
t.x[v] = true;
if(!u && !pre && (UNDEROVER==o.symbol.type||!!o.symbol.integral)){
!!node ?
node.insertAdjacentElement(
('apply'==mk_nodeName(node)? 'afterbegin' : 'afterend'),
t.cML('uplimit',mk_content(t,v))
) : mk_appendChild(
content,
t.cML('uplimit',mk_content(t,v))
);
}else{
//TODO: better check on contents of PHANTOM and share
b = (!!t.o[v].c&&1==t.o[v].c.length)?t.o[t.o[v].c[0]]:t.o[v];
if('T'==b.symbol.input && (!!o.matrix ||PHANTOM==o.symbol.type||!!o.origin ||!o.stackname)){
node = t.cML('apply', t.cML('transpose'));
mk_appendChild(node,content);
}else if('-1'==b.symbol.input || '-1'==b.text){
node = t.cML('apply', t.cML('inverse'));
mk_appendChild(node,content);
}else{
node = t.cML('apply', t.cML('power'));
mk_appendChild(node,content);
mk_appendChild(node, mk_content(t,v));
}
content = node;
}
t.o[p].content = content;
if(undefined != t.o[v][sub] || undefined != t.o[v][pow]){
mk_cSubPow(t,v,true,pre);
mk_appendChild(t.o[p].content,t.o[v].content);
}
}
if(!u && !pre && !!t.o[p].symbol.integral && 'oint'==t.o[p].symbol.input){
b = [];
if(!!(content = t.o[p].content.querySelector('lowlimit'))){
b.push((!!content.firstChild?content.firstChild:content).cloneNode(true));
t.o[p].content.removeChild(content);
}
if(!!(content = t.o[p].content.querySelector('uplimit'))){
b.push((!!content.firstChild?content.firstChild:content).cloneNode(true));
t.o[p].content.removeChild(content);
}
if(0<b.length){
if(1==b.length){
b[1]=b[0].cloneNode(true);
}
node = t.cML('csymbol');
node.innerHTML = 'oriented_interval';
node = t.cML('apply', node);
mk_appendChild(node,b[0]);
mk_appendChild(node,b[1]);
content = t.o[p].content.querySelector('int');
content.insertAdjacentElement('afterend', node);
}
}
if(!r){
t.o[p]._cSubPow=true;
}
if(!!pre){
t.o[p]._cemSubPow=true;
}
if(!pre && (undefined!=o._opower || undefined!=o._osubscript)){
o.power = o._opower;
o.subscript = o._osubscript;
delete o._opower;
delete o._osubscript;
}
return t.o[p].content;
};
var mk_cLambda = function(t, a, d='r', c=0, b={}){
var i = a.length, j = -1;
if(0<i){
if(!c){
j = i;
'r'==d? RIGHTBRACKET==t.o[a[0]].symbol.type && (a.shift() ^ --i) : LEFTBRACKET==t.o[a[i-1]].symbol.type && (a.pop() ^ --i);
if(1==a.length && i!=j && !!t.o[a[0]].c){
if(!!t.o[a[0]].matrix||!!t.o[a[0]].set||!!t.o[a[0]].vector){
return a;
}
return mk_cLambda(t,t.o[a[0]].c.slice(0),d,++c);
}
}else if(1<i && RIGHTBRACKET==t.o[a[0]].symbol.type && LEFTBRACKET==t.o[a[i-1]].symbol.type){
a.shift(); --i;
a.pop(); --i;
}
while(0<--i){
if(!!t.o[a[i]].args){
j = t.o[a[i]].args.length;
while(-1<--j){b[t.o[a[i]].args[j]]=true;}
}
if(!!t.o[a[i]].c){
j = t.o[a[i]].c.length;
while(-1<--j){b[t.o[a[i]].c[j]]=true;}
}
if(!!t.o[a[i]].symbol.sep){
b[a[i]] = true;
}
}
if(0==c){
a.unshift(null);
}
return a.filter(function(v){return !b[v];});
}
return a;
};
var mk_popOp = function(t, p){
var o = t.o[p], i = -1, b = null;
if(!!o.ipopop && !!o.ipoparg){
b = null;
i = o.ipopop.length;
while(-1<--i){
b = t.cML('apply', t.cML(o.ipopop.shift().ctag));
mk_appendChild(b, o.content);
if(0<o.ipoparg.length){
mk_content(t, o.ipoparg[0], true);
mk_appendChild(b, t.o[o.ipoparg.shift()].content.cloneNode(true));
}
o.content = b;
}
delete t.o[p].ipopop;
}
};
var mk_content = function(t, p, force=false){
var o = t.o[p];
return (!!o.content && (!!o._forced || !force || !(!!o.vector || !!o.origin || !!o.matrix || !!o.set || !!o.matrixrow || !!o.crow || !!o.piecewise || !!o.suffixop || !!o.prefixop || !!o.ofprefixop || !!o.symbol.acc ||(PHANTOM==o.symbol.type&&!o._cSubPow&&undefined!=o.power)))) ? ((o._forced=false), o.content) : ((o._forced = force), mk_cTerm(t,p));
};
var mk_isValidId = function(id=''){
return !id ? false : 0!==id.toLowerCase().indexOf('xml') && id.match(/[a-zA-Z]/u) && id.match(/^[_a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}][\-.0-9\u00B7\u0300-\u036F_a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u);
};
var mk_getValidId = function(id=''){
id = !id ? '' : id.replace(/^.*[#]+/u,'').replace(/^[^_a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*(?:[xX][mM][lL])?/ug,'').replace(/[^\-.0-9\u00B7\u0300-\u036F_a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]+/ug,'');
return !id ? '':(id.match(/[a-zA-Z]/u)? id : 'a'+id);
};
var mk_validStackRefName = function(sr='',s=false){
var k=sr.replace(/(?:^[",\s])|(?:[",\s]*$)/ug,'');
if(!k){
k = 'mk__'+mkHashSum.hash(sr);
}
return (!s&&!!mkExt.img[k]) ? mkExt.img[k] : k;
};
var mk_newStackOrigin = function(r='',s=''){
r=r.replace(/(?:^[",\s])|(?:[",\s]*$)/ug,'');
s=s.replace(/(?:^[",\s])|(?:[",\s]*$)/ug,'');
if(!r || !s){
return;
}
var k = r.length, j = -1;
while(k>++j){
mkRorigin[r.slice(-j)] = true;
}
mkOrigin[r]=s;
mkOrigin[' '+s]=r;
};
var mk_newStackName = function(sn='',s=''){
sn = mk_validStackRefName(sn,true===s);
var k = sn;
if(!!mkExt.sn[k] || (!!mkExt.sn[k=mk_trimUrl(sn)] && !!k)){
if(sn!=k){
mkExt.img[sn]=k;
}
return true===s? sn:k;
}
if(!k){
k=sn;
}
if(false===s){
return k;
}else if(true===s){
s='';
}
if(!!mkExt.cache[1] && 2>Math.abs(__levenshtein(k,mkExt.cache[1]))){
if(3<k.length || 1000>(Date.now()-mkExt.sn[mkExt.cache[1]].created) ){
mk_deleteExt(mkExt.cache[1]);
}
}
mkExt.cache[1]=k;
mkExt.sn[k] = {
data: '',
status: s,
original: '',
originalid: '',
hit: Date.now(),
created:Date.now(),
type: '',
hash: mk_idFromUrl(k),
id: '',
ref: '',
atype:''
};
return sn;
};
var mk_newStackRefId = function(id='',k=''){
var i = mk_getValidId(id), n='';
if(!i){
i = 'mk__'+mkHashSum.hash(id);
}
while(!!mkDoc.querySelector('#'+i+n) || (!!mkExt.id[id+n]&&k!=mkExt.id[i+n])){
if(0===mkExt.id[id+n].indexOf('mk__')){
mk_deleteExt(mkExt.id[id+n]);
break;
}
n=!n?1:++n;
}
return i+''+n;
};
var mk_newStackRef = function(r='',k=''){
var id = '';
r = mk_validStackRefName(r);
if(!k || !r){
return r;
}
if(!mkExt.sn[k]){
k=mk_newStackName(k);
}
if(!!mkExt.cache[0] && 2>Math.abs(__levenshtein(r,mkExt.cache[0])) && !!mkExt.ref[mkExt.cache[0]]){
if(3<r.length || 1000>(Date.now()-mkExt.sn[mkExt.ref[mkExt.cache[0]]].created) ){
mk_deleteExt(mkExt.ref[mkExt.cache[0]]);
}
}
if(!mkExt.sn[k]){
k=mk_newStackName(k);
}
mkExt.cache[0]=r;
id = mk_newStackRefId(r,k);
mkExt.ref[r]=k;
mkExt.id[id]=k;
if(!mkExt.sn[k].ref){
mkExt.sn[k].ref=r;
}
if(!mkExt.sn[k].id){
mkExt.sn[k].id=id;
}
return r;
};
var mk_getStackId = function(sn=''){
if(!mkExt.sn[sn] && !mkExt.sn[sn=mk_validStackRefName(sn)]){
return '';
}
if(!mkExt.sn[sn].id){
var id = mk_newStackRefId(mkExt.sn[sn].hash||sn, sn);
mkExt.id[id]=sn;
mkExt.sn[sn].id=id;
}
mkExt.sn[sn].hit = Date.now();
return mkExt.sn[sn].id;
};
var mk_getStackName = function(r=''){
var sn = '',b=(0==r.indexOf('#')?((r=r.substring(1)),'id'):'ref');
if(!(sn=mkExt[b][r]) && !(sn='ref'==b?mkExt.ref[mk_validStackRefName(r)]: mkExt.id[mk_validStackRefName(mk_getValidId(r))])){
return '';
}
mkExt.sn[sn].hit = Date.now();
return sn;
};
var mk_getStackRef = function(sn=''){
if(!mkExt.sn[sn] && !mkExt.sn[sn=mk_validStackRefName(sn)]){
return '';
}
mkExt.sn[sn].hit = Date.now();
return mkExt.sn[sn].ref;
};
var mk_getStackHref = function(sn=''){
if(!mkExt.sn[sn] && !mkExt.sn[sn=mk_validStackRefName(sn)]){
return '';
}
mk_getStackId(sn);
return 'math'==mkExt.sn[sn].type?sn.replace(/(\/\/[^a-z0-9]*\.?mathkey\.org)\/mk\//ui, '$1/ml/'):'#'+mkExt.sn[sn].id;
};
var mk_getExt = function(sn=''){
return mkExt.sn[sn] || mkExt.sn[mk_validStackRefName(sn)];
};
var mk_setExt = function(sn='', d=null, m={}){
if(!sn || !mkExt.sn[sn] || !mkExt.sn[sn=mk_validStackRefName(sn)]){
return;
}
var i;
if(!!d){
if('string'==typeof d){
if(0===d.indexOf('blob:')){
mkExt.sn[sn].status='completed';
mkExt.sn[sn].original = mkExt.sn[sn].data;
mkExt.sn[sn].data = d;
} else if(0===d.indexOf('data:image/')){
mkExt.sn[sn].status='imagetoblob';
mkExt.sn[sn].data = d;
mkExt.sn[sn].type = mk_typeImageUrl(sn);
}else {
mkExt.sn[sn].data = d;
}
}else if('object'==typeof d){
mkExt.sn[sn].status='completed';
if(!!d.querySelector && ('math'==mk_nodeName(d) || !!d.querySelector('math') )){
mkExt.sn[sn].data = d;
mkExt.sn[sn].type ='math';
}
}else{
mkExt.sn[sn].data = d;
}
}else if('string'==typeof d){
mk_deleteExt(sn);
return;
}
for(i in m){
mkExt.sn[sn][i] = m[i];
}
};
var mk_deleteExt = function(sn=''){
var i;
if(!sn){return;}
for(i in mkExt.id){
if(sn==mkExt.id[i]){
delete mkExt.id[i];
}
}
for(i in mkExt.img){
if(sn==mkExt.img[i]){
delete mkExt.img[i];
}
}
for(i in mkExt.ref){
if(sn==mkExt.ref[i]){
delete mkExt.ref[i];
}
}
var k ='',j=-1;
mkRorigin={};
delete mkOrigin[' '+sn];
for(i in mkOrigin){
if(sn==mkOrigin[i]){
delete mkOrigin[i];
continue;
}
if(' '==i.charAt(0)){
continue;
}
k=i.length;
j = -1;
while(k>++j){
mkRorigin[i.slice(-j)]=true;
}
}
delete mkExt.sn[sn];
};
var mk_findStackName = function(t,eq,i,a=false){
var f = i, k = i;
a = 1===a ? ',' : ')';
while(-1<--k && !t.o[k].pos);
while(-1<--f && !(t.o[i].l==t.o[f].l && a==t.o[f].symbol.input));
return eq.slice(t.o[k].pos,!!t.o[f]?t.o[f].pos:(eq.length-1));
};
var mk_cTerm = function(t,p){
var b = null, ext=null, i = -1, j = -1, k = '', o = t.o[p];
if(undefined==o.__thaw){
mk_thaw(t,p);
}
if(!o._cminus){
o._cminus=0;
}
if( !!o.origin && !!(k=mk_getStackHref(mk_getStackName(o.origin) ))){
o.content = t.cML('share');
o.content.setAttribute('href',k);
}else if(!!o.stackname && 'stackrel'==o.symbol.input){
ext = mk_getExt(o.stackname);
k = 'MathML-Content';
b = [null,null];
if(undefined===o.stackref && undefined===o.arg){
b[0]=t.cML('cs',undefined!==ext?ext.data:'');
b[1]=t.cML();
}else if(undefined===ext || 'error'===ext.data){
if(!!ext.data){
b[0]=mk_content(t,undefined===o.stackref?o.arg:o.stackref);
b[1]=t.cML('cs',ext.data);
}else if(undefined===o.stackref){
b[0]=mk_content(t,o.arg);
b[1]=t.cML();
}else {
i = mk_getStackId(o.stackname);
if(!!i){
b[0] = mk_appendChild(t.cML('lambda'), mk_content(t,o.stackrel));
b[0] = mk_appendChild(t.cML('apply'), b[0]);
b[0].setAttribute('id',i);
b[1] = mk_content(t, o.stackref);
}else{
b[0] = mk_content(t,o.stackref);
b[1] = mk_content(t, o.stackrel);
}
}
}else if('image'==o.stype.substring(0,5)){
k='text/html';
if(undefined===o.stackref){
b[0]=t.cML();
}else{
b[0]=mk_content(t,o.stackref);
}
b[1] = t.cML('img');
b[1].setAttribute('src', ext.data.replace(/"/ug,'&quote;'));
b[1].setAttribute('alt', ext.ref);
if(undefined!==o.stackref){
b[1].setAttribute('id',mk_getStackId(o.stackname));
}
}else if('math'==o.stype){
j = mk_getStackHref(o.stackname);
if(undefined===o.stackref){
if(-1!=o.stackname.indexOf('#')){
delete t.o[o.arg].mk;
o.content = t.cML('share');
o.content.setAttribute('href',j);
return o.content;
}
if(!ext.data.mathKey){
k = 'MathML-Presentation';
b[0] = t.cML();
b[1] = mk_replaceML(ext.data);
}else{
b[0] = mk_replaceML(t,ext.data.mathKey);
b[1] = t.cML('cs', o.stackname);
}
}else{
if(!ext.data.mathKey){
if(!h.hash){
k = 'MathML-Presentation';
b[0] = mk_content(t,o.stackref);
b[1] = mk_replaceML(t,ext.data);
}else if(-1!=o.stackname.indexOf('#')){
b[0] = mk_appendChild(t.cML('lambda'), mk_content(t,o.stackref));
b[0] = mk_appendChild(t.cML('apply'), b[0]);
b[0].setAttribute('id',ext.id);
b[1] = t.cML('share');
b[1].setAttribute('href',j);
}else{
k = 'MathML-Presentation';
b[0] = mk_appendChild(t.cML('lambda'), mk_content(t,o.stackref));
b[0] = mk_appendChild(t.cML('apply'), b[0]);
b[0].setAttribute('id',ext.id);
b[1] = mk_replaceML(t,ext.data);
}
}else{
b[0] = mk_replaceML(t, ext.data.mathKey);
b[1] = mk_content(t,o.stackref);
if(!!ext.id){
b[0] = mk_appendChild(t.cML('lambda'), b[0]);
b[0] = mk_appendChild(t.cML('apply'), b[0]);
b[0].setAttribute('id',ext.id);
}
}
}
}else if('function'==o.stype){
if(undefined===o.stackref){
b[0] = t.cML();
b[1] = mk_content(t,o.arg);
mk_setExt(o.stackname,b[1].cloneNode(true));
}else{
if(!!ext.id){
b[0] = mk_appendChild(t.cML('lambda'), mk_content(t,o.stackrel));
b[0] = mk_appendChild(t.cML('apply'), b[0]);
b[0].setAttribute('id',ext.id);
b[1] = mk_content(t, o.stackref);
mk_setExt(o.stackname,b[0].cloneNode(true));
}else{
b[0] = mk_content(t,o.stackref);
b[1] = mk_content(t, o.stackrel);
mk_setExt(o.stackname,b[1].cloneNode(true));
}
}
}else{
if(undefined===o.stackref){
b[0] = t.cML();
b[1] = mk_content(t,o.arg);
}else{
b[0] = mk_content(t,o.stackref);
b[1] = mk_content(t, o.stackrel);
}
mk_setExt(o.stackname,b[1].cloneNode(true));
}
b[0] = mk_appendChild(t.pML('semantics'),b[0]);
b[1] = mk_appendChild(t.pML('annotation-xml'), b[1]);
b[1].setAttribute('encoding',k);
o.content = mk_appendChild(b[0], b[1]);
if(undefined!==o.stackref){
delete t.o[o.stackref].mk;
delete t.o[o.stackref].mk;
}
return o.content;
} else if(!!o.symbol.output&&'e'==o.symbol.output&&undefined!=o.power){
if(!o.args){
o.args=[];
}
o.args.push(o.power);
delete t.o[o.power].ispower;
t.o[o.power].isarg = true;
t.o[o.power].symbol.type = PHANTOM;
delete t.o[p].power;
o.symbol.ctag = 'exp';
o.symbol.type = UNARY;
}else if(TEXT==o.symbol.type){
o.content = !!o.text ? t.cML('cs', o.text) : t.cML();
}else if('dot'==o.symbol.input || 'ddot'==o.symbol.input){
o.content = mk_appendChild(t.cML('apply', t.cML('diff')), t.cML('ci', o.text.replace(/^\.+/ug,'')));
if('ddot'==o.symbol.input){
o.content = mk_appendChild(t.cML('apply', t.cML('diff')), o.content);
}
}else if(undefined != o.p && t.o[o.p].piecewise){
if(!o.content){
o.content = t.cML(p);
}
if(!t.o[o.p].content){
t.o[o.p].content = t.cML(t.o[o.p].ctag);
t.o[p]._p = true;
}
while(!!(b = o.content.querySelector('if'))){
if(!b.parentNode){
b = t.cML('declare',b).children[0];
}
k = b.parentNode;
o.content = t.cML('apply', !!k.children[0] ? k.children[0].cloneNode(true):'approx');
while(!!b.nextElementSibling){
mk_appendChild(o.content, b.nextElementSibling.cloneNode(true));
k.removeChild(b.nextElementSibling);
}
k.removeChild(k.children[0]);
k.removeChild(b);
if('apply'==mk_nodeName(k) && 'apply'!=mk_nodeName(k=mk_unwrap(k,'apply')) ){
k = t.cML('declare',k);
}
k.insertAdjacentElement('afterend',o.content);
o.content = mk_unwrap(!!k.parentNode ? k.parentNode : k);
mk_appendChild(t.o[o.p].content, t.cML('piece', o.content));
}
return t.o[o.p].content;
}
if((!o.content || ('declare'==mk_nodeName(o.content) &&0==o.content.children.length) )&& !!(o.content = t.cML(p))){
t.o[p].content = mk_unwrap(o.content);
if(undefined!=o.calcopof){
mk_cMinus(t, p);
return o.content;
}
}
if(
(o[k='matrix'] || o[k='vector'] || o[k='set'] || o[k='matrixrow'] || o[k='piecewise']) || ((o['vectorcol'] || o['setcol'] ||
-1 != '|vector|set|matrixrow|matrix|'.indexOf('|'+mk_nodeName(o.content)+'|'))? (k='istrue') :
((k='apply'),((-1=='|apply|bvar|cn|ci|degree|lowlimit|uplimit|'.indexOf('|'+mk_nodeName(o.content)+'|') || ('ci'==mk_nodeName(o.content) && !!o.ctype && 'function'==o.ctype)) && (CONST!=o.symbol.type || !o.symbol.sym))))){
if('istrue'==k){
t.o[p]._p = true;
if((!!o.vectorcol||!!o.setcol)&&'declare'==mk_nodeName(o.content) && 1<o.content.children.length&&!mk_cFirstClosedTag(o.content)){
o.content = t.cML('list', o.content);
}
return o.content;
}else if('apply'!=k){
if(('declare'==(j=mk_nodeName(o.content)) && (0<o.content.children.length || k!=j)) ||k!=j){
o.content = t.cML(k, o.content);
t.o[p]._p = true;
}
if('matrixrow'!=k){
mk_cAffix(t,p);
mk_cSubPow(t,p);
mk_popOp(t,p);
}
return t.o[p].content;
}else if(!!o.args){
o.content = t.cML(k, o.content);
}
}
if(!!o.symbol.integral){
if(!o.int){
if(undefined!=o.dop){
mk_appendChild(o.content, mk_cBvar(t,o.dop));
mk_cSubPow(t, p);
mk_cAffix(t, p);
mk_cSubPow(t,p,false,'em');
if(undefined!=o.intop){
t.o[o.intop]._content = mk_appendChild(o.content, t.o[o.intop]._content);
if(p==o.intop){
}
delete o.intop;
}
delete o.dop;
return o.content;
}
}else{
o._int = [];
if(!o.args){
o.args = [];
}
k=-1;
b = null;
if(!(0==o.args.length || !t.o[i=o.args[0]].c || 0==t.o[i].c.length || undefined==(i=t.o[k=t.o[i].c[0]].calcop))){
++i;
b=[];
while(-1<--i){
if((undefined!=t.o[i].op && (p==t.o[i].op||(1<b.length && undefined!=t.o[i].calcopof && undefined!=t.o[b[1]].intop && t.o[b[1]].intop==t.o[i].op))) || (undefined!=t.o[i].calcop&&b[0]==t.o[i].calcop)){
b.unshift(i);
}
}
}
if(!!t.o[k]){
if(undefined!=t.o[k].power){
o._upower = t.o[k].power;
delete t.o[k].power;
}
if(undefined!=t.o[k].subscript){
o._usubscript = t.o[k].subscript;
delete t.o[k].subscript;
}
}
if(!!b){
k = -1;
i = b.length;
if(2<i && 1==o.int.length && !!t.o[o.int[0]].args && undefined!=(k=t.o[o.int[0]].args[0]) && !!t.o[k].calcop && !!t.o[k].suffixop){
delete o.suffixop;
o.suffixop = t.o[k].suffixop;
delete t.o[k].suffixop;
}
k=-1;
while(-1<--i){
if(undefined!=t.o[b[i]].intop||(undefined!=t.o[b[i]].calcop&&undefined!=t.o[t.o[b[i]].calcop].op&& t.o[t.o[t.o[b[i]].calcop].op].symbol.integral )){
if(undefined!=t.o[b[i]].calcop){
if(-1==k && !!t.o[b[i]].suffixop){
delete o.suffixop;
o.suffixop = t.o[b[i]].suffixop;
delete t.o[b[i]].suffixop;
}
k=t.o[b[i]].calcop;
}
if(undefined!=t.o[b[i]].intop){
t.o[t.o[b[i]].intop].dop = t.o[b[i]].calcopof;
o._int.unshift(t.o[b[i]].intop);
}
b.splice(i,1);
}
}
if(-1!=k && undefined!=(k=t.o[k].intop)){
if(undefined!=o._upower){
t.o[k]._upower = o._upower;
delete o._upower;
}
if(undefined!=o._usubscript){
t.o[k]._usubscript = o._usubscript;
delete o._usubscript;
}
if(undefined!=o.suffixop){
t.o[k].suffixop = o.suffixop;
delete o.suffixop;
}
}
}
if(!!o.int && undefined!=o.int[0]){
mk_appendChild(o.content, mk_cBvar(t,t.o[o.int[0]].calcopof));
}
}
}
if(!!(b=o.symbol.barge) && !!b.length){
i=-1;
k = b.length-1;
if(!o.args){
o.args = [];
}
while(k>(j=++i)){
mk_appendChild(o.content, t.cML(
('^'==b[i++].charAt(0) ? (o.args.push(undefined!=(o._power=o.power) ? mk_content(t,o.power) : t.cML(!b[i].toPrecision?'mi':'mn',b[i])), b[j].slice(1)) :
('_'==b[j].charAt(0) ? (o.args.push(undefined!=(o._subscript=o.subscript) ? mk_content(t,o.subscript) : t.cML(!b[i].toPrecision?'mi':'mn', b[i])), b[j].slice(1)) :
(o.args.push(1<o.args.length ? mk_content(t, o.args.pop()) : t.cML((!b[i].toPrecision?'mi':'mn'),b[i])), b[j]))), o.args.pop()));
}
if(0==o.args.length){
delete o.args;
}
}
if( UNDEROVER == o.symbol.type ||!!t.o[p].symbol.integral){
(!!o.suffixop && undefined!=o.power)?(mk_cAffix(t, p),mk_cSubPow(t, p)):(mk_cSubPow(t, p),mk_cAffix(t, p));
}
if(undefined == o.calcopof && !!o.args && 0<o.args.length){
j = -1;
if(undefined!=(j=o.apply) && 0<j && (b=t.o[o.args[0]]).c.length>++j){
o.farg = mk_cLambda(t, b.c.slice(j, b.c.length), 'l');
o.func = mk_cLambda(t, b.c.slice(0, --j));
i=o.farg.length;
if(0<i && null==o.farg[0]){
o.farg.shift();
--i;
}
b = [[],[]];
while(-1<--i){
b[0].push(mk_content(t, o.farg[i]).outerHTML.replace(/ xmlns="[^"]+"/ig,''));
mk_appendChild(o.content, t.cML('bvar', t.o[o.farg[i]].content));
}
i=o.func.length;
if(0<i){
if(null==o.func[0]){
o.func.shift();
--i;
while(-1<--i){
if(!!t.o[o.func[i]].mk){
t.o[o.func[i]].content = t.o[o.func[i]].mk;
b[1].unshift(o.func[i]);
}
}
if(0<b[1].length){
o.func = b[1].map(mk_acopy);
if(!!(b[1] = t.o[o.func[0]].content.querySelector('tendsto'))){
if(!!b[1].parentNode){
b[1] = b[1].parentNode;
}
if(!!b[1].parentNode){
b[1] = b[1].parentNode;
}
b[2] = b[1].innerHTML.replace(/<apply[^>]*><tendsto[^>]*>(.*)<\/apply>/ui, '<tendsto><\/tendsto>$1');
b[3] = b[2].substr(0,b[2].indexOf('<tendsto><\/tendsto>'));
b[4] = b[2].substr(b[2].indexOf('<tendsto><\/tendsto>')+19);
for(i in b[0]){
b[4] = b[4].replace(b[0][i], '');
}
try{
t.o[o.func[0]].content.innerHTML = b[3].replace(/\s*xmlns="[^"]+"/ug,'')+b[4].replace(/\s*xmlns="[^"]+"/ug,'');
}catch(e){
console.log(e);
}
t.o[o.func[0]].content = mk_unwrap(t.o[o.func[0]].content,'apply');
}
}
}else{
k = o.func[0];
if(false!==k && !!t.o[k].mk){
o.func = [k];
if(!!(k = t.o[k].mk.querySelector('tendsto'))){
t.o[o.func[0]].mk.removeChild(k);
}
t.o[o.func[0]].content = t.o[o.func[0]].mk;
t.o[o.func[0]]._p=true;
}
}
}
i=o.func.length;
while(-1<--i){
b = mk_content(t, o.func[i]);
if(!!b.outerHTML.match(/^<apply[^>]*><apply[^>]*>/i)){
b = mk_unwrap(b, 'apply');
}
mk_appendChild(o.content, b);
}
}else{
i = -1;
j=o.args.length;
o._arg = null;
while(j>++i){
b = o.args[i];
if((INFIX==t.o[b].symbol.type&&('_'==t.o[b].symbol.input||'^'==t.o[b].symbol.input))){
continue;
}
if(!!t.o[b][k='matrix'] || (!!t.o[b][k='vector'] || !!t.o[b][k='set'])){
if( ((undefined!=o.power && undefined!=t.o[b].power && o.power==t.o[b].power)&&((delete t.o[p].power),true))||!t.o[b].content || k!=mk_nodeName(t.o[b].content)){
t.o[b].content = t.cML(k, t.o[b].content);
delete t.o[b]._cAffix;
delete t.o[b]._cSubPow;
delete t.o[b]._cemSubPow;
mk_cAffix(t, b);
mk_cSubPow(t, b);
mk_cSubPow(t,b,false,'em');
}
}else{
!!t.o[b]._content ? ((t.o[b].content=t.o[b]._content),delete t.o[b]._content) : mk_content(t, b);
if(((undefined==t.o[p]._apower && undefined==t.o[p]._asubscript) && ((undefined!=o.arg?((k=o.arg),(o._arg = o.arg),(delete o.arg),1):0) || (1==j&&-1!=(k=b)))) && (UNDEROVER != o.symbol.type && !o.symbol.integral && !!t.o[k].c && undefined!=t.o[k].c[0] && RIGHTBRACKET==t.o[t.o[k].c[0]].symbol.type && (((undefined!=t.o[k].power && (undefined!=o.power || o.power!=t.o[k].power)) && ((o._apower=t.o[k].power),1) ) ^ ((undefined!=t.o[k].subscript && (undefined==o.subscript || o.subscript!=t.o[k].subscript)) && ((o._asubscript=t.o[k].subscript),0))) && (undefined!=o._apower||undefined!=o._asubscript))){
delete t.o[k]._cSubPow;
}else{
k = -1;
}
if(b!=k){
if(undefined!=o.power && undefined!=t.o[b].power && o.power==t.o[b].power){
delete t.o[b].power;
}
if(undefined!=o.subscript && undefined!=t.o[b].subscript && o.subscript==t.o[b].subscript){
delete t.o[b].power;
}
mk_cSubPow(t, b);
mk_cSubPow(t,b,false,'em');
}
}
'bvar'==mk_nodeName(t.o[b].content) ? (('apply'==mk_nodeName(o.content)&&!!o.content.firstChild)?o.content.firstChild.insertAdjacentElement('afterend', t.o[b].content.cloneNode(true)):o.content.insertAdjacentElement('afterbegin', t.o[b].content.cloneNode(true))): mk_appendChild(o.content, t.o[b]._content || t.o[b].content);
}
if(undefined!=o._arg){
o.arg = o._arg;
delete o._arg;
}
if(undefined!=o._apower||undefined!=o._asubscript){
o.power = o._apower;
o.subscript = o._subscript;
delete t.o[p]._cSubPow;
}
}
}
(!!o.suffixop && undefined!=o.power&&!o.args)?(mk_cAffix(t, p),mk_cSubPow(t, p)):(mk_cSubPow(t, p),mk_cAffix(t, p));
mk_cSubPow(t,p,false,'em');
if(!t.x[p]){
mk_cMinus(t, p);
o._cminus=true;
mk_popOp(t, p);
t.o[p].content = mk_unwrap(o.content);
}
if(!!o.symbol.integral && !!o._int && 0<(i=o._int.length)){
t.o[o._int[0]]._content = t.o[p].content;
while(-1<--i){
t.o[o._int[i]].intop = o._int[0];
}
}
return o.content;
};
var mk_cResolveDiff = function(t,a,i=null){
var content = null, j = -1, node = null, q = null, r = null;
while(a.length>++j){
r = a[j];
if(!Array.isArray(r)){
if(undefined!=t.o[r].calcopof && DIFFERENTIAL==t.o[r].symbol.type){
t.o[r]._cSubPow=true;
if(!!t.o[r].isnumerator || !!t.o[r].isdenominator){
if(undefined!=t.o[r].op && !!t.o[q = t.o[r].op].diff && !!t.o[q].diff[0] && !!t.o[q].diff[1] && null!==t.o[q].diff[0][0] && t.o[q].diff[0][0] == t.o[q].diff[1][0]){
if(!!t.o[r].neg){
!!t.o[q].neg? delete t.o[q].neg : t.o[q].neg=true;
}
if(null!=i){
t.o[t.o[t.c.op[i][j]].op].symbol.ctag = 1==t.o[q].diff[0][0].length ? 'diff' : 'partialdiff';
t.c.op[i].splice(j--,1);
}
delete t.o[q].symbol.arith;
}else{
//todo: algebra
content = t.o[r].content.cloneNode(true);
t.o[r].content = t.o[r].content.firstChild;
if(undefined!=t.o[t.o[r].calcopof].power){
t.o[r].power=t.o[t.o[r].calcopof].power;
delete t.o[r]._cSubPow;
mk_cSubPow(t,r);
}
node = t.cML('apply',t.cML('d'==t.o[r].symbol.input? 'diff' : 'partialdiff'));
mk_appendChild(node,content);
t.o[r].content = mk_appendChild(node,t.o[r].content);
}
}else if(undefined==t.o[r].op || !t.o[t.o[r].op].symbol.integral){
//todo: algebra
content = t.o[r].content.cloneNode(true);
t.o[r].content = t.o[r].content.firstChild;
if(undefined!=t.o[t.o[r].calcopof].power){
t.o[r].power=t.o[t.o[r].calcopof].power;
delete t.o[r]._cSubPow;
mk_cSubPow(t,r);
}
node = t.cML('apply',t.cML('d'==t.o[r].symbol.input? 'diff' : 'partialdiff'));
mk_appendChild(node,content);
t.o[r].content = mk_appendChild(node,t.o[r].content);
}
}
}
}
};
var mk_cChildren = function(t,p){
return !!t.o[p].c ? t.o[p].c :((1==t.o[p].args.length && !!t.o[t.o[p].args[0]].c) ? t.o[t.o[p].args[0]].c : ((undefined!=t.o[p].arg && !!t.o[t.o[p].arg].c) ? t.o[t.o[p].arg].c : [] ));
};
var mk_cText = function(t, p){
var content, i, j, k, o = t.o[p];
if(!o._text && !!o.text && Array.isArray(o.text)){
if(0<(j = o.text.length)){
content = t.cML();
k = '';
if('mi'==o.text[0].ptag){
if(o.symbol.acc){
k = '-'==o.text[0].text.charAt(0) ? ((o.text[0].text=o.text[0].text.replace('-','')),'-') : '';
o.text[0].text = k + o.symbol.output + o.text[0].text;
k = '';
}
k = o.text[0].text = o.text.map(mk_tcopy).join('');
o.text.splice(1);
j = o.text.length;
if(MULTI==o.symbol.type){
o.symbol.type = VAR;
}
}
mk_appendChild(content, t.cML(o.text[0].ptag, o.text[0].text));
if(1<j){
i = 0;
while(j>++i){
k+=o.text[i].text;
mk_appendChild(content,t.cML(o.text[i].ptag, o.text[i].text));
}
}
}
if(!!o.symbol.ctype && !!content.firstChild){
content.firstChild.setAttribute('type',o.symbol.ctype);
}
o._text = true;
!!o.symbol.output?o.text = k:o.symbol.output=k;
o.content = content;
}
};
var mk_cNeg = function(t,p,n=false){
var o = t.o[p],i,j,r;
i = undefined!=o.text && !o._text;
j = -1!='|mi|mn|munder|mover|'.indexOf(o.symbol.ptag)||DIFFERENTIAL==o.symbol.type;
r = !!o._text && !!o.text && !!o.text.firstChild;
if(!!n){
if(j && (!o.text || !o.text.charAt || '-'!=o.text.charAt(0) )){
o.symbol.output = '-'==o.symbol.output.charAt(0) ? o.symbol.output.slice(1):'-'+o.symbol.output;
}else if(i){
o.text = '-'==o.text.charAt(0) ? o.text.slice(1) : '-' + o.text;
}else if(r){
o.text.firstChild.textContent = '-'==o.text.firstChild.textContent.charAt(0) ? o.text.firstChild.textContent.slice(1) : '-' + o.text.firstChild.textContent;