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