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