Debian Codegraph @

unpacked/extensions/TeX/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-2020 The MathJax Consortium
14 *
15 * Licensed under the Apache License, Version 2.0 (the "License");
16 * you may not use this file except in compliance with the License.
17 * You may obtain a copy of the License at
18 *
19 * http://www.apache.org/licenses/LICENSE-2.0
20 *
21 * Unless required by applicable law or agreed to in writing, software
22 * distributed under the License is distributed on an "AS IS" BASIS,
23 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24 * See the License for the specific language governing permissions and
25 * limitations under the License.
26 */
27
28
29 //
30 // Don't replace [Contrib]/mhchem if it is already loaded
31 //
32 if (MathJax.Extension["TeX/mhchem"]) {
33 MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/mhchem.js");
34 } else {
35
36 MathJax.Extension["TeX/mhchem"] = {
37 version: "2.7.9",
38 config: MathJax.Hub.CombineConfig("TeX.mhchem",{
39 legacy: true
40 })
41 };
42
43 //
44 // Load [mhchem]/mhchem.js if not configured for legacy vesion
45 //
46 if (!MathJax.Extension["TeX/mhchem"].config.legacy) {
47 if (!MathJax.Ajax.config.path.mhchem) {
48 MathJax.Ajax.config.path.mhchem = MathJax.Hub.config.root + "/extensions/TeX/mhchem3";
49 }
50 MathJax.Callback.Queue(
51 ["Require",MathJax.Ajax,"[mhchem]/mhchem.js"],
52 ["loadComplete",MathJax.Ajax,"[MathJax]/extensions/TeX/mhchem.js"]
53 );
54 } else {
55
56 MathJax.Hub.Register.StartupHook("TeX Jax Ready",function () {
57
58 var TEX = MathJax.InputJax.TeX;
59
60 /*
61 * This is the main class for handing the \ce and related commands.
62 * Its main method is Parse() which takes the argument to \ce and
63 * returns the corresponding TeX string.
64 */
65
66 var CE = MathJax.Object.Subclass({
67 string: "", // the \ce string being parsed
68 i: 0, // the current position in the string
69 tex: "", // the partially processed TeX result
70 TEX: "", // the full TeX result
71 atom: false, // last processed token is an atom
72 sup: "", // pending superscript
73 sub: "", // pending subscript
74 presup: "", // pending pre-superscript
75 presub: "", // pending pre-subscript
76
77 //
78 // Store the string when a CE object is created
79 //
80 Init: function (string) {this.string = string},
81
82 //
83 // These are the special characters and the methods that
84 // handle them. All others are passed through verbatim.
85 //
86 ParseTable: {
87 '-': "Minus",
88 '+': "Plus",
89 '(': "Open",
90 ')': "Close",
91 '[': "Open",
92 ']': "Close",
93 '<': "Less",
94 '^': "Superscript",
95 '_': "Subscript",
96 '*': "Dot",
97 '.': "Dot",
98 '=': "Equal",
99 '#': "Pound",
100 '$': "Math",
101 '\\': "Macro",
102 ' ': "Space"
103 },
104 //
105 // Basic arrow names for reactions
106 //
107 Arrows: {
108 '->': "rightarrow",
109 '<-': "leftarrow",
110 '<->': "leftrightarrow",
111 '<=>': "rightleftharpoons",
112 '<=>>': "Rightleftharpoons",
113 '<<=>': "Leftrightharpoons",
114 '^': "uparrow",
115 'v': "downarrow"
116 },
117
118 //
119 // Implementations for the various bonds
120 // (the ~ ones are hacks that don't work well in NativeMML)
121 //
122 Bonds: {
123 '-': "-",
124 '=': "=",
125 '#': "\\equiv",
126 '~': "\\tripledash",
127 '~-': "\\begin{CEstack}{}\\tripledash\\\\-\\end{CEstack}",
128 '~=': "\\raise2mu{\\begin{CEstack}{}\\tripledash\\\\-\\\\-\\end{CEstack}}",
129 '~--': "\\raise2mu{\\begin{CEstack}{}\\tripledash\\\\-\\\\-\\end{CEstack}}",
130 '-~-': "\\raise2mu{\\begin{CEstack}{}-\\\\\\tripledash\\\\-\\end{CEstack}}",
131 '...': "{\\cdot}{\\cdot}{\\cdot}",
132 '....': "{\\cdot}{\\cdot}{\\cdot}{\\cdot}",
133 '->': "\\rightarrow",
134 '<-': "\\leftarrow",
135 '??': "\\text{??}" // unknown bond
136 },
137
138 //
139 // This converts the CE string to a TeX string.
140 // It loops through the string and calls the proper
141 // method depending on the ccurrent character.
142 //
143 Parse: function () {
144 this.tex = ""; this.atom = false;
145 while (this.i < this.string.length) {
146 var c = this.string.charAt(this.i);
147 if (c.match(/[a-z]/i)) {this.ParseLetter()}
148 else if (c.match(/[0-9]/)) {this.ParseNumber()}
149 else {this["Parse"+(this.ParseTable[c]||"Other")](c)}
150 }
151 this.FinishAtom(true);
152 return this.TEX;
153 },
154
155 //
156 // Make an atom name or a down arrow
157 //
158 ParseLetter: function () {
159 this.FinishAtom();
160 if (this.Match(/^v( |$)/)) {
161 this.tex += "{\\"+this.Arrows["v"]+"}";
162 } else {
163 this.tex += "\\text{"+this.Match(/^[a-z]+/i)+"}";
164 this.atom = true;
165 }
166 },
167
168 //
169 // Make a number or fraction preceding an atom,
170 // or a subscript for an atom.
171 //
172 ParseNumber: function () {
173 var n = this.Match(/^\d+/);
174 if (this.atom && !this.sub) {
175 this.sub = n;
176 } else {
177 this.FinishAtom();
178 var match = this.Match(/^\/\d+/);
179 if (match) {
180 var frac = "\\frac{"+n+"}{"+match.substr(1)+"}";
181 this.tex += "\\mathchoice{\\textstyle"+frac+"}{"+frac+"}{"+frac+"}{"+frac+"}";
182 } else {
183 this.tex += n;
184 if (this.i < this.string.length) {this.tex += "\\,"}
185 }
186 }
187 },
188
189 //
190 // Make a superscript minus, or an arrow, or a single bond.
191 //
192 ParseMinus: function (c) {
193 if (this.atom && (this.i === this.string.length-1 || this.string.charAt(this.i+1) === " ")) {
194 this.sup += c;
195 } else {
196 this.FinishAtom();
197 if (this.string.substr(this.i,2) === "->") {this.i += 2; this.AddArrow("->"); return}
198 else {this.tex += "{-}"}
199 }
200 this.i++;
201 },
202
203 //
204 // Make a superscript plus, or pass it through
205 //
206 ParsePlus: function (c) {
207 if (this.atom) {this.sup += c} else {this.FinishAtom(); this.tex += c}
208 this.i++;
209 },
210
211 //
212 // Handle dots and double or triple bonds
213 //
214 ParseDot: function (c) {this.FinishAtom(); this.tex += "\\cdot "; this.i++},
215 ParseEqual: function (c) {this.FinishAtom(); this.tex += "{=}"; this.i++},
216 ParsePound: function (c) {this.FinishAtom(); this.tex += "{\\equiv}"; this.i++},
217
218 //
219 // Look for (v) or (^), or pass it through
220 //
221 ParseOpen: function (c) {
222 this.FinishAtom();
223 var match = this.Match(/^\([v^]\)/);
224 if (match) {this.tex += "{\\"+this.Arrows[match.charAt(1)]+"}"}
225 else {this.tex += "{"+c; this.i++}
226 },
227 //
228 // Allow ) and ] to get super- and subscripts
229 //
230 ParseClose: function (c) {this.FinishAtom(); this.atom = true; this.tex += c+"}"; this.i++},
231
232 //
233 // Make the proper arrow
234 //
235 ParseLess: function (c) {
236 this.FinishAtom();
237 var arrow = this.Match(/^(<->?|<=>>?|<<=>)/);
238 if (!arrow) {this.tex += c; this.i++} else {this.AddArrow(arrow)}
239 },
240
241 //
242 // Look for a superscript, or an up arrow
243 //
244 ParseSuperscript: function (c) {
245 c = this.string.charAt(++this.i);
246 if (c === "{") {
247 this.i++; var m = this.Find("}");
248 if (m === "-.") {this.sup += "{-}{\\cdot}"}
249 else if (m) {this.sup += CE(m).Parse().replace(/^\{-\}/,"-")}
250 } else if (c === " " || c === "") {
251 this.tex += "{\\"+this.Arrows["^"]+"}"; this.i++;
252 } else {
253 var n = this.Match(/^(\d+|-\.)/);
254 if (n) {this.sup += n}
255 }
256 },
257 //
258 // Look for subscripts
259 //
260 ParseSubscript: function (c) {
261 if (this.string.charAt(++this.i) == "{") {
262 this.i++; this.sub += CE(this.Find("}")).Parse().replace(/^\{-\}/,"-");
263 } else {
264 var n = this.Match(/^\d+/);
265 if (n) {this.sub += n}
266 }
267 },
268
269 //
270 // Look for raw TeX code to include
271 //
272 ParseMath: function (c) {
273 this.FinishAtom();
274 this.i++; this.tex += this.Find(c);
275 },
276
277 //
278 // Look for specific macros for bonds
279 // and allow \} to have subscripts
280 //
281 ParseMacro: function (c) {
282 this.FinishAtom();
283 this.i++; var match = this.Match(/^([a-z]+|.)/i)||" ";
284 if (match === "sbond") {this.tex += "{-}"}
285 else if (match === "dbond") {this.tex += "{=}"}
286 else if (match === "tbond") {this.tex += "{\\equiv}"}
287 else if (match === "bond") {
288 var bond = (this.Match(/^\{.*?\}/)||"");
289 bond = bond.substr(1,bond.length-2);
290 this.tex += "{"+(this.Bonds[bond]||"\\text{??}")+"}";
291 }
292 else if (match === "{") {this.tex += "{\\{"}
293 else if (match === "}") {this.tex += "\\}}"; this.atom = true}
294 else {this.tex += c+match}
295 },
296
297 //
298 // Ignore spaces
299 //
300 ParseSpace: function (c) {this.FinishAtom(); this.i++},
301
302 //
303 // Pass anything else on verbatim
304 //
305 ParseOther: function (c) {this.FinishAtom(); this.tex += c; this.i++},
306
307 //
308 // Process an arrow (looking for brackets for above and below)
309 //
310 AddArrow: function (arrow) {
311 var c = this.Match(/^[CT]\[/);
312 if (c) {this.i--; c = c.charAt(0)}
313 var above = this.GetBracket(c), below = this.GetBracket(c);
314 arrow = this.Arrows[arrow];
315 if (above || below) {
316 if (below) {arrow += "["+below+"]"}
317 arrow += "{"+above+"}";
318 arrow = "\\mathrel{\\x"+arrow+"}";
319 } else {
320 arrow = "\\long"+arrow+" ";
321 }
322 this.tex += arrow;
323 },
324
325 //
326 // Handle the super and subscripts for an atom
327 //
328 FinishAtom: function (force) {
329 if (this.sup || this.sub || this.presup || this.presub) {
330 if (!force && !this.atom) {
331 if (this.tex === "" && !this.sup && !this.sub) return;
332 if (!this.presup && !this.presub &&
333 (this.tex === "" || this.tex === "{" ||
334 (this.tex === "}" && this.TEX.substr(-1) === "{"))) {
335 this.presup = this.sup, this.presub = this.sub; // save for later
336 this.sub = this.sup = "";
337 this.TEX += this.tex; this.tex = "";
338 return;
339 }
340 }
341 if (this.sub && !this.sup) {this.sup = "\\Space{0pt}{0pt}{.2em}"} // forces subscripts to align properly
342 if ((this.presup || this.presub) && this.tex !== "{") {
343 if (!this.presup && !this.sup) {this.presup = "\\Space{0pt}{0pt}{.2em}"}
344 this.tex = "\\CEprescripts{"+(this.presub||"\\CEnone")+"}{"+(this.presup||"\\CEnone")+"}"
345 + "{"+(this.tex !== "}" ? this.tex : "")+"}"
346 + "{"+(this.sub||"\\CEnone")+"}{"+(this.sup||"\\CEnone")+"}"
347 + (this.tex === "}" ? "}" : "");
348 this.presub = this.presup = "";
349 } else {
350 if (this.sup) this.tex += "^{"+this.sup+"}";
351 if (this.sub) this.tex += "_{"+this.sub+"}";
352 }
353 this.sup = this.sub = "";
354 }
355 this.TEX += this.tex; this.tex = "";
356 this.atom = false;
357 },
358
359 //
360 // Find a bracket group and handle C and T prefixes
361 //
362 GetBracket: function (c) {
363 if (this.string.charAt(this.i) !== "[") {return ""}
364 this.i++; var bracket = this.Find("]");
365 if (c === "C") {bracket = "\\ce{"+bracket+"}"} else
366 if (c === "T") {
367 if (!bracket.match(/^\{.*\}$/)) {bracket = "{"+bracket+"}"}
368 bracket = "\\text"+bracket;
369 };
370 return bracket;
371 },
372
373 //
374 // Check if the string matches a regular expression
375 // and move past it if so, returning the match
376 //
377 Match: function (regex) {
378 var match = regex.exec(this.string.substr(this.i));
379 if (match) {match = match[0]; this.i += match.length}
380 return match;
381 },
382
383 //
384 // Find a particular character, skipping over braced groups
385 //
386 Find: function (c) {
387 var m = this.string.length, i = this.i, braces = 0;
388 while (this.i < m) {
389 var C = this.string.charAt(this.i++);
390 if (C === c && braces === 0) {return this.string.substr(i,this.i-i-1)}
391 if (C === "{") {braces++} else
392 if (C === "}") {
393 if (braces) {braces--}
394 else {
395 TEX.Error(["ExtraCloseMissingOpen","Extra close brace or missing open brace"])
396 }
397 }
398 }
399 if (braces) {TEX.Error(["MissingCloseBrace","Missing close brace"])}
400 TEX.Error(["NoClosingChar","Can't find closing %1",c]);
401 }
402
403 });
404
405 MathJax.Extension["TeX/mhchem"].CE = CE;
406
407 /***************************************************************************/
408
409 TEX.Definitions.Add({
410 macros: {
411 //
412 // Set up the macros for chemistry
413 //
414 ce: 'CE',
415 cf: 'CE',
416 cee: 'CE',
417
418 //
419 // Make these load AMSmath package (redefined below when loaded)
420 //
421 xleftrightarrow: ['Extension','AMSmath'],
422 xrightleftharpoons: ['Extension','AMSmath'],
423 xRightleftharpoons: ['Extension','AMSmath'],
424 xLeftrightharpoons: ['Extension','AMSmath'],
425
426 // FIXME: These don't work well in FF NativeMML mode
427 longrightleftharpoons: ["Macro","\\stackrel{\\textstyle{{-}\\!\\!{\\rightharpoonup}}}{\\smash{{\\leftharpoondown}\\!\\!{-}}}"],
428 longRightleftharpoons: ["Macro","\\stackrel{\\textstyle{-}\\!\\!{\\rightharpoonup}}{\\small\\smash\\leftharpoondown}"],
429 longLeftrightharpoons: ["Macro","\\stackrel{\\rightharpoonup}{{{\\leftharpoondown}\\!\\!\\textstyle{-}}}"],
430
431 //
432 // Add \hyphen used in some mhchem examples
433 //
434 hyphen: ["Macro","\\text{-}"],
435
436 //
437 // Handle prescripts and none
438 //
439 CEprescripts: "CEprescripts",
440 CEnone: "CEnone",
441
442 //
443 // Needed for \bond for the ~ forms
444 //
445 tripledash: ["Macro","\\raise3mu{\\tiny\\text{-}\\kern2mu\\text{-}\\kern2mu\\text{-}}"]
446 },
447
448 //
449 // Needed for \bond for the ~ forms
450 //
451 environment: {
452 CEstack: ['Array',null,null,null,'r',null,"0.001em",'T',1]
453 }
454 },null,true);
455
456 if (!MathJax.Extension["TeX/AMSmath"]) {
457 TEX.Definitions.Add({
458 macros: {
459 xrightarrow: ['Extension','AMSmath'],
460 xleftarrow: ['Extension','AMSmath']
461 }
462 },null,true);
463 }
464
465 //
466 // These arrows need to wait until AMSmath is loaded
467 //
468 MathJax.Hub.Register.StartupHook("TeX AMSmath Ready",function () {
469 TEX.Definitions.Add({
470 macros: {
471 //
472 // Some of these are hacks for now
473 //
474 xleftrightarrow: ['xArrow',0x2194,6,6],
475 xrightleftharpoons: ['xArrow',0x21CC,5,7], // FIXME: doesn't stretch in HTML-CSS output
476 xRightleftharpoons: ['xArrow',0x21CC,5,7], // FIXME: how should this be handled?
477 xLeftrightharpoons: ['xArrow',0x21CC,5,7]
478 }
479 },null,true);
480 });
481
482 TEX.Parse.Augment({
483
484 //
485 // Implements \ce and friends
486 //
487 CE: function (name) {
488 var arg = this.GetArgument(name);
489 var tex = CE(arg).Parse();
490 this.string = tex + this.string.substr(this.i); this.i = 0;
491 },
492
493 //
494 // Implements \CEprescripts{presub}{presup}{base}{sub}{sup}
495 //
496 CEprescripts: function (name) {
497 var presub = this.ParseArg(name),
498 presup = this.ParseArg(name),
499 base = this.ParseArg(name),
500 sub = this.ParseArg(name),
501 sup = this.ParseArg(name);
502 var MML = MathJax.ElementJax.mml;
503 this.Push(MML.mmultiscripts(base,sub,sup,MML.mprescripts(),presub,presup));
504 },
505 CEnone: function (name) {
506 this.Push(MathJax.ElementJax.mml.none());
507 }
508
509 });
510
511 //
512 // Indicate that the extension is ready
513 //
514 MathJax.Hub.Startup.signal.Post("TeX mhchem Ready");
515
516 });
517
518 MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/mhchem.js");
519
520 }}