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