]> git.lyx.org Git - features.git/blob - src/mathed/math_extern.C
remove the passsing of naked pointers in a few cases
[features.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 * 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 * 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)->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 * 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 * 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 * 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 * sub = (*it)->asScriptInset();
609                 if (sub && sub->hasDown()) {
610                         // try to figure out the summation index from the subscript
611                         MathArray & ar = sub->down();
612                         MathArray::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 * 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 & 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 & denom = f->cell(1);
707                 for (MathArray::iterator dt = denom.begin(); dt != denom.end();) {
708                         // find the next 'd'
709                         MathArray::iterator et = find_if(dt + 1, denom.end(), &testDiffItem);
710
711                         // point before this
712                         MathArray::iterator st = et - 1;
713                         MathScriptInset * script = (*st)->asScriptInset();
714                         if (script && script->hasUp()) {
715                                 // things like   d.../dx^n
716                                 int mult = 1;
717                                 if (extractNumber(script->up(), mult)) {
718                                         //lyxerr << "mult: " << mult << endl;
719                                         for (int i = 0; i < mult; ++i)
720                                                 diff->addDer(MathArray(dt + 1, st));
721                                 }
722                         } else {
723                                 // just  d.../dx
724                                 diff->addDer(MathArray(dt + 1, et));
725                         }
726                         dt = et;
727                 }
728
729                 // cleanup
730                 ar.erase(it + 1, jt);
731                 *it = MathAtom(diff);
732         }
733         //lyxerr << "\nDiffs to: " << ar << "\n";
734 }
735
736
737 //
738 // search limits
739 //
740
741
742 bool testRightArrow(MathAtom const & at)
743 {
744         return testSymbol(at, "to") || testSymbol(at, "rightarrow");
745 }
746
747
748
749 // replace '\lim_{x->x0} f(x)' sequences by a real MathLimInset
750 // assume 'extractDelims' ran before
751 void extractLims(MathArray & ar)
752 {
753         // we need at least three items...
754         if (ar.size() < 3)
755                 return;
756
757         //lyxerr << "\nLimits from: " << ar << "\n";
758         for (MathArray::size_type i = 0; i + 2 < ar.size(); ++i) {
759                 MathArray::iterator it = ar.begin() + i;
760
761                 // is this a limit function?
762                 if (!testSymbol(*it, "lim")) 
763                         continue;
764
765                 // the next one must be a subscript (without superscript)
766                 MathScriptInset * sub = (*(it + 1))->asScriptInset();
767                 if (!sub || !sub->hasDown() || sub->hasUp())
768                         continue;
769
770                 // and it must contain a -> symbol
771                 MathArray & s = sub->down();
772                 MathArray::iterator st = find_if(s.begin(), s.end(), &testRightArrow);
773                 if (st == s.end())
774                         continue;
775
776                 // the -> splits the subscript int x and x0
777                 MathArray x  = MathArray(s.begin(), st);
778                 MathArray x0 = MathArray(st + 1, s.end());
779                 
780                 // use something behind the script as core
781                 MathArray f;
782                 MathArray::iterator tt = extractArgument(f, it + 2, ar.end());
783
784                 // cleanup
785                 ar.erase(it + 1, tt);
786
787                 // create a proper inset as replacement
788                 *it = MathAtom(new MathLimInset(f, x, x0));
789         }
790         //lyxerr << "\nLimits to: " << ar << "\n";
791 }
792
793
794 //
795 // combine searches
796 //
797
798 void extractStructure(MathArray & ar)
799 {
800         extractIntegrals(ar);
801         extractSums(ar);
802         splitScripts(ar);
803         extractNumbers(ar);
804         extractMatrices(ar);
805         extractDelims(ar);
806         extractFunctions(ar);
807         extractDets(ar);
808         extractDiff(ar);
809         extractExps(ar);
810         extractLims(ar);
811         extractStrings(ar);
812 }
813
814
815 void write(MathArray const & dat, WriteStream & wi)
816 {
817         MathArray ar = dat;
818         extractStrings(ar);
819         wi.firstitem() = true;
820         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
821                 (*it)->write(wi);
822                 wi.firstitem() = false;
823         }
824 }
825
826
827 void normalize(MathArray const & ar, NormalStream & os)
828 {
829         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
830                 (*it)->normalize(os);
831 }
832
833
834 void octavize(MathArray const & dat, OctaveStream & os)
835 {
836         MathArray ar = dat;
837         extractStructure(ar);
838         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
839                 (*it)->octavize(os);
840 }
841
842
843 void maplize(MathArray const & dat, MapleStream & os)
844 {
845         MathArray ar = dat;
846         extractStructure(ar);
847         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
848                 (*it)->maplize(os);
849 }
850
851
852 void mathematicize(MathArray const & dat, MathematicaStream & os)
853 {
854         MathArray ar = dat;
855         extractStructure(ar);
856         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
857                 (*it)->mathematicize(os);
858 }
859
860
861 void mathmlize(MathArray const & dat, MathMLStream & os)
862 {
863         MathArray ar = dat;
864         extractStructure(ar);
865         if (ar.size() == 0)
866                 os << "<mrow/>";
867         else if (ar.size() == 1)
868                 os << ar.begin()->nucleus();
869         else {
870                 os << MTag("mrow");
871                 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
872                         (*it)->mathmlize(os);
873                 os << ETag("mrow");
874         }
875 }
876
877
878
879
880 namespace {
881
882         string captureOutput(string const & cmd, string const & data)
883         {
884                 string outfile = lyx::tempName(string(), "mathextern");
885                 string full =  "echo '" + data + "' | (" + cmd + ") > " + outfile;
886                 lyxerr << "calling: " << full << endl;
887                 Systemcall dummy;
888                 dummy.startscript(Systemcall::Wait, full);
889                 string out = GetFileContents(outfile);
890                 lyx::unlink(outfile);
891                 lyxerr << "result: '" << out << "'" << endl;
892                 return out;
893         }
894
895
896         MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
897         {
898                 string header = "readlib(latex):\n";
899
900                 // remove the \\it for variable names
901                 //"#`latex/csname_font` := `\\it `:"
902                 header +=
903                         "`latex/csname_font` := ``:\n";
904
905                 // export matrices in (...) instead of [...]
906                 header +=
907                         "`latex/latex/matrix` := "
908                                 "subs(`[`=`(`, `]`=`)`,"
909                                         "eval(`latex/latex/matrix`)):\n";
910
911                 // replace \\cdots with proper '*'
912                 header +=
913                         "`latex/latex/*` := "
914                                 "subs(`\\,`=`\\cdot `,"
915                                         "eval(`latex/latex/*`)):\n";
916
917                 // remove spurious \\noalign{\\medskip} in matrix output
918                 header +=
919                         "`latex/latex/matrix`:= "
920                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
921                                         "eval(`latex/latex/matrix`)):\n";
922
923                 //"#`latex/latex/symbol` "
924                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
925
926                 string trailer = "quit;";
927                 ostringstream os;
928                 MapleStream ms(os);
929                 ms << ar;
930                 string expr = os.str().c_str();
931                 lyxerr << "ar: '" << ar << "'\n";
932                 lyxerr << "ms: '" << os.str() << "'\n";
933
934                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
935                         // try to fix missing '*' the hard way by using mint
936                         //
937                         // ... > echo "1A;" | mint -i 1 -S -s -q
938                         // on line     1: 1A;
939                         //                 ^ syntax error -
940                         //                   Probably missing an operator such as * p
941                         //
942                         lyxerr << "checking expr: '" << expr << "'\n";
943                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
944                         if (out.empty())
945                                 break; // expression syntax is ok
946                         istringstream is(out.c_str());
947                         string line;
948                         getline(is, line);
949                         if (line.find("on line") != 0)
950                                 break; // error message not identified
951                         getline(is, line);
952                         string::size_type pos = line.find('^');
953                         if (pos == string::npos || pos < 15)
954                                 break; // caret position not found
955                         pos -= 15; // skip the "on line ..." part
956                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
957                                 break; // two '*' in a row are definitely bad
958                         expr.insert(pos,  "*");
959                 }
960
961                 string full = "latex(" +  extra + '(' + expr + "));";
962                 string out = captureOutput("maple -q", header + full + trailer);
963
964                 // change \_ into _
965
966                 //
967                 MathArray res;
968                 mathed_parse_cell(res, out);
969                 return res;
970         }
971
972
973         MathArray pipeThroughOctave(string const &, MathArray const & ar)
974         {
975                 ostringstream os;
976                 OctaveStream vs(os);
977                 vs << ar;
978                 string expr = os.str().c_str();
979                 string out;
980
981                 lyxerr << "pipe: ar: '" << ar << "'\n";
982                 lyxerr << "pipe: expr: '" << expr << "'\n";
983
984                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
985                         //
986                         // try to fix missing '*' the hard way
987                         // parse error:
988                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
989                         //                                   ^
990                         //
991                         lyxerr << "checking expr: '" << expr << "'\n";
992                         out = captureOutput("octave -q 2>&1", expr);
993                         lyxerr << "checking out: '" << out << "'\n";
994
995                         // leave loop if expression syntax is probably ok
996                         if (out.find("parse error:") == string::npos)
997                                 break;
998
999                         // search line with single caret
1000                         istringstream is(out.c_str());
1001                         string line;
1002                         while (is) {
1003                                 getline(is, line);
1004                                 lyxerr << "skipping line: '" << line << "'\n";
1005                                 if (line.find(">>> ") != string::npos)
1006                                         break;
1007                         }
1008
1009                         // found line with error, next line is the one with caret
1010                         getline(is, line);
1011                         string::size_type pos = line.find('^');
1012                         lyxerr << "caret line: '" << line << "'\n";
1013                         lyxerr << "found caret at pos: '" << pos << "'\n";
1014                         if (pos == string::npos || pos < 4)
1015                                 break; // caret position not found
1016                         pos -= 4; // skip the ">>> " part
1017                         if (expr[pos] == '*')
1018                                 break; // two '*' in a row are definitely bad
1019                         expr.insert(pos,  "*");
1020                 }
1021
1022                 if (out.size() < 6)
1023                         return MathArray();
1024
1025                 // remove 'ans = '
1026                 out = out.substr(6);
1027
1028                 // parse output as matrix or single number
1029                 MathAtom at(new MathArrayInset("array", out));
1030                 MathArrayInset const * mat = at.nucleus()->asArrayInset();
1031                 MathArray res;
1032                 if (mat->ncols() == 1 && mat->nrows() == 1)
1033                         res.append(mat->cell(0));
1034                 else {
1035                         res.push_back(MathAtom(new MathDelimInset("(", ")")));
1036                         res.back()->cell(0).push_back(at);
1037                 }
1038                 return res;
1039         }
1040
1041 }
1042
1043
1044 MathArray pipeThroughExtern(string const & lang, string const & extra,
1045         MathArray const & ar)
1046 {
1047         if (lang == "octave")
1048                 return pipeThroughOctave(extra, ar);
1049
1050         if (lang == "maple")
1051                 return pipeThroughMaple(extra, ar);
1052
1053         // create normalized expression
1054         ostringstream os;
1055         NormalStream ns(os);
1056         os << "[" << extra << ' ';
1057         ns << ar;
1058         os << "]";
1059         string data = os.str().c_str();
1060
1061         // search external script
1062         string file = LibFileSearch("mathed", "extern_" + lang);
1063         if (file.empty()) {
1064                 lyxerr << "converter to '" << lang << "' not found\n";
1065                 return MathArray();
1066         }
1067
1068         // run external sript
1069         string out = captureOutput(file, data);
1070         MathArray res;
1071         mathed_parse_cell(res, out);
1072         return res;
1073 }