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