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