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