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