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