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