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