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_extern.h"
18 #include "math_arrayinset.h"
19 #include "math_charinset.h"
20 #include "math_deliminset.h"
21 #include "math_data.h"
22 #include "math_diffinset.h"
23 #include "math_exfuncinset.h"
24 #include "math_exintinset.h"
25 #include "math_fracinset.h"
26 #include "math_liminset.h"
27 #include "math_matrixinset.h"
28 #include "math_mathmlstream.h"
29 #include "math_numberinset.h"
30 #include "math_scriptinset.h"
31 #include "math_stringinset.h"
32 #include "math_symbolinset.h"
33 #include "math_parser.h"
34 #include "support/std_sstream.h"
36 #include "support/filetools.h"
37 #include "support/lstrings.h"
41 using lyx::support::cmd_ret;
42 using lyx::support::getVectorFromString;
43 using lyx::support::LibFileSearch;
44 using lyx::support::RunCommand;
45 using lyx::support::subst;
50 using std::istringstream;
52 using std::ostringstream;
55 ostream & operator<<(ostream & os, MathArray const & ar)
63 // define a function for tests
64 typedef bool TestItemFunc(MathAtom const &);
66 // define a function for replacing subexpressions
67 typedef MathAtom ReplaceArgumentFunc(const MathArray & ar);
71 // try to extract a super/subscript
72 // modify iterator position to point behind the thing
73 bool extractScript(MathArray & ar,
74 MathArray::iterator & pos, MathArray::iterator last)
76 // nothing to get here
80 // is this a scriptinset?
81 if (!(*pos)->asScriptInset())
84 // it is a scriptinset, use it.
91 // try to extract an "argument" to some function.
92 // returns position behind the argument
93 MathArray::iterator extractArgument(MathArray & ar,
94 MathArray::iterator pos, MathArray::iterator last, string const & = "")
96 // nothing to get here
100 // something deliminited _is_ an argument
101 if ((*pos)->asDelimInset()) {
106 // always take the first thing, no matter what it is
109 // go ahead if possible
114 // if the next item is a subscript, it most certainly belongs to the
116 extractScript(ar, pos, last);
120 // but it might be more than that.
121 // FIXME: not implemented
122 //for (MathArray::iterator it = pos + 1; it != last; ++it) {
123 // // always take the first thing, no matter
125 // ar.push_back(*it);
133 // returns sequence of char with same code starting at it up to end
134 // it might be less, though...
136 (MathArray::const_iterator it, MathArray::const_iterator end)
139 for (; it != end && (*it)->asCharInset(); ++it)
140 s += (*it)->getChar();
145 void extractStrings(MathArray & ar)
147 //lyxerr << "\nStrings from: " << ar << endl;
148 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
149 if (!ar[i]->asCharInset())
151 string s = charSequence(ar.begin() + i, ar.end());
152 ar[i] = MathAtom(new MathStringInset(s));
153 ar.erase(i + 1, i + s.size());
155 //lyxerr << "\nStrings to: " << ar << endl;
159 void extractMatrices(MathArray & ar)
161 //lyxerr << "\nMatrices from: " << ar << endl;
162 // first pass for explicitly delimited stuff
163 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
164 if (!ar[i]->asDelimInset())
166 MathArray const & arr = ar[i]->asDelimInset()->cell(0);
169 if (!arr.front()->asGridInset())
171 ar[i] = MathAtom(new MathMatrixInset(*(arr.front()->asGridInset())));
174 // second pass for AMS "pmatrix" etc
175 for (MathArray::size_type i = 0; i < ar.size(); ++i)
176 if (ar[i]->asAMSArrayInset())
177 ar[i] = MathAtom(new MathMatrixInset(*(ar[i]->asGridInset())));
178 //lyxerr << "\nMatrices to: " << ar << endl;
182 // convert this inset somehow to a string
183 bool extractString(MathAtom const & at, string & str)
186 str = string(1, at->getChar());
189 if (at->asStringInset()) {
190 str = at->asStringInset()->str();
197 // convert this inset somehow to a number
198 bool extractNumber(MathArray const & ar, int & i)
200 istringstream is(charSequence(ar.begin(), ar.end()).c_str());
206 bool extractNumber(MathArray const & ar, double & d)
208 istringstream is(charSequence(ar.begin(), ar.end()).c_str());
214 bool testString(MathAtom const & at, string const & str)
217 return extractString(at, s) && str == s;
221 // search end of nested sequence
222 MathArray::iterator endNestSearch(
223 MathArray::iterator it,
224 MathArray::iterator last,
225 TestItemFunc testOpen,
226 TestItemFunc testClose
229 for (int level = 0; it != last; ++it) {
241 // replace nested sequences by a real Insets
244 TestItemFunc testOpen,
245 TestItemFunc testClose,
246 ReplaceArgumentFunc replaceArg
249 // use indices rather than iterators for the loop because we are going
250 // to modify the array.
251 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
252 // check whether this is the begin of the sequence
253 if (!testOpen(ar[i]))
256 // search end of sequence
257 MathArray::iterator it = ar.begin() + i;
258 MathArray::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
262 // replace the original stuff by the new inset
263 ar[i] = replaceArg(MathArray(it + 1, jt));
264 ar.erase(it + 1, jt + 1);
271 // split scripts into seperate super- and subscript insets. sub goes in
275 void splitScripts(MathArray & ar)
277 //lyxerr << "\nScripts from: " << ar << endl;
278 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
279 // is this script inset?
280 if (!ar[i]->asScriptInset())
283 // no problem if we don't have both...
284 if (!ar[i]->asScriptInset()->hasUp())
286 if (!ar[i]->asScriptInset()->hasDown())
289 // create extra script inset and move superscript over
290 MathScriptInset * p = ar[i].nucleus()->asScriptInset();
291 MathScriptInset * q = new MathScriptInset(true);
292 std::swap(q->up(), p->up());
293 p->removeScript(true);
295 // insert new inset behind
297 ar.insert(i, MathAtom(q));
299 //lyxerr << "\nScripts to: " << ar << endl;
307 void extractExps(MathArray & ar)
309 //lyxerr << "\nExps from: " << ar << endl;
310 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
312 if (ar[i]->getChar() != 'e')
315 // we need an exponent but no subscript
316 MathScriptInset const * sup = ar[i + 1]->asScriptInset();
317 if (!sup || sup->hasDown())
320 // create a proper exp-inset as replacement
321 ar[i] = MathAtom(new MathExFuncInset("exp", sup->cell(1)));
324 //lyxerr << "\nExps to: " << ar << endl;
329 // extract det(...) from |matrix|
331 void extractDets(MathArray & ar)
333 //lyxerr << "\ndet from: " << ar << endl;
334 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it) {
335 MathDelimInset const * del = (*it)->asDelimInset();
340 *it = MathAtom(new MathExFuncInset("det", del->cell(0)));
342 //lyxerr << "\ndet to: " << ar << endl;
350 bool isDigitOrSimilar(char c)
352 return ('0' <= c && c <= '9') || c == '.';
356 // returns sequence of digits
358 (MathArray::const_iterator it, MathArray::const_iterator end)
361 for (; it != end && (*it)->asCharInset(); ++it) {
362 if (!isDigitOrSimilar((*it)->getChar()))
364 s += (*it)->getChar();
370 void extractNumbers(MathArray & ar)
372 //lyxerr << "\nNumbers from: " << ar << endl;
373 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
374 if (!ar[i]->asCharInset())
376 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
379 string s = digitSequence(ar.begin() + i, ar.end());
381 ar[i] = MathAtom(new MathNumberInset(s));
382 ar.erase(i + 1, i + s.size());
384 //lyxerr << "\nNumbers to: " << ar << endl;
390 // search deliminiters
393 bool testOpenParan(MathAtom const & at)
395 return testString(at, "(");
399 bool testCloseParan(MathAtom const & at)
401 return testString(at, ")");
405 MathAtom replaceDelims(const MathArray & ar)
407 return MathAtom(new MathDelimInset("(", ")", ar));
411 // replace '('...')' sequences by a real MathDelimInset
412 void extractDelims(MathArray & ar)
414 //lyxerr << "\nDelims from: " << ar << endl;
415 replaceNested(ar, testOpenParan, testCloseParan, replaceDelims);
416 //lyxerr << "\nDelims to: " << ar << endl;
422 // search well-known functions
426 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real MathExFuncInset
427 // assume 'extractDelims' ran before
428 void extractFunctions(MathArray & ar)
430 // we need at least two items...
434 //lyxerr << "\nFunctions from: " << ar << endl;
435 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
436 MathArray::iterator it = ar.begin() + i;
437 MathArray::iterator jt = it + 1;
441 if ((*it)->asUnknownInset()) {
442 // it certainly is if it is well known...
443 name = (*it)->name();
445 // is this a user defined function?
446 // it it probably not, if it doesn't have a name.
447 if (!extractString(*it, name))
449 // it is not if it has no argument
452 // guess so, if this is followed by
453 // a DelimInset with a single item in the cell
454 MathDelimInset const * del = (*jt)->asDelimInset();
455 if (!del || del->cell(0).size() != 1)
457 // fall trough into main branch
460 // do we have an exponent like in
461 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
463 extractScript(exp, jt, ar.end());
465 // create a proper inset as replacement
466 MathExFuncInset * p = new MathExFuncInset(name);
468 // jt points to the "argument". Get hold of this.
469 MathArray::iterator st = extractArgument(p->cell(0), jt, ar.end());
471 // replace the function name by a real function inset
474 // remove the source of the argument from the array
475 ar.erase(it + 1, st);
477 // re-insert exponent
478 ar.insert(i + 1, exp);
479 //lyxerr << "\nFunctions to: " << ar << endl;
488 bool testSymbol(MathAtom const & at, string const & name)
490 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
494 bool testIntSymbol(MathAtom const & at)
496 return testSymbol(at, "int");
500 bool testIntegral(MathAtom const & at)
504 ( at->asScriptInset()
505 && at->asScriptInset()->nuc().size()
506 && testIntSymbol(at->asScriptInset()->nuc().back()) );
511 bool testIntDiff(MathAtom const & at)
513 return testString(at, "d");
517 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real MathExIntInset
518 // assume 'extractDelims' ran before
519 void extractIntegrals(MathArray & ar)
521 // we need at least three items...
525 //lyxerr << "\nIntegrals from: " << ar << endl;
526 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
527 MathArray::iterator it = ar.begin() + i;
530 MathArray::iterator jt =
531 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
533 // something sensible found?
537 // is this a integral name?
538 if (!testIntegral(*it))
541 // core ist part from behind the scripts to the 'd'
542 MathExIntInset * p = new MathExIntInset("int");
544 // handle scripts if available
545 if (!testIntSymbol(*it)) {
546 p->cell(2) = (*it)->asScriptInset()->down();
547 p->cell(3) = (*it)->asScriptInset()->up();
549 p->cell(0) = MathArray(it + 1, jt);
551 // use the "thing" behind the 'd' as differential
552 MathArray::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
555 ar.erase(it + 1, tt);
558 //lyxerr << "\nIntegrals to: " << ar << endl;
567 bool testEqualSign(MathAtom const & at)
569 return testString(at, "=");
573 bool testSumSymbol(MathAtom const & p)
575 return testSymbol(p, "sum");
579 bool testSum(MathAtom const & at)
583 ( at->asScriptInset()
584 && at->asScriptInset()->nuc().size()
585 && testSumSymbol(at->asScriptInset()->nuc().back()) );
589 // replace '\sum' ['_^'] f(x) sequences by a real MathExIntInset
590 // assume 'extractDelims' ran before
591 void extractSums(MathArray & ar)
593 // we need at least two items...
597 //lyxerr << "\nSums from: " << ar << endl;
598 for (MathArray::size_type i = 0; i + 1 < ar.size(); ++i) {
599 MathArray::iterator it = ar.begin() + i;
601 // is this a sum name?
605 // create a proper inset as replacement
606 MathExIntInset * p = new MathExIntInset("sum");
608 // collect lower bound and summation index
609 MathScriptInset const * sub = ar[i]->asScriptInset();
610 if (sub && sub->hasDown()) {
611 // try to figure out the summation index from the subscript
612 MathArray const & ar = sub->down();
613 MathArray::const_iterator xt =
614 find_if(ar.begin(), ar.end(), &testEqualSign);
615 if (xt != ar.end()) {
616 // we found a '=', use everything in front of that as index,
617 // and everything behind as lower index
618 p->cell(1) = MathArray(ar.begin(), xt);
619 p->cell(2) = MathArray(xt + 1, ar.end());
621 // use everything as summation index, don't use scripts.
626 // collect upper bound
627 if (sub && sub->hasUp())
628 p->cell(3) = sub->up();
630 // use something behind the script as core
631 MathArray::iterator tt = extractArgument(p->cell(0), it + 1, ar.end());
634 ar.erase(it + 1, tt);
637 //lyxerr << "\nSums to: " << ar << endl;
642 // search differential stuff
645 // tests for 'd' or '\partial'
646 bool testDiffItem(MathAtom const & at)
648 return testString(at, "d");
652 bool testDiffArray(MathArray const & ar)
654 return ar.size() && testDiffItem(ar.front());
658 bool testDiffFrac(MathAtom const & at)
662 && testDiffArray(at->asFracInset()->cell(0))
663 && testDiffArray(at->asFracInset()->cell(1));
667 void extractDiff(MathArray & ar)
669 //lyxerr << "\nDiffs from: " << ar << endl;
670 for (MathArray::size_type i = 0; i < ar.size(); ++i) {
671 MathArray::iterator it = ar.begin() + i;
673 // is this a "differential fraction"?
674 if (!testDiffFrac(*it))
677 MathFracInset const * f = (*it)->asFracInset();
679 lyxerr << "should not happen" << endl;
683 // create a proper diff inset
684 MathDiffInset * diff = new MathDiffInset;
686 // collect function, let jt point behind last used item
687 MathArray::iterator jt = it + 1;
689 MathArray const & numer = f->cell(0);
690 if (numer.size() > 1 && numer[1]->asScriptInset()) {
691 // this is something like d^n f(x) / d... or d^n / d...
694 if (numer.size() > 2)
695 diff->cell(0) = MathArray(numer.begin() + 2, numer.end());
697 jt = extractArgument(diff->cell(0), jt, ar.end());
699 // simply d f(x) / d... or d/d...
700 if (numer.size() > 1)
701 diff->cell(0) = MathArray(numer.begin() + 1, numer.end());
703 jt = extractArgument(diff->cell(0), jt, ar.end());
706 // collect denominator parts
707 MathArray const & denom = f->cell(1);
708 for (MathArray::const_iterator dt = denom.begin(); dt != denom.end();) {
710 MathArray::const_iterator et
711 = find_if(dt + 1, denom.end(), &testDiffItem);
714 MathArray::const_iterator st = et - 1;
715 MathScriptInset const * script = (*st)->asScriptInset();
716 if (script && script->hasUp()) {
717 // things like d.../dx^n
719 if (extractNumber(script->up(), mult)) {
720 //lyxerr << "mult: " << mult << endl;
721 for (int i = 0; i < mult; ++i)
722 diff->addDer(MathArray(dt + 1, st));
726 diff->addDer(MathArray(dt + 1, et));
732 ar.erase(it + 1, jt);
733 *it = MathAtom(diff);
735 //lyxerr << "\nDiffs to: " << ar << endl;
744 bool testRightArrow(MathAtom const & at)
746 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
751 // replace '\lim_{x->x0} f(x)' sequences by a real MathLimInset
752 // assume 'extractDelims' ran before
753 void extractLims(MathArray & ar)
755 // we need at least three items...
759 //lyxerr << "\nLimits from: " << ar << endl;
760 for (MathArray::size_type i = 0; i + 2 < ar.size(); ++i) {
761 MathArray::iterator it = ar.begin() + i;
763 // is this a limit function?
764 if (!testSymbol(*it, "lim"))
767 // the next one must be a subscript (without superscript)
768 MathScriptInset const * sub = (*(it + 1))->asScriptInset();
769 if (!sub || !sub->hasDown() || sub->hasUp())
772 // and it must contain a -> symbol
773 MathArray const & s = sub->down();
774 MathArray::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
778 // the -> splits the subscript int x and x0
779 MathArray x = MathArray(s.begin(), st);
780 MathArray x0 = MathArray(st + 1, s.end());
782 // use something behind the script as core
784 MathArray::iterator tt = extractArgument(f, it + 2, ar.end());
787 ar.erase(it + 1, tt);
789 // create a proper inset as replacement
790 *it = MathAtom(new MathLimInset(f, x, x0));
792 //lyxerr << "\nLimits to: " << ar << endl;
800 void extractStructure(MathArray & ar)
802 //lyxerr << "\nStructure from: " << ar << endl;
803 extractIntegrals(ar);
809 extractFunctions(ar);
815 //lyxerr << "\nStructure to: " << ar << endl;
819 void write(MathArray const & dat, WriteStream & wi)
823 wi.firstitem() = true;
824 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
826 wi.firstitem() = false;
831 void normalize(MathArray const & ar, NormalStream & os)
833 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
834 (*it)->normalize(os);
838 void octave(MathArray const & dat, OctaveStream & os)
841 extractStructure(ar);
842 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
847 void maple(MathArray const & dat, MapleStream & os)
850 extractStructure(ar);
851 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
856 void maxima(MathArray const & dat, MaximaStream & os)
859 extractStructure(ar);
860 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
865 void mathematica(MathArray const & dat, MathematicaStream & os)
868 extractStructure(ar);
869 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
870 (*it)->mathematica(os);
874 void mathmlize(MathArray const & dat, MathMLStream & os)
877 extractStructure(ar);
880 else if (ar.size() == 1)
884 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
885 (*it)->mathmlize(os);
895 string captureOutput(string const & cmd, string const & data)
897 string command = "echo '" + data + "' | " + cmd;
898 lyxerr << "calling: " << command << endl;
899 cmd_ret const ret = RunCommand(command);
903 string::size_type get_matching_brace(string const & str, string::size_type i)
906 string::size_type n = str.size();
908 i = str.find_first_of("{}", i+1);
909 if (i == string::npos) return i;
920 string::size_type get_matching_brace_back(string const & str, string::size_type i)
924 i = str.find_last_of("{}", i-1);
925 if (i == string::npos) return i;
936 MathArray pipeThroughMaxima(string const &, MathArray const & ar)
941 string expr = STRCONV(os.str());
942 string const header = "SIMPSUM:true;";
945 for (int i = 0; i < 100; ++i) { // at most 100 attempts
946 // try to fix missing '*' the hard way
948 // > echo "2x;" | maxima
950 // (C1) Incorrect syntax: x is not an infix operator
954 lyxerr << "checking expr: '" << expr << "'" << endl;
955 string full = header + "tex(" + expr + ");";
956 out = captureOutput("maxima", full);
958 // leave loop if expression syntax is probably ok
959 if (out.find("Incorrect syntax") == string::npos)
962 // search line with "Incorrect syntax"
963 istringstream is(out.c_str());
967 if (line.find("Incorrect syntax") != string::npos)
971 // 2nd next line is the one with caret
974 string::size_type pos = line.find('^');
975 lyxerr << "found caret at pos: '" << pos << "'" << endl;
976 if (pos == string::npos || pos < 4)
977 break; // caret position not found
978 pos -= 4; // skip the "tex(" part
979 if (expr[pos] == '*')
980 break; // two '*' in a row are definitely bad
981 expr.insert(pos, "*");
984 std::vector<string> tmp = getVectorFromString(out, "$$");
988 out = subst(tmp[1],"\\>", "");
989 lyxerr << "out: '" << out << "'" << endl;
991 // Ugly code that tries to make the result prettier
993 string::size_type i = out.find("\\mathchoice");
994 while (i != string::npos) {
995 string::size_type j = get_matching_brace(out, i + 12);
996 string::size_type k = get_matching_brace(out, j + 1);
997 k = get_matching_brace(out, k + 1);
998 k = get_matching_brace(out, k + 1);
999 string mid = out.substr(i + 13,j - i - 13);
1000 if (mid.find("\\over") != string::npos)
1001 mid = '{' + mid + '}';
1002 out = out.substr(0,i)
1004 + out.substr(k + 1);
1005 //lyxerr << "out: " << out << endl;
1006 i = out.find("\\mathchoice", i);
1010 i = out.find("\\over");
1011 while (i != string::npos) {
1012 string::size_type j = get_matching_brace_back(out, i - 1);
1013 if (j == string::npos || j == 0) break;
1014 string::size_type k = get_matching_brace(out, i + 5);
1015 if (k == string::npos || k + 1 == out.size()) break;
1016 out = out.substr(0,j - 1)
1018 + out.substr(j,i - j)
1019 + out.substr(i + 5,k - i - 4)
1020 + out.substr(k + 2);
1021 //lyxerr << "out: " << out << endl;
1022 i = out.find("\\over", i + 4);
1025 mathed_parse_cell(res, out);
1030 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
1032 string header = "readlib(latex):\n";
1034 // remove the \\it for variable names
1035 //"#`latex/csname_font` := `\\it `:"
1037 "`latex/csname_font` := ``:\n";
1039 // export matrices in (...) instead of [...]
1041 "`latex/latex/matrix` := "
1042 "subs(`[`=`(`, `]`=`)`,"
1043 "eval(`latex/latex/matrix`)):\n";
1045 // replace \\cdots with proper '*'
1047 "`latex/latex/*` := "
1048 "subs(`\\,`=`\\cdot `,"
1049 "eval(`latex/latex/*`)):\n";
1051 // remove spurious \\noalign{\\medskip} in matrix output
1053 "`latex/latex/matrix`:= "
1054 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1055 "eval(`latex/latex/matrix`)):\n";
1057 //"#`latex/latex/symbol` "
1058 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1060 string trailer = "quit;";
1064 string expr = STRCONV(os.str());
1065 lyxerr << "ar: '" << ar << "'\n"
1066 << "ms: '" << os.str() << "'" << endl;
1068 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1069 // try to fix missing '*' the hard way by using mint
1071 // ... > echo "1A;" | mint -i 1 -S -s -q
1074 // Probably missing an operator such as * p
1076 lyxerr << "checking expr: '" << expr << "'" << endl;
1077 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1079 break; // expression syntax is ok
1080 istringstream is(out.c_str());
1083 if (line.find("on line") != 0)
1084 break; // error message not identified
1086 string::size_type pos = line.find('^');
1087 if (pos == string::npos || pos < 15)
1088 break; // caret position not found
1089 pos -= 15; // skip the "on line ..." part
1090 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1091 break; // two '*' in a row are definitely bad
1092 expr.insert(pos, 1, '*');
1095 string full = "latex(" + extra + '(' + expr + "));";
1096 string out = captureOutput("maple -q", header + full + trailer);
1102 mathed_parse_cell(res, out);
1107 MathArray pipeThroughOctave(string const &, MathArray const & ar)
1110 OctaveStream vs(os);
1112 string expr = STRCONV(os.str());
1115 lyxerr << "pipe: ar: '" << ar << "'\n"
1116 << "pipe: expr: '" << expr << "'" << endl;
1118 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1120 // try to fix missing '*' the hard way
1122 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1125 lyxerr << "checking expr: '" << expr << "'" << endl;
1126 out = captureOutput("octave -q 2>&1", expr);
1127 lyxerr << "checking out: '" << out << "'" << endl;
1129 // leave loop if expression syntax is probably ok
1130 if (out.find("parse error:") == string::npos)
1133 // search line with single caret
1134 istringstream is(out.c_str());
1138 lyxerr << "skipping line: '" << line << "'" << endl;
1139 if (line.find(">>> ") != string::npos)
1143 // found line with error, next line is the one with caret
1145 string::size_type pos = line.find('^');
1146 lyxerr << "caret line: '" << line << "'" << endl;
1147 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1148 if (pos == string::npos || pos < 4)
1149 break; // caret position not found
1150 pos -= 4; // skip the ">>> " part
1151 if (expr[pos] == '*')
1152 break; // two '*' in a row are definitely bad
1153 expr.insert(pos, 1, '*');
1160 out = out.substr(6);
1162 // parse output as matrix or single number
1163 MathAtom at(new MathArrayInset("array", out));
1164 MathArrayInset const * mat = at->asArrayInset();
1166 if (mat->ncols() == 1 && mat->nrows() == 1)
1167 res.append(mat->cell(0));
1169 res.push_back(MathAtom(new MathDelimInset("(", ")")));
1170 res.back().nucleus()->cell(0).push_back(at);
1178 MathArray pipeThroughExtern(string const & lang, string const & extra,
1179 MathArray const & ar)
1181 if (lang == "octave")
1182 return pipeThroughOctave(extra, ar);
1184 if (lang == "maxima")
1185 return pipeThroughMaxima(extra, ar);
1187 if (lang == "maple")
1188 return pipeThroughMaple(extra, ar);
1190 // create normalized expression
1192 NormalStream ns(os);
1193 os << '[' << extra << ' ';
1196 string data = STRCONV(os.str());
1198 // search external script
1199 string file = LibFileSearch("mathed", "extern_" + lang);
1201 lyxerr << "converter to '" << lang << "' not found" << endl;
1205 // run external sript
1206 string out = captureOutput(file, data);
1208 mathed_parse_cell(res, out);