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