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