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"
44 using lyx::odocstream;
45 using lyx::odocstringstream;
46 using lyx::support::cmd_ret;
47 using lyx::support::getVectorFromString;
48 using lyx::support::libFileSearch;
49 using lyx::support::runCommand;
50 using lyx::support::subst;
52 using lyx::frontend::function_names;
58 using std::istringstream;
64 // define a function for tests
65 typedef bool TestItemFunc(MathAtom const &);
67 // define a function for replacing subexpressions
68 typedef MathAtom ReplaceArgumentFunc(const MathArray & ar);
72 // try to extract a super/subscript
73 // modify iterator position to point behind the thing
74 bool extractScript(MathArray & ar,
75 MathArray::iterator & pos, MathArray::iterator last, bool superscript)
77 // nothing to get here
81 // is this a scriptinset?
82 if (!(*pos)->asScriptInset())
85 // do we want superscripts only?
86 if (superscript && !(*pos)->asScriptInset()->hasUp())
89 // it is a scriptinset, use it.
96 // try to extract an "argument" to some function.
97 // returns position behind the argument
98 MathArray::iterator extractArgument(MathArray & ar,
99 MathArray::iterator pos, MathArray::iterator last, bool function = false)
101 // nothing to get here
105 // something delimited _is_ an argument
106 if ((*pos)->asDelimInset()) {
107 // leave out delimiters if this is a function argument
109 MathArray const & arg = (*pos)->asDelimInset()->cell(0);
110 MathArray::const_iterator cur = arg.begin();
111 MathArray::const_iterator end = arg.end();
113 ar.push_back(*cur++);
119 // if there's one, get following superscript only if this
120 // isn't a function argument
122 extractScript(ar, pos, last, true);
126 // always take the first thing, no matter what it is
129 // go ahead if possible
134 // if the next item is a super/subscript, it most certainly belongs
135 // to the thing we have
136 extractScript(ar, pos, last, false);
140 // but it might be more than that.
141 // FIXME: not implemented
142 //for (MathArray::iterator it = pos + 1; it != last; ++it) {
143 // // always take the first thing, no matter
145 // ar.push_back(*it);
153 // returns sequence of char with same code starting at it up to end
154 // it might be less, though...
156 (MathArray::const_iterator it, MathArray::const_iterator end)
159 for (; it != end && (*it)->asCharInset(); ++it)
160 s += (*it)->getChar();
165 void extractStrings(MathArray & ar)
167 //lyxerr << "\nStrings from: " << ar << endl;
168 for (size_t i = 0; i < ar.size(); ++i) {
169 if (!ar[i]->asCharInset())
171 string s = charSequence(ar.begin() + i, ar.end());
172 ar[i] = MathAtom(new InsetMathString(s));
173 ar.erase(i + 1, i + s.size());
175 //lyxerr << "\nStrings to: " << ar << endl;
179 void extractMatrices(MathArray & ar)
181 //lyxerr << "\nMatrices from: " << ar << endl;
182 // first pass for explicitly delimited stuff
183 for (size_t i = 0; i < ar.size(); ++i) {
184 if (!ar[i]->asDelimInset())
186 MathArray const & arr = ar[i]->asDelimInset()->cell(0);
189 if (!arr.front()->asGridInset())
191 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset())));
194 // second pass for AMS "pmatrix" etc
195 for (size_t i = 0; i < ar.size(); ++i)
196 if (ar[i]->asAMSArrayInset())
197 ar[i] = MathAtom(new InsetMathMatrix(*(ar[i]->asGridInset())));
198 //lyxerr << "\nMatrices to: " << ar << endl;
202 // convert this inset somehow to a string
203 bool extractString(MathAtom const & at, string & str)
206 str = string(1, at->getChar());
209 if (at->asStringInset()) {
210 str = at->asStringInset()->str();
217 // is this a known function?
218 bool isKnownFunction(string const & str)
220 for (int i = 0; *function_names[i]; ++i) {
221 if (str == function_names[i])
228 // extract a function name from this inset
229 bool extractFunctionName(MathAtom const & at, string & str)
231 if (at->asSymbolInset()) {
232 str = at->asSymbolInset()->name();
233 return isKnownFunction(str);
235 if (at->asUnknownInset()) {
236 // assume it is well known...
240 if (at->asFontInset() && at->name() == "mathrm") {
241 // assume it is well known...
242 MathArray const & ar = at->asFontInset()->cell(0);
243 str = charSequence(ar.begin(), ar.end());
244 return ar.size() == str.size();
250 // convert this inset somehow to a number
251 bool extractNumber(MathArray const & ar, int & i)
253 istringstream is(charSequence(ar.begin(), ar.end()));
259 bool extractNumber(MathArray const & ar, double & d)
261 istringstream is(charSequence(ar.begin(), ar.end()));
267 bool testString(MathAtom const & at, string const & str)
270 return extractString(at, s) && str == s;
274 // search end of nested sequence
275 MathArray::iterator endNestSearch(
276 MathArray::iterator it,
277 MathArray::iterator last,
278 TestItemFunc testOpen,
279 TestItemFunc testClose
282 for (int level = 0; it != last; ++it) {
294 // replace nested sequences by a real Insets
297 TestItemFunc testOpen,
298 TestItemFunc testClose,
299 ReplaceArgumentFunc replaceArg
302 // use indices rather than iterators for the loop because we are going
303 // to modify the array.
304 for (size_t i = 0; i < ar.size(); ++i) {
305 // check whether this is the begin of the sequence
306 if (!testOpen(ar[i]))
309 // search end of sequence
310 MathArray::iterator it = ar.begin() + i;
311 MathArray::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
315 // replace the original stuff by the new inset
316 ar[i] = replaceArg(MathArray(it + 1, jt));
317 ar.erase(it + 1, jt + 1);
324 // split scripts into seperate super- and subscript insets. sub goes in
328 void splitScripts(MathArray & ar)
330 //lyxerr << "\nScripts from: " << ar << endl;
331 for (size_t i = 0; i < ar.size(); ++i) {
332 InsetMathScript const * script = ar[i]->asScriptInset();
334 // is this a script inset and do we also have a superscript?
335 if (!script || !script->hasUp())
338 // we must have a nucleus if we only have a superscript
339 if (!script->hasDown() && script->nuc().size() == 0)
342 if (script->nuc().size() == 1) {
343 // leave alone sums and integrals
344 InsetMathSymbol const * sym =
345 script->nuc().front()->asSymbolInset();
346 if (sym && (sym->name() == "sum" || sym->name() == "int"))
350 // create extra script inset and move superscript over
351 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
352 auto_ptr<InsetMathScript> q(new InsetMathScript(true));
353 swap(q->up(), p->up());
354 p->removeScript(true);
356 // if we don't have a subscript, get rid of the ScriptInset
357 if (!script->hasDown()) {
358 MathArray arg(p->nuc());
359 MathArray::const_iterator it = arg.begin();
360 MathArray::const_iterator et = arg.end();
363 ar.insert(i++, *it++);
367 // insert new inset behind
368 ar.insert(i, MathAtom(q.release()));
370 //lyxerr << "\nScripts to: " << ar << endl;
378 void extractExps(MathArray & ar)
380 //lyxerr << "\nExps from: " << ar << endl;
381 for (size_t i = 0; i + 1 < ar.size(); ++i) {
383 if (ar[i]->getChar() != 'e')
386 // we need an exponent but no subscript
387 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
388 if (!sup || sup->hasDown())
391 // create a proper exp-inset as replacement
392 ar[i] = MathAtom(new InsetMathExFunc("exp", sup->cell(1)));
395 //lyxerr << "\nExps to: " << ar << endl;
400 // extract det(...) from |matrix|
402 void extractDets(MathArray & ar)
404 //lyxerr << "\ndet from: " << ar << endl;
405 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it) {
406 InsetMathDelim const * del = (*it)->asDelimInset();
411 *it = MathAtom(new InsetMathExFunc("det", del->cell(0)));
413 //lyxerr << "\ndet to: " << ar << endl;
421 bool isDigitOrSimilar(char c)
423 return ('0' <= c && c <= '9') || c == '.';
427 // returns sequence of digits
429 (MathArray::const_iterator it, MathArray::const_iterator end)
432 for (; it != end && (*it)->asCharInset(); ++it) {
433 if (!isDigitOrSimilar((*it)->getChar()))
435 s += (*it)->getChar();
441 void extractNumbers(MathArray & ar)
443 //lyxerr << "\nNumbers from: " << ar << endl;
444 for (size_t i = 0; i < ar.size(); ++i) {
445 if (!ar[i]->asCharInset())
447 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
450 string s = digitSequence(ar.begin() + i, ar.end());
452 ar[i] = MathAtom(new InsetMathNumber(s));
453 ar.erase(i + 1, i + s.size());
455 //lyxerr << "\nNumbers to: " << ar << endl;
464 bool testOpenParen(MathAtom const & at)
466 return testString(at, "(");
470 bool testCloseParen(MathAtom const & at)
472 return testString(at, ")");
476 MathAtom replaceParenDelims(const MathArray & ar)
478 return MathAtom(new InsetMathDelim("(", ")", ar));
482 bool testOpenBracket(MathAtom const & at)
484 return testString(at, "[");
488 bool testCloseBracket(MathAtom const & at)
490 return testString(at, "]");
494 MathAtom replaceBracketDelims(const MathArray & ar)
496 return MathAtom(new InsetMathDelim("[", "]", ar));
500 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
501 void extractDelims(MathArray & ar)
503 //lyxerr << "\nDelims from: " << ar << endl;
504 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
505 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
506 //lyxerr << "\nDelims to: " << ar << endl;
512 // search well-known functions
516 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
517 // assume 'extractDelims' ran before
518 void extractFunctions(MathArray & ar)
520 // we need at least two items...
524 //lyxerr << "\nFunctions from: " << ar << endl;
525 for (size_t i = 0; i + 1 < ar.size(); ++i) {
526 MathArray::iterator it = ar.begin() + i;
527 MathArray::iterator jt = it + 1;
531 // it certainly is if it is well known...
532 if (!extractFunctionName(*it, name)) {
533 // is this a user defined function?
534 // it it probably not, if it doesn't have a name.
535 if (!extractString(*it, name))
537 // it is not if it has no argument
540 // guess so, if this is followed by
541 // a DelimInset with a single item in the cell
542 InsetMathDelim const * del = (*jt)->asDelimInset();
543 if (!del || del->cell(0).size() != 1)
545 // fall trough into main branch
548 // do we have an exponent like in
549 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
551 extractScript(exp, jt, ar.end(), true);
553 // create a proper inset as replacement
554 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(name));
556 // jt points to the "argument". Get hold of this.
557 MathArray::iterator st = extractArgument(p->cell(0), jt, ar.end(), true);
559 // replace the function name by a real function inset
560 *it = MathAtom(p.release());
562 // remove the source of the argument from the array
563 ar.erase(it + 1, st);
565 // re-insert exponent
566 ar.insert(i + 1, exp);
567 //lyxerr << "\nFunctions to: " << ar << endl;
576 bool testSymbol(MathAtom const & at, string const & name)
578 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
582 bool testIntSymbol(MathAtom const & at)
584 return testSymbol(at, "int");
588 bool testIntegral(MathAtom const & at)
592 ( at->asScriptInset()
593 && at->asScriptInset()->nuc().size()
594 && testIntSymbol(at->asScriptInset()->nuc().back()) );
599 bool testIntDiff(MathAtom const & at)
601 return testString(at, "d");
605 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
606 // assume 'extractDelims' ran before
607 void extractIntegrals(MathArray & ar)
609 // we need at least three items...
613 //lyxerr << "\nIntegrals from: " << ar << endl;
614 for (size_t i = 0; i + 1 < ar.size(); ++i) {
615 MathArray::iterator it = ar.begin() + i;
618 MathArray::iterator jt =
619 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
621 // something sensible found?
625 // is this a integral name?
626 if (!testIntegral(*it))
629 // core ist part from behind the scripts to the 'd'
630 auto_ptr<InsetMathExInt> p(new InsetMathExInt("int"));
632 // handle scripts if available
633 if (!testIntSymbol(*it)) {
634 p->cell(2) = (*it)->asScriptInset()->down();
635 p->cell(3) = (*it)->asScriptInset()->up();
637 p->cell(0) = MathArray(it + 1, jt);
639 // use the "thing" behind the 'd' as differential
640 MathArray::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
643 ar.erase(it + 1, tt);
644 *it = MathAtom(p.release());
646 //lyxerr << "\nIntegrals to: " << ar << endl;
650 bool testTermDelimiter(MathAtom const & at)
652 return testString(at, "+") || testString(at, "-");
656 // try to extract a "term", i.e., something delimited by '+' or '-'.
657 // returns position behind the term
658 MathArray::iterator extractTerm(MathArray & ar,
659 MathArray::iterator pos, MathArray::iterator last)
661 while (pos != last && !testTermDelimiter(*pos)) {
674 bool testEqualSign(MathAtom const & at)
676 return testString(at, "=");
680 bool testSumSymbol(MathAtom const & p)
682 return testSymbol(p, "sum");
686 bool testSum(MathAtom const & at)
690 ( at->asScriptInset()
691 && at->asScriptInset()->nuc().size()
692 && testSumSymbol(at->asScriptInset()->nuc().back()) );
696 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
697 // assume 'extractDelims' ran before
698 void extractSums(MathArray & ar)
700 // we need at least two items...
704 //lyxerr << "\nSums from: " << ar << endl;
705 for (size_t i = 0; i + 1 < ar.size(); ++i) {
706 MathArray::iterator it = ar.begin() + i;
708 // is this a sum name?
712 // create a proper inset as replacement
713 auto_ptr<InsetMathExInt> p(new InsetMathExInt("sum"));
715 // collect lower bound and summation index
716 InsetMathScript const * sub = ar[i]->asScriptInset();
717 if (sub && sub->hasDown()) {
718 // try to figure out the summation index from the subscript
719 MathArray const & ar = sub->down();
720 MathArray::const_iterator xt =
721 find_if(ar.begin(), ar.end(), &testEqualSign);
722 if (xt != ar.end()) {
723 // we found a '=', use everything in front of that as index,
724 // and everything behind as lower index
725 p->cell(1) = MathArray(ar.begin(), xt);
726 p->cell(2) = MathArray(xt + 1, ar.end());
728 // use everything as summation index, don't use scripts.
733 // collect upper bound
734 if (sub && sub->hasUp())
735 p->cell(3) = sub->up();
737 // use something behind the script as core
738 MathArray::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
741 ar.erase(it + 1, tt);
742 *it = MathAtom(p.release());
744 //lyxerr << "\nSums to: " << ar << endl;
749 // search differential stuff
752 // tests for 'd' or '\partial'
753 bool testDiffItem(MathAtom const & at)
755 if (testString(at, "d") || testSymbol(at, "partial"))
758 // we may have d^n .../d and splitScripts() has not yet seen it
759 InsetMathScript const * sup = at->asScriptInset();
760 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
761 MathAtom const & ma = sup->nuc().front();
762 return testString(ma, "d") || testSymbol(ma, "partial");
768 bool testDiffArray(MathArray const & ar)
770 return ar.size() && testDiffItem(ar.front());
774 bool testDiffFrac(MathAtom const & at)
778 && testDiffArray(at->asFracInset()->cell(0))
779 && testDiffArray(at->asFracInset()->cell(1));
783 void extractDiff(MathArray & ar)
785 //lyxerr << "\nDiffs from: " << ar << endl;
786 for (size_t i = 0; i < ar.size(); ++i) {
787 MathArray::iterator it = ar.begin() + i;
789 // is this a "differential fraction"?
790 if (!testDiffFrac(*it))
793 InsetMathFrac const * f = (*it)->asFracInset();
795 lyxerr << "should not happen" << endl;
799 // create a proper diff inset
800 auto_ptr<InsetMathDiff> diff(new InsetMathDiff);
802 // collect function, let jt point behind last used item
803 MathArray::iterator jt = it + 1;
805 MathArray numer(f->cell(0));
807 if (numer.size() > 1 && numer[1]->asScriptInset()) {
808 // this is something like d^n f(x) / d... or d^n / d...
811 if (numer.size() > 2)
812 diff->cell(0) = MathArray(numer.begin() + 2, numer.end());
814 jt = extractTerm(diff->cell(0), jt, ar.end());
816 // simply d f(x) / d... or d/d...
817 if (numer.size() > 1)
818 diff->cell(0) = MathArray(numer.begin() + 1, numer.end());
820 jt = extractTerm(diff->cell(0), jt, ar.end());
823 // collect denominator parts
824 MathArray denom(f->cell(1));
826 for (MathArray::iterator dt = denom.begin(); dt != denom.end();) {
828 MathArray::iterator et
829 = find_if(dt + 1, denom.end(), &testDiffItem);
832 MathArray::iterator st = et - 1;
833 InsetMathScript const * script = (*st)->asScriptInset();
834 if (script && script->hasUp()) {
835 // things like d.../dx^n
837 if (extractNumber(script->up(), mult)) {
838 //lyxerr << "mult: " << mult << endl;
839 for (int i = 0; i < mult; ++i)
840 diff->addDer(MathArray(dt + 1, st));
844 diff->addDer(MathArray(dt + 1, et));
850 ar.erase(it + 1, jt);
851 *it = MathAtom(diff.release());
853 //lyxerr << "\nDiffs to: " << ar << endl;
862 bool testRightArrow(MathAtom const & at)
864 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
869 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
870 // assume 'extractDelims' ran before
871 void extractLims(MathArray & ar)
873 //lyxerr << "\nLimits from: " << ar << endl;
874 for (size_t i = 0; i < ar.size(); ++i) {
875 MathArray::iterator it = ar.begin() + i;
877 // must be a script inset with a subscript (without superscript)
878 InsetMathScript const * sub = (*it)->asScriptInset();
879 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
882 // is this a limit function?
883 if (!testSymbol(sub->nuc().front(), "lim"))
886 // subscript must contain a -> symbol
887 MathArray const & s = sub->down();
888 MathArray::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
892 // the -> splits the subscript int x and x0
893 MathArray x = MathArray(s.begin(), st);
894 MathArray x0 = MathArray(st + 1, s.end());
896 // use something behind the script as core
898 MathArray::iterator tt = extractTerm(f, it + 1, ar.end());
901 ar.erase(it + 1, tt);
903 // create a proper inset as replacement
904 *it = MathAtom(new InsetMathLim(f, x, x0));
906 //lyxerr << "\nLimits to: " << ar << endl;
914 void extractStructure(MathArray & ar)
916 //lyxerr << "\nStructure from: " << ar << endl;
919 extractIntegrals(ar);
923 extractFunctions(ar);
929 //lyxerr << "\nStructure to: " << ar << endl;
933 void write(MathArray const & dat, WriteStream & wi)
937 wi.firstitem() = true;
938 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
940 wi.firstitem() = false;
945 void normalize(MathArray const & ar, NormalStream & os)
947 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
948 (*it)->normalize(os);
952 void octave(MathArray const & dat, OctaveStream & os)
955 extractStructure(ar);
956 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
961 void maple(MathArray const & dat, MapleStream & os)
964 extractStructure(ar);
965 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
970 void maxima(MathArray const & dat, MaximaStream & os)
973 extractStructure(ar);
974 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
979 void mathematica(MathArray const & dat, MathematicaStream & os)
982 extractStructure(ar);
983 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
984 (*it)->mathematica(os);
988 void mathmlize(MathArray const & dat, MathMLStream & os)
991 extractStructure(ar);
994 else if (ar.size() == 1)
998 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
999 (*it)->mathmlize(os);
1009 string captureOutput(string const & cmd, string const & data)
1011 string command = "echo '" + data + "' | " + cmd;
1012 lyxerr << "calling: " << command << endl;
1013 cmd_ret const ret = runCommand(command);
1017 string::size_type get_matching_brace(string const & str, string::size_type i)
1020 string::size_type n = str.size();
1022 i = str.find_first_of("{}", i+1);
1023 if (i == string::npos) return i;
1031 return string::npos;
1034 string::size_type get_matching_brace_back(string const & str, string::size_type i)
1038 i = str.find_last_of("{}", i-1);
1039 if (i == string::npos) return i;
1047 return string::npos;
1050 MathArray pipeThroughMaxima(docstring const &, MathArray const & ar)
1052 lyx::odocstringstream os;
1053 MaximaStream ms(os);
1055 // FIXME UNICODE Is utf8 encoding correct?
1056 string expr = lyx::to_utf8(os.str());
1057 string const header = "simpsum:true;";
1060 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1061 // try to fix missing '*' the hard way
1063 // > echo "2x;" | maxima
1065 // (C1) Incorrect syntax: x is not an infix operator
1069 lyxerr << "checking expr: '" << expr << "'" << endl;
1070 string full = header + "tex(" + expr + ");";
1071 out = captureOutput("maxima", full);
1073 // leave loop if expression syntax is probably ok
1074 if (out.find("Incorrect syntax") == string::npos)
1077 // search line with "Incorrect syntax"
1078 istringstream is(out);
1082 if (line.find("Incorrect syntax") != string::npos)
1086 // 2nd next line is the one with caret
1089 string::size_type pos = line.find('^');
1090 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1091 if (pos == string::npos || pos < 4)
1092 break; // caret position not found
1093 pos -= 4; // skip the "tex(" part
1094 if (expr[pos] == '*')
1095 break; // two '*' in a row are definitely bad
1096 expr.insert(pos, "*");
1099 vector<string> tmp = getVectorFromString(out, "$$");
1103 out = subst(tmp[1],"\\>", "");
1104 lyxerr << "out: '" << out << "'" << endl;
1106 // Ugly code that tries to make the result prettier
1108 string::size_type i = out.find("\\mathchoice");
1109 while (i != string::npos) {
1110 string::size_type j = get_matching_brace(out, i + 12);
1111 string::size_type k = get_matching_brace(out, j + 1);
1112 k = get_matching_brace(out, k + 1);
1113 k = get_matching_brace(out, k + 1);
1114 string mid = out.substr(i + 13,j - i - 13);
1115 if (mid.find("\\over") != string::npos)
1116 mid = '{' + mid + '}';
1117 out = out.substr(0,i)
1119 + out.substr(k + 1);
1120 //lyxerr << "out: " << out << endl;
1121 i = out.find("\\mathchoice", i);
1125 i = out.find("\\over");
1126 while (i != string::npos) {
1127 string::size_type j = get_matching_brace_back(out, i - 1);
1128 if (j == string::npos || j == 0) break;
1129 string::size_type k = get_matching_brace(out, i + 5);
1130 if (k == string::npos || k + 1 == out.size()) break;
1131 out = out.substr(0,j - 1)
1133 + out.substr(j,i - j)
1134 + out.substr(i + 5,k - i - 4)
1135 + out.substr(k + 2);
1136 //lyxerr << "out: " << out << endl;
1137 i = out.find("\\over", i + 4);
1140 mathed_parse_cell(res, out);
1145 MathArray pipeThroughMaple(docstring const & extra, MathArray const & ar)
1147 string header = "readlib(latex):\n";
1149 // remove the \\it for variable names
1150 //"#`latex/csname_font` := `\\it `:"
1152 "`latex/csname_font` := ``:\n";
1154 // export matrices in (...) instead of [...]
1156 "`latex/latex/matrix` := "
1157 "subs(`[`=`(`, `]`=`)`,"
1158 "eval(`latex/latex/matrix`)):\n";
1160 // replace \\cdots with proper '*'
1162 "`latex/latex/*` := "
1163 "subs(`\\,`=`\\cdot `,"
1164 "eval(`latex/latex/*`)):\n";
1166 // remove spurious \\noalign{\\medskip} in matrix output
1168 "`latex/latex/matrix`:= "
1169 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1170 "eval(`latex/latex/matrix`)):\n";
1172 //"#`latex/latex/symbol` "
1173 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1175 string trailer = "quit;";
1176 lyx::odocstringstream os;
1179 // FIXME UNICODE Is utf8 encoding correct?
1180 string expr = lyx::to_utf8(os.str());
1181 lyxerr << "ar: '" << ar << "'\n"
1182 << "ms: '" << expr << "'" << endl;
1184 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1185 // try to fix missing '*' the hard way by using mint
1187 // ... > echo "1A;" | mint -i 1 -S -s -q
1190 // Probably missing an operator such as * p
1192 lyxerr << "checking expr: '" << expr << "'" << endl;
1193 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1195 break; // expression syntax is ok
1196 istringstream is(out);
1199 if (line.find("on line") != 0)
1200 break; // error message not identified
1202 string::size_type pos = line.find('^');
1203 if (pos == string::npos || pos < 15)
1204 break; // caret position not found
1205 pos -= 15; // skip the "on line ..." part
1206 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1207 break; // two '*' in a row are definitely bad
1208 expr.insert(pos, 1, '*');
1211 // FIXME UNICODE Is utf8 encoding correct?
1212 string full = "latex(" + lyx::to_utf8(extra) + '(' + expr + "));";
1213 string out = captureOutput("maple -q", header + full + trailer);
1219 mathed_parse_cell(res, out);
1224 MathArray pipeThroughOctave(docstring const &, MathArray const & ar)
1226 lyx::odocstringstream os;
1227 OctaveStream vs(os);
1229 // FIXME UNICODE Is utf8 encoding correct?
1230 string expr = lyx::to_utf8(os.str());
1233 lyxerr << "pipe: ar: '" << ar << "'\n"
1234 << "pipe: expr: '" << expr << "'" << endl;
1236 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1238 // try to fix missing '*' the hard way
1240 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1243 lyxerr << "checking expr: '" << expr << "'" << endl;
1244 out = captureOutput("octave -q 2>&1", expr);
1245 lyxerr << "checking out: '" << out << "'" << endl;
1247 // leave loop if expression syntax is probably ok
1248 if (out.find("parse error:") == string::npos)
1251 // search line with single caret
1252 istringstream is(out);
1256 lyxerr << "skipping line: '" << line << "'" << endl;
1257 if (line.find(">>> ") != string::npos)
1261 // found line with error, next line is the one with caret
1263 string::size_type pos = line.find('^');
1264 lyxerr << "caret line: '" << line << "'" << endl;
1265 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1266 if (pos == string::npos || pos < 4)
1267 break; // caret position not found
1268 pos -= 4; // skip the ">>> " part
1269 if (expr[pos] == '*')
1270 break; // two '*' in a row are definitely bad
1271 expr.insert(pos, 1, '*');
1278 out = out.substr(6);
1280 // parse output as matrix or single number
1281 MathAtom at(new InsetMathArray("array", out));
1282 InsetMathArray const * mat = at->asArrayInset();
1284 if (mat->ncols() == 1 && mat->nrows() == 1)
1285 res.append(mat->cell(0));
1287 res.push_back(MathAtom(new InsetMathDelim("(", ")")));
1288 res.back().nucleus()->cell(0).push_back(at);
1294 string fromMathematicaName(string const & name)
1296 if (name == "Sin") return "sin";
1297 if (name == "Sinh") return "sinh";
1298 if (name == "ArcSin") return "arcsin";
1299 if (name == "Cos") return "cos";
1300 if (name == "Cosh") return "cosh";
1301 if (name == "ArcCos") return "arccos";
1302 if (name == "Tan") return "tan";
1303 if (name == "Tanh") return "tanh";
1304 if (name == "ArcTan") return "arctan";
1305 if (name == "Cot") return "cot";
1306 if (name == "Coth") return "coth";
1307 if (name == "Csc") return "csc";
1308 if (name == "Sec") return "sec";
1309 if (name == "Exp") return "exp";
1310 if (name == "Log") return "log";
1311 if (name == "Arg" ) return "arg";
1312 if (name == "Det" ) return "det";
1313 if (name == "GCD" ) return "gcd";
1314 if (name == "Max" ) return "max";
1315 if (name == "Min" ) return "min";
1316 if (name == "Erf" ) return "erf";
1317 if (name == "Erfc" ) return "erfc";
1322 void prettifyMathematicaOutput(string & out, string const & macroName,
1323 bool roman, bool translate)
1325 string const macro = "\\" + macroName + "{";
1326 string::size_type const len = macro.length();
1327 string::size_type i = out.find(macro);
1329 while (i != string::npos) {
1330 string::size_type const j = get_matching_brace(out, i + len);
1331 string const name = out.substr(i + len, j - i - len);
1332 out = out.substr(0, i)
1333 + (roman ? "\\mathrm{" : "")
1334 + (translate ? fromMathematicaName(name) : name)
1335 + out.substr(roman ? j : j + 1);
1336 //lyxerr << "out: " << out << endl;
1337 i = out.find(macro, i);
1342 MathArray pipeThroughMathematica(docstring const &, MathArray const & ar)
1344 lyx::odocstringstream os;
1345 MathematicaStream ms(os);
1347 // FIXME UNICODE Is utf8 encoding correct?
1348 string const expr = lyx::to_utf8(os.str());
1351 lyxerr << "expr: '" << expr << "'" << endl;
1353 string const full = "TeXForm[" + expr + "]";
1354 out = captureOutput("math", full);
1355 lyxerr << "out: '" << out << "'" << endl;
1357 string::size_type pos1 = out.find("Out[1]//TeXForm= ");
1358 string::size_type pos2 = out.find("In[2]:=");
1360 if (pos1 == string::npos || pos2 == string::npos)
1363 // get everything from pos1+17 to pos2
1364 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1365 out = subst(subst(out, '\r', ' '), '\n', ' ');
1367 // tries to make the result prettier
1368 prettifyMathematicaOutput(out, "Mfunction", true, true);
1369 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1370 prettifyMathematicaOutput(out, "Mvariable", false, false);
1373 mathed_parse_cell(res, out);
1380 MathArray pipeThroughExtern(string const & lang, docstring const & extra,
1381 MathArray const & ar)
1383 if (lang == "octave")
1384 return pipeThroughOctave(extra, ar);
1386 if (lang == "maxima")
1387 return pipeThroughMaxima(extra, ar);
1389 if (lang == "maple")
1390 return pipeThroughMaple(extra, ar);
1392 if (lang == "mathematica")
1393 return pipeThroughMathematica(extra, ar);
1395 // create normalized expression
1396 lyx::odocstringstream os;
1397 NormalStream ns(os);
1398 os << '[' << extra << ' ';
1401 // FIXME UNICODE Is utf8 encoding correct?
1402 string data = lyx::to_utf8(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);