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