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