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