3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
11 // This file contains most of the magic that extracts "context
12 // information" from the unstructered layout-oriented stuff in an
17 #include "math_amsarrayinset.h"
18 #include "math_arrayinset.h"
19 #include "math_charinset.h"
20 #include "math_deliminset.h"
21 #include "math_diffinset.h"
22 #include "math_exfuncinset.h"
23 #include "math_exintinset.h"
24 #include "math_fracinset.h"
25 #include "math_liminset.h"
26 #include "math_matrixinset.h"
27 #include "math_mathmlstream.h"
28 #include "math_numberinset.h"
29 #include "math_scriptinset.h"
30 #include "math_stringinset.h"
31 #include "math_symbolinset.h"
32 #include "math_unknowninset.h"
33 #include "math_parser.h"
36 #include "support/lyxlib.h"
37 #include "support/systemcall.h"
38 #include "support/filetools.h"
39 #include "support/lstrings.h"
43 using namespace lyx::support;
46 using std::istringstream;
51 ostream & operator<<(ostream & os, MathArray const & ar)
59 // define a function for tests
60 typedef bool TestItemFunc(MathAtom const &);
62 // define a function for replacing subexpressions
63 typedef MathAtom ReplaceArgumentFunc(const MathArray & ar);
67 // try to extract a super/subscript
68 // modify iterator position to point behind the thing
69 bool extractScript(MathArray & ar,
70 MathArray::iterator & pos, MathArray::iterator last)
72 // nothing to get here
76 // is this a scriptinset?
77 if (!(*pos)->asScriptInset())
80 // it is a scriptinset, use it.
87 // try to extract an "argument" to some function.
88 // returns position behind the argument
89 MathArray::iterator extractArgument(MathArray & ar,
90 MathArray::iterator pos, MathArray::iterator last, string const & = "")
92 // nothing to get here
96 // something deliminited _is_ an argument
97 if ((*pos)->asDelimInset()) {
102 // always take the first thing, no matter what it is
105 // go ahead if possible
110 // if the next item is a subscript, it most certainly belongs to the
112 extractScript(ar, pos, last);
116 // but it might be more than that.
117 // FIXME: not implemented
118 //for (MathArray::iterator it = pos + 1; it != last; ++it) {
119 // // always take the first thing, no matter
121 // ar.push_back(*it);
129 // returns sequence of char with same code starting at it up to end
130 // it might be less, though...
132 (MathArray::const_iterator it, MathArray::const_iterator end)
135 for (; it != end && (*it)->asCharInset(); ++it)
136 s += (*it)->getChar();
141 void extractStrings(MathArray & ar)
143 //lyxerr << "\nStrings from: " << ar << endl;
144 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
145 if (!ar[i]->asCharInset())
147 string s = charSequence(ar.begin() + i, ar.end());
148 ar[i] = MathAtom(new MathStringInset(s));
149 ar.erase(i + 1, i + s.size());
151 //lyxerr << "\nStrings to: " << ar << endl;
155 void extractMatrices(MathArray & ar)
157 //lyxerr << "\nMatrices from: " << ar << endl;
158 // first pass for explicitly delimited stuff
159 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
160 if (!ar[i]->asDelimInset())
162 MathArray const & arr = ar[i]->asDelimInset()->cell(0);
165 if (!arr.front()->asGridInset())
167 ar[i] = MathAtom(new MathMatrixInset(*(arr.front()->asGridInset())));
170 // second pass for AMS "pmatrix" etc
171 for (MathArray::size_type i = 0; i < ar.size(); ++i)
172 if (ar[i]->asAMSArrayInset())
173 ar[i] = MathAtom(new MathMatrixInset(*(ar[i]->asGridInset())));
174 //lyxerr << "\nMatrices to: " << ar << endl;
178 // convert this inset somehow to a string
179 bool extractString(MathAtom const & at, string & str)
182 str = string(1, at->getChar());
185 if (at->asStringInset()) {
186 str = at->asStringInset()->str();
193 // convert this inset somehow to a number
194 bool extractNumber(MathArray const & ar, int & i)
196 istringstream is(charSequence(ar.begin(), ar.end()).c_str());
202 bool extractNumber(MathArray const & ar, double & d)
204 istringstream is(charSequence(ar.begin(), ar.end()).c_str());
210 bool testString(MathAtom const & at, string const & str)
213 return extractString(at, s) && str == s;
217 // search end of nested sequence
218 MathArray::iterator endNestSearch(
219 MathArray::iterator it,
220 MathArray::iterator last,
221 TestItemFunc testOpen,
222 TestItemFunc testClose
225 for (int level = 0; it != last; ++it) {
237 // replace nested sequences by a real Insets
240 TestItemFunc testOpen,
241 TestItemFunc testClose,
242 ReplaceArgumentFunc replaceArg
245 // use indices rather than iterators for the loop because we are going
246 // to modify the array.
247 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
248 // check whether this is the begin of the sequence
249 if (!testOpen(ar[i]))
252 // search end of sequence
253 MathArray::iterator it = ar.begin() + i;
254 MathArray::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
258 // replace the original stuff by the new inset
259 ar[i] = replaceArg(MathArray(it + 1, jt));
260 ar.erase(it + 1, jt + 1);
267 // split scripts into seperate super- and subscript insets. sub goes in
271 void splitScripts(MathArray & ar)
273 //lyxerr << "\nScripts from: " << ar << endl;
274 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
275 // is this script inset?
276 if (!ar[i]->asScriptInset())
279 // no problem if we don't have both...
280 if (!ar[i]->asScriptInset()->hasUp())
282 if (!ar[i]->asScriptInset()->hasDown())
285 // create extra script inset and move superscript over
286 MathScriptInset * p = ar[i].nucleus()->asScriptInset();
287 MathScriptInset * q = new MathScriptInset(true);
288 std::swap(q->up(), p->up());
289 p->removeScript(true);
291 // insert new inset behind
293 ar.insert(i, MathAtom(q));
295 //lyxerr << "\nScripts to: " << ar << endl;
303 void extractExps(MathArray & ar)
305 //lyxerr << "\nExps from: " << ar << endl;
306 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
308 if (ar[i]->getChar() != 'e')
311 // we need an exponent but no subscript
312 MathScriptInset const * sup = ar[i + 1]->asScriptInset();
313 if (!sup || sup->hasDown())
316 // create a proper exp-inset as replacement
317 ar[i] = MathAtom(new MathExFuncInset("exp", sup->cell(1)));
320 //lyxerr << "\nExps to: " << ar << endl;
325 // extract det(...) from |matrix|
327 void extractDets(MathArray & ar)
329 //lyxerr << "\ndet from: " << ar << endl;
330 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it) {
331 MathDelimInset const * del = (*it)->asDelimInset();
336 *it = MathAtom(new MathExFuncInset("det", del->cell(0)));
338 //lyxerr << "\ndet to: " << ar << endl;
346 bool isDigitOrSimilar(char c)
348 return ('0' <= c && c <= '9') || c == '.';
352 // returns sequence of digits
354 (MathArray::const_iterator it, MathArray::const_iterator end)
357 for (; it != end && (*it)->asCharInset(); ++it) {
358 if (!isDigitOrSimilar((*it)->getChar()))
360 s += (*it)->getChar();
366 void extractNumbers(MathArray & ar)
368 //lyxerr << "\nNumbers from: " << ar << endl;
369 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
370 if (!ar[i]->asCharInset())
372 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
375 string s = digitSequence(ar.begin() + i, ar.end());
377 ar[i] = MathAtom(new MathNumberInset(s));
378 ar.erase(i + 1, i + s.size());
380 //lyxerr << "\nNumbers to: " << ar << endl;
386 // search deliminiters
389 bool testOpenParan(MathAtom const & at)
391 return testString(at, "(");
395 bool testCloseParan(MathAtom const & at)
397 return testString(at, ")");
401 MathAtom replaceDelims(const MathArray & ar)
403 return MathAtom(new MathDelimInset("(", ")", ar));
407 // replace '('...')' sequences by a real MathDelimInset
408 void extractDelims(MathArray & ar)
410 //lyxerr << "\nDelims from: " << ar << endl;
411 replaceNested(ar, testOpenParan, testCloseParan, replaceDelims);
412 //lyxerr << "\nDelims to: " << ar << endl;
418 // search well-known functions
422 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real MathExFuncInset
423 // assume 'extractDelims' ran before
424 void extractFunctions(MathArray & ar)
426 // we need at least two items...
430 //lyxerr << "\nFunctions from: " << ar << endl;
431 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
432 MathArray::iterator it = ar.begin() + i;
433 MathArray::iterator jt = it + 1;
437 if ((*it)->asUnknownInset()) {
438 // it certainly is if it is well known...
439 name = (*it)->name();
441 // is this a user defined function?
442 // it it probably not, if it doesn't have a name.
443 if (!extractString(*it, name))
445 // it is not if it has no argument
448 // guess so, if this is followed by
449 // a DelimInset with a single item in the cell
450 MathDelimInset const * del = (*jt)->asDelimInset();
451 if (!del || del->cell(0).size() != 1)
453 // fall trough into main branch
456 // do we have an exponent like in
457 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
459 extractScript(exp, jt, ar.end());
461 // create a proper inset as replacement
462 MathExFuncInset * p = new MathExFuncInset(name);
464 // jt points to the "argument". Get hold of this.
465 MathArray::iterator st = extractArgument(p->cell(0), jt, ar.end());
467 // replace the function name by a real function inset
470 // remove the source of the argument from the array
471 ar.erase(it + 1, st);
473 // re-insert exponent
474 ar.insert(i + 1, exp);
475 //lyxerr << "\nFunctions to: " << ar << endl;
484 bool testSymbol(MathAtom const & at, string const & name)
486 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
490 bool testIntSymbol(MathAtom const & at)
492 return testSymbol(at, "int");
496 bool testIntegral(MathAtom const & at)
500 ( at->asScriptInset()
501 && at->asScriptInset()->nuc().size()
502 && testIntSymbol(at->asScriptInset()->nuc().back()) );
507 bool testIntDiff(MathAtom const & at)
509 return testString(at, "d");
513 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real MathExIntInset
514 // assume 'extractDelims' ran before
515 void extractIntegrals(MathArray & ar)
517 // we need at least three items...
521 //lyxerr << "\nIntegrals from: " << ar << endl;
522 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
523 MathArray::iterator it = ar.begin() + i;
526 MathArray::iterator jt =
527 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
529 // something sensible found?
533 // is this a integral name?
534 if (!testIntegral(*it))
537 // core ist part from behind the scripts to the 'd'
538 MathExIntInset * p = new MathExIntInset("int");
540 // handle scripts if available
541 if (!testIntSymbol(*it)) {
542 p->cell(2) = (*it)->asScriptInset()->down();
543 p->cell(3) = (*it)->asScriptInset()->up();
545 p->cell(0) = MathArray(it + 1, jt);
547 // use the "thing" behind the 'd' as differential
548 MathArray::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
551 ar.erase(it + 1, tt);
554 //lyxerr << "\nIntegrals to: " << ar << endl;
563 bool testEqualSign(MathAtom const & at)
565 return testString(at, "=");
569 bool testSumSymbol(MathAtom const & p)
571 return testSymbol(p, "sum");
575 bool testSum(MathAtom const & at)
579 ( at->asScriptInset()
580 && at->asScriptInset()->nuc().size()
581 && testSumSymbol(at->asScriptInset()->nuc().back()) );
585 // replace '\sum' ['_^'] f(x) sequences by a real MathExIntInset
586 // assume 'extractDelims' ran before
587 void extractSums(MathArray & ar)
589 // we need at least two items...
593 //lyxerr << "\nSums from: " << ar << endl;
594 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
595 MathArray::iterator it = ar.begin() + i;
597 // is this a sum name?
601 // create a proper inset as replacement
602 MathExIntInset * p = new MathExIntInset("sum");
604 // collect lower bound and summation index
605 MathScriptInset const * sub = ar[i]->asScriptInset();
606 if (sub && sub->hasDown()) {
607 // try to figure out the summation index from the subscript
608 MathArray const & ar = sub->down();
609 MathArray::const_iterator xt =
610 find_if(ar.begin(), ar.end(), &testEqualSign);
611 if (xt != ar.end()) {
612 // we found a '=', use everything in front of that as index,
613 // and everything behind as lower index
614 p->cell(1) = MathArray(ar.begin(), xt);
615 p->cell(2) = MathArray(xt + 1, ar.end());
617 // use everything as summation index, don't use scripts.
622 // collect upper bound
623 if (sub && sub->hasUp())
624 p->cell(3) = sub->up();
626 // use something behind the script as core
627 MathArray::iterator tt = extractArgument(p->cell(0), it + 1, ar.end());
630 ar.erase(it + 1, tt);
633 //lyxerr << "\nSums to: " << ar << endl;
638 // search differential stuff
641 // tests for 'd' or '\partial'
642 bool testDiffItem(MathAtom const & at)
644 return testString(at, "d");
648 bool testDiffArray(MathArray const & ar)
650 return ar.size() && testDiffItem(ar.front());
654 bool testDiffFrac(MathAtom const & at)
658 && testDiffArray(at->asFracInset()->cell(0))
659 && testDiffArray(at->asFracInset()->cell(1));
663 void extractDiff(MathArray & ar)
665 //lyxerr << "\nDiffs from: " << ar << endl;
666 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
667 MathArray::iterator it = ar.begin() + i;
669 // is this a "differential fraction"?
670 if (!testDiffFrac(*it))
673 MathFracInset const * f = (*it)->asFracInset();
675 lyxerr << "should not happen" << endl;
679 // create a proper diff inset
680 MathDiffInset * diff = new MathDiffInset;
682 // collect function, let jt point behind last used item
683 MathArray::iterator jt = it + 1;
685 MathArray const & numer = f->cell(0);
686 if (numer.size() > 1 && numer[1]->asScriptInset()) {
687 // this is something like d^n f(x) / d... or d^n / d...
690 if (numer.size() > 2)
691 diff->cell(0) = MathArray(numer.begin() + 2, numer.end());
693 jt = extractArgument(diff->cell(0), jt, ar.end());
695 // simply d f(x) / d... or d/d...
696 if (numer.size() > 1)
697 diff->cell(0) = MathArray(numer.begin() + 1, numer.end());
699 jt = extractArgument(diff->cell(0), jt, ar.end());
702 // collect denominator parts
703 MathArray const & denom = f->cell(1);
704 for (MathArray::const_iterator dt = denom.begin(); dt != denom.end();) {
706 MathArray::const_iterator et
707 = find_if(dt + 1, denom.end(), &testDiffItem);
710 MathArray::const_iterator st = et - 1;
711 MathScriptInset const * script = (*st)->asScriptInset();
712 if (script && script->hasUp()) {
713 // things like d.../dx^n
715 if (extractNumber(script->up(), mult)) {
716 //lyxerr << "mult: " << mult << endl;
717 for (int i = 0; i < mult; ++i)
718 diff->addDer(MathArray(dt + 1, st));
722 diff->addDer(MathArray(dt + 1, et));
728 ar.erase(it + 1, jt);
729 *it = MathAtom(diff);
731 //lyxerr << "\nDiffs to: " << ar << endl;
740 bool testRightArrow(MathAtom const & at)
742 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
747 // replace '\lim_{x->x0} f(x)' sequences by a real MathLimInset
748 // assume 'extractDelims' ran before
749 void extractLims(MathArray & ar)
751 // we need at least three items...
755 //lyxerr << "\nLimits from: " << ar << endl;
756 for (MathArray::size_type i = 0; i + 2 < ar.size(); ++i) {
757 MathArray::iterator it = ar.begin() + i;
759 // is this a limit function?
760 if (!testSymbol(*it, "lim"))
763 // the next one must be a subscript (without superscript)
764 MathScriptInset const * sub = (*(it + 1))->asScriptInset();
765 if (!sub || !sub->hasDown() || sub->hasUp())
768 // and it must contain a -> symbol
769 MathArray const & s = sub->down();
770 MathArray::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
774 // the -> splits the subscript int x and x0
775 MathArray x = MathArray(s.begin(), st);
776 MathArray x0 = MathArray(st + 1, s.end());
778 // use something behind the script as core
780 MathArray::iterator tt = extractArgument(f, it + 2, ar.end());
783 ar.erase(it + 1, tt);
785 // create a proper inset as replacement
786 *it = MathAtom(new MathLimInset(f, x, x0));
788 //lyxerr << "\nLimits to: " << ar << endl;
796 void extractStructure(MathArray & ar)
798 //lyxerr << "\nStructure from: " << ar << endl;
799 extractIntegrals(ar);
805 extractFunctions(ar);
811 //lyxerr << "\nStructure to: " << ar << endl;
815 void write(MathArray const & dat, WriteStream & wi)
819 wi.firstitem() = true;
820 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
822 wi.firstitem() = false;
827 void normalize(MathArray const & ar, NormalStream & os)
829 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
830 (*it)->normalize(os);
834 void octave(MathArray const & dat, OctaveStream & os)
837 extractStructure(ar);
838 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
843 void maple(MathArray const & dat, MapleStream & os)
846 extractStructure(ar);
847 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
852 void maxima(MathArray const & dat, MaximaStream & os)
855 extractStructure(ar);
856 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
861 void mathematica(MathArray const & dat, MathematicaStream & os)
864 extractStructure(ar);
865 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
866 (*it)->mathematica(os);
870 void mathmlize(MathArray const & dat, MathMLStream & os)
873 extractStructure(ar);
876 else if (ar.size() == 1)
880 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
881 (*it)->mathmlize(os);
891 string captureOutput(string const & cmd, string const & data)
893 string command = "echo '" + data + "' | " + cmd;
894 lyxerr << "calling: " << command << endl;
895 cmd_ret const ret = RunCommand(command);
899 string::size_type get_matching_brace(string const & str, string::size_type i)
902 string::size_type n = str.size();
904 i = str.find_first_of("{}", i+1);
905 if (i == string::npos) return i;
916 string::size_type get_matching_brace_back(string const & str, string::size_type i)
920 i = str.find_last_of("{}", i-1);
921 if (i == string::npos) return i;
932 MathArray pipeThroughMaxima(string const &, MathArray const & ar)
937 string expr = STRCONV(os.str());
938 string const header = "SIMPSUM:true;";
941 for (int i = 0; i < 100; ++i) { // at most 100 attempts
942 // try to fix missing '*' the hard way
944 // > echo "2x;" | maxima
946 // (C1) Incorrect syntax: x is not an infix operator
950 lyxerr << "checking expr: '" << expr << "'" << endl;
951 string full = header + "tex(" + expr + ");";
952 out = captureOutput("maxima", full);
954 // leave loop if expression syntax is probably ok
955 if (out.find("Incorrect syntax") == string::npos)
958 // search line with "Incorrect syntax"
959 istringstream is(out.c_str());
963 if (line.find("Incorrect syntax") != string::npos)
967 // 2nd next line is the one with caret
970 string::size_type pos = line.find('^');
971 lyxerr << "found caret at pos: '" << pos << "'" << endl;
972 if (pos == string::npos || pos < 4)
973 break; // caret position not found
974 pos -= 4; // skip the "tex(" part
975 if (expr[pos] == '*')
976 break; // two '*' in a row are definitely bad
977 expr.insert(pos, "*");
980 std::vector<string> tmp = getVectorFromString(out, "$$");
984 out = subst(tmp[1],"\\>", "");
985 lyxerr << "out: '" << out << "'" << endl;
987 // Ugly code that tries to make the result prettier
989 string::size_type i = out.find("\\mathchoice");
990 while (i != string::npos) {
991 string::size_type j = get_matching_brace(out, i + 12);
992 string::size_type k = get_matching_brace(out, j + 1);
993 k = get_matching_brace(out, k + 1);
994 k = get_matching_brace(out, k + 1);
995 string mid = out.substr(i + 13,j - i - 13);
996 if (mid.find("\\over") != string::npos)
997 mid = '{' + mid + '}';
998 out = out.substr(0,i)
1000 + out.substr(k + 1);
1001 //lyxerr << "out: " << out << endl;
1002 i = out.find("\\mathchoice", i);
1006 i = out.find("\\over");
1007 while (i != string::npos) {
1008 string::size_type j = get_matching_brace_back(out, i - 1);
1009 if (j == string::npos || j == 0) break;
1010 string::size_type k = get_matching_brace(out, i + 5);
1011 if (k == string::npos || k + 1 == out.size()) break;
1012 out = out.substr(0,j - 1)
1014 + out.substr(j,i - j)
1015 + out.substr(i + 5,k - i - 4)
1016 + out.substr(k + 2);
1017 //lyxerr << "out: " << out << endl;
1018 i = out.find("\\over", i + 4);
1021 mathed_parse_cell(res, out);
1026 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
1028 string header = "readlib(latex):\n";
1030 // remove the \\it for variable names
1031 //"#`latex/csname_font` := `\\it `:"
1033 "`latex/csname_font` := ``:\n";
1035 // export matrices in (...) instead of [...]
1037 "`latex/latex/matrix` := "
1038 "subs(`[`=`(`, `]`=`)`,"
1039 "eval(`latex/latex/matrix`)):\n";
1041 // replace \\cdots with proper '*'
1043 "`latex/latex/*` := "
1044 "subs(`\\,`=`\\cdot `,"
1045 "eval(`latex/latex/*`)):\n";
1047 // remove spurious \\noalign{\\medskip} in matrix output
1049 "`latex/latex/matrix`:= "
1050 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1051 "eval(`latex/latex/matrix`)):\n";
1053 //"#`latex/latex/symbol` "
1054 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1056 string trailer = "quit;";
1060 string expr = STRCONV(os.str());
1061 lyxerr << "ar: '" << ar << "'\n"
1062 << "ms: '" << os.str() << "'" << endl;
1064 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1065 // try to fix missing '*' the hard way by using mint
1067 // ... > echo "1A;" | mint -i 1 -S -s -q
1070 // Probably missing an operator such as * p
1072 lyxerr << "checking expr: '" << expr << "'" << endl;
1073 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1075 break; // expression syntax is ok
1076 istringstream is(out.c_str());
1079 if (line.find("on line") != 0)
1080 break; // error message not identified
1082 string::size_type pos = line.find('^');
1083 if (pos == string::npos || pos < 15)
1084 break; // caret position not found
1085 pos -= 15; // skip the "on line ..." part
1086 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1087 break; // two '*' in a row are definitely bad
1088 expr.insert(pos, 1, '*');
1091 string full = "latex(" + extra + '(' + expr + "));";
1092 string out = captureOutput("maple -q", header + full + trailer);
1098 mathed_parse_cell(res, out);
1103 MathArray pipeThroughOctave(string const &, MathArray const & ar)
1106 OctaveStream vs(os);
1108 string expr = STRCONV(os.str());
1111 lyxerr << "pipe: ar: '" << ar << "'\n"
1112 << "pipe: expr: '" << expr << "'" << endl;
1114 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1116 // try to fix missing '*' the hard way
1118 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1121 lyxerr << "checking expr: '" << expr << "'" << endl;
1122 out = captureOutput("octave -q 2>&1", expr);
1123 lyxerr << "checking out: '" << out << "'" << endl;
1125 // leave loop if expression syntax is probably ok
1126 if (out.find("parse error:") == string::npos)
1129 // search line with single caret
1130 istringstream is(out.c_str());
1134 lyxerr << "skipping line: '" << line << "'" << endl;
1135 if (line.find(">>> ") != string::npos)
1139 // found line with error, next line is the one with caret
1141 string::size_type pos = line.find('^');
1142 lyxerr << "caret line: '" << line << "'" << endl;
1143 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1144 if (pos == string::npos || pos < 4)
1145 break; // caret position not found
1146 pos -= 4; // skip the ">>> " part
1147 if (expr[pos] == '*')
1148 break; // two '*' in a row are definitely bad
1149 expr.insert(pos, 1, '*');
1156 out = out.substr(6);
1158 // parse output as matrix or single number
1159 MathAtom at(new MathArrayInset("array", out));
1160 MathArrayInset const * mat = at->asArrayInset();
1162 if (mat->ncols() == 1 && mat->nrows() == 1)
1163 res.append(mat->cell(0));
1165 res.push_back(MathAtom(new MathDelimInset("(", ")")));
1166 res.back().nucleus()->cell(0).push_back(at);
1174 MathArray pipeThroughExtern(string const & lang, string const & extra,
1175 MathArray const & ar)
1177 if (lang == "octave")
1178 return pipeThroughOctave(extra, ar);
1180 if (lang == "maxima")
1181 return pipeThroughMaxima(extra, ar);
1183 if (lang == "maple")
1184 return pipeThroughMaple(extra, ar);
1186 // create normalized expression
1188 NormalStream ns(os);
1189 os << '[' << extra << ' ';
1192 string data = STRCONV(os.str());
1194 // search external script
1195 string file = LibFileSearch("mathed", "extern_" + lang);
1197 lyxerr << "converter to '" << lang << "' not found" << endl;
1201 // run external sript
1202 string out = captureOutput(file, data);
1204 mathed_parse_cell(res, out);