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