mhchem.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. /* eslint-disable */
  2. /* -*- Mode: JavaScript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
  3. /* vim: set ts=2 et sw=2 tw=80: */
  4. /*************************************************************
  5. *
  6. * KaTeX mhchem.js
  7. *
  8. * This file implements a KaTeX version of mhchem version 3.3.0.
  9. * It is adapted from MathJax/extensions/TeX/mhchem.js
  10. * It differs from the MathJax version as follows:
  11. * 1. The interface is changed so that it can be called from KaTeX, not MathJax.
  12. * 2. \rlap and \llap are replaced with \mathrlap and \mathllap.
  13. * 3. Four lines of code are edited in order to use \raisebox instead of \raise.
  14. * 4. The reaction arrow code is simplified. All reaction arrows are rendered
  15. * using KaTeX extensible arrows instead of building non-extensible arrows.
  16. * 5. \tripledash vertical alignment is slightly adjusted.
  17. *
  18. * This code, as other KaTeX code, is released under the MIT license.
  19. *
  20. * /*************************************************************
  21. *
  22. * MathJax/extensions/TeX/mhchem.js
  23. *
  24. * Implements the \ce command for handling chemical formulas
  25. * from the mhchem LaTeX package.
  26. *
  27. * ---------------------------------------------------------------------
  28. *
  29. * Copyright (c) 2011-2015 The MathJax Consortium
  30. * Copyright (c) 2015-2018 Martin Hensel
  31. *
  32. * Licensed under the Apache License, Version 2.0 (the "License");
  33. * you may not use this file except in compliance with the License.
  34. * You may obtain a copy of the License at
  35. *
  36. * http://www.apache.org/licenses/LICENSE-2.0
  37. *
  38. * Unless required by applicable law or agreed to in writing, software
  39. * distributed under the License is distributed on an "AS IS" BASIS,
  40. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41. * See the License for the specific language governing permissions and
  42. * limitations under the License.
  43. */
  44. //
  45. // Coding Style
  46. // - use '' for identifiers that can by minified/uglified
  47. // - use "" for strings that need to stay untouched
  48. // version: "3.3.0" for MathJax and KaTeX
  49. // Add \ce, \pu, and \tripledash to the KaTeX macros.
  50. katex.__defineMacro("\\ce", function(context) {
  51. return chemParse(context.consumeArgs(1)[0], "ce")
  52. });
  53. katex.__defineMacro("\\pu", function(context) {
  54. return chemParse(context.consumeArgs(1)[0], "pu");
  55. });
  56. // Needed for \bond for the ~ forms
  57. // Raise by 2.56mu, not 2mu. We're raising a hyphen-minus, U+002D, not
  58. // a mathematical minus, U+2212. So we need that extra 0.56.
  59. katex.__defineMacro("\\tripledash", "{\\vphantom{-}\\raisebox{2.56mu}{$\\mkern2mu"
  60. + "\\tiny\\text{-}\\mkern1mu\\text{-}\\mkern1mu\\text{-}\\mkern2mu$}}");
  61. import katex from "katex";
  62. //
  63. // This is the main function for handing the \ce and \pu commands.
  64. // It takes the argument to \ce or \pu and returns the corresponding TeX string.
  65. //
  66. var chemParse = function (tokens, stateMachine) {
  67. // Recreate the argument string from KaTeX's array of tokens.
  68. var str = "";
  69. var expectedLoc = tokens.length && tokens[tokens.length - 1].loc.start
  70. for (var i = tokens.length - 1; i >= 0; i--) {
  71. if(tokens[i].loc.start > expectedLoc) {
  72. // context.consumeArgs has eaten a space.
  73. str += " ";
  74. expectedLoc = tokens[i].loc.start;
  75. }
  76. str += tokens[i].text;
  77. expectedLoc += tokens[i].text.length;
  78. }
  79. var tex = texify.go(mhchemParser.go(str, stateMachine));
  80. return tex;
  81. };
  82. //
  83. // Core parser for mhchem syntax (recursive)
  84. //
  85. /** @type {MhchemParser} */
  86. var mhchemParser = {
  87. //
  88. // Parses mchem \ce syntax
  89. //
  90. // Call like
  91. // go("H2O");
  92. //
  93. go: function (input, stateMachine) {
  94. if (!input) { return []; }
  95. if (stateMachine === undefined) { stateMachine = 'ce'; }
  96. var state = '0';
  97. //
  98. // String buffers for parsing:
  99. //
  100. // buffer.a == amount
  101. // buffer.o == element
  102. // buffer.b == left-side superscript
  103. // buffer.p == left-side subscript
  104. // buffer.q == right-side subscript
  105. // buffer.d == right-side superscript
  106. //
  107. // buffer.r == arrow
  108. // buffer.rdt == arrow, script above, type
  109. // buffer.rd == arrow, script above, content
  110. // buffer.rqt == arrow, script below, type
  111. // buffer.rq == arrow, script below, content
  112. //
  113. // buffer.text_
  114. // buffer.rm
  115. // etc.
  116. //
  117. // buffer.parenthesisLevel == int, starting at 0
  118. // buffer.sb == bool, space before
  119. // buffer.beginsWithBond == bool
  120. //
  121. // These letters are also used as state names.
  122. //
  123. // Other states:
  124. // 0 == begin of main part (arrow/operator unlikely)
  125. // 1 == next entity
  126. // 2 == next entity (arrow/operator unlikely)
  127. // 3 == next atom
  128. // c == macro
  129. //
  130. /** @type {Buffer} */
  131. var buffer = {};
  132. buffer['parenthesisLevel'] = 0;
  133. input = input.replace(/\n/g, " ");
  134. input = input.replace(/[\u2212\u2013\u2014\u2010]/g, "-");
  135. input = input.replace(/[\u2026]/g, "...");
  136. //
  137. // Looks through mhchemParser.transitions, to execute a matching action
  138. // (recursive)
  139. //
  140. var lastInput;
  141. var watchdog = 10;
  142. /** @type {ParserOutput[]} */
  143. var output = [];
  144. while (true) {
  145. if (lastInput !== input) {
  146. watchdog = 10;
  147. lastInput = input;
  148. } else {
  149. watchdog--;
  150. }
  151. //
  152. // Find actions in transition table
  153. //
  154. var machine = mhchemParser.stateMachines[stateMachine];
  155. var t = machine.transitions[state] || machine.transitions['*'];
  156. iterateTransitions:
  157. for (var i=0; i<t.length; i++) {
  158. var matches = mhchemParser.patterns.match_(t[i].pattern, input);
  159. if (matches) {
  160. //
  161. // Execute actions
  162. //
  163. var task = t[i].task;
  164. for (var iA=0; iA<task.action_.length; iA++) {
  165. var o;
  166. //
  167. // Find and execute action
  168. //
  169. if (machine.actions[task.action_[iA].type_]) {
  170. o = machine.actions[task.action_[iA].type_](buffer, matches.match_, task.action_[iA].option);
  171. } else if (mhchemParser.actions[task.action_[iA].type_]) {
  172. o = mhchemParser.actions[task.action_[iA].type_](buffer, matches.match_, task.action_[iA].option);
  173. } else {
  174. throw ["MhchemBugA", "mhchem bug A. Please report. (" + task.action_[iA].type_ + ")"]; // Trying to use non-existing action
  175. }
  176. //
  177. // Add output
  178. //
  179. mhchemParser.concatArray(output, o);
  180. }
  181. //
  182. // Set next state,
  183. // Shorten input,
  184. // Continue with next character
  185. // (= apply only one transition per position)
  186. //
  187. state = task.nextState || state;
  188. if (input.length > 0) {
  189. if (!task.revisit) {
  190. input = matches.remainder;
  191. }
  192. if (!task.toContinue) {
  193. break iterateTransitions;
  194. }
  195. } else {
  196. return output;
  197. }
  198. }
  199. }
  200. //
  201. // Prevent infinite loop
  202. //
  203. if (watchdog <= 0) {
  204. throw ["MhchemBugU", "mhchem bug U. Please report."]; // Unexpected character
  205. }
  206. }
  207. },
  208. concatArray: function (a, b) {
  209. if (b) {
  210. if (Array.isArray(b)) {
  211. for (var iB=0; iB<b.length; iB++) {
  212. a.push(b[iB]);
  213. }
  214. } else {
  215. a.push(b);
  216. }
  217. }
  218. },
  219. patterns: {
  220. //
  221. // Matching patterns
  222. // either regexps or function that return null or {match_:"a", remainder:"bc"}
  223. //
  224. patterns: {
  225. // property names must not look like integers ("2") for correct property traversal order, later on
  226. 'empty': /^$/,
  227. 'else': /^./,
  228. 'else2': /^./,
  229. 'space': /^\s/,
  230. 'space A': /^\s(?=[A-Z\\$])/,
  231. 'space$': /^\s$/,
  232. 'a-z': /^[a-z]/,
  233. 'x': /^x/,
  234. 'x$': /^x$/,
  235. 'i$': /^i$/,
  236. 'letters': /^(?:[a-zA-Z\u03B1-\u03C9\u0391-\u03A9?@]|(?:\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))))+/,
  237. '\\greek': /^\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))/,
  238. 'one lowercase latin letter $': /^(?:([a-z])(?:$|[^a-zA-Z]))$/,
  239. '$one lowercase latin letter$ $': /^\$(?:([a-z])(?:$|[^a-zA-Z]))\$$/,
  240. 'one lowercase greek letter $': /^(?:\$?[\u03B1-\u03C9]\$?|\$?\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega)\s*\$?)(?:\s+|\{\}|(?![a-zA-Z]))$/,
  241. 'digits': /^[0-9]+/,
  242. '-9.,9': /^[+\-]?(?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))/,
  243. '-9.,9 no missing 0': /^[+\-]?[0-9]+(?:[.,][0-9]+)?/,
  244. '(-)(9.,9)(e)(99)': function (input) {
  245. var m = input.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))?(\((?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))\))?(?:([eE]|\s*(\*|x|\\times|\u00D7)\s*10\^)([+\-]?[0-9]+|\{[+\-]?[0-9]+\}))?/);
  246. if (m && m[0]) {
  247. return { match_: m.splice(1), remainder: input.substr(m[0].length) };
  248. }
  249. return null;
  250. },
  251. '(-)(9)^(-9)': function (input) {
  252. var m = input.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+)?)\^([+\-]?[0-9]+|\{[+\-]?[0-9]+\})/);
  253. if (m && m[0]) {
  254. return { match_: m.splice(1), remainder: input.substr(m[0].length) };
  255. }
  256. return null;
  257. },
  258. 'state of aggregation $': function (input) { // ... or crystal system
  259. var a = mhchemParser.patterns.findObserveGroups(input, "", /^\([a-z]{1,3}(?=[\),])/, ")", ""); // (aq), (aq,$\infty$), (aq, sat)
  260. if (a && a.remainder.match(/^($|[\s,;\)\]\}])/)) { return a; } // AND end of 'phrase'
  261. var m = input.match(/^(?:\((?:\\ca\s?)?\$[amothc]\$\))/); // OR crystal system ($o$) (\ca$c$)
  262. if (m) {
  263. return { match_: m[0], remainder: input.substr(m[0].length) };
  264. }
  265. return null;
  266. },
  267. '_{(state of aggregation)}$': /^_\{(\([a-z]{1,3}\))\}/,
  268. '{[(': /^(?:\\\{|\[|\()/,
  269. ')]}': /^(?:\)|\]|\\\})/,
  270. ', ': /^[,;]\s*/,
  271. ',': /^[,;]/,
  272. '.': /^[.]/,
  273. '. ': /^([.\u22C5\u00B7\u2022])\s*/,
  274. '...': /^\.\.\.(?=$|[^.])/,
  275. '* ': /^([*])\s*/,
  276. '^{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "^{", "", "", "}"); },
  277. '^($...$)': function (input) { return mhchemParser.patterns.findObserveGroups(input, "^", "$", "$", ""); },
  278. '^a': /^\^([0-9]+|[^\\_])/,
  279. '^\\x{}{}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "^", /^\\[a-zA-Z]+\{/, "}", "", "", "{", "}", "", true); },
  280. '^\\x{}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "^", /^\\[a-zA-Z]+\{/, "}", ""); },
  281. '^\\x': /^\^(\\[a-zA-Z]+)\s*/,
  282. '^(-1)': /^\^(-?\d+)/,
  283. '\'': /^'/,
  284. '_{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "_{", "", "", "}"); },
  285. '_($...$)': function (input) { return mhchemParser.patterns.findObserveGroups(input, "_", "$", "$", ""); },
  286. '_9': /^_([+\-]?[0-9]+|[^\\])/,
  287. '_\\x{}{}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "_", /^\\[a-zA-Z]+\{/, "}", "", "", "{", "}", "", true); },
  288. '_\\x{}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "_", /^\\[a-zA-Z]+\{/, "}", ""); },
  289. '_\\x': /^_(\\[a-zA-Z]+)\s*/,
  290. '^_': /^(?:\^(?=_)|\_(?=\^)|[\^_]$)/,
  291. '{}': /^\{\}/,
  292. '{...}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "", "{", "}", ""); },
  293. '{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "{", "", "", "}"); },
  294. '$...$': function (input) { return mhchemParser.patterns.findObserveGroups(input, "", "$", "$", ""); },
  295. '${(...)}$': function (input) { return mhchemParser.patterns.findObserveGroups(input, "${", "", "", "}$"); },
  296. '$(...)$': function (input) { return mhchemParser.patterns.findObserveGroups(input, "$", "", "", "$"); },
  297. '=<>': /^[=<>]/,
  298. '#': /^[#\u2261]/,
  299. '+': /^\+/,
  300. '-$': /^-(?=[\s_},;\]/]|$|\([a-z]+\))/, // -space -, -; -] -/ -$ -state-of-aggregation
  301. '-9': /^-(?=[0-9])/,
  302. '- orbital overlap': /^-(?=(?:[spd]|sp)(?:$|[\s,;\)\]\}]))/,
  303. '-': /^-/,
  304. 'pm-operator': /^(?:\\pm|\$\\pm\$|\+-|\+\/-)/,
  305. 'operator': /^(?:\+|(?:[\-=<>]|<<|>>|\\approx|\$\\approx\$)(?=\s|$|-?[0-9]))/,
  306. 'arrowUpDown': /^(?:v|\(v\)|\^|\(\^\))(?=$|[\s,;\)\]\}])/,
  307. '\\bond{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\bond{", "", "", "}"); },
  308. '->': /^(?:<->|<-->|->|<-|<=>>|<<=>|<=>|[\u2192\u27F6\u21CC])/,
  309. 'CMT': /^[CMT](?=\[)/,
  310. '[(...)]': function (input) { return mhchemParser.patterns.findObserveGroups(input, "[", "", "", "]"); },
  311. '1st-level escape': /^(&|\\\\|\\hline)\s*/,
  312. '\\,': /^(?:\\[,\ ;:])/, // \\x - but output no space before
  313. '\\x{}{}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "", /^\\[a-zA-Z]+\{/, "}", "", "", "{", "}", "", true); },
  314. '\\x{}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "", /^\\[a-zA-Z]+\{/, "}", ""); },
  315. '\\ca': /^\\ca(?:\s+|(?![a-zA-Z]))/,
  316. '\\x': /^(?:\\[a-zA-Z]+\s*|\\[_&{}%])/,
  317. 'orbital': /^(?:[0-9]{1,2}[spdfgh]|[0-9]{0,2}sp)(?=$|[^a-zA-Z])/, // only those with numbers in front, because the others will be formatted correctly anyway
  318. 'others': /^[\/~|]/,
  319. '\\frac{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\frac{", "", "", "}", "{", "", "", "}"); },
  320. '\\overset{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\overset{", "", "", "}", "{", "", "", "}"); },
  321. '\\underset{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\underset{", "", "", "}", "{", "", "", "}"); },
  322. '\\underbrace{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\underbrace{", "", "", "}_", "{", "", "", "}"); },
  323. '\\color{(...)}0': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\color{", "", "", "}"); },
  324. '\\color{(...)}{(...)}1': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\color{", "", "", "}", "{", "", "", "}"); },
  325. '\\color(...){(...)}2': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\color", "\\", "", /^(?=\{)/, "{", "", "", "}"); },
  326. '\\ce{(...)}': function (input) { return mhchemParser.patterns.findObserveGroups(input, "\\ce{", "", "", "}"); },
  327. 'oxidation$': /^(?:[+-][IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,
  328. 'd-oxidation$': /^(?:[+-]?\s?[IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/, // 0 could be oxidation or charge
  329. 'roman numeral': /^[IVX]+/,
  330. '1/2$': /^[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+(?:\$[a-z]\$|[a-z])?$/,
  331. 'amount': function (input) {
  332. var match;
  333. // e.g. 2, 0.5, 1/2, -2, n/2, +; $a$ could be added later in parsing
  334. match = input.match(/^(?:(?:(?:\([+\-]?[0-9]+\/[0-9]+\)|[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+|[+\-]?[0-9]+[.,][0-9]+|[+\-]?\.[0-9]+|[+\-]?[0-9]+)(?:[a-z](?=\s*[A-Z]))?)|[+\-]?[a-z](?=\s*[A-Z])|\+(?!\s))/);
  335. if (match) {
  336. return { match_: match[0], remainder: input.substr(match[0].length) };
  337. }
  338. var a = mhchemParser.patterns.findObserveGroups(input, "", "$", "$", "");
  339. if (a) { // e.g. $2n-1$, $-$
  340. match = a.match_.match(/^\$(?:\(?[+\-]?(?:[0-9]*[a-z]?[+\-])?[0-9]*[a-z](?:[+\-][0-9]*[a-z]?)?\)?|\+|-)\$$/);
  341. if (match) {
  342. return { match_: match[0], remainder: input.substr(match[0].length) };
  343. }
  344. }
  345. return null;
  346. },
  347. 'amount2': function (input) { return this['amount'](input); },
  348. '(KV letters),': /^(?:[A-Z][a-z]{0,2}|i)(?=,)/,
  349. 'formula$': function (input) {
  350. if (input.match(/^\([a-z]+\)$/)) { return null; } // state of aggregation = no formula
  351. var match = input.match(/^(?:[a-z]|(?:[0-9\ \+\-\,\.\(\)]+[a-z])+[0-9\ \+\-\,\.\(\)]*|(?:[a-z][0-9\ \+\-\,\.\(\)]+)+[a-z]?)$/);
  352. if (match) {
  353. return { match_: match[0], remainder: input.substr(match[0].length) };
  354. }
  355. return null;
  356. },
  357. 'uprightEntities': /^(?:pH|pOH|pC|pK|iPr|iBu)(?=$|[^a-zA-Z])/,
  358. '/': /^\s*(\/)\s*/,
  359. '//': /^\s*(\/\/)\s*/,
  360. '*': /^\s*[*.]\s*/
  361. },
  362. findObserveGroups: function (input, begExcl, begIncl, endIncl, endExcl, beg2Excl, beg2Incl, end2Incl, end2Excl, combine) {
  363. /** @type {{(input: string, pattern: string | RegExp): string | string[] | null;}} */
  364. var _match = function (input, pattern) {
  365. if (typeof pattern === "string") {
  366. if (input.indexOf(pattern) !== 0) { return null; }
  367. return pattern;
  368. } else {
  369. var match = input.match(pattern);
  370. if (!match) { return null; }
  371. return match[0];
  372. }
  373. };
  374. /** @type {{(input: string, i: number, endChars: string | RegExp): {endMatchBegin: number, endMatchEnd: number} | null;}} */
  375. var _findObserveGroups = function (input, i, endChars) {
  376. var braces = 0;
  377. while (i < input.length) {
  378. var a = input.charAt(i);
  379. var match = _match(input.substr(i), endChars);
  380. if (match !== null && braces === 0) {
  381. return { endMatchBegin: i, endMatchEnd: i + match.length };
  382. } else if (a === "{") {
  383. braces++;
  384. } else if (a === "}") {
  385. if (braces === 0) {
  386. throw ["ExtraCloseMissingOpen", "Extra close brace or missing open brace"];
  387. } else {
  388. braces--;
  389. }
  390. }
  391. i++;
  392. }
  393. if (braces > 0) {
  394. return null;
  395. }
  396. return null;
  397. };
  398. var match = _match(input, begExcl);
  399. if (match === null) { return null; }
  400. input = input.substr(match.length);
  401. match = _match(input, begIncl);
  402. if (match === null) { return null; }
  403. var e = _findObserveGroups(input, match.length, endIncl || endExcl);
  404. if (e === null) { return null; }
  405. var match1 = input.substring(0, (endIncl ? e.endMatchEnd : e.endMatchBegin));
  406. if (!(beg2Excl || beg2Incl)) {
  407. return {
  408. match_: match1,
  409. remainder: input.substr(e.endMatchEnd)
  410. };
  411. } else {
  412. var group2 = this.findObserveGroups(input.substr(e.endMatchEnd), beg2Excl, beg2Incl, end2Incl, end2Excl);
  413. if (group2 === null) { return null; }
  414. /** @type {string[]} */
  415. var matchRet = [match1, group2.match_];
  416. return {
  417. match_: (combine ? matchRet.join("") : matchRet),
  418. remainder: group2.remainder
  419. };
  420. }
  421. },
  422. //
  423. // Matching function
  424. // e.g. match("a", input) will look for the regexp called "a" and see if it matches
  425. // returns null or {match_:"a", remainder:"bc"}
  426. //
  427. match_: function (m, input) {
  428. var pattern = mhchemParser.patterns.patterns[m];
  429. if (pattern === undefined) {
  430. throw ["MhchemBugP", "mhchem bug P. Please report. (" + m + ")"]; // Trying to use non-existing pattern
  431. } else if (typeof pattern === "function") {
  432. return mhchemParser.patterns.patterns[m](input); // cannot use cached var pattern here, because some pattern functions need this===mhchemParser
  433. } else { // RegExp
  434. var match = input.match(pattern);
  435. if (match) {
  436. var mm;
  437. if (match[2]) {
  438. mm = [ match[1], match[2] ];
  439. } else if (match[1]) {
  440. mm = match[1];
  441. } else {
  442. mm = match[0];
  443. }
  444. return { match_: mm, remainder: input.substr(match[0].length) };
  445. }
  446. return null;
  447. }
  448. }
  449. },
  450. //
  451. // Generic state machine actions
  452. //
  453. actions: {
  454. 'a=': function (buffer, m) { buffer.a = (buffer.a || "") + m; },
  455. 'b=': function (buffer, m) { buffer.b = (buffer.b || "") + m; },
  456. 'p=': function (buffer, m) { buffer.p = (buffer.p || "") + m; },
  457. 'o=': function (buffer, m) { buffer.o = (buffer.o || "") + m; },
  458. 'q=': function (buffer, m) { buffer.q = (buffer.q || "") + m; },
  459. 'd=': function (buffer, m) { buffer.d = (buffer.d || "") + m; },
  460. 'rm=': function (buffer, m) { buffer.rm = (buffer.rm || "") + m; },
  461. 'text=': function (buffer, m) { buffer.text_ = (buffer.text_ || "") + m; },
  462. 'insert': function (buffer, m, a) { return { type_: a }; },
  463. 'insert+p1': function (buffer, m, a) { return { type_: a, p1: m }; },
  464. 'insert+p1+p2': function (buffer, m, a) { return { type_: a, p1: m[0], p2: m[1] }; },
  465. 'copy': function (buffer, m) { return m; },
  466. 'rm': function (buffer, m) { return { type_: 'rm', p1: m || ""}; },
  467. 'text': function (buffer, m) { return mhchemParser.go(m, 'text'); },
  468. '{text}': function (buffer, m) {
  469. var ret = [ "{" ];
  470. mhchemParser.concatArray(ret, mhchemParser.go(m, 'text'));
  471. ret.push("}");
  472. return ret;
  473. },
  474. 'tex-math': function (buffer, m) { return mhchemParser.go(m, 'tex-math'); },
  475. 'tex-math tight': function (buffer, m) { return mhchemParser.go(m, 'tex-math tight'); },
  476. 'bond': function (buffer, m, k) { return { type_: 'bond', kind_: k || m }; },
  477. 'color0-output': function (buffer, m) { return { type_: 'color0', color: m[0] }; },
  478. 'ce': function (buffer, m) { return mhchemParser.go(m); },
  479. '1/2': function (buffer, m) {
  480. /** @type {ParserOutput[]} */
  481. var ret = [];
  482. if (m.match(/^[+\-]/)) {
  483. ret.push(m.substr(0, 1));
  484. m = m.substr(1);
  485. }
  486. var n = m.match(/^([0-9]+|\$[a-z]\$|[a-z])\/([0-9]+)(\$[a-z]\$|[a-z])?$/);
  487. n[1] = n[1].replace(/\$/g, "");
  488. ret.push({ type_: 'frac', p1: n[1], p2: n[2] });
  489. if (n[3]) {
  490. n[3] = n[3].replace(/\$/g, "");
  491. ret.push({ type_: 'tex-math', p1: n[3] });
  492. }
  493. return ret;
  494. },
  495. '9,9': function (buffer, m) { return mhchemParser.go(m, '9,9'); }
  496. },
  497. //
  498. // createTransitions
  499. // convert { 'letter': { 'state': { action_: 'output' } } } to { 'state' => [ { pattern: 'letter', task: { action_: [{type_: 'output'}] } } ] }
  500. // with expansion of 'a|b' to 'a' and 'b' (at 2 places)
  501. //
  502. createTransitions: function (o) {
  503. var pattern, state;
  504. /** @type {string[]} */
  505. var stateArray;
  506. var i;
  507. //
  508. // 1. Collect all states
  509. //
  510. /** @type {Transitions} */
  511. var transitions = {};
  512. for (pattern in o) {
  513. for (state in o[pattern]) {
  514. stateArray = state.split("|");
  515. o[pattern][state].stateArray = stateArray;
  516. for (i=0; i<stateArray.length; i++) {
  517. transitions[stateArray[i]] = [];
  518. }
  519. }
  520. }
  521. //
  522. // 2. Fill states
  523. //
  524. for (pattern in o) {
  525. for (state in o[pattern]) {
  526. stateArray = o[pattern][state].stateArray || [];
  527. for (i=0; i<stateArray.length; i++) {
  528. //
  529. // 2a. Normalize actions into array: 'text=' ==> [{type_:'text='}]
  530. // (Note to myself: Resolving the function here would be problematic. It would need .bind (for *this*) and currying (for *option*).)
  531. //
  532. /** @type {any} */
  533. var p = o[pattern][state];
  534. if (p.action_) {
  535. p.action_ = [].concat(p.action_);
  536. for (var k=0; k<p.action_.length; k++) {
  537. if (typeof p.action_[k] === "string") {
  538. p.action_[k] = { type_: p.action_[k] };
  539. }
  540. }
  541. } else {
  542. p.action_ = [];
  543. }
  544. //
  545. // 2.b Multi-insert
  546. //
  547. var patternArray = pattern.split("|");
  548. for (var j=0; j<patternArray.length; j++) {
  549. if (stateArray[i] === '*') { // insert into all
  550. for (var t in transitions) {
  551. transitions[t].push({ pattern: patternArray[j], task: p });
  552. }
  553. } else {
  554. transitions[stateArray[i]].push({ pattern: patternArray[j], task: p });
  555. }
  556. }
  557. }
  558. }
  559. }
  560. return transitions;
  561. },
  562. stateMachines: {}
  563. };
  564. //
  565. // Definition of state machines
  566. //
  567. mhchemParser.stateMachines = {
  568. //
  569. // \ce state machines
  570. //
  571. //#region ce
  572. 'ce': { // main parser
  573. transitions: mhchemParser.createTransitions({
  574. 'empty': {
  575. '*': { action_: 'output' } },
  576. 'else': {
  577. '0|1|2': { action_: 'beginsWithBond=false', revisit: true, toContinue: true } },
  578. 'oxidation$': {
  579. '0': { action_: 'oxidation-output' } },
  580. 'CMT': {
  581. 'r': { action_: 'rdt=', nextState: 'rt' },
  582. 'rd': { action_: 'rqt=', nextState: 'rdt' } },
  583. 'arrowUpDown': {
  584. '0|1|2|as': { action_: [ 'sb=false', 'output', 'operator' ], nextState: '1' } },
  585. 'uprightEntities': {
  586. '0|1|2': { action_: [ 'o=', 'output' ], nextState: '1' } },
  587. 'orbital': {
  588. '0|1|2|3': { action_: 'o=', nextState: 'o' } },
  589. '->': {
  590. '0|1|2|3': { action_: 'r=', nextState: 'r' },
  591. 'a|as': { action_: [ 'output', 'r=' ], nextState: 'r' },
  592. '*': { action_: [ 'output', 'r=' ], nextState: 'r' } },
  593. '+': {
  594. 'o': { action_: 'd= kv', nextState: 'd' },
  595. 'd|D': { action_: 'd=', nextState: 'd' },
  596. 'q': { action_: 'd=', nextState: 'qd' },
  597. 'qd|qD': { action_: 'd=', nextState: 'qd' },
  598. 'dq': { action_: [ 'output', 'd=' ], nextState: 'd' },
  599. '3': { action_: [ 'sb=false', 'output', 'operator' ], nextState: '0' } },
  600. 'amount': {
  601. '0|2': { action_: 'a=', nextState: 'a' } },
  602. 'pm-operator': {
  603. '0|1|2|a|as': { action_: [ 'sb=false', 'output', { type_: 'operator', option: '\\pm' } ], nextState: '0' } },
  604. 'operator': {
  605. '0|1|2|a|as': { action_: [ 'sb=false', 'output', 'operator' ], nextState: '0' } },
  606. '-$': {
  607. 'o|q': { action_: [ 'charge or bond', 'output' ], nextState: 'qd' },
  608. 'd': { action_: 'd=', nextState: 'd' },
  609. 'D': { action_: [ 'output', { type_: 'bond', option: "-" } ], nextState: '3' },
  610. 'q': { action_: 'd=', nextState: 'qd' },
  611. 'qd': { action_: 'd=', nextState: 'qd' },
  612. 'qD|dq': { action_: [ 'output', { type_: 'bond', option: "-" } ], nextState: '3' } },
  613. '-9': {
  614. '3|o': { action_: [ 'output', { type_: 'insert', option: 'hyphen' } ], nextState: '3' } },
  615. '- orbital overlap': {
  616. 'o': { action_: [ 'output', { type_: 'insert', option: 'hyphen' } ], nextState: '2' },
  617. 'd': { action_: [ 'output', { type_: 'insert', option: 'hyphen' } ], nextState: '2' } },
  618. '-': {
  619. '0|1|2': { action_: [ { type_: 'output', option: 1 }, 'beginsWithBond=true', { type_: 'bond', option: "-" } ], nextState: '3' },
  620. '3': { action_: { type_: 'bond', option: "-" } },
  621. 'a': { action_: [ 'output', { type_: 'insert', option: 'hyphen' } ], nextState: '2' },
  622. 'as': { action_: [ { type_: 'output', option: 2 }, { type_: 'bond', option: "-" } ], nextState: '3' },
  623. 'b': { action_: 'b=' },
  624. 'o': { action_: { type_: '- after o/d', option: false }, nextState: '2' },
  625. 'q': { action_: { type_: '- after o/d', option: false }, nextState: '2' },
  626. 'd|qd|dq': { action_: { type_: '- after o/d', option: true }, nextState: '2' },
  627. 'D|qD|p': { action_: [ 'output', { type_: 'bond', option: "-" } ], nextState: '3' } },
  628. 'amount2': {
  629. '1|3': { action_: 'a=', nextState: 'a' } },
  630. 'letters': {
  631. '0|1|2|3|a|as|b|p|bp|o': { action_: 'o=', nextState: 'o' },
  632. 'q|dq': { action_: ['output', 'o='], nextState: 'o' },
  633. 'd|D|qd|qD': { action_: 'o after d', nextState: 'o' } },
  634. 'digits': {
  635. 'o': { action_: 'q=', nextState: 'q' },
  636. 'd|D': { action_: 'q=', nextState: 'dq' },
  637. 'q': { action_: [ 'output', 'o=' ], nextState: 'o' },
  638. 'a': { action_: 'o=', nextState: 'o' } },
  639. 'space A': {
  640. 'b|p|bp': {} },
  641. 'space': {
  642. 'a': { nextState: 'as' },
  643. '0': { action_: 'sb=false' },
  644. '1|2': { action_: 'sb=true' },
  645. 'r|rt|rd|rdt|rdq': { action_: 'output', nextState: '0' },
  646. '*': { action_: [ 'output', 'sb=true' ], nextState: '1'} },
  647. '1st-level escape': {
  648. '1|2': { action_: [ 'output', { type_: 'insert+p1', option: '1st-level escape' } ] },
  649. '*': { action_: [ 'output', { type_: 'insert+p1', option: '1st-level escape' } ], nextState: '0' } },
  650. '[(...)]': {
  651. 'r|rt': { action_: 'rd=', nextState: 'rd' },
  652. 'rd|rdt': { action_: 'rq=', nextState: 'rdq' } },
  653. '...': {
  654. 'o|d|D|dq|qd|qD': { action_: [ 'output', { type_: 'bond', option: "..." } ], nextState: '3' },
  655. '*': { action_: [ { type_: 'output', option: 1 }, { type_: 'insert', option: 'ellipsis' } ], nextState: '1' } },
  656. '. |* ': {
  657. '*': { action_: [ 'output', { type_: 'insert', option: 'addition compound' } ], nextState: '1' } },
  658. 'state of aggregation $': {
  659. '*': { action_: [ 'output', 'state of aggregation' ], nextState: '1' } },
  660. '{[(': {
  661. 'a|as|o': { action_: [ 'o=', 'output', 'parenthesisLevel++' ], nextState: '2' },
  662. '0|1|2|3': { action_: [ 'o=', 'output', 'parenthesisLevel++' ], nextState: '2' },
  663. '*': { action_: [ 'output', 'o=', 'output', 'parenthesisLevel++' ], nextState: '2' } },
  664. ')]}': {
  665. '0|1|2|3|b|p|bp|o': { action_: [ 'o=', 'parenthesisLevel--' ], nextState: 'o' },
  666. 'a|as|d|D|q|qd|qD|dq': { action_: [ 'output', 'o=', 'parenthesisLevel--' ], nextState: 'o' } },
  667. ', ': {
  668. '*': { action_: [ 'output', 'comma' ], nextState: '0' } },
  669. '^_': { // ^ and _ without a sensible argument
  670. '*': { } },
  671. '^{(...)}|^($...$)': {
  672. '0|1|2|as': { action_: 'b=', nextState: 'b' },
  673. 'p': { action_: 'b=', nextState: 'bp' },
  674. '3|o': { action_: 'd= kv', nextState: 'D' },
  675. 'q': { action_: 'd=', nextState: 'qD' },
  676. 'd|D|qd|qD|dq': { action_: [ 'output', 'd=' ], nextState: 'D' } },
  677. '^a|^\\x{}{}|^\\x{}|^\\x|\'': {
  678. '0|1|2|as': { action_: 'b=', nextState: 'b' },
  679. 'p': { action_: 'b=', nextState: 'bp' },
  680. '3|o': { action_: 'd= kv', nextState: 'd' },
  681. 'q': { action_: 'd=', nextState: 'qd' },
  682. 'd|qd|D|qD': { action_: 'd=' },
  683. 'dq': { action_: [ 'output', 'd=' ], nextState: 'd' } },
  684. '_{(state of aggregation)}$': {
  685. 'd|D|q|qd|qD|dq': { action_: [ 'output', 'q=' ], nextState: 'q' } },
  686. '_{(...)}|_($...$)|_9|_\\x{}{}|_\\x{}|_\\x': {
  687. '0|1|2|as': { action_: 'p=', nextState: 'p' },
  688. 'b': { action_: 'p=', nextState: 'bp' },
  689. '3|o': { action_: 'q=', nextState: 'q' },
  690. 'd|D': { action_: 'q=', nextState: 'dq' },
  691. 'q|qd|qD|dq': { action_: [ 'output', 'q=' ], nextState: 'q' } },
  692. '=<>': {
  693. '0|1|2|3|a|as|o|q|d|D|qd|qD|dq': { action_: [ { type_: 'output', option: 2 }, 'bond' ], nextState: '3' } },
  694. '#': {
  695. '0|1|2|3|a|as|o': { action_: [ { type_: 'output', option: 2 }, { type_: 'bond', option: "#" } ], nextState: '3' } },
  696. '{}': {
  697. '*': { action_: { type_: 'output', option: 1 }, nextState: '1' } },
  698. '{...}': {
  699. '0|1|2|3|a|as|b|p|bp': { action_: 'o=', nextState: 'o' },
  700. 'o|d|D|q|qd|qD|dq': { action_: [ 'output', 'o=' ], nextState: 'o' } },
  701. '$...$': {
  702. 'a': { action_: 'a=' }, // 2$n$
  703. '0|1|2|3|as|b|p|bp|o': { action_: 'o=', nextState: 'o' }, // not 'amount'
  704. 'as|o': { action_: 'o=' },
  705. 'q|d|D|qd|qD|dq': { action_: [ 'output', 'o=' ], nextState: 'o' } },
  706. '\\bond{(...)}': {
  707. '*': { action_: [ { type_: 'output', option: 2 }, 'bond' ], nextState: "3" } },
  708. '\\frac{(...)}': {
  709. '*': { action_: [ { type_: 'output', option: 1 }, 'frac-output' ], nextState: '3' } },
  710. '\\overset{(...)}': {
  711. '*': { action_: [ { type_: 'output', option: 2 }, 'overset-output' ], nextState: '3' } },
  712. '\\underset{(...)}': {
  713. '*': { action_: [ { type_: 'output', option: 2 }, 'underset-output' ], nextState: '3' } },
  714. '\\underbrace{(...)}': {
  715. '*': { action_: [ { type_: 'output', option: 2 }, 'underbrace-output' ], nextState: '3' } },
  716. '\\color{(...)}{(...)}1|\\color(...){(...)}2': {
  717. '*': { action_: [ { type_: 'output', option: 2 }, 'color-output' ], nextState: '3' } },
  718. '\\color{(...)}0': {
  719. '*': { action_: [ { type_: 'output', option: 2 }, 'color0-output' ] } },
  720. '\\ce{(...)}': {
  721. '*': { action_: [ { type_: 'output', option: 2 }, 'ce' ], nextState: '3' } },
  722. '\\,': {
  723. '*': { action_: [ { type_: 'output', option: 1 }, 'copy' ], nextState: '1' } },
  724. '\\x{}{}|\\x{}|\\x': {
  725. '0|1|2|3|a|as|b|p|bp|o|c0': { action_: [ 'o=', 'output' ], nextState: '3' },
  726. '*': { action_: ['output', 'o=', 'output' ], nextState: '3' } },
  727. 'others': {
  728. '*': { action_: [ { type_: 'output', option: 1 }, 'copy' ], nextState: '3' } },
  729. 'else2': {
  730. 'a': { action_: 'a to o', nextState: 'o', revisit: true },
  731. 'as': { action_: [ 'output', 'sb=true' ], nextState: '1', revisit: true },
  732. 'r|rt|rd|rdt|rdq': { action_: [ 'output' ], nextState: '0', revisit: true },
  733. '*': { action_: [ 'output', 'copy' ], nextState: '3' } }
  734. }),
  735. actions: {
  736. 'o after d': function (buffer, m) {
  737. var ret;
  738. if ((buffer.d || "").match(/^[0-9]+$/)) {
  739. var tmp = buffer.d;
  740. buffer.d = undefined;
  741. ret = this['output'](buffer);
  742. buffer.b = tmp;
  743. } else {
  744. ret = this['output'](buffer);
  745. }
  746. mhchemParser.actions['o='](buffer, m);
  747. return ret;
  748. },
  749. 'd= kv': function (buffer, m) {
  750. buffer.d = m;
  751. buffer.dType = 'kv';
  752. },
  753. 'charge or bond': function (buffer, m) {
  754. if (buffer['beginsWithBond']) {
  755. /** @type {ParserOutput[]} */
  756. var ret = [];
  757. mhchemParser.concatArray(ret, this['output'](buffer));
  758. mhchemParser.concatArray(ret, mhchemParser.actions['bond'](buffer, m, "-"));
  759. return ret;
  760. } else {
  761. buffer.d = m;
  762. }
  763. },
  764. '- after o/d': function (buffer, m, isAfterD) {
  765. var c1 = mhchemParser.patterns.match_('orbital', buffer.o || "");
  766. var c2 = mhchemParser.patterns.match_('one lowercase greek letter $', buffer.o || "");
  767. var c3 = mhchemParser.patterns.match_('one lowercase latin letter $', buffer.o || "");
  768. var c4 = mhchemParser.patterns.match_('$one lowercase latin letter$ $', buffer.o || "");
  769. var hyphenFollows = m==="-" && ( c1 && c1.remainder==="" || c2 || c3 || c4 );
  770. if (hyphenFollows && !buffer.a && !buffer.b && !buffer.p && !buffer.d && !buffer.q && !c1 && c3) {
  771. buffer.o = '$' + buffer.o + '$';
  772. }
  773. /** @type {ParserOutput[]} */
  774. var ret = [];
  775. if (hyphenFollows) {
  776. mhchemParser.concatArray(ret, this['output'](buffer));
  777. ret.push({ type_: 'hyphen' });
  778. } else {
  779. c1 = mhchemParser.patterns.match_('digits', buffer.d || "");
  780. if (isAfterD && c1 && c1.remainder==='') {
  781. mhchemParser.concatArray(ret, mhchemParser.actions['d='](buffer, m));
  782. mhchemParser.concatArray(ret, this['output'](buffer));
  783. } else {
  784. mhchemParser.concatArray(ret, this['output'](buffer));
  785. mhchemParser.concatArray(ret, mhchemParser.actions['bond'](buffer, m, "-"));
  786. }
  787. }
  788. return ret;
  789. },
  790. 'a to o': function (buffer) {
  791. buffer.o = buffer.a;
  792. buffer.a = undefined;
  793. },
  794. 'sb=true': function (buffer) { buffer.sb = true; },
  795. 'sb=false': function (buffer) { buffer.sb = false; },
  796. 'beginsWithBond=true': function (buffer) { buffer['beginsWithBond'] = true; },
  797. 'beginsWithBond=false': function (buffer) { buffer['beginsWithBond'] = false; },
  798. 'parenthesisLevel++': function (buffer) { buffer['parenthesisLevel']++; },
  799. 'parenthesisLevel--': function (buffer) { buffer['parenthesisLevel']--; },
  800. 'state of aggregation': function (buffer, m) {
  801. return { type_: 'state of aggregation', p1: mhchemParser.go(m, 'o') };
  802. },
  803. 'comma': function (buffer, m) {
  804. var a = m.replace(/\s*$/, '');
  805. var withSpace = (a !== m);
  806. if (withSpace && buffer['parenthesisLevel'] === 0) {
  807. return { type_: 'comma enumeration L', p1: a };
  808. } else {
  809. return { type_: 'comma enumeration M', p1: a };
  810. }
  811. },
  812. 'output': function (buffer, m, entityFollows) {
  813. // entityFollows:
  814. // undefined = if we have nothing else to output, also ignore the just read space (buffer.sb)
  815. // 1 = an entity follows, never omit the space if there was one just read before (can only apply to state 1)
  816. // 2 = 1 + the entity can have an amount, so output a\, instead of converting it to o (can only apply to states a|as)
  817. /** @type {ParserOutput | ParserOutput[]} */
  818. var ret;
  819. if (!buffer.r) {
  820. ret = [];
  821. if (!buffer.a && !buffer.b && !buffer.p && !buffer.o && !buffer.q && !buffer.d && !entityFollows) {
  822. //ret = [];
  823. } else {
  824. if (buffer.sb) {
  825. ret.push({ type_: 'entitySkip' });
  826. }
  827. if (!buffer.o && !buffer.q && !buffer.d && !buffer.b && !buffer.p && entityFollows!==2) {
  828. buffer.o = buffer.a;
  829. buffer.a = undefined;
  830. } else if (!buffer.o && !buffer.q && !buffer.d && (buffer.b || buffer.p)) {
  831. buffer.o = buffer.a;
  832. buffer.d = buffer.b;
  833. buffer.q = buffer.p;
  834. buffer.a = buffer.b = buffer.p = undefined;
  835. } else {
  836. if (buffer.o && buffer.dType==='kv' && mhchemParser.patterns.match_('d-oxidation$', buffer.d || "")) {
  837. buffer.dType = 'oxidation';
  838. } else if (buffer.o && buffer.dType==='kv' && !buffer.q) {
  839. buffer.dType = undefined;
  840. }
  841. }
  842. ret.push({
  843. type_: 'chemfive',
  844. a: mhchemParser.go(buffer.a, 'a'),
  845. b: mhchemParser.go(buffer.b, 'bd'),
  846. p: mhchemParser.go(buffer.p, 'pq'),
  847. o: mhchemParser.go(buffer.o, 'o'),
  848. q: mhchemParser.go(buffer.q, 'pq'),
  849. d: mhchemParser.go(buffer.d, (buffer.dType === 'oxidation' ? 'oxidation' : 'bd')),
  850. dType: buffer.dType
  851. });
  852. }
  853. } else { // r
  854. /** @type {ParserOutput[]} */
  855. var rd;
  856. if (buffer.rdt === 'M') {
  857. rd = mhchemParser.go(buffer.rd, 'tex-math');
  858. } else if (buffer.rdt === 'T') {
  859. rd = [ { type_: 'text', p1: buffer.rd || "" } ];
  860. } else {
  861. rd = mhchemParser.go(buffer.rd);
  862. }
  863. /** @type {ParserOutput[]} */
  864. var rq;
  865. if (buffer.rqt === 'M') {
  866. rq = mhchemParser.go(buffer.rq, 'tex-math');
  867. } else if (buffer.rqt === 'T') {
  868. rq = [ { type_: 'text', p1: buffer.rq || ""} ];
  869. } else {
  870. rq = mhchemParser.go(buffer.rq);
  871. }
  872. ret = {
  873. type_: 'arrow',
  874. r: buffer.r,
  875. rd: rd,
  876. rq: rq
  877. };
  878. }
  879. for (var p in buffer) {
  880. if (p !== 'parenthesisLevel' && p !== 'beginsWithBond') {
  881. delete buffer[p];
  882. }
  883. }
  884. return ret;
  885. },
  886. 'oxidation-output': function (buffer, m) {
  887. var ret = [ "{" ];
  888. mhchemParser.concatArray(ret, mhchemParser.go(m, 'oxidation'));
  889. ret.push("}");
  890. return ret;
  891. },
  892. 'frac-output': function (buffer, m) {
  893. return { type_: 'frac-ce', p1: mhchemParser.go(m[0]), p2: mhchemParser.go(m[1]) };
  894. },
  895. 'overset-output': function (buffer, m) {
  896. return { type_: 'overset', p1: mhchemParser.go(m[0]), p2: mhchemParser.go(m[1]) };
  897. },
  898. 'underset-output': function (buffer, m) {
  899. return { type_: 'underset', p1: mhchemParser.go(m[0]), p2: mhchemParser.go(m[1]) };
  900. },
  901. 'underbrace-output': function (buffer, m) {
  902. return { type_: 'underbrace', p1: mhchemParser.go(m[0]), p2: mhchemParser.go(m[1]) };
  903. },
  904. 'color-output': function (buffer, m) {
  905. return { type_: 'color', color1: m[0], color2: mhchemParser.go(m[1]) };
  906. },
  907. 'r=': function (buffer, m) { buffer.r = m; },
  908. 'rdt=': function (buffer, m) { buffer.rdt = m; },
  909. 'rd=': function (buffer, m) { buffer.rd = m; },
  910. 'rqt=': function (buffer, m) { buffer.rqt = m; },
  911. 'rq=': function (buffer, m) { buffer.rq = m; },
  912. 'operator': function (buffer, m, p1) { return { type_: 'operator', kind_: (p1 || m) }; }
  913. }
  914. },
  915. 'a': {
  916. transitions: mhchemParser.createTransitions({
  917. 'empty': {
  918. '*': {} },
  919. '1/2$': {
  920. '0': { action_: '1/2' } },
  921. 'else': {
  922. '0': { nextState: '1', revisit: true } },
  923. '$(...)$': {
  924. '*': { action_: 'tex-math tight', nextState: '1' } },
  925. ',': {
  926. '*': { action_: { type_: 'insert', option: 'commaDecimal' } } },
  927. 'else2': {
  928. '*': { action_: 'copy' } }
  929. }),
  930. actions: {}
  931. },
  932. 'o': {
  933. transitions: mhchemParser.createTransitions({
  934. 'empty': {
  935. '*': {} },
  936. '1/2$': {
  937. '0': { action_: '1/2' } },
  938. 'else': {
  939. '0': { nextState: '1', revisit: true } },
  940. 'letters': {
  941. '*': { action_: 'rm' } },
  942. '\\ca': {
  943. '*': { action_: { type_: 'insert', option: 'circa' } } },
  944. '\\x{}{}|\\x{}|\\x': {
  945. '*': { action_: 'copy' } },
  946. '${(...)}$|$(...)$': {
  947. '*': { action_: 'tex-math' } },
  948. '{(...)}': {
  949. '*': { action_: '{text}' } },
  950. 'else2': {
  951. '*': { action_: 'copy' } }
  952. }),
  953. actions: {}
  954. },
  955. 'text': {
  956. transitions: mhchemParser.createTransitions({
  957. 'empty': {
  958. '*': { action_: 'output' } },
  959. '{...}': {
  960. '*': { action_: 'text=' } },
  961. '${(...)}$|$(...)$': {
  962. '*': { action_: 'tex-math' } },
  963. '\\greek': {
  964. '*': { action_: [ 'output', 'rm' ] } },
  965. '\\,|\\x{}{}|\\x{}|\\x': {
  966. '*': { action_: [ 'output', 'copy' ] } },
  967. 'else': {
  968. '*': { action_: 'text=' } }
  969. }),
  970. actions: {
  971. 'output': function (buffer) {
  972. if (buffer.text_) {
  973. /** @type {ParserOutput} */
  974. var ret = { type_: 'text', p1: buffer.text_ };
  975. for (var p in buffer) { delete buffer[p]; }
  976. return ret;
  977. }
  978. }
  979. }
  980. },
  981. 'pq': {
  982. transitions: mhchemParser.createTransitions({
  983. 'empty': {
  984. '*': {} },
  985. 'state of aggregation $': {
  986. '*': { action_: 'state of aggregation' } },
  987. 'i$': {
  988. '0': { nextState: '!f', revisit: true } },
  989. '(KV letters),': {
  990. '0': { action_: 'rm', nextState: '0' } },
  991. 'formula$': {
  992. '0': { nextState: 'f', revisit: true } },
  993. '1/2$': {
  994. '0': { action_: '1/2' } },
  995. 'else': {
  996. '0': { nextState: '!f', revisit: true } },
  997. '${(...)}$|$(...)$': {
  998. '*': { action_: 'tex-math' } },
  999. '{(...)}': {
  1000. '*': { action_: 'text' } },
  1001. 'a-z': {
  1002. 'f': { action_: 'tex-math' } },
  1003. 'letters': {
  1004. '*': { action_: 'rm' } },
  1005. '-9.,9': {
  1006. '*': { action_: '9,9' } },
  1007. ',': {
  1008. '*': { action_: { type_: 'insert+p1', option: 'comma enumeration S' } } },
  1009. '\\color{(...)}{(...)}1|\\color(...){(...)}2': {
  1010. '*': { action_: 'color-output' } },
  1011. '\\color{(...)}0': {
  1012. '*': { action_: 'color0-output' } },
  1013. '\\ce{(...)}': {
  1014. '*': { action_: 'ce' } },
  1015. '\\,|\\x{}{}|\\x{}|\\x': {
  1016. '*': { action_: 'copy' } },
  1017. 'else2': {
  1018. '*': { action_: 'copy' } }
  1019. }),
  1020. actions: {
  1021. 'state of aggregation': function (buffer, m) {
  1022. return { type_: 'state of aggregation subscript', p1: mhchemParser.go(m, 'o') };
  1023. },
  1024. 'color-output': function (buffer, m) {
  1025. return { type_: 'color', color1: m[0], color2: mhchemParser.go(m[1], 'pq') };
  1026. }
  1027. }
  1028. },
  1029. 'bd': {
  1030. transitions: mhchemParser.createTransitions({
  1031. 'empty': {
  1032. '*': {} },
  1033. 'x$': {
  1034. '0': { nextState: '!f', revisit: true } },
  1035. 'formula$': {
  1036. '0': { nextState: 'f', revisit: true } },
  1037. 'else': {
  1038. '0': { nextState: '!f', revisit: true } },
  1039. '-9.,9 no missing 0': {
  1040. '*': { action_: '9,9' } },
  1041. '.': {
  1042. '*': { action_: { type_: 'insert', option: 'electron dot' } } },
  1043. 'a-z': {
  1044. 'f': { action_: 'tex-math' } },
  1045. 'x': {
  1046. '*': { action_: { type_: 'insert', option: 'KV x' } } },
  1047. 'letters': {
  1048. '*': { action_: 'rm' } },
  1049. '\'': {
  1050. '*': { action_: { type_: 'insert', option: 'prime' } } },
  1051. '${(...)}$|$(...)$': {
  1052. '*': { action_: 'tex-math' } },
  1053. '{(...)}': {
  1054. '*': { action_: 'text' } },
  1055. '\\color{(...)}{(...)}1|\\color(...){(...)}2': {
  1056. '*': { action_: 'color-output' } },
  1057. '\\color{(...)}0': {
  1058. '*': { action_: 'color0-output' } },
  1059. '\\ce{(...)}': {
  1060. '*': { action_: 'ce' } },
  1061. '\\,|\\x{}{}|\\x{}|\\x': {
  1062. '*': { action_: 'copy' } },
  1063. 'else2': {
  1064. '*': { action_: 'copy' } }
  1065. }),
  1066. actions: {
  1067. 'color-output': function (buffer, m) {
  1068. return { type_: 'color', color1: m[0], color2: mhchemParser.go(m[1], 'bd') };
  1069. }
  1070. }
  1071. },
  1072. 'oxidation': {
  1073. transitions: mhchemParser.createTransitions({
  1074. 'empty': {
  1075. '*': {} },
  1076. 'roman numeral': {
  1077. '*': { action_: 'roman-numeral' } },
  1078. '${(...)}$|$(...)$': {
  1079. '*': { action_: 'tex-math' } },
  1080. 'else': {
  1081. '*': { action_: 'copy' } }
  1082. }),
  1083. actions: {
  1084. 'roman-numeral': function (buffer, m) { return { type_: 'roman numeral', p1: m || "" }; }
  1085. }
  1086. },
  1087. 'tex-math': {
  1088. transitions: mhchemParser.createTransitions({
  1089. 'empty': {
  1090. '*': { action_: 'output' } },
  1091. '\\ce{(...)}': {
  1092. '*': { action_: [ 'output', 'ce' ] } },
  1093. '{...}|\\,|\\x{}{}|\\x{}|\\x': {
  1094. '*': { action_: 'o=' } },
  1095. 'else': {
  1096. '*': { action_: 'o=' } }
  1097. }),
  1098. actions: {
  1099. 'output': function (buffer) {
  1100. if (buffer.o) {
  1101. /** @type {ParserOutput} */
  1102. var ret = { type_: 'tex-math', p1: buffer.o };
  1103. for (var p in buffer) { delete buffer[p]; }
  1104. return ret;
  1105. }
  1106. }
  1107. }
  1108. },
  1109. 'tex-math tight': {
  1110. transitions: mhchemParser.createTransitions({
  1111. 'empty': {
  1112. '*': { action_: 'output' } },
  1113. '\\ce{(...)}': {
  1114. '*': { action_: [ 'output', 'ce' ] } },
  1115. '{...}|\\,|\\x{}{}|\\x{}|\\x': {
  1116. '*': { action_: 'o=' } },
  1117. '-|+': {
  1118. '*': { action_: 'tight operator' } },
  1119. 'else': {
  1120. '*': { action_: 'o=' } }
  1121. }),
  1122. actions: {
  1123. 'tight operator': function (buffer, m) { buffer.o = (buffer.o || "") + "{"+m+"}"; },
  1124. 'output': function (buffer) {
  1125. if (buffer.o) {
  1126. /** @type {ParserOutput} */
  1127. var ret = { type_: 'tex-math', p1: buffer.o };
  1128. for (var p in buffer) { delete buffer[p]; }
  1129. return ret;
  1130. }
  1131. }
  1132. }
  1133. },
  1134. '9,9': {
  1135. transitions: mhchemParser.createTransitions({
  1136. 'empty': {
  1137. '*': {} },
  1138. ',': {
  1139. '*': { action_: 'comma' } },
  1140. 'else': {
  1141. '*': { action_: 'copy' } }
  1142. }),
  1143. actions: {
  1144. 'comma': function () { return { type_: 'commaDecimal' }; }
  1145. }
  1146. },
  1147. //#endregion
  1148. //
  1149. // \pu state machines
  1150. //
  1151. //#region pu
  1152. 'pu': {
  1153. transitions: mhchemParser.createTransitions({
  1154. 'empty': {
  1155. '*': { action_: 'output' } },
  1156. 'space$': {
  1157. '*': { action_: [ 'output', 'space' ] } },
  1158. '{[(|)]}': {
  1159. '0|a': { action_: 'copy' } },
  1160. '(-)(9)^(-9)': {
  1161. '0': { action_: 'number^', nextState: 'a' } },
  1162. '(-)(9.,9)(e)(99)': {
  1163. '0': { action_: 'enumber', nextState: 'a' } },
  1164. 'space': {
  1165. '0|a': {} },
  1166. 'pm-operator': {
  1167. '0|a': { action_: { type_: 'operator', option: '\\pm' }, nextState: '0' } },
  1168. 'operator': {
  1169. '0|a': { action_: 'copy', nextState: '0' } },
  1170. '//': {
  1171. 'd': { action_: 'o=', nextState: '/' } },
  1172. '/': {
  1173. 'd': { action_: 'o=', nextState: '/' } },
  1174. '{...}|else': {
  1175. '0|d': { action_: 'd=', nextState: 'd' },
  1176. 'a': { action_: [ 'space', 'd=' ], nextState: 'd' },
  1177. '/|q': { action_: 'q=', nextState: 'q' } }
  1178. }),
  1179. actions: {
  1180. 'enumber': function (buffer, m) {
  1181. /** @type {ParserOutput[]} */
  1182. var ret = [];
  1183. if (m[0] === "+-" || m[0] === "+/-") {
  1184. ret.push("\\pm ");
  1185. } else if (m[0]) {
  1186. ret.push(m[0]);
  1187. }
  1188. if (m[1]) {
  1189. mhchemParser.concatArray(ret, mhchemParser.go(m[1], 'pu-9,9'));
  1190. if (m[2]) {
  1191. if (m[2].match(/[,.]/)) {
  1192. mhchemParser.concatArray(ret, mhchemParser.go(m[2], 'pu-9,9'));
  1193. } else {
  1194. ret.push(m[2]);
  1195. }
  1196. }
  1197. m[3] = m[4] || m[3];
  1198. if (m[3]) {
  1199. m[3] = m[3].trim();
  1200. if (m[3] === "e" || m[3].substr(0, 1) === "*") {
  1201. ret.push({ type_: 'cdot' });
  1202. } else {
  1203. ret.push({ type_: 'times' });
  1204. }
  1205. }
  1206. }
  1207. if (m[3]) {
  1208. ret.push("10^{"+m[5]+"}");
  1209. }
  1210. return ret;
  1211. },
  1212. 'number^': function (buffer, m) {
  1213. /** @type {ParserOutput[]} */
  1214. var ret = [];
  1215. if (m[0] === "+-" || m[0] === "+/-") {
  1216. ret.push("\\pm ");
  1217. } else if (m[0]) {
  1218. ret.push(m[0]);
  1219. }
  1220. mhchemParser.concatArray(ret, mhchemParser.go(m[1], 'pu-9,9'));
  1221. ret.push("^{"+m[2]+"}");
  1222. return ret;
  1223. },
  1224. 'operator': function (buffer, m, p1) { return { type_: 'operator', kind_: (p1 || m) }; },
  1225. 'space': function () { return { type_: 'pu-space-1' }; },
  1226. 'output': function (buffer) {
  1227. /** @type {ParserOutput | ParserOutput[]} */
  1228. var ret;
  1229. var md = mhchemParser.patterns.match_('{(...)}', buffer.d || "");
  1230. if (md && md.remainder === '') { buffer.d = md.match_; }
  1231. var mq = mhchemParser.patterns.match_('{(...)}', buffer.q || "");
  1232. if (mq && mq.remainder === '') { buffer.q = mq.match_; }
  1233. if (buffer.d) {
  1234. buffer.d = buffer.d.replace(/\u00B0C|\^oC|\^{o}C/g, "{}^{\\circ}C");
  1235. buffer.d = buffer.d.replace(/\u00B0F|\^oF|\^{o}F/g, "{}^{\\circ}F");
  1236. }
  1237. if (buffer.q) { // fraction
  1238. buffer.q = buffer.q.replace(/\u00B0C|\^oC|\^{o}C/g, "{}^{\\circ}C");
  1239. buffer.q = buffer.q.replace(/\u00B0F|\^oF|\^{o}F/g, "{}^{\\circ}F");
  1240. var b5 = {
  1241. d: mhchemParser.go(buffer.d, 'pu'),
  1242. q: mhchemParser.go(buffer.q, 'pu')
  1243. };
  1244. if (buffer.o === '//') {
  1245. ret = { type_: 'pu-frac', p1: b5.d, p2: b5.q };
  1246. } else {
  1247. ret = b5.d;
  1248. if (b5.d.length > 1 || b5.q.length > 1) {
  1249. ret.push({ type_: ' / ' });
  1250. } else {
  1251. ret.push({ type_: '/' });
  1252. }
  1253. mhchemParser.concatArray(ret, b5.q);
  1254. }
  1255. } else { // no fraction
  1256. ret = mhchemParser.go(buffer.d, 'pu-2');
  1257. }
  1258. for (var p in buffer) { delete buffer[p]; }
  1259. return ret;
  1260. }
  1261. }
  1262. },
  1263. 'pu-2': {
  1264. transitions: mhchemParser.createTransitions({
  1265. 'empty': {
  1266. '*': { action_: 'output' } },
  1267. '*': {
  1268. '*': { action_: [ 'output', 'cdot' ], nextState: '0' } },
  1269. '\\x': {
  1270. '*': { action_: 'rm=' } },
  1271. 'space': {
  1272. '*': { action_: [ 'output', 'space' ], nextState: '0' } },
  1273. '^{(...)}|^(-1)': {
  1274. '1': { action_: '^(-1)' } },
  1275. '-9.,9': {
  1276. '0': { action_: 'rm=', nextState: '0' },
  1277. '1': { action_: '^(-1)', nextState: '0' } },
  1278. '{...}|else': {
  1279. '*': { action_: 'rm=', nextState: '1' } }
  1280. }),
  1281. actions: {
  1282. 'cdot': function () { return { type_: 'tight cdot' }; },
  1283. '^(-1)': function (buffer, m) { buffer.rm += "^{"+m+"}"; },
  1284. 'space': function () { return { type_: 'pu-space-2' }; },
  1285. 'output': function (buffer) {
  1286. /** @type {ParserOutput | ParserOutput[]} */
  1287. var ret = [];
  1288. if (buffer.rm) {
  1289. var mrm = mhchemParser.patterns.match_('{(...)}', buffer.rm || "");
  1290. if (mrm && mrm.remainder === '') {
  1291. ret = mhchemParser.go(mrm.match_, 'pu');
  1292. } else {
  1293. ret = { type_: 'rm', p1: buffer.rm };
  1294. }
  1295. }
  1296. for (var p in buffer) { delete buffer[p]; }
  1297. return ret;
  1298. }
  1299. }
  1300. },
  1301. 'pu-9,9': {
  1302. transitions: mhchemParser.createTransitions({
  1303. 'empty': {
  1304. '0': { action_: 'output-0' },
  1305. 'o': { action_: 'output-o' } },
  1306. ',': {
  1307. '0': { action_: [ 'output-0', 'comma' ], nextState: 'o' } },
  1308. '.': {
  1309. '0': { action_: [ 'output-0', 'copy' ], nextState: 'o' } },
  1310. 'else': {
  1311. '*': { action_: 'text=' } }
  1312. }),
  1313. actions: {
  1314. 'comma': function () { return { type_: 'commaDecimal' }; },
  1315. 'output-0': function (buffer) {
  1316. /** @type {ParserOutput[]} */
  1317. var ret = [];
  1318. buffer.text_ = buffer.text_ || "";
  1319. if (buffer.text_.length > 4) {
  1320. var a = buffer.text_.length % 3;
  1321. if (a === 0) { a = 3; }
  1322. for (var i=buffer.text_.length-3; i>0; i-=3) {
  1323. ret.push(buffer.text_.substr(i, 3));
  1324. ret.push({ type_: '1000 separator' });
  1325. }
  1326. ret.push(buffer.text_.substr(0, a));
  1327. ret.reverse();
  1328. } else {
  1329. ret.push(buffer.text_);
  1330. }
  1331. for (var p in buffer) { delete buffer[p]; }
  1332. return ret;
  1333. },
  1334. 'output-o': function (buffer) {
  1335. /** @type {ParserOutput[]} */
  1336. var ret = [];
  1337. buffer.text_ = buffer.text_ || "";
  1338. if (buffer.text_.length > 4) {
  1339. var a = buffer.text_.length - 3;
  1340. for (var i=0; i<a; i+=3) {
  1341. ret.push(buffer.text_.substr(i, 3));
  1342. ret.push({ type_: '1000 separator' });
  1343. }
  1344. ret.push(buffer.text_.substr(i));
  1345. } else {
  1346. ret.push(buffer.text_);
  1347. }
  1348. for (var p in buffer) { delete buffer[p]; }
  1349. return ret;
  1350. }
  1351. }
  1352. }
  1353. //#endregion
  1354. };
  1355. //
  1356. // texify: Take MhchemParser output and convert it to TeX
  1357. //
  1358. /** @type {Texify} */
  1359. var texify = {
  1360. go: function (input, isInner) { // (recursive, max 4 levels)
  1361. if (!input) { return ""; }
  1362. var res = "";
  1363. var cee = false;
  1364. for (var i=0; i < input.length; i++) {
  1365. var inputi = input[i];
  1366. if (typeof inputi === "string") {
  1367. res += inputi;
  1368. } else {
  1369. res += texify._go2(inputi);
  1370. if (inputi.type_ === '1st-level escape') { cee = true; }
  1371. }
  1372. }
  1373. if (!isInner && !cee && res) {
  1374. res = "{" + res + "}";
  1375. }
  1376. return res;
  1377. },
  1378. _goInner: function (input) {
  1379. if (!input) { return input; }
  1380. return texify.go(input, true);
  1381. },
  1382. _go2: function (buf) {
  1383. /** @type {undefined | string} */
  1384. var res;
  1385. switch (buf.type_) {
  1386. case 'chemfive':
  1387. res = "";
  1388. var b5 = {
  1389. a: texify._goInner(buf.a),
  1390. b: texify._goInner(buf.b),
  1391. p: texify._goInner(buf.p),
  1392. o: texify._goInner(buf.o),
  1393. q: texify._goInner(buf.q),
  1394. d: texify._goInner(buf.d)
  1395. };
  1396. //
  1397. // a
  1398. //
  1399. if (b5.a) {
  1400. if (b5.a.match(/^[+\-]/)) { b5.a = "{"+b5.a+"}"; }
  1401. res += b5.a + "\\,";
  1402. }
  1403. //
  1404. // b and p
  1405. //
  1406. if (b5.b || b5.p) {
  1407. res += "{\\vphantom{X}}";
  1408. res += "^{\\hphantom{"+(b5.b||"")+"}}_{\\hphantom{"+(b5.p||"")+"}}";
  1409. res += "{\\vphantom{X}}";
  1410. res += "^{\\smash[t]{\\vphantom{2}}\\mathllap{"+(b5.b||"")+"}}";
  1411. res += "_{\\vphantom{2}\\mathllap{\\smash[t]{"+(b5.p||"")+"}}}";
  1412. }
  1413. //
  1414. // o
  1415. //
  1416. if (b5.o) {
  1417. if (b5.o.match(/^[+\-]/)) { b5.o = "{"+b5.o+"}"; }
  1418. res += b5.o;
  1419. }
  1420. //
  1421. // q and d
  1422. //
  1423. if (buf.dType === 'kv') {
  1424. if (b5.d || b5.q) {
  1425. res += "{\\vphantom{X}}";
  1426. }
  1427. if (b5.d) {
  1428. res += "^{"+b5.d+"}";
  1429. }
  1430. if (b5.q) {
  1431. res += "_{\\smash[t]{"+b5.q+"}}";
  1432. }
  1433. } else if (buf.dType === 'oxidation') {
  1434. if (b5.d) {
  1435. res += "{\\vphantom{X}}";
  1436. res += "^{"+b5.d+"}";
  1437. }
  1438. if (b5.q) {
  1439. res += "{\\vphantom{X}}";
  1440. res += "_{\\smash[t]{"+b5.q+"}}";
  1441. }
  1442. } else {
  1443. if (b5.q) {
  1444. res += "{\\vphantom{X}}";
  1445. res += "_{\\smash[t]{"+b5.q+"}}";
  1446. }
  1447. if (b5.d) {
  1448. res += "{\\vphantom{X}}";
  1449. res += "^{"+b5.d+"}";
  1450. }
  1451. }
  1452. break;
  1453. case 'rm':
  1454. res = "\\mathrm{"+buf.p1+"}";
  1455. break;
  1456. case 'text':
  1457. if (buf.p1.match(/[\^_]/)) {
  1458. buf.p1 = buf.p1.replace(" ", "~").replace("-", "\\text{-}");
  1459. res = "\\mathrm{"+buf.p1+"}";
  1460. } else {
  1461. res = "\\text{"+buf.p1+"}";
  1462. }
  1463. break;
  1464. case 'roman numeral':
  1465. res = "\\mathrm{"+buf.p1+"}";
  1466. break;
  1467. case 'state of aggregation':
  1468. res = "\\mskip2mu "+texify._goInner(buf.p1);
  1469. break;
  1470. case 'state of aggregation subscript':
  1471. res = "\\mskip1mu "+texify._goInner(buf.p1);
  1472. break;
  1473. case 'bond':
  1474. res = texify._getBond(buf.kind_);
  1475. if (!res) {
  1476. throw ["MhchemErrorBond", "mhchem Error. Unknown bond type (" + buf.kind_ + ")"];
  1477. }
  1478. break;
  1479. case 'frac':
  1480. var c = "\\frac{" + buf.p1 + "}{" + buf.p2 + "}";
  1481. res = "\\mathchoice{\\textstyle"+c+"}{"+c+"}{"+c+"}{"+c+"}";
  1482. break;
  1483. case 'pu-frac':
  1484. var d = "\\frac{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
  1485. res = "\\mathchoice{\\textstyle"+d+"}{"+d+"}{"+d+"}{"+d+"}";
  1486. break;
  1487. case 'tex-math':
  1488. res = buf.p1 + " ";
  1489. break;
  1490. case 'frac-ce':
  1491. res = "\\frac{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
  1492. break;
  1493. case 'overset':
  1494. res = "\\overset{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
  1495. break;
  1496. case 'underset':
  1497. res = "\\underset{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
  1498. break;
  1499. case 'underbrace':
  1500. res = "\\underbrace{" + texify._goInner(buf.p1) + "}_{" + texify._goInner(buf.p2) + "}";
  1501. break;
  1502. case 'color':
  1503. res = "{\\color{" + buf.color1 + "}{" + texify._goInner(buf.color2) + "}}";
  1504. break;
  1505. case 'color0':
  1506. res = "\\color{" + buf.color + "}";
  1507. break;
  1508. case 'arrow':
  1509. var b6 = {
  1510. rd: texify._goInner(buf.rd),
  1511. rq: texify._goInner(buf.rq)
  1512. };
  1513. var arrow = "\\x" + texify._getArrow(buf.r);
  1514. if (b6.rq) { arrow += "[{" + b6.rq + "}]"; }
  1515. if (b6.rd) {
  1516. arrow += "{" + b6.rd + "}";
  1517. } else {
  1518. arrow += "{}";
  1519. }
  1520. res = arrow;
  1521. break;
  1522. case 'operator':
  1523. res = texify._getOperator(buf.kind_);
  1524. break;
  1525. case '1st-level escape':
  1526. res = buf.p1+" "; // &, \\\\, \\hlin
  1527. break;
  1528. case 'space':
  1529. res = " ";
  1530. break;
  1531. case 'entitySkip':
  1532. res = "~";
  1533. break;
  1534. case 'pu-space-1':
  1535. res = "~";
  1536. break;
  1537. case 'pu-space-2':
  1538. res = "\\mkern3mu ";
  1539. break;
  1540. case '1000 separator':
  1541. res = "\\mkern2mu ";
  1542. break;
  1543. case 'commaDecimal':
  1544. res = "{,}";
  1545. break;
  1546. case 'comma enumeration L':
  1547. res = "{"+buf.p1+"}\\mkern6mu ";
  1548. break;
  1549. case 'comma enumeration M':
  1550. res = "{"+buf.p1+"}\\mkern3mu ";
  1551. break;
  1552. case 'comma enumeration S':
  1553. res = "{"+buf.p1+"}\\mkern1mu ";
  1554. break;
  1555. case 'hyphen':
  1556. res = "\\text{-}";
  1557. break;
  1558. case 'addition compound':
  1559. res = "\\,{\\cdot}\\,";
  1560. break;
  1561. case 'electron dot':
  1562. res = "\\mkern1mu \\bullet\\mkern1mu ";
  1563. break;
  1564. case 'KV x':
  1565. res = "{\\times}";
  1566. break;
  1567. case 'prime':
  1568. res = "\\prime ";
  1569. break;
  1570. case 'cdot':
  1571. res = "\\cdot ";
  1572. break;
  1573. case 'tight cdot':
  1574. res = "\\mkern1mu{\\cdot}\\mkern1mu ";
  1575. break;
  1576. case 'times':
  1577. res = "\\times ";
  1578. break;
  1579. case 'circa':
  1580. res = "{\\sim}";
  1581. break;
  1582. case '^':
  1583. res = "uparrow";
  1584. break;
  1585. case 'v':
  1586. res = "downarrow";
  1587. break;
  1588. case 'ellipsis':
  1589. res = "\\ldots ";
  1590. break;
  1591. case '/':
  1592. res = "/";
  1593. break;
  1594. case ' / ':
  1595. res = "\\,/\\,";
  1596. break;
  1597. default:
  1598. assertNever(buf);
  1599. throw ["MhchemBugT", "mhchem bug T. Please report."]; // Missing texify rule or unknown MhchemParser output
  1600. }
  1601. assertString(res);
  1602. return res;
  1603. },
  1604. _getArrow: function (a) {
  1605. switch (a) {
  1606. case "->": return "rightarrow";
  1607. case "\u2192": return "rightarrow";
  1608. case "\u27F6": return "rightarrow";
  1609. case "<-": return "leftarrow";
  1610. case "<->": return "leftrightarrow";
  1611. case "<-->": return "rightleftarrows";
  1612. case "<=>": return "rightleftharpoons";
  1613. case "\u21CC": return "rightleftharpoons";
  1614. case "<=>>": return "rightequilibrium";
  1615. case "<<=>": return "leftequilibrium";
  1616. default:
  1617. assertNever(a);
  1618. throw ["MhchemBugT", "mhchem bug T. Please report."];
  1619. }
  1620. },
  1621. _getBond: function (a) {
  1622. switch (a) {
  1623. case "-": return "{-}";
  1624. case "1": return "{-}";
  1625. case "=": return "{=}";
  1626. case "2": return "{=}";
  1627. case "#": return "{\\equiv}";
  1628. case "3": return "{\\equiv}";
  1629. case "~": return "{\\tripledash}";
  1630. case "~-": return "{\\mathrlap{\\raisebox{-.1em}{$-$}}\\raisebox{.1em}{$\\tripledash$}}";
  1631. case "~=": return "{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$\\tripledash$}}-}";
  1632. case "~--": return "{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$\\tripledash$}}-}";
  1633. case "-~-": return "{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$-$}}\\tripledash}";
  1634. case "...": return "{{\\cdot}{\\cdot}{\\cdot}}";
  1635. case "....": return "{{\\cdot}{\\cdot}{\\cdot}{\\cdot}}";
  1636. case "->": return "{\\rightarrow}";
  1637. case "<-": return "{\\leftarrow}";
  1638. case "<": return "{<}";
  1639. case ">": return "{>}";
  1640. default:
  1641. assertNever(a);
  1642. throw ["MhchemBugT", "mhchem bug T. Please report."];
  1643. }
  1644. },
  1645. _getOperator: function (a) {
  1646. switch (a) {
  1647. case "+": return " {}+{} ";
  1648. case "-": return " {}-{} ";
  1649. case "=": return " {}={} ";
  1650. case "<": return " {}<{} ";
  1651. case ">": return " {}>{} ";
  1652. case "<<": return " {}\\ll{} ";
  1653. case ">>": return " {}\\gg{} ";
  1654. case "\\pm": return " {}\\pm{} ";
  1655. case "\\approx": return " {}\\approx{} ";
  1656. case "$\\approx$": return " {}\\approx{} ";
  1657. case "v": return " \\downarrow{} ";
  1658. case "(v)": return " \\downarrow{} ";
  1659. case "^": return " \\uparrow{} ";
  1660. case "(^)": return " \\uparrow{} ";
  1661. default:
  1662. assertNever(a);
  1663. throw ["MhchemBugT", "mhchem bug T. Please report."];
  1664. }
  1665. }
  1666. };
  1667. //
  1668. // Helpers for code analysis
  1669. // Will show type error at calling position
  1670. //
  1671. /** @param {number} a */
  1672. function assertNever(a) {}
  1673. /** @param {string} a */
  1674. function assertString(a) {}