]> git.lyx.org Git - lyx.git/blob - src/mathed/math_extern.C
a bit more const correctness
[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 const *);
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] = MathAtom(new MathStringInset(s));
136                 ar.erase(i + 1, i + s.size());
137         }
138         //lyxerr << "\nStrings to: " << ar << "\n";
139 }
140
141
142 MathInset const * singleItem(MathArray const & 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 const * 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 const * 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 const * 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 = MathAtom(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 = MathAtom(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 = MathAtom(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] = MathAtom(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 const * p)
395 {
396         return testString(p, "(");
397 }
398
399
400 bool testCloseParan(MathInset const * 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)->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 = MathAtom(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 const * p, string const & name)
490 {
491         return p->asSymbolInset() && p->asSymbolInset()->name() == name;
492 }
493
494
495 bool testIntSymbol(MathInset const * p)
496 {
497         return testSymbol(p, "int");
498 }
499
500
501 bool testIntegral(MathInset const * 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 const * 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();
548                         p->cell(3) = it->nucleus()->asScriptInset()->up();
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 = MathAtom(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 const * p)
575 {
576         return testSymbol(p, "sum");
577 }
578
579
580 bool testSum(MathInset const * 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();
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();
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 = MathAtom(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 const * p)
660 {
661         MathFracInset const * 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(), 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 = MathAtom(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();
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                 // cleanup
802                 ar.erase(it + 1, tt);
803
804                 // create a proper inset as replacement
805                 *it = MathAtom(new MathLimInset(f, x, x0));
806         }
807         //lyxerr << "\nLimits to: " << ar << "\n";
808 }
809
810
811 //
812 // combine searches
813 //
814
815 void extractStructure(MathArray & ar)
816 {
817         extractIntegrals(ar);
818         extractSums(ar);
819         splitScripts(ar);
820         extractNumbers(ar);
821         extractMatrices(ar);
822         extractDelims(ar);
823         extractFunctions(ar);
824         extractDets(ar);
825         extractDiff(ar);
826         extractExps(ar);
827         extractLims(ar);
828         extractStrings(ar);
829 }
830
831
832 void write(MathArray const & dat, WriteStream & wi)
833 {
834         MathArray ar = dat;
835         extractStrings(ar);
836         wi.firstitem() = true;
837         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
838                 (*it)->write(wi);
839                 wi.firstitem() = false;
840         }
841 }
842
843
844 void normalize(MathArray const & ar, NormalStream & os)
845 {
846         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
847                 (*it)->normalize(os);
848 }
849
850
851 void octavize(MathArray const & dat, OctaveStream & os)
852 {
853         MathArray ar = dat;
854         extractStructure(ar);
855         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
856                 (*it)->octavize(os);
857 }
858
859
860 void maplize(MathArray const & dat, MapleStream & os)
861 {
862         MathArray ar = dat;
863         extractStructure(ar);
864         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
865                 (*it)->maplize(os);
866 }
867
868
869 void mathematicize(MathArray const & dat, MathematicaStream & os)
870 {
871         MathArray ar = dat;
872         extractStructure(ar);
873         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
874                 (*it)->mathematicize(os);
875 }
876
877
878 void mathmlize(MathArray const & dat, MathMLStream & os)
879 {
880         MathArray ar = dat;
881         extractStructure(ar);
882         if (ar.size() == 0)
883                 os << "<mrow/>";
884         else if (ar.size() == 1)
885                 os << ar.begin()->nucleus();
886         else {
887                 os << MTag("mrow");
888                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
889                         (*it)->mathmlize(os);
890                 os << ETag("mrow");
891         }
892 }
893
894
895
896
897 namespace {
898
899         string captureOutput(string const & cmd, string const & data)
900         {
901                 string outfile = lyx::tempName(string(), "mathextern");
902                 string full =  "echo '" + data + "' | (" + cmd + ") > " + outfile;
903                 lyxerr << "calling: " << full << endl;
904                 Systemcall dummy;
905                 dummy.startscript(Systemcall::Wait, full);
906                 string out = GetFileContents(outfile);
907                 lyx::unlink(outfile);
908                 lyxerr << "result: '" << out << "'" << endl;
909                 return out;
910         }
911
912
913         MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
914         {
915                 string header = "readlib(latex):\n";
916
917                 // remove the \\it for variable names
918                 //"#`latex/csname_font` := `\\it `:"
919                 header +=
920                         "`latex/csname_font` := ``:\n";
921
922                 // export matrices in (...) instead of [...]
923                 header +=
924                         "`latex/latex/matrix` := "
925                                 "subs(`[`=`(`, `]`=`)`,"
926                                         "eval(`latex/latex/matrix`)):\n";
927
928                 // replace \\cdots with proper '*'
929                 header +=
930                         "`latex/latex/*` := "
931                                 "subs(`\\,`=`\\cdot `,"
932                                         "eval(`latex/latex/*`)):\n";
933
934                 // remove spurious \\noalign{\\medskip} in matrix output
935                 header +=
936                         "`latex/latex/matrix`:= "
937                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
938                                         "eval(`latex/latex/matrix`)):\n";
939
940                 //"#`latex/latex/symbol` "
941                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
942
943                 string trailer = "quit;";
944                 ostringstream os;
945                 MapleStream ms(os);
946                 ms << ar;
947                 string expr = os.str().c_str();
948                 lyxerr << "ar: '" << ar << "'\n";
949                 lyxerr << "ms: '" << os.str() << "'\n";
950
951                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
952                         // try to fix missing '*' the hard way by using mint
953                         //
954                         // ... > echo "1A;" | mint -i 1 -S -s -q
955                         // on line     1: 1A;
956                         //                 ^ syntax error -
957                         //                   Probably missing an operator such as * p
958                         //
959                         lyxerr << "checking expr: '" << expr << "'\n";
960                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
961                         if (out.empty())
962                                 break; // expression syntax is ok
963                         istringstream is(out.c_str());
964                         string line;
965                         getline(is, line);
966                         if (line.find("on line") != 0)
967                                 break; // error message not identified
968                         getline(is, line);
969                         string::size_type pos = line.find('^');
970                         if (pos == string::npos || pos < 15)
971                                 break; // caret position not found
972                         pos -= 15; // skip the "on line ..." part
973                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
974                                 break; // two '*' in a row are definitely bad
975                         expr.insert(pos,  "*");
976                 }
977
978                 string full = "latex(" +  extra + '(' + expr + "));";
979                 string out = captureOutput("maple -q", header + full + trailer);
980
981                 // change \_ into _
982
983                 //
984                 MathArray res;
985                 mathed_parse_cell(res, out);
986                 return res;
987         }
988
989
990         MathArray pipeThroughOctave(string const &, MathArray const & ar)
991         {
992                 ostringstream os;
993                 OctaveStream vs(os);
994                 vs << ar;
995                 string expr = os.str().c_str();
996                 string out;
997
998                 lyxerr << "pipe: ar: '" << ar << "'\n";
999                 lyxerr << "pipe: expr: '" << expr << "'\n";
1000
1001                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1002                         //
1003                         // try to fix missing '*' the hard way
1004                         // parse error:
1005                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1006                         //                                   ^
1007                         //
1008                         lyxerr << "checking expr: '" << expr << "'\n";
1009                         out = captureOutput("octave -q 2>&1", expr);
1010                         lyxerr << "checking out: '" << out << "'\n";
1011
1012                         // leave loop if expression syntax is probably ok
1013                         if (out.find("parse error:") == string::npos)
1014                                 break;
1015
1016                         // search line with single caret
1017                         istringstream is(out.c_str());
1018                         string line;
1019                         while (is) {
1020                                 getline(is, line);
1021                                 lyxerr << "skipping line: '" << line << "'\n";
1022                                 if (line.find(">>> ") != string::npos)
1023                                         break;
1024                         }
1025
1026                         // found line with error, next line is the one with caret
1027                         getline(is, line);
1028                         string::size_type pos = line.find('^');
1029                         lyxerr << "caret line: '" << line << "'\n";
1030                         lyxerr << "found caret at pos: '" << pos << "'\n";
1031                         if (pos == string::npos || pos < 4)
1032                                 break; // caret position not found
1033                         pos -= 4; // skip the ">>> " part
1034                         if (expr[pos] == '*')
1035                                 break; // two '*' in a row are definitely bad
1036                         expr.insert(pos,  "*");
1037                 }
1038
1039                 if (out.size() < 6)
1040                         return MathArray();
1041
1042                 // remove 'ans = '
1043                 out = out.substr(6);
1044
1045                 // parse output as matrix or single number
1046                 MathAtom at(new MathArrayInset("array", out));
1047                 MathArrayInset const * mat = at.nucleus()->asArrayInset();
1048                 MathArray res;
1049                 if (mat->ncols() == 1 && mat->nrows() == 1)
1050                         res.append(mat->cell(0));
1051                 else {
1052                         res.push_back(MathAtom(new MathDelimInset("(", ")")));
1053                         res.back()->cell(0).push_back(at);
1054                 }
1055                 return res;
1056         }
1057
1058 }
1059
1060
1061 MathArray pipeThroughExtern(string const & lang, string const & extra,
1062         MathArray const & ar)
1063 {
1064         if (lang == "octave")
1065                 return pipeThroughOctave(extra, ar);
1066
1067         if (lang == "maple")
1068                 return pipeThroughMaple(extra, ar);
1069
1070         // create normalized expression
1071         ostringstream os;
1072         NormalStream ns(os);
1073         os << "[" << extra << ' ';
1074         ns << ar;
1075         os << "]";
1076         string data = os.str().c_str();
1077
1078         // search external script
1079         string file = LibFileSearch("mathed", "extern_" + lang);
1080         if (file.empty()) {
1081                 lyxerr << "converter to '" << lang << "' not found\n";
1082                 return MathArray();
1083         }
1084
1085         // run external sript
1086         string out = captureOutput(file, data);
1087         MathArray res;
1088         mathed_parse_cell(res, out);
1089         return res;
1090 }