Debian Codegraph @

unpacked/extensions/TeX/mhchem3/mhchem.js

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