]> git.lyx.org Git - lyx.git/blob - src/mathed/MathExtern.cpp
status.22x
[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                 // Since the CAS is supposed to read the temp file we need
1004                 // to unlock it on windows (bug 10262).
1005                 auto_ptr<TempFile> tempfile(new TempFile("casinput"));
1006                 tempfile->setAutoRemove(false);
1007                 FileName const cas_tmpfile = tempfile->name();
1008                 tempfile.reset();
1009
1010                 if (cas_tmpfile.empty()) {
1011                         lyxerr << "Warning: cannot create temporary file."
1012                                << endl;
1013                         return string();
1014                 }
1015                 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
1016                 os << data << endl;
1017                 os.close();
1018                 string command =  cmd + " < "
1019                         + quoteName(cas_tmpfile.toFilesystemEncoding());
1020                 lyxerr << "calling: " << cmd
1021                        << "\ninput: '" << data << "'" << endl;
1022                 cmd_ret const ret = runCommand(command);
1023                 cas_tmpfile.removeFile();
1024                 return ret.second;
1025         }
1026
1027         size_t get_matching_brace(string const & str, size_t i)
1028         {
1029                 int count = 1;
1030                 size_t n = str.size();
1031                 while (i < n) {
1032                         i = str.find_first_of("{}", i+1);
1033                         if (i == npos)
1034                                 return i;
1035                         if (str[i] == '{')
1036                                 ++count;
1037                         else
1038                                 --count;
1039                         if (count == 0)
1040                                 return i;
1041                 }
1042                 return npos;
1043         }
1044
1045         size_t get_matching_brace_back(string const & str, size_t i)
1046         {
1047                 int count = 1;
1048                 while (i > 0) {
1049                         i = str.find_last_of("{}", i-1);
1050                         if (i == npos)
1051                                 return i;
1052                         if (str[i] == '}')
1053                                 ++count;
1054                         else
1055                                 --count;
1056                         if (count == 0)
1057                                 return i;
1058                 }
1059                 return npos;
1060         }
1061
1062         MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1063         {
1064                 odocstringstream os;
1065                 MaximaStream ms(os);
1066                 ms << ar;
1067                 docstring expr = os.str();
1068                 docstring const header = from_ascii("simpsum:true;");
1069
1070                 string out;
1071                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1072                         // try to fix missing '*' the hard way
1073                         //
1074                         // > echo "2x;" | maxima
1075                         // ...
1076                         // (C1) Incorrect syntax: x is not an infix operator
1077                         // 2x;
1078                         //  ^
1079                         //
1080                         lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1081                         docstring full = header + "tex(" + expr + ");";
1082                         out = captureOutput("maxima", to_utf8(full));
1083
1084                         // leave loop if expression syntax is probably ok
1085                         if (out.find("Incorrect syntax") == npos)
1086                                 break;
1087
1088                         // search line with "Incorrect syntax"
1089                         istringstream is(out);
1090                         string line;
1091                         while (is) {
1092                                 getline(is, line);
1093                                 if (line.find("Incorrect syntax") != npos)
1094                                         break;
1095                         }
1096
1097                         // 2nd next line is the one with caret
1098                         getline(is, line);
1099                         getline(is, line);
1100                         size_t pos = line.find('^');
1101                         lyxerr << "found caret at pos: '" << pos << "'" << endl;
1102                         if (pos == npos || pos < 4)
1103                                 break; // caret position not found
1104                         pos -= 4; // skip the "tex(" part
1105                         if (expr[pos] == '*')
1106                                 break; // two '*' in a row are definitely bad
1107                         expr.insert(pos, from_ascii("*"));
1108                 }
1109
1110                 vector<string> tmp = getVectorFromString(out, "$$");
1111                 if (tmp.size() < 2)
1112                         return MathData();
1113
1114                 out = subst(tmp[1], "\\>", string());
1115                 lyxerr << "output: '" << out << "'" << endl;
1116
1117                 // Ugly code that tries to make the result prettier
1118                 size_t i = out.find("\\mathchoice");
1119                 while (i != npos) {
1120                         size_t j = get_matching_brace(out, i + 12);
1121                         size_t k = get_matching_brace(out, j + 1);
1122                         k = get_matching_brace(out, k + 1);
1123                         k = get_matching_brace(out, k + 1);
1124                         string mid = out.substr(i + 13, j - i - 13);
1125                         if (mid.find("\\over") != npos)
1126                                 mid = '{' + mid + '}';
1127                         out = out.substr(0, i)
1128                                 + mid
1129                                 + out.substr(k + 1);
1130                         //lyxerr << "output: " << out << endl;
1131                         i = out.find("\\mathchoice", i);
1132                 }
1133
1134                 i = out.find("\\over");
1135                 while (i != npos) {
1136                         size_t j = get_matching_brace_back(out, i - 1);
1137                         if (j == npos || j == 0)
1138                                 break;
1139                         size_t k = get_matching_brace(out, i + 5);
1140                         if (k == npos || k + 1 == out.size())
1141                                 break;
1142                         out = out.substr(0, j - 1)
1143                                 + "\\frac"
1144                                 + out.substr(j, i - j)
1145                                 + out.substr(i + 5, k - i - 4)
1146                                 + out.substr(k + 2);
1147                         //lyxerr << "output: " << out << endl;
1148                         i = out.find("\\over", i + 4);
1149                 }
1150                 MathData res;
1151                 mathed_parse_cell(res, from_utf8(out));
1152                 return res;
1153         }
1154
1155
1156         MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1157         {
1158                 string header = "readlib(latex):\n";
1159
1160                 // remove the \\it for variable names
1161                 //"#`latex/csname_font` := `\\it `:"
1162                 header +=
1163                         "`latex/csname_font` := ``:\n";
1164
1165                 // export matrices in (...) instead of [...]
1166                 header +=
1167                         "`latex/latex/matrix` := "
1168                                 "subs(`[`=`(`, `]`=`)`,"
1169                                         "eval(`latex/latex/matrix`)):\n";
1170
1171                 // replace \\cdots with proper '*'
1172                 header +=
1173                         "`latex/latex/*` := "
1174                                 "subs(`\\,`=`\\cdot `,"
1175                                         "eval(`latex/latex/*`)):\n";
1176
1177                 // remove spurious \\noalign{\\medskip} in matrix output
1178                 header +=
1179                         "`latex/latex/matrix`:= "
1180                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1181                                         "eval(`latex/latex/matrix`)):\n";
1182
1183                 //"#`latex/latex/symbol` "
1184                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1185
1186                 string trailer = "quit;";
1187                 odocstringstream os;
1188                 MapleStream ms(os);
1189                 ms << ar;
1190                 string expr = to_utf8(os.str());
1191                 lyxerr << "ar: '" << ar << "'\n"
1192                        << "ms: '" << expr << "'" << endl;
1193
1194                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1195                         // try to fix missing '*' the hard way by using mint
1196                         //
1197                         // ... > echo "1A;" | mint -i 1 -S -s -q
1198                         // on line     1: 1A;
1199                         //                 ^ syntax error -
1200                         //                   Probably missing an operator such as * p
1201                         //
1202                         lyxerr << "checking expr: '" << expr << "'" << endl;
1203                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1204                         if (out.empty())
1205                                 break; // expression syntax is ok
1206                         istringstream is(out);
1207                         string line;
1208                         getline(is, line);
1209                         if (!prefixIs(line, "on line"))
1210                                 break; // error message not identified
1211                         getline(is, line);
1212                         size_t pos = line.find('^');
1213                         if (pos == string::npos || pos < 15)
1214                                 break; // caret position not found
1215                         pos -= 15; // skip the "on line ..." part
1216                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1217                                 break; // two '*' in a row are definitely bad
1218                         expr.insert(pos, 1, '*');
1219                 }
1220
1221                 // FIXME UNICODE Is utf8 encoding correct?
1222                 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1223                 string out = captureOutput("maple -q", header + full + trailer);
1224
1225                 // change \_ into _
1226
1227                 //
1228                 MathData res;
1229                 mathed_parse_cell(res, from_utf8(out));
1230                 return res;
1231         }
1232
1233
1234         MathData pipeThroughOctave(docstring const &, MathData const & ar)
1235         {
1236                 odocstringstream os;
1237                 OctaveStream vs(os);
1238                 vs << ar;
1239                 string expr = to_utf8(os.str());
1240                 string out;
1241                 // FIXME const cast
1242                 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1243                 lyxerr << "pipe: ar: '" << ar << "'\n"
1244                        << "pipe: expr: '" << expr << "'" << endl;
1245
1246                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1247                         //
1248                         // try to fix missing '*' the hard way
1249                         // parse error:
1250                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1251                         //                                   ^
1252                         //
1253                         lyxerr << "checking expr: '" << expr << "'" << endl;
1254                         out = captureOutput("octave -q 2>&1", expr);
1255                         lyxerr << "output: '" << out << "'" << endl;
1256
1257                         // leave loop if expression syntax is probably ok
1258                         if (out.find("parse error:") == string::npos)
1259                                 break;
1260
1261                         // search line with single caret
1262                         istringstream is(out);
1263                         string line;
1264                         while (is) {
1265                                 getline(is, line);
1266                                 lyxerr << "skipping line: '" << line << "'" << endl;
1267                                 if (line.find(">>> ") != string::npos)
1268                                         break;
1269                         }
1270
1271                         // found line with error, next line is the one with caret
1272                         getline(is, line);
1273                         size_t pos = line.find('^');
1274                         lyxerr << "caret line: '" << line << "'" << endl;
1275                         lyxerr << "found caret at pos: '" << pos << "'" << endl;
1276                         if (pos == string::npos || pos < 4)
1277                                 break; // caret position not found
1278                         pos -= 4; // skip the ">>> " part
1279                         if (expr[pos] == '*')
1280                                 break; // two '*' in a row are definitely bad
1281                         expr.insert(pos, 1, '*');
1282                 }
1283
1284                 // remove 'ans = ' taking into account that there may be an
1285                 // ansi control sequence before, such as '\033[?1034hans = '
1286                 size_t i = out.find("ans = ");
1287                 if (i == string::npos)
1288                         return MathData();
1289                 out = out.substr(i + 6);
1290
1291                 // parse output as matrix or single number
1292                 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1293                 InsetMathArray const * mat = at->asArrayInset();
1294                 MathData res(buf);
1295                 if (mat->ncols() == 1 && mat->nrows() == 1)
1296                         res.append(mat->cell(0));
1297                 else {
1298                         res.push_back(MathAtom(
1299                                 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1300                         res.back().nucleus()->cell(0).push_back(at);
1301                 }
1302                 return res;
1303         }
1304
1305
1306         string fromMathematicaName(string const & name)
1307         {
1308                 if (name == "Sin")    return "sin";
1309                 if (name == "Sinh")   return "sinh";
1310                 if (name == "ArcSin") return "arcsin";
1311                 if (name == "Cos")    return "cos";
1312                 if (name == "Cosh")   return "cosh";
1313                 if (name == "ArcCos") return "arccos";
1314                 if (name == "Tan")    return "tan";
1315                 if (name == "Tanh")   return "tanh";
1316                 if (name == "ArcTan") return "arctan";
1317                 if (name == "Cot")    return "cot";
1318                 if (name == "Coth")   return "coth";
1319                 if (name == "Csc")    return "csc";
1320                 if (name == "Sec")    return "sec";
1321                 if (name == "Exp")    return "exp";
1322                 if (name == "Log")    return "log";
1323                 if (name == "Arg" )   return "arg";
1324                 if (name == "Det" )   return "det";
1325                 if (name == "GCD" )   return "gcd";
1326                 if (name == "Max" )   return "max";
1327                 if (name == "Min" )   return "min";
1328                 if (name == "Erf" )   return "erf";
1329                 if (name == "Erfc" )  return "erfc";
1330                 return name;
1331         }
1332
1333
1334         void prettifyMathematicaOutput(string & out, string const & macroName,
1335                         bool roman, bool translate)
1336         {
1337                 string const macro = "\\" + macroName + "{";
1338                 size_t const len = macro.length();
1339                 size_t i = out.find(macro);
1340
1341                 while (i != npos) {
1342                         size_t const j = get_matching_brace(out, i + len);
1343                         string const name = out.substr(i + len, j - i - len);
1344                         out = out.substr(0, i)
1345                                 + (roman ? "\\mathrm{" : "")
1346                                 + (translate ? fromMathematicaName(name) : name)
1347                                 + out.substr(roman ? j : j + 1);
1348                         //lyxerr << "output: " << out << endl;
1349                         i = out.find(macro, i);
1350                 }
1351         }
1352
1353
1354         MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1355         {
1356                 odocstringstream os;
1357                 MathematicaStream ms(os);
1358                 ms << ar;
1359                 // FIXME UNICODE Is utf8 encoding correct?
1360                 string const expr = to_utf8(os.str());
1361                 string out;
1362
1363                 lyxerr << "expr: '" << expr << "'" << endl;
1364
1365                 string const full = "TeXForm[" + expr + "]";
1366                 out = captureOutput("math", full);
1367                 lyxerr << "output: '" << out << "'" << endl;
1368
1369                 size_t pos1 = out.find("Out[1]//TeXForm= ");
1370                 size_t pos2 = out.find("In[2]:=");
1371
1372                 if (pos1 == string::npos || pos2 == string::npos)
1373                         return MathData();
1374
1375                 // get everything from pos1+17 to pos2
1376                 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1377                 out = subst(subst(out, '\r', ' '), '\n', ' ');
1378
1379                 // tries to make the result prettier
1380                 prettifyMathematicaOutput(out, "Mfunction", true, true);
1381                 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1382                 prettifyMathematicaOutput(out, "Mvariable", false, false);
1383
1384                 MathData res;
1385                 mathed_parse_cell(res, from_utf8(out));
1386                 return res;
1387         }
1388
1389 }
1390
1391 } // anon namespace
1392
1393 void write(MathData const & dat, WriteStream & wi)
1394 {
1395         wi.firstitem() = true;
1396         docstring s;
1397         for (MathData::const_iterator it = dat.begin(); it != dat.end(); ++it) {
1398                 InsetMathChar const * const c = (*it)->asCharInset();
1399                 if (c)
1400                         s += c->getChar();
1401                 else {
1402                         if (!s.empty()) {
1403                                 writeString(s, wi);
1404                                 s.clear();
1405                         }
1406                         (*it)->write(wi);
1407                         wi.firstitem() = false;
1408                 }
1409         }
1410         if (!s.empty()) {
1411                 writeString(s, wi);
1412                 wi.firstitem() = false;
1413         }
1414 }
1415
1416
1417 void writeString(docstring const & s, WriteStream & os)
1418 {
1419         if (!os.latex() || os.lockedMode()) {
1420                 os << (os.asciiOnly() ? escape(s) : s);
1421                 return;
1422         }
1423
1424         docstring::const_iterator cit = s.begin();
1425         docstring::const_iterator end = s.end();
1426
1427         // We may already be inside an \ensuremath command.
1428         bool in_forced_mode = os.pendingBrace();
1429
1430         // We will take care of matching braces.
1431         os.pendingBrace(false);
1432
1433         while (cit != end) {
1434                 bool mathmode = in_forced_mode ? os.textMode() : !os.textMode();
1435                 char_type const c = *cit;
1436                 docstring command(1, c);
1437                 try {
1438                         bool termination = false;
1439                         if (isASCII(c) ||
1440                             Encodings::latexMathChar(c, mathmode, os.encoding(), command, termination)) {
1441                                 if (os.textMode()) {
1442                                         if (in_forced_mode) {
1443                                                 // we were inside \lyxmathsym
1444                                                 os << '}';
1445                                                 os.textMode(false);
1446                                                 in_forced_mode = false;
1447                                         }
1448                                         if (!isASCII(c) && os.textMode()) {
1449                                                 os << "\\ensuremath{";
1450                                                 os.textMode(false);
1451                                                 in_forced_mode = true;
1452                                         }
1453                                 } else if (isASCII(c) && in_forced_mode) {
1454                                         // we were inside \ensuremath
1455                                         os << '}';
1456                                         os.textMode(true);
1457                                         in_forced_mode = false;
1458                                 }
1459                         } else if (!os.textMode()) {
1460                                         if (in_forced_mode) {
1461                                                 // we were inside \ensuremath
1462                                                 os << '}';
1463                                                 in_forced_mode = false;
1464                                         } else {
1465                                                 os << "\\lyxmathsym{";
1466                                                 in_forced_mode = true;
1467                                         }
1468                                         os.textMode(true);
1469                         }
1470                         os << command;
1471                         // We may need a space if the command contains a macro
1472                         // and the last char is ASCII.
1473                         if (termination)
1474                                 os.pendingSpace(true);
1475                 } catch (EncodingException const & e) {
1476                         switch (os.output()) {
1477                         case WriteStream::wsDryrun: {
1478                                 os << "<" << _("LyX Warning: ")
1479                                    << _("uncodable character") << " '";
1480                                 os << docstring(1, e.failed_char);
1481                                 os << "'>";
1482                                 break;
1483                         }
1484                         case WriteStream::wsPreview: {
1485                                 // indicate the encoding error by a boxed '?'
1486                                 os << "{\\fboxsep=1pt\\fbox{?}}";
1487                                 LYXERR0("Uncodable character" << " '"
1488                                         << docstring(1, e.failed_char)
1489                                         << "'");
1490                                 break;
1491                         }
1492                         case WriteStream::wsDefault:
1493                         default:
1494                                 // throw again
1495                                 throw(e);
1496                         }
1497                 }
1498                 ++cit;
1499         }
1500
1501         if (in_forced_mode && os.textMode()) {
1502                 // We have to care for closing \lyxmathsym
1503                 os << '}';
1504                 os.textMode(false);
1505         } else {
1506                 os.pendingBrace(in_forced_mode);
1507         }
1508 }
1509
1510
1511 void normalize(MathData const & ar, NormalStream & os)
1512 {
1513         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1514                 (*it)->normalize(os);
1515 }
1516
1517
1518 void octave(MathData const & dat, OctaveStream & os)
1519 {
1520         MathData ar = dat;
1521         extractStructure(ar, OCTAVE);
1522         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1523                 (*it)->octave(os);
1524 }
1525
1526
1527 void maple(MathData const & dat, MapleStream & os)
1528 {
1529         MathData ar = dat;
1530         extractStructure(ar, MAPLE);
1531         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1532                 (*it)->maple(os);
1533 }
1534
1535
1536 void maxima(MathData const & dat, MaximaStream & os)
1537 {
1538         MathData ar = dat;
1539         extractStructure(ar, MAXIMA);
1540         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1541                 (*it)->maxima(os);
1542 }
1543
1544
1545 void mathematica(MathData const & dat, MathematicaStream & os)
1546 {
1547         MathData ar = dat;
1548         extractStructure(ar, MATHEMATICA);
1549         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1550                 (*it)->mathematica(os);
1551 }
1552
1553
1554 void mathmlize(MathData const & dat, MathStream & os)
1555 {
1556         MathData ar = dat;
1557         extractStructure(ar, MATHML);
1558         if (ar.empty())
1559                 os << "<mrow/>";
1560         else if (ar.size() == 1)
1561                 os << ar.front();
1562         else {
1563                 os << MTag("mrow");
1564                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1565                         (*it)->mathmlize(os);
1566                 os << ETag("mrow");
1567         }
1568 }
1569
1570
1571 void htmlize(MathData const & dat, HtmlStream & os)
1572 {
1573         MathData ar = dat;
1574         extractStructure(ar, HTML);
1575         if (ar.empty())
1576                 return;
1577         if (ar.size() == 1) {
1578                 os << ar.front();
1579                 return;
1580         }
1581         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1582                 (*it)->htmlize(os);
1583 }
1584
1585
1586 // convert this inset somehow to a number
1587 bool extractNumber(MathData const & ar, int & i)
1588 {
1589         idocstringstream is(charSequence(ar.begin(), ar.end()));
1590         is >> i;
1591         // Do not convert is implicitly to bool, since that is forbidden in C++11.
1592         return !is.fail();
1593 }
1594
1595
1596 bool extractNumber(MathData const & ar, double & d)
1597 {
1598         idocstringstream is(charSequence(ar.begin(), ar.end()));
1599         is >> d;
1600         // Do not convert is implicitly to bool, since that is forbidden in C++11.
1601         return !is.fail();
1602 }
1603
1604
1605 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1606         MathData const & ar)
1607 {
1608         if (lang == "octave")
1609                 return pipeThroughOctave(extra, ar);
1610
1611         if (lang == "maxima")
1612                 return pipeThroughMaxima(extra, ar);
1613
1614         if (lang == "maple")
1615                 return pipeThroughMaple(extra, ar);
1616
1617         if (lang == "mathematica")
1618                 return pipeThroughMathematica(extra, ar);
1619
1620         // create normalized expression
1621         odocstringstream os;
1622         NormalStream ns(os);
1623         os << '[' << extra << ' ';
1624         ns << ar;
1625         os << ']';
1626         // FIXME UNICODE Is utf8 encoding correct?
1627         string data = to_utf8(os.str());
1628
1629         // search external script
1630         FileName const file = libFileSearch("mathed", "extern_" + lang);
1631         if (file.empty()) {
1632                 lyxerr << "converter to '" << lang << "' not found" << endl;
1633                 return MathData();
1634         }
1635
1636         // run external sript
1637         string out = captureOutput(file.absFileName(), data);
1638         MathData res;
1639         mathed_parse_cell(res, from_utf8(out));
1640         return res;
1641 }
1642
1643
1644 } // namespace lyx