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