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 "MathExtern.h"
18 #include "InsetMathArray.h"
19 #include "InsetMathChar.h"
20 #include "InsetMathDelim.h"
22 #include "InsetMathDiff.h"
23 #include "InsetMathExFunc.h"
24 #include "InsetMathExInt.h"
25 #include "InsetMathFont.h"
26 #include "InsetMathFrac.h"
27 #include "InsetMathLim.h"
28 #include "InsetMathMatrix.h"
29 #include "MathMLStream.h"
30 #include "InsetMathNumber.h"
31 #include "InsetMathScript.h"
32 #include "InsetMathString.h"
33 #include "InsetMathSymbol.h"
34 #include "MathParser.h"
36 #include "support/filetools.h"
37 #include "support/lstrings.h"
38 #include "frontends/controllers/ControlMath.h"
43 using lyx::support::cmd_ret;
44 using lyx::support::getVectorFromString;
45 using lyx::support::libFileSearch;
46 using lyx::support::runCommand;
47 using lyx::support::subst;
49 using lyx::frontend::function_names;
55 using std::istringstream;
57 using std::ostringstream;
62 ostream & operator<<(ostream & os, MathArray const & ar)
70 // define a function for tests
71 typedef bool TestItemFunc(MathAtom const &);
73 // define a function for replacing subexpressions
74 typedef MathAtom ReplaceArgumentFunc(const MathArray & ar);
78 // try to extract a super/subscript
79 // modify iterator position to point behind the thing
80 bool extractScript(MathArray & ar,
81 MathArray::iterator & pos, MathArray::iterator last, bool superscript)
83 // nothing to get here
87 // is this a scriptinset?
88 if (!(*pos)->asScriptInset())
91 // do we want superscripts only?
92 if (superscript && !(*pos)->asScriptInset()->hasUp())
95 // it is a scriptinset, use it.
102 // try to extract an "argument" to some function.
103 // returns position behind the argument
104 MathArray::iterator extractArgument(MathArray & ar,
105 MathArray::iterator pos, MathArray::iterator last, bool function = false)
107 // nothing to get here
111 // something delimited _is_ an argument
112 if ((*pos)->asDelimInset()) {
113 // leave out delimiters if this is a function argument
115 MathArray const & arg = (*pos)->asDelimInset()->cell(0);
116 MathArray::const_iterator cur = arg.begin();
117 MathArray::const_iterator end = arg.end();
119 ar.push_back(*cur++);
125 // if there's one, get following superscript only if this
126 // isn't a function argument
128 extractScript(ar, pos, last, true);
132 // always take the first thing, no matter what it is
135 // go ahead if possible
140 // if the next item is a super/subscript, it most certainly belongs
141 // to the thing we have
142 extractScript(ar, pos, last, false);
146 // but it might be more than that.
147 // FIXME: not implemented
148 //for (MathArray::iterator it = pos + 1; it != last; ++it) {
149 // // always take the first thing, no matter
151 // ar.push_back(*it);
159 // returns sequence of char with same code starting at it up to end
160 // it might be less, though...
162 (MathArray::const_iterator it, MathArray::const_iterator end)
165 for (; it != end && (*it)->asCharInset(); ++it)
166 s += (*it)->getChar();
171 void extractStrings(MathArray & ar)
173 //lyxerr << "\nStrings from: " << ar << endl;
174 for (size_t i = 0; i < ar.size(); ++i) {
175 if (!ar[i]->asCharInset())
177 string s = charSequence(ar.begin() + i, ar.end());
178 ar[i] = MathAtom(new InsetMathString(s));
179 ar.erase(i + 1, i + s.size());
181 //lyxerr << "\nStrings to: " << ar << endl;
185 void extractMatrices(MathArray & ar)
187 //lyxerr << "\nMatrices from: " << ar << endl;
188 // first pass for explicitly delimited stuff
189 for (size_t i = 0; i < ar.size(); ++i) {
190 if (!ar[i]->asDelimInset())
192 MathArray const & arr = ar[i]->asDelimInset()->cell(0);
195 if (!arr.front()->asGridInset())
197 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset())));
200 // second pass for AMS "pmatrix" etc
201 for (size_t i = 0; i < ar.size(); ++i)
202 if (ar[i]->asAMSArrayInset())
203 ar[i] = MathAtom(new InsetMathMatrix(*(ar[i]->asGridInset())));
204 //lyxerr << "\nMatrices to: " << ar << endl;
208 // convert this inset somehow to a string
209 bool extractString(MathAtom const & at, string & str)
212 str = string(1, at->getChar());
215 if (at->asStringInset()) {
216 str = at->asStringInset()->str();
223 // is this a known function?
224 bool isKnownFunction(string const & str)
226 for (int i = 0; *function_names[i]; ++i) {
227 if (str == function_names[i])
234 // extract a function name from this inset
235 bool extractFunctionName(MathAtom const & at, string & str)
237 if (at->asSymbolInset()) {
238 str = at->asSymbolInset()->name();
239 return isKnownFunction(str);
241 if (at->asUnknownInset()) {
242 // assume it is well known...
246 if (at->asFontInset() && at->name() == "mathrm") {
247 // assume it is well known...
248 MathArray const & ar = at->asFontInset()->cell(0);
249 str = charSequence(ar.begin(), ar.end());
250 return ar.size() == str.size();
256 // convert this inset somehow to a number
257 bool extractNumber(MathArray const & ar, int & i)
259 istringstream is(charSequence(ar.begin(), ar.end()));
265 bool extractNumber(MathArray const & ar, double & d)
267 istringstream is(charSequence(ar.begin(), ar.end()));
273 bool testString(MathAtom const & at, string const & str)
276 return extractString(at, s) && str == s;
280 // search end of nested sequence
281 MathArray::iterator endNestSearch(
282 MathArray::iterator it,
283 MathArray::iterator last,
284 TestItemFunc testOpen,
285 TestItemFunc testClose
288 for (int level = 0; it != last; ++it) {
300 // replace nested sequences by a real Insets
303 TestItemFunc testOpen,
304 TestItemFunc testClose,
305 ReplaceArgumentFunc replaceArg
308 // use indices rather than iterators for the loop because we are going
309 // to modify the array.
310 for (size_t i = 0; i < ar.size(); ++i) {
311 // check whether this is the begin of the sequence
312 if (!testOpen(ar[i]))
315 // search end of sequence
316 MathArray::iterator it = ar.begin() + i;
317 MathArray::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
321 // replace the original stuff by the new inset
322 ar[i] = replaceArg(MathArray(it + 1, jt));
323 ar.erase(it + 1, jt + 1);
330 // split scripts into seperate super- and subscript insets. sub goes in
334 void splitScripts(MathArray & ar)
336 //lyxerr << "\nScripts from: " << ar << endl;
337 for (size_t i = 0; i < ar.size(); ++i) {
338 InsetMathScript const * script = ar[i]->asScriptInset();
340 // is this a script inset and do we also have a superscript?
341 if (!script || !script->hasUp())
344 // we must have a nucleus if we only have a superscript
345 if (!script->hasDown() && script->nuc().size() == 0)
348 if (script->nuc().size() == 1) {
349 // leave alone sums and integrals
350 InsetMathSymbol const * sym =
351 script->nuc().front()->asSymbolInset();
352 if (sym && (sym->name() == "sum" || sym->name() == "int"))
356 // create extra script inset and move superscript over
357 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
358 auto_ptr<InsetMathScript> q(new InsetMathScript(true));
359 swap(q->up(), p->up());
360 p->removeScript(true);
362 // if we don't have a subscript, get rid of the ScriptInset
363 if (!script->hasDown()) {
364 MathArray arg(p->nuc());
365 MathArray::const_iterator it = arg.begin();
366 MathArray::const_iterator et = arg.end();
369 ar.insert(i++, *it++);
373 // insert new inset behind
374 ar.insert(i, MathAtom(q.release()));
376 //lyxerr << "\nScripts to: " << ar << endl;
384 void extractExps(MathArray & ar)
386 //lyxerr << "\nExps from: " << ar << endl;
387 for (size_t i = 0; i + 1 < ar.size(); ++i) {
389 if (ar[i]->getChar() != 'e')
392 // we need an exponent but no subscript
393 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
394 if (!sup || sup->hasDown())
397 // create a proper exp-inset as replacement
398 ar[i] = MathAtom(new InsetMathExFunc("exp", sup->cell(1)));
401 //lyxerr << "\nExps to: " << ar << endl;
406 // extract det(...) from |matrix|
408 void extractDets(MathArray & ar)
410 //lyxerr << "\ndet from: " << ar << endl;
411 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it) {
412 InsetMathDelim const * del = (*it)->asDelimInset();
417 *it = MathAtom(new InsetMathExFunc("det", del->cell(0)));
419 //lyxerr << "\ndet to: " << ar << endl;
427 bool isDigitOrSimilar(char c)
429 return ('0' <= c && c <= '9') || c == '.';
433 // returns sequence of digits
435 (MathArray::const_iterator it, MathArray::const_iterator end)
438 for (; it != end && (*it)->asCharInset(); ++it) {
439 if (!isDigitOrSimilar((*it)->getChar()))
441 s += (*it)->getChar();
447 void extractNumbers(MathArray & ar)
449 //lyxerr << "\nNumbers from: " << ar << endl;
450 for (size_t i = 0; i < ar.size(); ++i) {
451 if (!ar[i]->asCharInset())
453 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
456 string s = digitSequence(ar.begin() + i, ar.end());
458 ar[i] = MathAtom(new InsetMathNumber(s));
459 ar.erase(i + 1, i + s.size());
461 //lyxerr << "\nNumbers to: " << ar << endl;
470 bool testOpenParen(MathAtom const & at)
472 return testString(at, "(");
476 bool testCloseParen(MathAtom const & at)
478 return testString(at, ")");
482 MathAtom replaceParenDelims(const MathArray & ar)
484 return MathAtom(new InsetMathDelim("(", ")", ar));
488 bool testOpenBracket(MathAtom const & at)
490 return testString(at, "[");
494 bool testCloseBracket(MathAtom const & at)
496 return testString(at, "]");
500 MathAtom replaceBracketDelims(const MathArray & ar)
502 return MathAtom(new InsetMathDelim("[", "]", ar));
506 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
507 void extractDelims(MathArray & ar)
509 //lyxerr << "\nDelims from: " << ar << endl;
510 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
511 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
512 //lyxerr << "\nDelims to: " << ar << endl;
518 // search well-known functions
522 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
523 // assume 'extractDelims' ran before
524 void extractFunctions(MathArray & ar)
526 // we need at least two items...
530 //lyxerr << "\nFunctions from: " << ar << endl;
531 for (size_t i = 0; i + 1 < ar.size(); ++i) {
532 MathArray::iterator it = ar.begin() + i;
533 MathArray::iterator jt = it + 1;
537 // it certainly is if it is well known...
538 if (!extractFunctionName(*it, name)) {
539 // is this a user defined function?
540 // it it probably not, if it doesn't have a name.
541 if (!extractString(*it, name))
543 // it is not if it has no argument
546 // guess so, if this is followed by
547 // a DelimInset with a single item in the cell
548 InsetMathDelim const * del = (*jt)->asDelimInset();
549 if (!del || del->cell(0).size() != 1)
551 // fall trough into main branch
554 // do we have an exponent like in
555 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
557 extractScript(exp, jt, ar.end(), true);
559 // create a proper inset as replacement
560 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(name));
562 // jt points to the "argument". Get hold of this.
563 MathArray::iterator st = extractArgument(p->cell(0), jt, ar.end(), true);
565 // replace the function name by a real function inset
566 *it = MathAtom(p.release());
568 // remove the source of the argument from the array
569 ar.erase(it + 1, st);
571 // re-insert exponent
572 ar.insert(i + 1, exp);
573 //lyxerr << "\nFunctions to: " << ar << endl;
582 bool testSymbol(MathAtom const & at, string const & name)
584 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
588 bool testIntSymbol(MathAtom const & at)
590 return testSymbol(at, "int");
594 bool testIntegral(MathAtom const & at)
598 ( at->asScriptInset()
599 && at->asScriptInset()->nuc().size()
600 && testIntSymbol(at->asScriptInset()->nuc().back()) );
605 bool testIntDiff(MathAtom const & at)
607 return testString(at, "d");
611 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
612 // assume 'extractDelims' ran before
613 void extractIntegrals(MathArray & ar)
615 // we need at least three items...
619 //lyxerr << "\nIntegrals from: " << ar << endl;
620 for (size_t i = 0; i + 1 < ar.size(); ++i) {
621 MathArray::iterator it = ar.begin() + i;
624 MathArray::iterator jt =
625 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
627 // something sensible found?
631 // is this a integral name?
632 if (!testIntegral(*it))
635 // core ist part from behind the scripts to the 'd'
636 auto_ptr<InsetMathExInt> p(new InsetMathExInt("int"));
638 // handle scripts if available
639 if (!testIntSymbol(*it)) {
640 p->cell(2) = (*it)->asScriptInset()->down();
641 p->cell(3) = (*it)->asScriptInset()->up();
643 p->cell(0) = MathArray(it + 1, jt);
645 // use the "thing" behind the 'd' as differential
646 MathArray::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
649 ar.erase(it + 1, tt);
650 *it = MathAtom(p.release());
652 //lyxerr << "\nIntegrals to: " << ar << endl;
656 bool testTermDelimiter(MathAtom const & at)
658 return testString(at, "+") || testString(at, "-");
662 // try to extract a "term", i.e., something delimited by '+' or '-'.
663 // returns position behind the term
664 MathArray::iterator extractTerm(MathArray & ar,
665 MathArray::iterator pos, MathArray::iterator last)
667 while (pos != last && !testTermDelimiter(*pos)) {
680 bool testEqualSign(MathAtom const & at)
682 return testString(at, "=");
686 bool testSumSymbol(MathAtom const & p)
688 return testSymbol(p, "sum");
692 bool testSum(MathAtom const & at)
696 ( at->asScriptInset()
697 && at->asScriptInset()->nuc().size()
698 && testSumSymbol(at->asScriptInset()->nuc().back()) );
702 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
703 // assume 'extractDelims' ran before
704 void extractSums(MathArray & ar)
706 // we need at least two items...
710 //lyxerr << "\nSums from: " << ar << endl;
711 for (size_t i = 0; i + 1 < ar.size(); ++i) {
712 MathArray::iterator it = ar.begin() + i;
714 // is this a sum name?
718 // create a proper inset as replacement
719 auto_ptr<InsetMathExInt> p(new InsetMathExInt("sum"));
721 // collect lower bound and summation index
722 InsetMathScript const * sub = ar[i]->asScriptInset();
723 if (sub && sub->hasDown()) {
724 // try to figure out the summation index from the subscript
725 MathArray const & ar = sub->down();
726 MathArray::const_iterator xt =
727 find_if(ar.begin(), ar.end(), &testEqualSign);
728 if (xt != ar.end()) {
729 // we found a '=', use everything in front of that as index,
730 // and everything behind as lower index
731 p->cell(1) = MathArray(ar.begin(), xt);
732 p->cell(2) = MathArray(xt + 1, ar.end());
734 // use everything as summation index, don't use scripts.
739 // collect upper bound
740 if (sub && sub->hasUp())
741 p->cell(3) = sub->up();
743 // use something behind the script as core
744 MathArray::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
747 ar.erase(it + 1, tt);
748 *it = MathAtom(p.release());
750 //lyxerr << "\nSums to: " << ar << endl;
755 // search differential stuff
758 // tests for 'd' or '\partial'
759 bool testDiffItem(MathAtom const & at)
761 if (testString(at, "d") || testSymbol(at, "partial"))
764 // we may have d^n .../d and splitScripts() has not yet seen it
765 InsetMathScript const * sup = at->asScriptInset();
766 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
767 MathAtom const & ma = sup->nuc().front();
768 return testString(ma, "d") || testSymbol(ma, "partial");
774 bool testDiffArray(MathArray const & ar)
776 return ar.size() && testDiffItem(ar.front());
780 bool testDiffFrac(MathAtom const & at)
784 && testDiffArray(at->asFracInset()->cell(0))
785 && testDiffArray(at->asFracInset()->cell(1));
789 void extractDiff(MathArray & ar)
791 //lyxerr << "\nDiffs from: " << ar << endl;
792 for (size_t i = 0; i < ar.size(); ++i) {
793 MathArray::iterator it = ar.begin() + i;
795 // is this a "differential fraction"?
796 if (!testDiffFrac(*it))
799 InsetMathFrac const * f = (*it)->asFracInset();
801 lyxerr << "should not happen" << endl;
805 // create a proper diff inset
806 auto_ptr<InsetMathDiff> diff(new InsetMathDiff);
808 // collect function, let jt point behind last used item
809 MathArray::iterator jt = it + 1;
811 MathArray numer(f->cell(0));
813 if (numer.size() > 1 && numer[1]->asScriptInset()) {
814 // this is something like d^n f(x) / d... or d^n / d...
817 if (numer.size() > 2)
818 diff->cell(0) = MathArray(numer.begin() + 2, numer.end());
820 jt = extractTerm(diff->cell(0), jt, ar.end());
822 // simply d f(x) / d... or d/d...
823 if (numer.size() > 1)
824 diff->cell(0) = MathArray(numer.begin() + 1, numer.end());
826 jt = extractTerm(diff->cell(0), jt, ar.end());
829 // collect denominator parts
830 MathArray denom(f->cell(1));
832 for (MathArray::iterator dt = denom.begin(); dt != denom.end();) {
834 MathArray::iterator et
835 = find_if(dt + 1, denom.end(), &testDiffItem);
838 MathArray::iterator st = et - 1;
839 InsetMathScript const * script = (*st)->asScriptInset();
840 if (script && script->hasUp()) {
841 // things like d.../dx^n
843 if (extractNumber(script->up(), mult)) {
844 //lyxerr << "mult: " << mult << endl;
845 for (int i = 0; i < mult; ++i)
846 diff->addDer(MathArray(dt + 1, st));
850 diff->addDer(MathArray(dt + 1, et));
856 ar.erase(it + 1, jt);
857 *it = MathAtom(diff.release());
859 //lyxerr << "\nDiffs to: " << ar << endl;
868 bool testRightArrow(MathAtom const & at)
870 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
875 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
876 // assume 'extractDelims' ran before
877 void extractLims(MathArray & ar)
879 //lyxerr << "\nLimits from: " << ar << endl;
880 for (size_t i = 0; i < ar.size(); ++i) {
881 MathArray::iterator it = ar.begin() + i;
883 // must be a script inset with a subscript (without superscript)
884 InsetMathScript const * sub = (*it)->asScriptInset();
885 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
888 // is this a limit function?
889 if (!testSymbol(sub->nuc().front(), "lim"))
892 // subscript must contain a -> symbol
893 MathArray const & s = sub->down();
894 MathArray::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
898 // the -> splits the subscript int x and x0
899 MathArray x = MathArray(s.begin(), st);
900 MathArray x0 = MathArray(st + 1, s.end());
902 // use something behind the script as core
904 MathArray::iterator tt = extractTerm(f, it + 1, ar.end());
907 ar.erase(it + 1, tt);
909 // create a proper inset as replacement
910 *it = MathAtom(new InsetMathLim(f, x, x0));
912 //lyxerr << "\nLimits to: " << ar << endl;
920 void extractStructure(MathArray & ar)
922 //lyxerr << "\nStructure from: " << ar << endl;
925 extractIntegrals(ar);
929 extractFunctions(ar);
935 //lyxerr << "\nStructure to: " << ar << endl;
939 void write(MathArray const & dat, WriteStream & wi)
943 wi.firstitem() = true;
944 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
946 wi.firstitem() = false;
951 void normalize(MathArray const & ar, NormalStream & os)
953 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
954 (*it)->normalize(os);
958 void octave(MathArray const & dat, OctaveStream & os)
961 extractStructure(ar);
962 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
967 void maple(MathArray const & dat, MapleStream & os)
970 extractStructure(ar);
971 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
976 void maxima(MathArray const & dat, MaximaStream & os)
979 extractStructure(ar);
980 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
985 void mathematica(MathArray const & dat, MathematicaStream & os)
988 extractStructure(ar);
989 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
990 (*it)->mathematica(os);
994 void mathmlize(MathArray const & dat, MathMLStream & os)
997 extractStructure(ar);
1000 else if (ar.size() == 1)
1004 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1005 (*it)->mathmlize(os);
1015 string captureOutput(string const & cmd, string const & data)
1017 string command = "echo '" + data + "' | " + cmd;
1018 lyxerr << "calling: " << command << endl;
1019 cmd_ret const ret = runCommand(command);
1023 string::size_type get_matching_brace(string const & str, string::size_type i)
1026 string::size_type n = str.size();
1028 i = str.find_first_of("{}", i+1);
1029 if (i == string::npos) return i;
1037 return string::npos;
1040 string::size_type get_matching_brace_back(string const & str, string::size_type i)
1044 i = str.find_last_of("{}", i-1);
1045 if (i == string::npos) return i;
1053 return string::npos;
1056 MathArray pipeThroughMaxima(string const &, MathArray const & ar)
1059 MaximaStream ms(os);
1061 string expr = os.str();
1062 string const header = "simpsum:true;";
1065 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1066 // try to fix missing '*' the hard way
1068 // > echo "2x;" | maxima
1070 // (C1) Incorrect syntax: x is not an infix operator
1074 lyxerr << "checking expr: '" << expr << "'" << endl;
1075 string full = header + "tex(" + expr + ");";
1076 out = captureOutput("maxima", full);
1078 // leave loop if expression syntax is probably ok
1079 if (out.find("Incorrect syntax") == string::npos)
1082 // search line with "Incorrect syntax"
1083 istringstream is(out);
1087 if (line.find("Incorrect syntax") != string::npos)
1091 // 2nd next line is the one with caret
1094 string::size_type pos = line.find('^');
1095 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1096 if (pos == string::npos || pos < 4)
1097 break; // caret position not found
1098 pos -= 4; // skip the "tex(" part
1099 if (expr[pos] == '*')
1100 break; // two '*' in a row are definitely bad
1101 expr.insert(pos, "*");
1104 vector<string> tmp = getVectorFromString(out, "$$");
1108 out = subst(tmp[1],"\\>", "");
1109 lyxerr << "out: '" << out << "'" << endl;
1111 // Ugly code that tries to make the result prettier
1113 string::size_type i = out.find("\\mathchoice");
1114 while (i != string::npos) {
1115 string::size_type j = get_matching_brace(out, i + 12);
1116 string::size_type k = get_matching_brace(out, j + 1);
1117 k = get_matching_brace(out, k + 1);
1118 k = get_matching_brace(out, k + 1);
1119 string mid = out.substr(i + 13,j - i - 13);
1120 if (mid.find("\\over") != string::npos)
1121 mid = '{' + mid + '}';
1122 out = out.substr(0,i)
1124 + out.substr(k + 1);
1125 //lyxerr << "out: " << out << endl;
1126 i = out.find("\\mathchoice", i);
1130 i = out.find("\\over");
1131 while (i != string::npos) {
1132 string::size_type j = get_matching_brace_back(out, i - 1);
1133 if (j == string::npos || j == 0) break;
1134 string::size_type k = get_matching_brace(out, i + 5);
1135 if (k == string::npos || k + 1 == out.size()) break;
1136 out = out.substr(0,j - 1)
1138 + out.substr(j,i - j)
1139 + out.substr(i + 5,k - i - 4)
1140 + out.substr(k + 2);
1141 //lyxerr << "out: " << out << endl;
1142 i = out.find("\\over", i + 4);
1145 mathed_parse_cell(res, out);
1150 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
1152 string header = "readlib(latex):\n";
1154 // remove the \\it for variable names
1155 //"#`latex/csname_font` := `\\it `:"
1157 "`latex/csname_font` := ``:\n";
1159 // export matrices in (...) instead of [...]
1161 "`latex/latex/matrix` := "
1162 "subs(`[`=`(`, `]`=`)`,"
1163 "eval(`latex/latex/matrix`)):\n";
1165 // replace \\cdots with proper '*'
1167 "`latex/latex/*` := "
1168 "subs(`\\,`=`\\cdot `,"
1169 "eval(`latex/latex/*`)):\n";
1171 // remove spurious \\noalign{\\medskip} in matrix output
1173 "`latex/latex/matrix`:= "
1174 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1175 "eval(`latex/latex/matrix`)):\n";
1177 //"#`latex/latex/symbol` "
1178 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1180 string trailer = "quit;";
1184 string expr = os.str();
1185 lyxerr << "ar: '" << ar << "'\n"
1186 << "ms: '" << os.str() << "'" << endl;
1188 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1189 // try to fix missing '*' the hard way by using mint
1191 // ... > echo "1A;" | mint -i 1 -S -s -q
1194 // Probably missing an operator such as * p
1196 lyxerr << "checking expr: '" << expr << "'" << endl;
1197 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1199 break; // expression syntax is ok
1200 istringstream is(out);
1203 if (line.find("on line") != 0)
1204 break; // error message not identified
1206 string::size_type pos = line.find('^');
1207 if (pos == string::npos || pos < 15)
1208 break; // caret position not found
1209 pos -= 15; // skip the "on line ..." part
1210 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1211 break; // two '*' in a row are definitely bad
1212 expr.insert(pos, 1, '*');
1215 string full = "latex(" + extra + '(' + expr + "));";
1216 string out = captureOutput("maple -q", header + full + trailer);
1222 mathed_parse_cell(res, out);
1227 MathArray pipeThroughOctave(string const &, MathArray const & ar)
1230 OctaveStream vs(os);
1232 string expr = os.str();
1235 lyxerr << "pipe: ar: '" << ar << "'\n"
1236 << "pipe: expr: '" << expr << "'" << endl;
1238 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1240 // try to fix missing '*' the hard way
1242 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1245 lyxerr << "checking expr: '" << expr << "'" << endl;
1246 out = captureOutput("octave -q 2>&1", expr);
1247 lyxerr << "checking out: '" << out << "'" << endl;
1249 // leave loop if expression syntax is probably ok
1250 if (out.find("parse error:") == string::npos)
1253 // search line with single caret
1254 istringstream is(out);
1258 lyxerr << "skipping line: '" << line << "'" << endl;
1259 if (line.find(">>> ") != string::npos)
1263 // found line with error, next line is the one with caret
1265 string::size_type pos = line.find('^');
1266 lyxerr << "caret line: '" << line << "'" << endl;
1267 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1268 if (pos == string::npos || pos < 4)
1269 break; // caret position not found
1270 pos -= 4; // skip the ">>> " part
1271 if (expr[pos] == '*')
1272 break; // two '*' in a row are definitely bad
1273 expr.insert(pos, 1, '*');
1280 out = out.substr(6);
1282 // parse output as matrix or single number
1283 MathAtom at(new InsetMathArray("array", out));
1284 InsetMathArray const * mat = at->asArrayInset();
1286 if (mat->ncols() == 1 && mat->nrows() == 1)
1287 res.append(mat->cell(0));
1289 res.push_back(MathAtom(new InsetMathDelim("(", ")")));
1290 res.back().nucleus()->cell(0).push_back(at);
1296 string fromMathematicaName(string const & name)
1298 if (name == "Sin") return "sin";
1299 if (name == "Sinh") return "sinh";
1300 if (name == "ArcSin") return "arcsin";
1301 if (name == "Cos") return "cos";
1302 if (name == "Cosh") return "cosh";
1303 if (name == "ArcCos") return "arccos";
1304 if (name == "Tan") return "tan";
1305 if (name == "Tanh") return "tanh";
1306 if (name == "ArcTan") return "arctan";
1307 if (name == "Cot") return "cot";
1308 if (name == "Coth") return "coth";
1309 if (name == "Csc") return "csc";
1310 if (name == "Sec") return "sec";
1311 if (name == "Exp") return "exp";
1312 if (name == "Log") return "log";
1313 if (name == "Arg" ) return "arg";
1314 if (name == "Det" ) return "det";
1315 if (name == "GCD" ) return "gcd";
1316 if (name == "Max" ) return "max";
1317 if (name == "Min" ) return "min";
1318 if (name == "Erf" ) return "erf";
1319 if (name == "Erfc" ) return "erfc";
1324 void prettifyMathematicaOutput(string & out, string const & macroName,
1325 bool roman, bool translate)
1327 string const macro = "\\" + macroName + "{";
1328 string::size_type const len = macro.length();
1329 string::size_type i = out.find(macro);
1331 while (i != string::npos) {
1332 string::size_type const j = get_matching_brace(out, i + len);
1333 string const name = out.substr(i + len, j - i - len);
1334 out = out.substr(0, i)
1335 + (roman ? "\\mathrm{" : "")
1336 + (translate ? fromMathematicaName(name) : name)
1337 + out.substr(roman ? j : j + 1);
1338 //lyxerr << "out: " << out << endl;
1339 i = out.find(macro, i);
1344 MathArray pipeThroughMathematica(string const &, MathArray const & ar)
1347 MathematicaStream ms(os);
1349 string const expr = os.str();
1352 lyxerr << "expr: '" << expr << "'" << endl;
1354 string const full = "TeXForm[" + expr + "]";
1355 out = captureOutput("math", full);
1356 lyxerr << "out: '" << out << "'" << endl;
1358 string::size_type pos1 = out.find("Out[1]//TeXForm= ");
1359 string::size_type pos2 = out.find("In[2]:=");
1361 if (pos1 == string::npos || pos2 == string::npos)
1364 // get everything from pos1+17 to pos2
1365 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1366 out = subst(subst(out, '\r', ' '), '\n', ' ');
1368 // tries to make the result prettier
1369 prettifyMathematicaOutput(out, "Mfunction", true, true);
1370 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1371 prettifyMathematicaOutput(out, "Mvariable", false, false);
1374 mathed_parse_cell(res, out);
1381 MathArray pipeThroughExtern(string const & lang, string const & extra,
1382 MathArray const & ar)
1384 if (lang == "octave")
1385 return pipeThroughOctave(extra, ar);
1387 if (lang == "maxima")
1388 return pipeThroughMaxima(extra, ar);
1390 if (lang == "maple")
1391 return pipeThroughMaple(extra, ar);
1393 if (lang == "mathematica")
1394 return pipeThroughMathematica(extra, ar);
1396 // create normalized expression
1398 NormalStream ns(os);
1399 os << '[' << extra << ' ';
1402 string data = os.str();
1404 // search external script
1405 string file = libFileSearch("mathed", "extern_" + lang);
1407 lyxerr << "converter to '" << lang << "' not found" << endl;
1411 // run external sript
1412 string out = captureOutput(file, data);
1414 mathed_parse_cell(res, out);