]> git.lyx.org Git - lyx.git/blob - src/mathed/math_extern.C
small up/down tweaking
[lyx.git] / src / mathed / math_extern.C
1 #ifdef __GNUG__
2 #pragma implementation
3 #endif
4
5 // This file contains most of the magic that extracts "context
6 // information" from the unstructered layout-oriented stuff in an
7 // MathArray.
8
9 #include <config.h>
10
11 #include "math_amsarrayinset.h"
12 #include "math_arrayinset.h"
13 #include "math_charinset.h"
14 #include "math_deliminset.h"
15 #include "math_diffinset.h"
16 #include "math_exfuncinset.h"
17 #include "math_exintinset.h"
18 #include "math_fracinset.h"
19 #include "math_liminset.h"
20 #include "math_matrixinset.h"
21 #include "math_mathmlstream.h"
22 #include "math_numberinset.h"
23 #include "math_scriptinset.h"
24 #include "math_stringinset.h"
25 #include "math_symbolinset.h"
26 #include "math_unknowninset.h"
27 #include "math_parser.h"
28 #include "Lsstream.h"
29 #include "debug.h"
30 #include "support/lyxlib.h"
31 #include "support/systemcall.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.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[i] = replaceArg(MathArray(it + 1, jt));
252                 ar.erase(it + 1, jt + 1);
253         }
254 }
255
256
257
258 //
259 // split scripts into seperate super- and subscript insets. sub goes in
260 // front of super...
261 //
262
263 void splitScripts(MathArray & ar)
264 {
265         //lyxerr << "\nScripts from: " << ar << "\n";
266         for (MathArray::size_type i = 0; i < ar.size(); ++i) {
267                 // is this script inset?
268                 if (!ar[i]->asScriptInset())
269                         continue;
270
271                 // no problem if we don't have both...
272                 if (!ar[i]->asScriptInset()->hasUp())
273                         continue;
274                 if (!ar[i]->asScriptInset()->hasDown())
275                         continue;
276
277                 // create extra script inset and move superscript over
278                 MathScriptInset * p = ar[i].nucleus()->asScriptInset();
279                 MathScriptInset * q = new MathScriptInset(true);
280                 std::swap(q->up(), p->up());
281                 p->removeScript(true);
282
283                 // insert new inset behind
284                 ++i;
285                 ar.insert(i, MathAtom(q));
286         }
287         //lyxerr << "\nScripts to: " << ar << "\n";
288 }
289
290
291 //
292 // extract exp(...)
293 //
294
295 void extractExps(MathArray & ar)
296 {
297         //lyxerr << "\nExps from: " << ar << "\n";
298         for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
299                 // is this 'e'?
300                 if (ar[i]->getChar() != 'e')
301                         continue;
302
303                 // we need an exponent but no subscript
304                 MathScriptInset const * sup = ar[i + 1]->asScriptInset();
305                 if (!sup || sup->hasDown())
306                         continue;
307
308                 // create a proper exp-inset as replacement
309                 ar[i] = MathAtom(new MathExFuncInset("exp", sup->cell(1)));
310                 ar.erase(i + 1);
311         }
312         //lyxerr << "\nExps to: " << ar << "\n";
313 }
314
315
316 //
317 // extract det(...)  from |matrix|
318 //
319 void extractDets(MathArray & ar)
320 {
321         //lyxerr << "\ndet from: " << ar << "\n";
322         for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it) {
323                 MathDelimInset const * del = (*it)->asDelimInset();
324                 if (!del)
325                         continue;
326                 if (!del->isAbs())
327                         continue;
328                 *it = MathAtom(new MathExFuncInset("det", del->cell(0)));
329         }
330         //lyxerr << "\ndet to: " << ar << "\n";
331 }
332
333
334 //
335 // search numbers
336 //
337
338 bool isDigitOrSimilar(char c)
339 {
340         return ('0' <= c && c <= '9') || c == '.';
341 }
342
343
344 // returns sequence of digits
345 string digitSequence
346         (MathArray::const_iterator it, MathArray::const_iterator end)
347 {
348         string s;
349         for (; it != end && (*it)->asCharInset(); ++it) {
350                 if (!isDigitOrSimilar((*it)->getChar()))
351                         break;
352                 s += (*it)->getChar();
353         }
354         return s;
355 }
356
357
358 void extractNumbers(MathArray & ar)
359 {
360         //lyxerr << "\nNumbers from: " << ar << "\n";
361         for (MathArray::size_type i = 0; i < ar.size(); ++i) {
362                 if (!ar[i]->asCharInset())
363                         continue;
364                 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
365                         continue;
366
367                 string s = digitSequence(ar.begin() + i, ar.end());
368
369                 ar[i] = MathAtom(new MathNumberInset(s));
370                 ar.erase(i + 1, i + s.size());
371         }
372         //lyxerr << "\nNumbers to: " << ar << "\n";
373 }
374
375
376
377 //
378 // search deliminiters
379 //
380
381 bool testOpenParan(MathAtom const & at)
382 {
383         return testString(at, "(");
384 }
385
386
387 bool testCloseParan(MathAtom const & at)
388 {
389         return testString(at, ")");
390 }
391
392
393 MathAtom replaceDelims(const MathArray & ar)
394 {
395         return MathAtom(new MathDelimInset("(", ")", ar));
396 }
397
398
399 // replace '('...')' sequences by a real MathDelimInset
400 void extractDelims(MathArray & ar)
401 {
402         //lyxerr << "\nDelims from: " << ar << "\n";
403         replaceNested(ar, testOpenParan, testCloseParan, replaceDelims);
404         //lyxerr << "\nDelims to: " << ar << "\n";
405 }
406
407
408
409 //
410 // search well-known functions
411 //
412
413
414 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real MathExFuncInset
415 // assume 'extractDelims' ran before
416 void extractFunctions(MathArray & ar)
417 {
418         // we need at least two items...
419         if (ar.size() < 2)
420                 return;
421
422         //lyxerr << "\nFunctions from: " << ar << "\n";
423         for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
424                 MathArray::iterator it = ar.begin() + i;
425                 MathArray::iterator jt = it + 1;
426
427                 string name;
428                 // is it a function?
429                 if ((*it)->asUnknownInset()) {
430                         // it certainly is if it is well known...
431                         name = (*it)->name();
432                 } else {
433                         // is this a user defined function?
434                         // it it probably not, if it doesn't have a name.
435                         if (!extractString(*it, name))
436                                 continue;
437                         // it is not if it has no argument
438                         if (jt == ar.end())
439                                 continue;
440                         // guess so, if this is followed by
441                         // a DelimInset with a single item in the cell
442                         MathDelimInset const * del = (*jt)->asDelimInset();
443                         if (!del || del->cell(0).size() != 1)
444                                 continue;
445                         // fall trough into main branch
446                 }
447
448                 // do we have an exponent like in
449                 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
450                 MathArray exp;
451                 extractScript(exp, jt, ar.end());
452
453                 // create a proper inset as replacement
454                 MathExFuncInset * p = new MathExFuncInset(name);
455
456                 // jt points to the "argument". Get hold of this.
457                 MathArray::iterator st = extractArgument(p->cell(0), jt, ar.end());
458
459                 // replace the function name by a real function inset
460                 *it = MathAtom(p);
461
462                 // remove the source of the argument from the array
463                 ar.erase(it + 1, st);
464
465                 // re-insert exponent
466                 ar.insert(i + 1, exp);
467                 //lyxerr << "\nFunctions to: " << ar << "\n";
468         }
469 }
470
471
472 //
473 // search integrals
474 //
475
476 bool testSymbol(MathAtom const & at, string const & name)
477 {
478         return at->asSymbolInset() && at->asSymbolInset()->name() == name;
479 }
480
481
482 bool testIntSymbol(MathAtom const & at)
483 {
484         return testSymbol(at, "int");
485 }
486
487
488 bool testIntegral(MathAtom const & at)
489 {
490         return
491          testIntSymbol(at) ||
492                 ( at->asScriptInset()
493                   && at->asScriptInset()->nuc().size()
494                         && testIntSymbol(at->asScriptInset()->nuc().back()) );
495 }
496
497
498
499 bool testIntDiff(MathAtom const & at)
500 {
501         return testString(at, "d");
502 }
503
504
505 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real MathExIntInset
506 // assume 'extractDelims' ran before
507 void extractIntegrals(MathArray & ar)
508 {
509         // we need at least three items...
510         if (ar.size() < 3)
511                 return;
512
513         //lyxerr << "\nIntegrals from: " << ar << "\n";
514         for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
515                 MathArray::iterator it = ar.begin() + i;
516
517                 // search 'd'
518                 MathArray::iterator jt =
519                         endNestSearch(it, ar.end(), testIntegral, testIntDiff);
520
521                 // something sensible found?
522                 if (jt == ar.end())
523                         continue;
524
525                 // is this a integral name?
526                 if (!testIntegral(*it))
527                         continue;
528
529                 // core ist part from behind the scripts to the 'd'
530                 MathExIntInset * p = new MathExIntInset("int");
531
532                 // handle scripts if available
533                 if (!testIntSymbol(*it)) {
534                         p->cell(2) = (*it)->asScriptInset()->down();
535                         p->cell(3) = (*it)->asScriptInset()->up();
536                 }
537                 p->cell(0) = MathArray(it + 1, jt);
538
539                 // use the "thing" behind the 'd' as differential
540                 MathArray::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
541
542                 // remove used parts
543                 ar.erase(it + 1, tt);
544                 *it = MathAtom(p);
545         }
546         //lyxerr << "\nIntegrals to: " << ar << "\n";
547 }
548
549
550 //
551 // search sums
552 //
553
554
555 bool testEqualSign(MathAtom const & at)
556 {
557         return testString(at, "=");
558 }
559
560
561 bool testSumSymbol(MathAtom const & p)
562 {
563         return testSymbol(p, "sum");
564 }
565
566
567 bool testSum(MathAtom const & at)
568 {
569         return
570          testSumSymbol(at) ||
571                 ( at->asScriptInset()
572                   && at->asScriptInset()->nuc().size()
573                         && testSumSymbol(at->asScriptInset()->nuc().back()) );
574 }
575
576
577 // replace '\sum' ['_^'] f(x) sequences by a real MathExIntInset
578 // assume 'extractDelims' ran before
579 void extractSums(MathArray & ar)
580 {
581         // we need at least two items...
582         if (ar.size() < 2)
583                 return;
584
585         //lyxerr << "\nSums from: " << ar << "\n";
586         for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
587                 MathArray::iterator it = ar.begin() + i;
588
589                 // is this a sum name?
590                 if (!testSum(ar[i]))
591                         continue;
592
593                 // create a proper inset as replacement
594                 MathExIntInset * p = new MathExIntInset("sum");
595
596                 // collect lower bound and summation index
597                 MathScriptInset const * sub = ar[i]->asScriptInset();
598                 if (sub && sub->hasDown()) {
599                         // try to figure out the summation index from the subscript
600                         MathArray const & ar = sub->down();
601                         MathArray::const_iterator xt =
602                                 find_if(ar.begin(), ar.end(), &testEqualSign);
603                         if (xt != ar.end()) {
604                                 // we found a '=', use everything in front of that as index,
605                                 // and everything behind as lower index
606                                 p->cell(1) = MathArray(ar.begin(), xt);
607                                 p->cell(2) = MathArray(xt + 1, ar.end());
608                         } else {
609                                 // use everything as summation index, don't use scripts.
610                                 p->cell(1) = ar;
611                         }
612                 }
613
614                 // collect upper bound
615                 if (sub && sub->hasUp())
616                         p->cell(3) = sub->up();
617
618                 // use something  behind the script as core
619                 MathArray::iterator tt = extractArgument(p->cell(0), it + 1, ar.end());
620
621                 // cleanup
622                 ar.erase(it + 1, tt);
623                 *it = MathAtom(p);
624         }
625         //lyxerr << "\nSums to: " << ar << "\n";
626 }
627
628
629 //
630 // search differential stuff
631 //
632
633 // tests for 'd' or '\partial'
634 bool testDiffItem(MathAtom const & at)
635 {
636         return testString(at, "d");
637 }
638
639
640 bool testDiffArray(MathArray const & ar)
641 {
642         return ar.size() && testDiffItem(ar.front());
643 }
644
645
646 bool testDiffFrac(MathAtom const & at)
647 {
648         return
649                 at->asFracInset()
650                         && testDiffArray(at->asFracInset()->cell(0))
651                         && testDiffArray(at->asFracInset()->cell(1));
652 }
653
654
655 void extractDiff(MathArray & ar)
656 {
657         //lyxerr << "\nDiffs from: " << ar << "\n";
658         for (MathArray::size_type i = 0; i < ar.size(); ++i) {
659                 MathArray::iterator it = ar.begin() + i;
660
661                 // is this a "differential fraction"?
662                 if (!testDiffFrac(*it))
663                         continue;
664
665                 MathFracInset const * f = (*it)->asFracInset();
666                 if (!f) {
667                         lyxerr << "should not happen\n";
668                         continue;
669                 }
670
671                 // create a proper diff inset
672                 MathDiffInset * diff = new MathDiffInset;
673
674                 // collect function, let jt point behind last used item
675                 MathArray::iterator jt = it + 1;
676                 //int n = 1;
677                 MathArray const & numer = f->cell(0);
678                 if (numer.size() > 1 && numer[1]->asScriptInset()) {
679                         // this is something like  d^n f(x) / d... or  d^n / d...
680                         // FIXME
681                         //n = 1;
682                         if (numer.size() > 2)
683                                 diff->cell(0) = MathArray(numer.begin() + 2, numer.end());
684                         else
685                                 jt = extractArgument(diff->cell(0), jt, ar.end());
686                 } else {
687                         // simply d f(x) / d... or  d/d...
688                         if (numer.size() > 1)
689                                 diff->cell(0) = MathArray(numer.begin() + 1, numer.end());
690                         else
691                                 jt = extractArgument(diff->cell(0), jt, ar.end());
692                 }
693
694                 // collect denominator parts
695                 MathArray const & denom = f->cell(1);
696                 for (MathArray::const_iterator dt = denom.begin(); dt != denom.end();) {
697                         // find the next 'd'
698                         MathArray::const_iterator et
699                                 = find_if(dt + 1, denom.end(), &testDiffItem);
700
701                         // point before this
702                         MathArray::const_iterator st = et - 1;
703                         MathScriptInset const * script = (*st)->asScriptInset();
704                         if (script && script->hasUp()) {
705                                 // things like   d.../dx^n
706                                 int mult = 1;
707                                 if (extractNumber(script->up(), mult)) {
708                                         //lyxerr << "mult: " << mult << endl;
709                                         for (int i = 0; i < mult; ++i)
710                                                 diff->addDer(MathArray(dt + 1, st));
711                                 }
712                         } else {
713                                 // just  d.../dx
714                                 diff->addDer(MathArray(dt + 1, et));
715                         }
716                         dt = et;
717                 }
718
719                 // cleanup
720                 ar.erase(it + 1, jt);
721                 *it = MathAtom(diff);
722         }
723         //lyxerr << "\nDiffs to: " << ar << "\n";
724 }
725
726
727 //
728 // search limits
729 //
730
731
732 bool testRightArrow(MathAtom const & at)
733 {
734         return testSymbol(at, "to") || testSymbol(at, "rightarrow");
735 }
736
737
738
739 // replace '\lim_{x->x0} f(x)' sequences by a real MathLimInset
740 // assume 'extractDelims' ran before
741 void extractLims(MathArray & ar)
742 {
743         // we need at least three items...
744         if (ar.size() < 3)
745                 return;
746
747         //lyxerr << "\nLimits from: " << ar << "\n";
748         for (MathArray::size_type i = 0; i + 2 < ar.size(); ++i) {
749                 MathArray::iterator it = ar.begin() + i;
750
751                 // is this a limit function?
752                 if (!testSymbol(*it, "lim"))
753                         continue;
754
755                 // the next one must be a subscript (without superscript)
756                 MathScriptInset const * sub = (*(it + 1))->asScriptInset();
757                 if (!sub || !sub->hasDown() || sub->hasUp())
758                         continue;
759
760                 // and it must contain a -> symbol
761                 MathArray const & s = sub->down();
762                 MathArray::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
763                 if (st == s.end())
764                         continue;
765
766                 // the -> splits the subscript int x and x0
767                 MathArray x  = MathArray(s.begin(), st);
768                 MathArray x0 = MathArray(st + 1, s.end());
769
770                 // use something behind the script as core
771                 MathArray f;
772                 MathArray::iterator tt = extractArgument(f, it + 2, ar.end());
773
774                 // cleanup
775                 ar.erase(it + 1, tt);
776
777                 // create a proper inset as replacement
778                 *it = MathAtom(new MathLimInset(f, x, x0));
779         }
780         //lyxerr << "\nLimits to: " << ar << "\n";
781 }
782
783
784 //
785 // combine searches
786 //
787
788 void extractStructure(MathArray & ar)
789 {
790         //lyxerr << "\nStructure from: " << ar << "\n";
791         extractIntegrals(ar);
792         extractSums(ar);
793         splitScripts(ar);
794         extractNumbers(ar);
795         extractMatrices(ar);
796         extractDelims(ar);
797         extractFunctions(ar);
798         extractDets(ar);
799         extractDiff(ar);
800         extractExps(ar);
801         extractLims(ar);
802         extractStrings(ar);
803         //lyxerr << "\nStructure to: " << ar << "\n";
804 }
805
806
807 void write(MathArray const & dat, WriteStream & wi)
808 {
809         MathArray ar = dat;
810         extractStrings(ar);
811         wi.firstitem() = true;
812         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
813                 (*it)->write(wi);
814                 wi.firstitem() = false;
815         }
816 }
817
818
819 void normalize(MathArray const & ar, NormalStream & os)
820 {
821         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
822                 (*it)->normalize(os);
823 }
824
825
826 void octavize(MathArray const & dat, OctaveStream & os)
827 {
828         MathArray ar = dat;
829         extractStructure(ar);
830         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
831                 (*it)->octavize(os);
832 }
833
834
835 void maplize(MathArray const & dat, MapleStream & os)
836 {
837         MathArray ar = dat;
838         extractStructure(ar);
839         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
840                 (*it)->maplize(os);
841 }
842
843
844 void maximize(MathArray const & dat, MaximaStream & os)
845 {
846         MathArray ar = dat;
847         extractStructure(ar);
848         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
849                 (*it)->maximize(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 command =  "echo '" + data + "' | " + cmd;
886                 lyxerr << "calling: " << command << endl;
887                 cmd_ret const ret = RunCommand(command);
888                 return ret.second;
889         }
890
891         string::size_type get_matching_brace(string const & str, string::size_type i)
892         {
893                 int count = 1;
894                 string::size_type n = str.size();
895                 while (i < n) {
896                         i = str.find_first_of("{}", i+1);
897                         if (i == string::npos) return i;
898                         if (str[i] == '{')
899                                 ++count;
900                         else
901                                 --count;
902                         if (count == 0)
903                                 return i;
904                 }
905                 return string::npos;
906         }
907
908         string::size_type get_matching_brace_back(string const & str, string::size_type i)
909         {
910                 int count = 1;
911                 while (i > 0) {
912                         i = str.find_last_of("{}", i-1);
913                         if (i == string::npos) return i;
914                         if (str[i] == '}')
915                                 ++count;
916                         else
917                                 --count;
918                         if (count == 0)
919                                 return i;
920                 }
921                 return string::npos;
922         }
923
924         MathArray pipeThroughMaxima(string const &, MathArray const & ar)
925         {
926                 ostringstream os;
927                 MaximaStream ms(os);
928                 ms << ar;
929                 string expr = STRCONV(os.str());
930                 string const header = "SIMPSUM:true;";
931
932                 string out;
933                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
934                         // try to fix missing '*' the hard way
935                         //
936                         // > echo "2x;" | maxima
937                         // ...
938                         // (C1) Incorrect syntax: x is not an infix operator
939                         // 2x;
940                         //  ^
941                         //
942                         lyxerr << "checking expr: '" << expr << "'\n";
943                         string full = header + "tex(" + expr + ");";
944                         out = captureOutput("maxima", full);
945
946                         // leave loop if expression syntax is probably ok
947                         if (out.find("Incorrect syntax") == string::npos)
948                                 break;
949
950                         // search line with "Incorrect syntax"
951                         istringstream is(out.c_str());
952                         string line;
953                         while (is) {
954                                 getline(is, line);
955                                 if (line.find("Incorrect syntax") != string::npos)
956                                         break;
957                         }
958
959                         // 2nd next line is the one with caret
960                         getline(is, line);
961                         getline(is, line);
962                         string::size_type pos = line.find('^');
963                         lyxerr << "found caret at pos: '" << pos << "'\n";
964                         if (pos == string::npos || pos < 4)
965                                 break; // caret position not found
966                         pos -= 4; // skip the "tex(" part
967                         if (expr[pos] == '*')
968                                 break; // two '*' in a row are definitely bad
969                         expr.insert(pos,  "*");
970                 }
971
972                 std::vector<string> tmp = getVectorFromString(out, "$$");
973                 if (tmp.size() < 2)
974                         return MathArray();
975
976                 out = subst(tmp[1],"\\>", "");
977                 lyxerr << "out: '" << out << "'\n";
978
979                 // Ugly code that tries to make the result prettier
980
981                 string::size_type i = out.find("\\mathchoice");
982                 while (i != string::npos) {
983                         string::size_type j = get_matching_brace(out, i + 12);
984                         string::size_type k = get_matching_brace(out, j + 1);
985                         k = get_matching_brace(out, k + 1);
986                         k = get_matching_brace(out, k + 1);
987                         string mid = out.substr(i + 13,j - i - 13);
988                         if (mid.find("\\over") != string::npos)
989                                 mid = '{' + mid + '}';
990                         out = out.substr(0,i)
991                                 + mid
992                                 + out.substr(k + 1);
993                         //lyxerr << "out: " << out << endl;
994                         i = out.find("\\mathchoice", i);
995                         break;
996                 }
997
998                 i = out.find("\\over");
999                 while (i != string::npos) {
1000                         string::size_type j = get_matching_brace_back(out, i - 1);
1001                         if (j == string::npos || j == 0) break;
1002                         string::size_type k = get_matching_brace(out, i + 5);
1003                         if (k == string::npos || k + 1 == out.size()) break;
1004                         out = out.substr(0,j - 1)
1005                                 + "\\frac"
1006                                 + out.substr(j,i - j)
1007                                 + out.substr(i + 5,k - i - 4)
1008                                 + out.substr(k + 2);
1009                         //lyxerr << "out: " << out << endl;
1010                         i = out.find("\\over", i + 4);
1011                 }
1012                 MathArray res;
1013                 mathed_parse_cell(res, out);
1014                 return res;
1015         }
1016
1017
1018         MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
1019         {
1020                 string header = "readlib(latex):\n";
1021
1022                 // remove the \\it for variable names
1023                 //"#`latex/csname_font` := `\\it `:"
1024                 header +=
1025                         "`latex/csname_font` := ``:\n";
1026
1027                 // export matrices in (...) instead of [...]
1028                 header +=
1029                         "`latex/latex/matrix` := "
1030                                 "subs(`[`=`(`, `]`=`)`,"
1031                                         "eval(`latex/latex/matrix`)):\n";
1032
1033                 // replace \\cdots with proper '*'
1034                 header +=
1035                         "`latex/latex/*` := "
1036                                 "subs(`\\,`=`\\cdot `,"
1037                                         "eval(`latex/latex/*`)):\n";
1038
1039                 // remove spurious \\noalign{\\medskip} in matrix output
1040                 header +=
1041                         "`latex/latex/matrix`:= "
1042                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1043                                         "eval(`latex/latex/matrix`)):\n";
1044
1045                 //"#`latex/latex/symbol` "
1046                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1047
1048                 string trailer = "quit;";
1049                 ostringstream os;
1050                 MapleStream ms(os);
1051                 ms << ar;
1052                 string expr = STRCONV(os.str());
1053                 lyxerr << "ar: '" << ar << "'\n";
1054                 lyxerr << "ms: '" << os.str() << "'\n";
1055
1056                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1057                         // try to fix missing '*' the hard way by using mint
1058                         //
1059                         // ... > echo "1A;" | mint -i 1 -S -s -q
1060                         // on line     1: 1A;
1061                         //                 ^ syntax error -
1062                         //                   Probably missing an operator such as * p
1063                         //
1064                         lyxerr << "checking expr: '" << expr << "'\n";
1065                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1066                         if (out.empty())
1067                                 break; // expression syntax is ok
1068                         istringstream is(out.c_str());
1069                         string line;
1070                         getline(is, line);
1071                         if (line.find("on line") != 0)
1072                                 break; // error message not identified
1073                         getline(is, line);
1074                         string::size_type pos = line.find('^');
1075                         if (pos == string::npos || pos < 15)
1076                                 break; // caret position not found
1077                         pos -= 15; // skip the "on line ..." part
1078                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1079                                 break; // two '*' in a row are definitely bad
1080                         expr.insert(pos, 1, '*');
1081                 }
1082
1083                 string full = "latex(" +  extra + '(' + expr + "));";
1084                 string out = captureOutput("maple -q", header + full + trailer);
1085
1086                 // change \_ into _
1087
1088                 //
1089                 MathArray res;
1090                 mathed_parse_cell(res, out);
1091                 return res;
1092         }
1093
1094
1095         MathArray pipeThroughOctave(string const &, MathArray const & ar)
1096         {
1097                 ostringstream os;
1098                 OctaveStream vs(os);
1099                 vs << ar;
1100                 string expr = STRCONV(os.str());
1101                 string out;
1102
1103                 lyxerr << "pipe: ar: '" << ar << "'\n";
1104                 lyxerr << "pipe: expr: '" << expr << "'\n";
1105
1106                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1107                         //
1108                         // try to fix missing '*' the hard way
1109                         // parse error:
1110                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1111                         //                                   ^
1112                         //
1113                         lyxerr << "checking expr: '" << expr << "'\n";
1114                         out = captureOutput("octave -q 2>&1", expr);
1115                         lyxerr << "checking out: '" << out << "'\n";
1116
1117                         // leave loop if expression syntax is probably ok
1118                         if (out.find("parse error:") == string::npos)
1119                                 break;
1120
1121                         // search line with single caret
1122                         istringstream is(out.c_str());
1123                         string line;
1124                         while (is) {
1125                                 getline(is, line);
1126                                 lyxerr << "skipping line: '" << line << "'\n";
1127                                 if (line.find(">>> ") != string::npos)
1128                                         break;
1129                         }
1130
1131                         // found line with error, next line is the one with caret
1132                         getline(is, line);
1133                         string::size_type pos = line.find('^');
1134                         lyxerr << "caret line: '" << line << "'\n";
1135                         lyxerr << "found caret at pos: '" << pos << "'\n";
1136                         if (pos == string::npos || pos < 4)
1137                                 break; // caret position not found
1138                         pos -= 4; // skip the ">>> " part
1139                         if (expr[pos] == '*')
1140                                 break; // two '*' in a row are definitely bad
1141                         expr.insert(pos, 1, '*');
1142                 }
1143
1144                 if (out.size() < 6)
1145                         return MathArray();
1146
1147                 // remove 'ans = '
1148                 out = out.substr(6);
1149
1150                 // parse output as matrix or single number
1151                 MathAtom at(new MathArrayInset("array", out));
1152                 MathArrayInset const * mat = at->asArrayInset();
1153                 MathArray res;
1154                 if (mat->ncols() == 1 && mat->nrows() == 1)
1155                         res.append(mat->cell(0));
1156                 else {
1157                         res.push_back(MathAtom(new MathDelimInset("(", ")")));
1158                         res.back().nucleus()->cell(0).push_back(at);
1159                 }
1160                 return res;
1161         }
1162
1163 }
1164
1165
1166 MathArray pipeThroughExtern(string const & lang, string const & extra,
1167         MathArray const & ar)
1168 {
1169         if (lang == "octave")
1170                 return pipeThroughOctave(extra, ar);
1171
1172         if (lang == "maxima")
1173                 return pipeThroughMaxima(extra, ar);
1174
1175         if (lang == "maple")
1176                 return pipeThroughMaple(extra, ar);
1177
1178         // create normalized expression
1179         ostringstream os;
1180         NormalStream ns(os);
1181         os << '[' << extra << ' ';
1182         ns << ar;
1183         os << ']';
1184         string data = STRCONV(os.str());
1185
1186         // search external script
1187         string file = LibFileSearch("mathed", "extern_" + lang);
1188         if (file.empty()) {
1189                 lyxerr << "converter to '" << lang << "' not found" << endl;
1190                 return MathArray();
1191         }
1192
1193         // run external sript
1194         string out = captureOutput(file, data);
1195         MathArray res;
1196         mathed_parse_cell(res, out);
1197         return res;
1198 }