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