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