]> git.lyx.org Git - lyx.git/blob - src/mathed/MathExtern.cpp
0f7ad7cb0ee63238830b8805f6c69fed7376cbf9
[lyx.git] / src / mathed / MathExtern.cpp
1 /**
2  * \file MathExtern.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 // This file contains most of the magic that extracts "context
12 // information" from the unstructered layout-oriented stuff in
13 // MathData.
14
15 #include <config.h>
16
17 #include "MathExtern.h"
18
19 #include "InsetMathAMSArray.h"
20 #include "InsetMathArray.h"
21 #include "InsetMathChar.h"
22 #include "InsetMathDelim.h"
23 #include "InsetMathDiff.h"
24 #include "InsetMathExFunc.h"
25 #include "InsetMathExInt.h"
26 #include "InsetMathFont.h"
27 #include "InsetMathFrac.h"
28 #include "InsetMathLim.h"
29 #include "InsetMathMatrix.h"
30 #include "InsetMathNumber.h"
31 #include "InsetMathScript.h"
32 #include "InsetMathString.h"
33 #include "InsetMathSymbol.h"
34 #include "MathData.h"
35 #include "MathParser.h"
36 #include "MathStream.h"
37
38 #include "Encoding.h"
39
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/FileName.h"
43 #include "support/filetools.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/TempFile.h"
47 #include "support/textutils.h"
48 #include "support/unique_ptr.h"
49
50 #include <algorithm>
51 #include <sstream>
52 #include <fstream>
53 #include <memory>
54
55 using namespace std;
56 using namespace lyx::support;
57
58 namespace lyx {
59
60 namespace {
61
62 enum ExternalMath {
63         HTML,
64         MAPLE,
65         MAXIMA,
66         MATHEMATICA,
67         MATHML,
68         OCTAVE
69 };
70
71
72 static char const * function_names[] = {
73         "arccos", "arcsin", "arctan", "arg", "bmod",
74         "cos", "cosh", "cot", "coth", "csc", "deg",
75         "det", "dim", "exp", "gcd", "hom", "inf", "ker",
76         "lg", "lim", "liminf", "limsup", "ln", "log",
77         "max", "min", "sec", "sin", "sinh", "sup",
78         "tan", "tanh", "Pr", nullptr
79 };
80
81 static size_t const npos = lyx::docstring::npos;
82
83 // define a function for tests
84 typedef bool TestItemFunc(MathAtom const &);
85
86 // define a function for replacing subexpressions
87 typedef MathAtom ReplaceArgumentFunc(const MathData & ar);
88
89
90
91 // try to extract a super/subscript
92 // modify iterator position to point behind the thing
93 bool extractScript(MathData & ar,
94         MathData::iterator & pos, MathData::iterator last, bool superscript)
95 {
96         // nothing to get here
97         if (pos == last)
98                 return false;
99
100         // is this a scriptinset?
101         if (!(*pos)->asScriptInset())
102                 return false;
103
104         // do we want superscripts only?
105         if (superscript && !(*pos)->asScriptInset()->hasUp())
106                 return false;
107
108         // it is a scriptinset, use it.
109         ar.push_back(*pos);
110         ++pos;
111         return true;
112 }
113
114
115 // try to extract an "argument" to some function.
116 // returns position behind the argument
117 MathData::iterator extractArgument(MathData & ar,
118         MathData::iterator pos, MathData::iterator last,
119         ExternalMath kind, bool function = false)
120 {
121         // nothing to get here
122         if (pos == last)
123                 return pos;
124
125         // something delimited _is_ an argument
126         if ((*pos)->asDelimInset()) {
127                 // leave out delimiters if this is a function argument
128                 // unless we are doing MathML, in which case we do want
129                 // the delimiters
130                 if (function && kind != MATHML && kind != HTML) {
131                         MathData const & arg = (*pos)->asDelimInset()->cell(0);
132                         MathData::const_iterator cur = arg.begin();
133                         MathData::const_iterator end = arg.end();
134                         while (cur != end)
135                                 ar.push_back(*cur++);
136                 } else
137                         ar.push_back(*pos);
138                 ++pos;
139                 if (pos == last)
140                         return pos;
141                 // if there's one, get following superscript only if this
142                 // isn't a function argument
143                 if (!function)
144                         extractScript(ar, pos, last, true);
145                 return pos;
146         }
147
148         // always take the first thing, no matter what it is
149         ar.push_back(*pos);
150
151         // go ahead if possible
152         ++pos;
153         if (pos == last)
154                 return pos;
155
156         // if the next item is a super/subscript, it most certainly belongs
157         // to the thing we have
158         extractScript(ar, pos, last, false);
159         if (pos == last)
160                 return pos;
161
162         // but it might be more than that.
163         // FIXME: not implemented
164         //for (MathData::iterator it = pos + 1; it != last; ++it) {
165         //      // always take the first thing, no matter
166         //      if (it == pos) {
167         //              ar.push_back(*it);
168         //              continue;
169         //      }
170         //}
171         return pos;
172 }
173
174
175 // returns sequence of char with same code starting at it up to end
176 // it might be less, though...
177 docstring charSequence
178         (MathData::const_iterator it, MathData::const_iterator end)
179 {
180         docstring s;
181         for (; it != end && (*it)->asCharInset(); ++it)
182                 s += (*it)->getChar();
183         return s;
184 }
185
186
187 void extractStrings(MathData & ar)
188 {
189         //lyxerr << "\nStrings from: " << ar << endl;
190         for (size_t i = 0; i < ar.size(); ++i) {
191                 if (!ar[i]->asCharInset())
192                         continue;
193                 docstring s = charSequence(ar.begin() + i, ar.end());
194                 ar[i] = MathAtom(new InsetMathString(s));
195                 ar.erase(i + 1, i + s.size());
196         }
197         //lyxerr << "\nStrings to: " << ar << endl;
198 }
199
200
201 void extractMatrices(MathData & ar)
202 {
203         //lyxerr << "\nMatrices from: " << ar << endl;
204         // first pass for explicitly delimited stuff
205         for (size_t i = 0; i < ar.size(); ++i) {
206                 InsetMathDelim const * const inset = ar[i]->asDelimInset();
207                 if (!inset)
208                         continue;
209                 MathData const & arr = inset->cell(0);
210                 if (arr.size() != 1)
211                         continue;
212                 if (!arr.front()->asGridInset())
213                         continue;
214                 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset()),
215                                  inset->left_, inset->right_));
216         }
217
218         // second pass for AMS "pmatrix" etc
219         for (size_t i = 0; i < ar.size(); ++i) {
220                 InsetMathAMSArray const * const inset = ar[i]->asAMSArrayInset();
221                 if (inset) {
222                         string left = inset->name_left();
223                         if (left == "Vert")
224                                 left = "[";
225                         string right = inset->name_right();
226                         if (right == "Vert")
227                                 right = "]";
228                         ar[i] = MathAtom(new InsetMathMatrix(*inset, from_ascii(left), from_ascii(right)));
229                 }
230         }
231         //lyxerr << "\nMatrices to: " << ar << endl;
232 }
233
234
235 // convert this inset somehow to a string
236 bool extractString(MathAtom const & at, docstring & str)
237 {
238         if (at->getChar()) {
239                 str = docstring(1, at->getChar());
240                 return true;
241         }
242         if (at->asStringInset()) {
243                 str = at->asStringInset()->str();
244                 return true;
245         }
246         return false;
247 }
248
249
250 // is this a known function?
251 bool isKnownFunction(docstring const & str)
252 {
253         for (int i = 0; function_names[i]; ++i) {
254                 if (str == function_names[i])
255                         return true;
256         }
257         return false;
258 }
259
260
261 // extract a function name from this inset
262 bool extractFunctionName(MathAtom const & at, docstring & str)
263 {
264         if (at->asSymbolInset()) {
265                 str = at->asSymbolInset()->name();
266                 return isKnownFunction(str);
267         }
268         if (at->asUnknownInset()) {
269                 // assume it is well known...
270                 str = at->name();
271                 return true;
272         }
273         if (at->asFontInset() && at->name() == "mathrm") {
274                 // assume it is well known...
275                 MathData const & ar = at->asFontInset()->cell(0);
276                 str = charSequence(ar.begin(), ar.end());
277                 return ar.size() == str.size();
278         }
279         return false;
280 }
281
282
283 bool testString(MathAtom const & at, docstring const & str)
284 {
285         docstring s;
286         return extractString(at, s) && str == s;
287 }
288
289
290 bool testString(MathAtom const & at, char const * const str)
291 {
292         return testString(at, from_ascii(str));
293 }
294
295
296 bool testSymbol(MathAtom const & at, docstring const & name)
297 {
298         return at->asSymbolInset() && at->asSymbolInset()->name() == name;
299 }
300
301
302 bool testSymbol(MathAtom const & at, char const * const name)
303 {
304         return testSymbol(at, from_ascii(name));
305 }
306
307
308 // search end of nested sequence
309 MathData::iterator endNestSearch(
310         MathData::iterator it,
311         const MathData::iterator& last,
312         TestItemFunc testOpen,
313         TestItemFunc testClose
314 )
315 {
316         for (int level = 0; it != last; ++it) {
317                 if (testOpen(*it))
318                         ++level;
319                 if (testClose(*it))
320                         --level;
321                 if (level == 0)
322                         break;
323         }
324         return it;
325 }
326
327
328 // replace nested sequences by a real Insets
329 void replaceNested(
330         MathData & ar,
331         TestItemFunc testOpen,
332         TestItemFunc testClose,
333         ReplaceArgumentFunc replaceArg)
334 {
335         Buffer * buf = ar.buffer();
336         // use indices rather than iterators for the loop  because we are going
337         // to modify the array.
338         for (size_t i = 0; i < ar.size(); ++i) {
339                 // check whether this is the begin of the sequence
340                 if (!testOpen(ar[i]))
341                         continue;
342
343                 // search end of sequence
344                 MathData::iterator it = ar.begin() + i;
345                 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
346                 if (jt == ar.end())
347                         continue;
348
349                 // replace the original stuff by the new inset
350                 ar[i] = replaceArg(MathData(buf, it + 1, jt));
351                 ar.erase(it + 1, jt + 1);
352         }
353 }
354
355
356
357 //
358 // split scripts into separate super- and subscript insets. sub goes in
359 // front of super...
360 //
361
362 void splitScripts(MathData & ar)
363 {
364         Buffer * buf = ar.buffer();
365         //lyxerr << "\nScripts from: " << ar << endl;
366         for (size_t i = 0; i < ar.size(); ++i) {
367                 InsetMathScript const * script = ar[i]->asScriptInset();
368
369                 // is this a script inset and do we also have a superscript?
370                 if (!script || !script->hasUp())
371                         continue;
372
373                 // we must have a nucleus if we only have a superscript
374                 if (!script->hasDown() && script->nuc().empty())
375                         continue;
376
377                 if (script->nuc().size() == 1) {
378                         // leave alone sums and integrals
379                         InsetMathSymbol const * sym =
380                                 script->nuc().front()->asSymbolInset();
381                         if (sym && (sym->name() == "sum" || sym->name() == "int"))
382                                 continue;
383                 }
384
385                 // create extra script inset and move superscript over
386                 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
387                 auto q = make_unique<InsetMathScript>(buf, true);
388                 swap(q->up(), p->up());
389                 p->removeScript(true);
390
391                 // if we don't have a subscript, get rid of the ScriptInset
392                 if (!script->hasDown()) {
393                         MathData arg(p->nuc());
394                         MathData::const_iterator it = arg.begin();
395                         MathData::const_iterator et = arg.end();
396                         ar.erase(i);
397                         while (it != et)
398                                 ar.insert(i++, *it++);
399                 } else
400                         ++i;
401
402                 // insert new inset behind
403                 ar.insert(i, MathAtom(q.release()));
404         }
405         //lyxerr << "\nScripts to: " << ar << endl;
406 }
407
408
409 //
410 // extract exp(...)
411 //
412
413 void extractExps(MathData & ar)
414 {
415         Buffer * buf = ar.buffer();
416         //lyxerr << "\nExps from: " << ar << endl;
417         for (size_t i = 0; i + 1 < ar.size(); ++i) {
418                 // is this 'e'?
419                 if (ar[i]->getChar() != 'e')
420                         continue;
421
422                 // we need an exponent but no subscript
423                 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
424                 if (!sup || sup->hasDown())
425                         continue;
426
427                 // create a proper exp-inset as replacement
428                 ar[i] = MathAtom(new InsetMathExFunc(buf, from_ascii("exp"), sup->cell(1)));
429                 ar.erase(i + 1);
430         }
431         //lyxerr << "\nExps to: " << ar << endl;
432 }
433
434
435 //
436 // extract det(...)  from |matrix|
437 //
438 void extractDets(MathData & ar)
439 {
440         Buffer * buf = ar.buffer();
441         //lyxerr << "\ndet from: " << ar << endl;
442         for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
443                 InsetMathDelim const * del = (*it)->asDelimInset();
444                 if (!del)
445                         continue;
446                 if (!del->isAbs())
447                         continue;
448                 *it = MathAtom(new InsetMathExFunc(buf, from_ascii("det"), del->cell(0)));
449         }
450         //lyxerr << "\ndet to: " << ar << endl;
451 }
452
453
454 //
455 // search numbers
456 //
457
458 bool isDigitOrSimilar(char_type c)
459 {
460         return ('0' <= c && c <= '9') || c == '.';
461 }
462
463
464 // returns sequence of digits
465 docstring digitSequence
466         (MathData::const_iterator it, MathData::const_iterator end)
467 {
468         docstring s;
469         for (; it != end && (*it)->asCharInset(); ++it) {
470                 if (!isDigitOrSimilar((*it)->getChar()))
471                         break;
472                 s += (*it)->getChar();
473         }
474         return s;
475 }
476
477
478 void extractNumbers(MathData & ar)
479 {
480         //lyxerr << "\nNumbers from: " << ar << endl;
481         for (size_t i = 0; i < ar.size(); ++i) {
482                 if (!ar[i]->asCharInset())
483                         continue;
484                 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
485                         continue;
486
487                 docstring s = digitSequence(ar.begin() + i, ar.end());
488
489                 ar[i] = MathAtom(new InsetMathNumber(s));
490                 ar.erase(i + 1, i + s.size());
491         }
492         //lyxerr << "\nNumbers to: " << ar << endl;
493 }
494
495
496
497 //
498 // search delimiters
499 //
500
501 bool testOpenParen(MathAtom const & at)
502 {
503         return testString(at, "(");
504 }
505
506
507 bool testCloseParen(MathAtom const & at)
508 {
509         return testString(at, ")");
510 }
511
512
513 MathAtom replaceParenDelims(const MathData & ar)
514 {
515         return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
516                 from_ascii("("), from_ascii(")"), ar, true));
517 }
518
519
520 bool testOpenBracket(MathAtom const & at)
521 {
522         return testString(at, "[");
523 }
524
525
526 bool testCloseBracket(MathAtom const & at)
527 {
528         return testString(at, "]");
529 }
530
531
532 MathAtom replaceBracketDelims(const MathData & ar)
533 {
534         return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
535                 from_ascii("["), from_ascii("]"), ar, true));
536 }
537
538
539 bool testOpenVert(MathAtom const & at)
540 {
541         return testSymbol(at, "lvert");
542 }
543
544
545 bool testCloseVert(MathAtom const & at)
546 {
547         return testSymbol(at, "rvert");
548 }
549
550
551 MathAtom replaceVertDelims(const MathData & ar)
552 {
553         return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
554                 from_ascii("lvert"), from_ascii("rvert"), ar, true));
555 }
556
557
558 bool testOpenAngled(MathAtom const & at)
559 {
560         return testSymbol(at, "langle");
561 }
562
563
564 bool testCloseAngled(MathAtom const & at)
565 {
566         return testSymbol(at, "rangle");
567 }
568
569
570 MathAtom replaceAngledDelims(const MathData & ar)
571 {
572         return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
573                 from_ascii("langle"), from_ascii("rangle"), ar, true));
574 }
575
576
577 // replace '('...')', '['...']', '|'...'|', and '<'...'>' sequences by a real InsetMathDelim
578 void extractDelims(MathData & ar)
579 {
580         //lyxerr << "\nDelims from: " << ar << endl;
581         replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
582         replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
583         replaceNested(ar, testOpenVert, testCloseVert, replaceVertDelims);
584         replaceNested(ar, testOpenAngled, testCloseAngled, replaceAngledDelims);
585         //lyxerr << "\nDelims to: " << ar << endl;
586 }
587
588
589
590 //
591 // search well-known functions
592 //
593
594
595 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
596 // assume 'extractDelims' ran before
597 void extractFunctions(MathData & ar, ExternalMath kind)
598 {
599         // FIXME From what I can see, this is quite broken right now, for reasons
600         // I will note below. (RGH)
601
602         // we need at least two items...
603         if (ar.size() < 2)
604                 return;
605
606         Buffer * buf = ar.buffer();
607
608         //lyxerr << "\nFunctions from: " << ar << endl;
609         for (size_t i = 0; i + 1 < ar.size(); ++i) {
610                 MathData::iterator it = ar.begin() + i;
611                 MathData::iterator jt = it + 1;
612
613                 docstring name;
614                 // is it a function?
615                 // it certainly is if it is well known...
616
617                 // FIXME This will never give us anything. When we get here, *it will
618                 // never point at a string, but only at a character. I.e., if we are
619                 // working on "sin(x)", then we are seeing:
620                 // [char s mathalpha][char i mathalpha][char n mathalpha][delim ( ) [char x mathalpha]]
621                 // and of course we will not find the function name "sin" in there, but
622                 // rather "n(x)".
623                 //
624                 // It appears that we original ran extractStrings() before we ran
625                 // extractFunctions(), but Andre changed this at f200be55, I think
626                 // because this messed up what he was trying to do with "dx" in the
627                 // context of integrals.
628                 //
629                 // This could be fixed by looking at a charSequence instead of just at
630                 // the various characters, one by one. But I am not sure I understand
631                 // exactly what we are trying to do here. And it involves a lot of
632                 // guessing.
633                 if (!extractFunctionName(*it, name)) {
634                         // is this a user defined function?
635                         // probably not, if it doesn't have a name.
636                         if (!extractString(*it, name))
637                                 continue;
638                         // it is not if it has no argument
639                         if (jt == ar.end())
640                                 continue;
641                         // guess so, if this is followed by
642                         // a DelimInset with a single item in the cell
643                         InsetMathDelim const * del = (*jt)->asDelimInset();
644                         if (!del || del->cell(0).size() != 1)
645                                 continue;
646                         // fall through into main branch
647                 }
648
649                 // do we have an exponent like in
650                 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
651                 MathData exp(buf);
652                 extractScript(exp, jt, ar.end(), true);
653
654                 // create a proper inset as replacement
655                 auto p = lyx::make_unique<InsetMathExFunc>(buf, name);
656
657                 // jt points to the "argument". Get hold of this.
658                 MathData::iterator st =
659                                 extractArgument(p->cell(0), jt, ar.end(), kind, true);
660
661                 // replace the function name by a real function inset
662                 *it = MathAtom(p.release());
663
664                 // remove the source of the argument from the array
665                 ar.erase(it + 1, st);
666
667                 // re-insert exponent
668                 ar.insert(i + 1, exp);
669                 //lyxerr << "\nFunctions to: " << ar << endl;
670         }
671 }
672
673
674 //
675 // search integrals
676 //
677
678 bool testIntSymbol(MathAtom const & at)
679 {
680         return testSymbol(at, from_ascii("int"));
681 }
682
683
684 bool testIntegral(MathAtom const & at)
685 {
686         return
687          testIntSymbol(at) ||
688                 ( at->asScriptInset()
689                   && !at->asScriptInset()->nuc().empty()
690                         && testIntSymbol(at->asScriptInset()->nuc().back()) );
691 }
692
693
694
695 bool testIntDiff(MathAtom const & at)
696 {
697         return testString(at, "d");
698 }
699
700
701 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
702 // assume 'extractDelims' ran before
703 void extractIntegrals(MathData & ar, ExternalMath kind)
704 {
705         // we need at least three items...
706         if (ar.size() < 3)
707                 return;
708
709         Buffer * buf = ar.buffer();
710
711         //lyxerr << "\nIntegrals from: " << ar << endl;
712         for (size_t i = 0; i + 1 < ar.size(); ++i) {
713                 MathData::iterator it = ar.begin() + i;
714
715                 // search 'd'
716                 MathData::iterator jt =
717                         endNestSearch(it, ar.end(), testIntegral, testIntDiff);
718
719                 // something sensible found?
720                 if (jt == ar.end())
721                         continue;
722
723                 // is this a integral name?
724                 if (!testIntegral(*it))
725                         continue;
726
727                 // core is part from behind the scripts to the 'd'
728                 auto p = lyx::make_unique<InsetMathExInt>(buf, from_ascii("int"));
729
730                 // handle scripts if available
731                 if (!testIntSymbol(*it)) {
732                         p->cell(2) = (*it)->asScriptInset()->down();
733                         p->cell(3) = (*it)->asScriptInset()->up();
734                 }
735                 p->cell(0) = MathData(buf, it + 1, jt);
736
737                 // use the "thing" behind the 'd' as differential
738                 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end(), kind);
739
740                 // remove used parts
741                 ar.erase(it + 1, tt);
742                 *it = MathAtom(p.release());
743         }
744         //lyxerr << "\nIntegrals to: " << ar << endl;
745 }
746
747
748 bool testTermDelimiter(MathAtom const & at)
749 {
750         return testString(at, "+") || testString(at, "-");
751 }
752
753
754 // try to extract a "term", i.e., something delimited by '+' or '-'.
755 // returns position behind the term
756 MathData::iterator extractTerm(MathData & ar,
757         MathData::iterator pos, MathData::iterator last)
758 {
759         while (pos != last && !testTermDelimiter(*pos)) {
760                 ar.push_back(*pos);
761                 ++pos;
762         }
763         return pos;
764 }
765
766
767 //
768 // search sums
769 //
770
771
772 bool testEqualSign(MathAtom const & at)
773 {
774         return testString(at, "=");
775 }
776
777
778 bool testSumSymbol(MathAtom const & p)
779 {
780         return testSymbol(p, from_ascii("sum"));
781 }
782
783
784 bool testSum(MathAtom const & at)
785 {
786         return
787          testSumSymbol(at) ||
788                 ( at->asScriptInset()
789                   && !at->asScriptInset()->nuc().empty()
790                         && testSumSymbol(at->asScriptInset()->nuc().back()) );
791 }
792
793
794 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
795 // assume 'extractDelims' ran before
796 void extractSums(MathData & ar)
797 {
798         // we need at least two items...
799         if (ar.size() < 2)
800                 return;
801
802         Buffer * buf = ar.buffer();
803
804         //lyxerr << "\nSums from: " << ar << endl;
805         for (size_t i = 0; i + 1 < ar.size(); ++i) {
806                 MathData::iterator it = ar.begin() + i;
807
808                 // is this a sum name?
809                 if (!testSum(ar[i]))
810                         continue;
811
812                 // create a proper inset as replacement
813                 auto p = lyx::make_unique<InsetMathExInt>(buf, from_ascii("sum"));
814
815                 // collect lower bound and summation index
816                 InsetMathScript const * sub = ar[i]->asScriptInset();
817                 if (sub && sub->hasDown()) {
818                         // try to figure out the summation index from the subscript
819                         MathData const & md = sub->down();
820                         MathData::const_iterator xt =
821                                 find_if(md.begin(), md.end(), &testEqualSign);
822                         if (xt != md.end()) {
823                                 // we found a '=', use everything in front of that as index,
824                                 // and everything behind as lower index
825                                 p->cell(1) = MathData(buf, md.begin(), xt);
826                                 p->cell(2) = MathData(buf, xt + 1, md.end());
827                         } else {
828                                 // use everything as summation index, don't use scripts.
829                                 p->cell(1) = md;
830                         }
831                 }
832
833                 // collect upper bound
834                 if (sub && sub->hasUp())
835                         p->cell(3) = sub->up();
836
837                 // use something  behind the script as core
838                 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
839
840                 // cleanup
841                 ar.erase(it + 1, tt);
842                 *it = MathAtom(p.release());
843         }
844         //lyxerr << "\nSums to: " << ar << endl;
845 }
846
847
848 //
849 // search differential stuff
850 //
851
852 // tests for 'd' or '\partial'
853 bool testDiffItem(MathAtom const & at)
854 {
855         if (testString(at, "d") || testSymbol(at, "partial"))
856                 return true;
857
858         // we may have d^n .../d and splitScripts() has not yet seen it
859         InsetMathScript const * sup = at->asScriptInset();
860         if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
861                 MathAtom const & ma = sup->nuc().front();
862                 return testString(ma, "d") || testSymbol(ma, "partial");
863         }
864         return false;
865 }
866
867
868 bool testDiffArray(MathData const & ar)
869 {
870         return !ar.empty() && testDiffItem(ar.front());
871 }
872
873
874 bool testDiffFrac(MathAtom const & at)
875 {
876         return
877                 at->asFracInset()
878                         && testDiffArray(at->asFracInset()->cell(0))
879                         && testDiffArray(at->asFracInset()->cell(1));
880 }
881
882
883 void extractDiff(MathData & ar)
884 {
885         Buffer * buf = ar.buffer();
886         //lyxerr << "\nDiffs from: " << ar << endl;
887         for (size_t i = 0; i < ar.size(); ++i) {
888                 MathData::iterator it = ar.begin() + i;
889
890                 // is this a "differential fraction"?
891                 if (!testDiffFrac(*it))
892                         continue;
893
894                 InsetMathFrac const * f = (*it)->asFracInset();
895                 if (!f) {
896                         lyxerr << "should not happen" << endl;
897                         continue;
898                 }
899
900                 // create a proper diff inset
901                 auto diff = lyx::make_unique<InsetMathDiff>(buf);
902
903                 // collect function, let jt point behind last used item
904                 MathData::iterator jt = it + 1;
905                 //int n = 1;
906                 MathData numer(f->cell(0));
907                 splitScripts(numer);
908                 if (numer.size() > 1 && numer[1]->asScriptInset()) {
909                         // this is something like  d^n f(x) / d... or  d^n / d...
910                         // FIXME
911                         //n = 1;
912                         if (numer.size() > 2)
913                                 diff->cell(0) = MathData(buf, numer.begin() + 2, numer.end());
914                         else
915                                 jt = extractTerm(diff->cell(0), jt, ar.end());
916                 } else {
917                         // simply d f(x) / d... or  d/d...
918                         if (numer.size() > 1)
919                                 diff->cell(0) = MathData(buf, numer.begin() + 1, numer.end());
920                         else
921                                 jt = extractTerm(diff->cell(0), jt, ar.end());
922                 }
923
924                 // collect denominator parts
925                 MathData denom(f->cell(1));
926                 splitScripts(denom);
927                 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
928                         // find the next 'd'
929                         MathData::iterator et
930                                 = find_if(dt + 1, denom.end(), &testDiffItem);
931
932                         // point before this
933                         MathData::iterator st = et - 1;
934                         InsetMathScript const * script = (*st)->asScriptInset();
935                         if (script && script->hasUp()) {
936                                 // things like   d.../dx^n
937                                 int mult = 1;
938                                 if (extractNumber(script->up(), mult)) {
939                                         //lyxerr << "mult: " << mult << endl;
940                                         if (mult < 0 || mult > 1000) {
941                                                 lyxerr << "Cannot differentiate less than 0 or more than 1000 times !" << endl;
942                                                 continue;
943                                         }
944                                         for (int ii = 0; ii < mult; ++ii)
945                                                 diff->addDer(MathData(buf, dt + 1, st));
946                                 }
947                         } else {
948                                 // just  d.../dx
949                                 diff->addDer(MathData(buf, dt + 1, et));
950                         }
951                         dt = et;
952                 }
953
954                 // cleanup
955                 ar.erase(it + 1, jt);
956                 *it = MathAtom(diff.release());
957         }
958         //lyxerr << "\nDiffs to: " << ar << endl;
959 }
960
961
962 //
963 // search limits
964 //
965
966
967 bool testRightArrow(MathAtom const & at)
968 {
969         return testSymbol(at, "to") || testSymbol(at, "rightarrow");
970 }
971
972
973
974 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
975 // assume 'extractDelims' ran before
976 void extractLims(MathData & ar)
977 {
978         Buffer * buf = ar.buffer();
979         //lyxerr << "\nLimits from: " << ar << endl;
980         for (size_t i = 0; i < ar.size(); ++i) {
981                 MathData::iterator it = ar.begin() + i;
982
983                 // must be a script inset with a subscript (without superscript)
984                 InsetMathScript const * sub = (*it)->asScriptInset();
985                 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
986                         continue;
987
988                 // is this a limit function?
989                 if (!testSymbol(sub->nuc().front(), "lim"))
990                         continue;
991
992                 // subscript must contain a -> symbol
993                 MathData const & s = sub->down();
994                 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
995                 if (st == s.end())
996                         continue;
997
998                 // the -> splits the subscript int x and x0
999                 MathData x  = MathData(buf, s.begin(), st);
1000                 MathData x0 = MathData(buf, st + 1, s.end());
1001
1002                 // use something behind the script as core
1003                 MathData f(buf);
1004                 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
1005
1006                 // cleanup
1007                 ar.erase(it + 1, tt);
1008
1009                 // create a proper inset as replacement
1010                 *it = MathAtom(new InsetMathLim(buf, f, x, x0));
1011         }
1012         //lyxerr << "\nLimits to: " << ar << endl;
1013 }
1014
1015
1016 //
1017 // combine searches
1018 //
1019
1020 void extractStructure(MathData & ar, ExternalMath kind)
1021 {
1022         //lyxerr << "\nStructure from: " << ar << endl;
1023         if (kind != MATHML && kind != HTML)
1024                 splitScripts(ar);
1025         extractDelims(ar);
1026         extractIntegrals(ar, kind);
1027         if (kind != MATHML && kind != HTML)
1028                 extractSums(ar);
1029         extractNumbers(ar);
1030         extractMatrices(ar);
1031         if (kind != MATHML && kind != HTML) {
1032                 extractFunctions(ar, kind);
1033                 extractDets(ar);
1034                 extractDiff(ar);
1035                 extractExps(ar);
1036                 extractLims(ar);
1037                 extractStrings(ar);
1038         }
1039         //lyxerr << "\nStructure to: " << ar << endl;
1040 }
1041
1042
1043 namespace {
1044
1045         string captureOutput(string const & cmd, string const & data)
1046         {
1047                 // In order to avoid parsing problems with command interpreters
1048                 // we pass input data through a file
1049                 // Since the CAS is supposed to read the temp file we need
1050                 // to unlock it on windows (bug 10262).
1051                 unique_ptr<TempFile> tempfile(new TempFile("casinput"));
1052                 tempfile->setAutoRemove(false);
1053                 FileName const cas_tmpfile = tempfile->name();
1054                 tempfile.reset();
1055
1056                 if (cas_tmpfile.empty()) {
1057                         lyxerr << "Warning: cannot create temporary file."
1058                                << endl;
1059                         return string();
1060                 }
1061                 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
1062                 os << data << endl;
1063                 os.close();
1064                 string command =  cmd + " < "
1065                         + quoteName(cas_tmpfile.toFilesystemEncoding());
1066                 lyxerr << "calling: " << cmd
1067                        << "\ninput: '" << data << "'" << endl;
1068                 cmd_ret const ret = runCommand(command);
1069                 cas_tmpfile.removeFile();
1070                 return ret.result;
1071         }
1072
1073         size_t get_matching_brace(string const & str, size_t i)
1074         {
1075                 int count = 1;
1076                 size_t n = str.size();
1077                 while (i < n) {
1078                         i = str.find_first_of("{}", i+1);
1079                         if (i == npos)
1080                                 return i;
1081                         if (str[i] == '{')
1082                                 ++count;
1083                         else
1084                                 --count;
1085                         if (count == 0)
1086                                 return i;
1087                 }
1088                 return npos;
1089         }
1090
1091         size_t get_matching_brace_back(string const & str, size_t i)
1092         {
1093                 int count = 1;
1094                 while (i > 0) {
1095                         i = str.find_last_of("{}", i-1);
1096                         if (i == npos)
1097                                 return i;
1098                         if (str[i] == '}')
1099                                 ++count;
1100                         else
1101                                 --count;
1102                         if (count == 0)
1103                                 return i;
1104                 }
1105                 return npos;
1106         }
1107
1108         MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1109         {
1110                 odocstringstream os;
1111                 MaximaStream ms(os);
1112                 ms << ar;
1113                 docstring expr = os.str();
1114                 docstring const header = from_ascii("simpsum:true;");
1115
1116                 string out;
1117                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1118                         // try to fix missing '*' the hard way
1119                         //
1120                         // > echo "2x;" | maxima
1121                         // ...
1122                         // (C1) Incorrect syntax: x is not an infix operator
1123                         // 2x;
1124                         //  ^
1125                         //
1126                         lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1127                         docstring full = header + "tex(" + expr + ");";
1128                         out = captureOutput("maxima", to_utf8(full));
1129
1130                         // leave loop if expression syntax is probably ok
1131                         if (out.find("Incorrect syntax") == npos)
1132                                 break;
1133
1134                         // search line with "Incorrect syntax"
1135                         istringstream is(out);
1136                         string line;
1137                         while (is) {
1138                                 getline(is, line);
1139                                 if (line.find("Incorrect syntax") != npos)
1140                                         break;
1141                         }
1142
1143                         // 2nd next line is the one with caret
1144                         getline(is, line);
1145                         getline(is, line);
1146                         size_t pos = line.find('^');
1147                         lyxerr << "found caret at pos: '" << pos << "'" << endl;
1148                         if (pos == npos || pos < 4)
1149                                 break; // caret position not found
1150                         pos -= 4; // skip the "tex(" part
1151                         if (expr[pos] == '*')
1152                                 break; // two '*' in a row are definitely bad
1153                         expr.insert(pos, from_ascii("*"));
1154                 }
1155
1156                 vector<string> tmp = getVectorFromString(out, "$$");
1157                 if (tmp.size() < 2)
1158                         return MathData(nullptr);
1159
1160                 out = subst(subst(tmp[1], "\\>", string()), "{\\it ", "\\mathit{");
1161                 lyxerr << "output: '" << out << "'" << endl;
1162
1163                 // Ugly code that tries to make the result prettier
1164                 size_t i = out.find("\\mathchoice");
1165                 while (i != npos) {
1166                         size_t j = get_matching_brace(out, i + 12);
1167                         size_t k = get_matching_brace(out, j + 1);
1168                         k = get_matching_brace(out, k + 1);
1169                         k = get_matching_brace(out, k + 1);
1170                         string mid = out.substr(i + 13, j - i - 13);
1171                         if (mid.find("\\over") != npos)
1172                                 mid = '{' + mid + '}';
1173                         out = out.substr(0, i)
1174                                 + mid
1175                                 + out.substr(k + 1);
1176                         //lyxerr << "output: " << out << endl;
1177                         i = out.find("\\mathchoice", i);
1178                 }
1179
1180                 i = out.find("\\over");
1181                 while (i != npos) {
1182                         size_t j = get_matching_brace_back(out, i - 1);
1183                         if (j == npos || j == 0)
1184                                 break;
1185                         size_t k = get_matching_brace(out, i + 5);
1186                         if (k == npos || k + 1 == out.size())
1187                                 break;
1188                         out = out.substr(0, j - 1)
1189                                 + "\\frac"
1190                                 + out.substr(j, i - j)
1191                                 + out.substr(i + 5, k - i - 4)
1192                                 + out.substr(k + 2);
1193                         //lyxerr << "output: " << out << endl;
1194                         i = out.find("\\over", i + 4);
1195                 }
1196                 MathData res(nullptr);
1197                 mathed_parse_cell(res, from_utf8(out));
1198                 return res;
1199         }
1200
1201
1202         MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1203         {
1204                 string header = "readlib(latex):\n";
1205
1206                 // remove the \\it for variable names
1207                 //"#`latex/csname_font` := `\\it `:"
1208                 header +=
1209                         "`latex/csname_font` := ``:\n";
1210
1211                 // export matrices in (...) instead of [...]
1212                 header +=
1213                         "`latex/latex/matrix` := "
1214                                 "subs(`[`=`(`, `]`=`)`,"
1215                                         "eval(`latex/latex/matrix`)):\n";
1216
1217                 // replace \\cdots with proper '*'
1218                 header +=
1219                         "`latex/latex/*` := "
1220                                 "subs(`\\,`=`\\cdot `,"
1221                                         "eval(`latex/latex/*`)):\n";
1222
1223                 // remove spurious \\noalign{\\medskip} in matrix output
1224                 header +=
1225                         "`latex/latex/matrix`:= "
1226                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1227                                         "eval(`latex/latex/matrix`)):\n";
1228
1229                 //"#`latex/latex/symbol` "
1230                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1231
1232                 string trailer = "quit;";
1233                 odocstringstream os;
1234                 MapleStream ms(os);
1235                 ms << ar;
1236                 string expr = to_utf8(os.str());
1237                 lyxerr << "ar: '" << ar << "'\n"
1238                        << "ms: '" << expr << "'" << endl;
1239
1240                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1241                         // try to fix missing '*' the hard way by using mint
1242                         //
1243                         // ... > echo "1A;" | mint -i 1 -S -s -q
1244                         // on line     1: 1A;
1245                         //                 ^ syntax error -
1246                         //                   Probably missing an operator such as * p
1247                         //
1248                         lyxerr << "checking expr: '" << expr << "'" << endl;
1249                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1250                         if (out.empty())
1251                                 break; // expression syntax is ok
1252                         istringstream is(out);
1253                         string line;
1254                         getline(is, line);
1255                         if (!prefixIs(line, "on line"))
1256                                 break; // error message not identified
1257                         getline(is, line);
1258                         size_t pos = line.find('^');
1259                         if (pos == string::npos || pos < 15)
1260                                 break; // caret position not found
1261                         pos -= 15; // skip the "on line ..." part
1262                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1263                                 break; // two '*' in a row are definitely bad
1264                         expr.insert(pos, 1, '*');
1265                 }
1266
1267                 // FIXME UNICODE Is utf8 encoding correct?
1268                 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1269                 string out = captureOutput("maple -q", header + full + trailer);
1270
1271                 // change \_ into _
1272
1273                 //
1274                 MathData res(nullptr);
1275                 mathed_parse_cell(res, from_utf8(out));
1276                 return res;
1277         }
1278
1279
1280         MathData pipeThroughOctave(docstring const &, MathData const & ar)
1281         {
1282                 odocstringstream os;
1283                 OctaveStream vs(os);
1284                 vs << ar;
1285                 string expr = to_utf8(os.str());
1286                 string out;
1287                 // FIXME const cast
1288                 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1289                 lyxerr << "pipe: ar: '" << ar << "'\n"
1290                        << "pipe: expr: '" << expr << "'" << endl;
1291
1292                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1293                         //
1294                         // try to fix missing '*' the hard way
1295                         // parse error:
1296                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1297                         //                                   ^
1298                         //
1299                         lyxerr << "checking expr: '" << expr << "'" << endl;
1300                         out = captureOutput("octave -q 2>&1", expr);
1301                         lyxerr << "output: '" << out << "'" << endl;
1302
1303                         // leave loop if expression syntax is probably ok
1304                         if (out.find("parse error:") == string::npos)
1305                                 break;
1306
1307                         // search line with single caret
1308                         istringstream is(out);
1309                         string line;
1310                         while (is) {
1311                                 getline(is, line);
1312                                 lyxerr << "skipping line: '" << line << "'" << endl;
1313                                 if (line.find(">>> ") != string::npos)
1314                                         break;
1315                         }
1316
1317                         // found line with error, next line is the one with caret
1318                         getline(is, line);
1319                         size_t pos = line.find('^');
1320                         lyxerr << "caret line: '" << line << "'" << endl;
1321                         lyxerr << "found caret at pos: '" << pos << "'" << endl;
1322                         if (pos == string::npos || pos < 4)
1323                                 break; // caret position not found
1324                         pos -= 4; // skip the ">>> " part
1325                         if (expr[pos] == '*')
1326                                 break; // two '*' in a row are definitely bad
1327                         expr.insert(pos, 1, '*');
1328                 }
1329
1330                 // remove 'ans = ' taking into account that there may be an
1331                 // ansi control sequence before, such as '\033[?1034hans = '
1332                 size_t i = out.find("ans = ");
1333                 if (i == string::npos)
1334                         return MathData(nullptr);
1335                 out = out.substr(i + 6);
1336
1337                 // parse output as matrix or single number
1338                 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1339                 InsetMathArray const * mat = at->asArrayInset();
1340                 MathData res(buf);
1341                 if (mat->ncols() == 1 && mat->nrows() == 1)
1342                         res.append(mat->cell(0));
1343                 else {
1344                         res.push_back(MathAtom(
1345                                 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1346                         res.back().nucleus()->cell(0).push_back(at);
1347                 }
1348                 return res;
1349         }
1350
1351
1352         string fromMathematicaName(string const & name)
1353         {
1354                 if (name == "Sin")    return "sin";
1355                 if (name == "Sinh")   return "sinh";
1356                 if (name == "ArcSin") return "arcsin";
1357                 if (name == "Cos")    return "cos";
1358                 if (name == "Cosh")   return "cosh";
1359                 if (name == "ArcCos") return "arccos";
1360                 if (name == "Tan")    return "tan";
1361                 if (name == "Tanh")   return "tanh";
1362                 if (name == "ArcTan") return "arctan";
1363                 if (name == "Cot")    return "cot";
1364                 if (name == "Coth")   return "coth";
1365                 if (name == "Csc")    return "csc";
1366                 if (name == "Sec")    return "sec";
1367                 if (name == "Exp")    return "exp";
1368                 if (name == "Log")    return "log";
1369                 if (name == "Arg" )   return "arg";
1370                 if (name == "Det" )   return "det";
1371                 if (name == "GCD" )   return "gcd";
1372                 if (name == "Max" )   return "max";
1373                 if (name == "Min" )   return "min";
1374                 if (name == "Erf" )   return "erf";
1375                 if (name == "Erfc" )  return "erfc";
1376                 return name;
1377         }
1378
1379
1380         void prettifyMathematicaOutput(string & out, string const & macroName,
1381                         bool roman, bool translate)
1382         {
1383                 string const macro = "\\" + macroName + "{";
1384                 size_t const len = macro.length();
1385                 size_t i = out.find(macro);
1386
1387                 while (i != npos) {
1388                         size_t const j = get_matching_brace(out, i + len);
1389                         string const name = out.substr(i + len, j - i - len);
1390                         out = out.substr(0, i)
1391                                 + (roman ? "\\mathrm{" : "")
1392                                 + (translate ? fromMathematicaName(name) : name)
1393                                 + out.substr(roman ? j : j + 1);
1394                         //lyxerr << "output: " << out << endl;
1395                         i = out.find(macro, i);
1396                 }
1397         }
1398
1399
1400         MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1401         {
1402                 odocstringstream os;
1403                 MathematicaStream ms(os);
1404                 ms << ar;
1405                 // FIXME UNICODE Is utf8 encoding correct?
1406                 string const expr = to_utf8(os.str());
1407                 string out;
1408
1409                 lyxerr << "expr: '" << expr << "'" << endl;
1410
1411                 string const full = "TeXForm[" + expr + "]";
1412                 out = captureOutput("math", full);
1413                 lyxerr << "output: '" << out << "'" << endl;
1414
1415                 size_t pos1 = out.find("Out[1]//TeXForm= ");
1416                 size_t pos2 = out.find("In[2]:=");
1417
1418                 if (pos1 == string::npos || pos2 == string::npos)
1419                         return MathData(nullptr);
1420
1421                 // get everything from pos1+17 to pos2
1422                 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1423                 out = subst(subst(out, '\r', ' '), '\n', ' ');
1424
1425                 // tries to make the result prettier
1426                 prettifyMathematicaOutput(out, "Mfunction", true, true);
1427                 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1428                 prettifyMathematicaOutput(out, "Mvariable", false, false);
1429
1430                 MathData res(nullptr);
1431                 mathed_parse_cell(res, from_utf8(out));
1432                 return res;
1433         }
1434
1435 } // namespace
1436
1437 } // namespace
1438
1439 void write(MathData const & dat, TeXMathStream & wi)
1440 {
1441         wi.firstitem() = true;
1442         docstring s;
1443         for (MathData::const_iterator it = dat.begin(); it != dat.end(); ++it) {
1444                 InsetMathChar const * const c = (*it)->asCharInset();
1445                 if (c)
1446                         s += c->getChar();
1447                 else {
1448                         if (!s.empty()) {
1449                                 writeString(s, wi);
1450                                 s.clear();
1451                         }
1452                         (*it)->write(wi);
1453                         wi.firstitem() = false;
1454                 }
1455         }
1456         if (!s.empty()) {
1457                 writeString(s, wi);
1458                 wi.firstitem() = false;
1459         }
1460 }
1461
1462
1463 void writeString(docstring const & s, TeXMathStream & os)
1464 {
1465         if (!os.latex()) {
1466                 os << s;
1467                 return;
1468         }
1469
1470         docstring str = s;
1471         if (os.asciiOnly())
1472                 str = escape(s);
1473
1474         if (os.output() == TeXMathStream::wsSearchAdv) {
1475                 os << str;
1476                 return;
1477         }
1478
1479         if (os.lockedMode()) {
1480                 bool space;
1481                 docstring cmd;
1482                 for (char_type c : str) {
1483                         try {
1484                                 Encodings::latexMathChar(c, true, os.encoding(), cmd, space);
1485                                 os << cmd;
1486                                 os.pendingSpace(space);
1487                         } catch (EncodingException const & e) {
1488                                 switch (os.output()) {
1489                                 case TeXMathStream::wsDryrun: {
1490                                         os << "<" << _("LyX Warning: ")
1491                                            << _("uncodable character") << " '";
1492                                         os << docstring(1, e.failed_char);
1493                                         os << "'>";
1494                                         break;
1495                                 }
1496                                 case TeXMathStream::wsPreview: {
1497                                         // indicate the encoding error by a boxed '?'
1498                                         os << "{\\fboxsep=1pt\\fbox{?}}";
1499                                         LYXERR0("Uncodable character" << " '"
1500                                                 << docstring(1, e.failed_char)
1501                                                 << "'");
1502                                         break;
1503                                 }
1504                                 case TeXMathStream::wsDefault:
1505                                 default:
1506                                         // throw again
1507                                         throw;
1508                                 }
1509                         }
1510                 }
1511                 return;
1512         }
1513
1514         // We may already be inside an \ensuremath command.
1515         bool in_forced_mode = os.pendingBrace();
1516
1517         // We will take care of matching braces.
1518         os.pendingBrace(false);
1519
1520         for (char_type const c : str) {
1521                 bool mathmode = in_forced_mode ? os.textMode() : !os.textMode();
1522                 docstring command(1, c);
1523                 try {
1524                         bool termination = false;
1525                         if (isASCII(c) ||
1526                             Encodings::latexMathChar(c, mathmode, os.encoding(), command, termination)) {
1527                                 if (os.textMode()) {
1528                                         if (in_forced_mode) {
1529                                                 // we were inside \lyxmathsym
1530                                                 os << '}';
1531                                                 os.textMode(false);
1532                                                 in_forced_mode = false;
1533                                         }
1534                                         if (!isASCII(c) && os.textMode()) {
1535                                                 os << "\\ensuremath{";
1536                                                 os.textMode(false);
1537                                                 in_forced_mode = true;
1538                                         }
1539                                 } else if (isASCII(c) && in_forced_mode) {
1540                                         // we were inside \ensuremath
1541                                         os << '}';
1542                                         os.textMode(true);
1543                                         in_forced_mode = false;
1544                                 }
1545                         } else if (!os.textMode()) {
1546                                         if (in_forced_mode) {
1547                                                 // we were inside \ensuremath
1548                                                 os << '}';
1549                                                 in_forced_mode = false;
1550                                         } else {
1551                                                 os << "\\lyxmathsym{";
1552                                                 in_forced_mode = true;
1553                                         }
1554                                         os.textMode(true);
1555                         }
1556                         os << command;
1557                         // We may need a space if the command contains a macro
1558                         // and the last char is ASCII.
1559                         if (termination)
1560                                 os.pendingSpace(true);
1561                 } catch (EncodingException const & e) {
1562                         switch (os.output()) {
1563                         case TeXMathStream::wsDryrun: {
1564                                 os << "<" << _("LyX Warning: ")
1565                                    << _("uncodable character") << " '";
1566                                 os << docstring(1, e.failed_char);
1567                                 os << "'>";
1568                                 break;
1569                         }
1570                         case TeXMathStream::wsPreview: {
1571                                 // indicate the encoding error by a boxed '?'
1572                                 os << "{\\fboxsep=1pt\\fbox{?}}";
1573                                 LYXERR0("Uncodable character" << " '"
1574                                         << docstring(1, e.failed_char)
1575                                         << "'");
1576                                 break;
1577                         }
1578                         case TeXMathStream::wsDefault:
1579                         default:
1580                                 // throw again
1581                                 throw;
1582                         }
1583                 }
1584         }
1585
1586         if (in_forced_mode && os.textMode()) {
1587                 // We have to care for closing \lyxmathsym
1588                 os << '}';
1589                 os.textMode(false);
1590         } else {
1591                 os.pendingBrace(in_forced_mode);
1592         }
1593 }
1594
1595
1596 void normalize(MathData const & ar, NormalStream & os)
1597 {
1598         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1599                 (*it)->normalize(os);
1600 }
1601
1602
1603 void octave(MathData const & dat, OctaveStream & os)
1604 {
1605         MathData ar = dat;
1606         extractStructure(ar, OCTAVE);
1607         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1608                 (*it)->octave(os);
1609 }
1610
1611
1612 void maple(MathData const & dat, MapleStream & os)
1613 {
1614         MathData ar = dat;
1615         extractStructure(ar, MAPLE);
1616         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1617                 (*it)->maple(os);
1618 }
1619
1620
1621 void maxima(MathData const & dat, MaximaStream & os)
1622 {
1623         MathData ar = dat;
1624         extractStructure(ar, MAXIMA);
1625         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1626                 (*it)->maxima(os);
1627 }
1628
1629
1630 void mathematica(MathData const & dat, MathematicaStream & os)
1631 {
1632         MathData ar = dat;
1633         extractStructure(ar, MATHEMATICA);
1634         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1635                 (*it)->mathematica(os);
1636 }
1637
1638
1639 void mathmlize(MathData const & dat, MathMLStream & ms)
1640 {
1641         MathData ar = dat;
1642         extractStructure(ar, MATHML);
1643         if (ar.empty()) {
1644                 if (!ms.inText())
1645                         ms << CTag("mrow");
1646         } else if (ar.size() == 1) {
1647                 ms << ar.front();
1648         } else {
1649                 if (!ms.inText())
1650                         ms << MTag("mrow");
1651                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1652                         (*it)->mathmlize(ms);
1653                 if (!ms.inText())
1654                         ms << ETag("mrow");
1655         }
1656 }
1657
1658
1659 void htmlize(MathData const & dat, HtmlStream & os)
1660 {
1661         MathData ar = dat;
1662         extractStructure(ar, HTML);
1663         if (ar.empty())
1664                 return;
1665         if (ar.size() == 1) {
1666                 os << ar.front();
1667                 return;
1668         }
1669         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1670                 (*it)->htmlize(os);
1671 }
1672
1673
1674 // convert this inset somehow to a number
1675 bool extractNumber(MathData const & ar, int & i)
1676 {
1677         idocstringstream is(charSequence(ar.begin(), ar.end()));
1678         is >> i;
1679         // Do not convert is implicitly to bool, since that is forbidden in C++11.
1680         return !is.fail();
1681 }
1682
1683
1684 bool extractNumber(MathData const & ar, double & d)
1685 {
1686         idocstringstream is(charSequence(ar.begin(), ar.end()));
1687         is >> d;
1688         // Do not convert is implicitly to bool, since that is forbidden in C++11.
1689         return !is.fail();
1690 }
1691
1692
1693 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1694         MathData const & ar)
1695 {
1696         if (lang == "octave")
1697                 return pipeThroughOctave(extra, ar);
1698
1699         if (lang == "maxima")
1700                 return pipeThroughMaxima(extra, ar);
1701
1702         if (lang == "maple")
1703                 return pipeThroughMaple(extra, ar);
1704
1705         if (lang == "mathematica")
1706                 return pipeThroughMathematica(extra, ar);
1707
1708         // create normalized expression
1709         odocstringstream os;
1710         NormalStream ns(os);
1711         os << '[' << extra << ' ';
1712         ns << ar;
1713         os << ']';
1714         // FIXME UNICODE Is utf8 encoding correct?
1715         string data = to_utf8(os.str());
1716
1717         // search external script
1718         FileName const file = libFileSearch("mathed", "extern_" + lang);
1719         if (file.empty()) {
1720                 lyxerr << "converter to '" << lang << "' not found" << endl;
1721                 return MathData(nullptr);
1722         }
1723
1724         // run external sript
1725         string out = captureOutput(file.absFileName(), data);
1726         MathData res(nullptr);
1727         mathed_parse_cell(res, from_utf8(out));
1728         return res;
1729 }
1730
1731
1732 } // namespace lyx