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