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