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