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