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