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