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
17 #include "MathExtern.h"
19 #include "support/debug.h"
20 #include "InsetMathArray.h"
21 #include "InsetMathChar.h"
22 #include "InsetMathDelim.h"
23 #include "InsetMathDiff.h"
24 #include "InsetMathExFunc.h"
25 #include "InsetMathExInt.h"
26 #include "InsetMathFont.h"
27 #include "InsetMathFrac.h"
28 #include "InsetMathLim.h"
29 #include "InsetMathMatrix.h"
30 #include "InsetMathNumber.h"
31 #include "InsetMathScript.h"
32 #include "InsetMathString.h"
33 #include "InsetMathSymbol.h"
35 #include "MathParser.h"
36 #include "MathStream.h"
38 #include "support/docstream.h"
39 #include "support/filetools.h"
40 #include "support/lstrings.h"
47 using namespace lyx::support;
51 static char const * function_names[] = {
52 "arccos", "arcsin", "arctan", "arg", "bmod",
53 "cos", "cosh", "cot", "coth", "csc", "deg",
54 "det", "dim", "exp", "gcd", "hom", "inf", "ker",
55 "lg", "lim", "liminf", "limsup", "ln", "log",
56 "max", "min", "sec", "sin", "sinh", "sup",
57 "tan", "tanh", "Pr", 0
60 static size_t const npos = lyx::docstring::npos;
62 // define a function for tests
63 typedef bool TestItemFunc(MathAtom const &);
65 // define a function for replacing subexpressions
66 typedef MathAtom ReplaceArgumentFunc(const MathData & ar);
70 // try to extract a super/subscript
71 // modify iterator position to point behind the thing
72 bool extractScript(MathData & ar,
73 MathData::iterator & pos, MathData::iterator last, bool superscript)
75 // nothing to get here
79 // is this a scriptinset?
80 if (!(*pos)->asScriptInset())
83 // do we want superscripts only?
84 if (superscript && !(*pos)->asScriptInset()->hasUp())
87 // it is a scriptinset, use it.
94 // try to extract an "argument" to some function.
95 // returns position behind the argument
96 MathData::iterator extractArgument(MathData & ar,
97 MathData::iterator pos, MathData::iterator last, bool function = false)
99 // nothing to get here
103 // something delimited _is_ an argument
104 if ((*pos)->asDelimInset()) {
105 // leave out delimiters if this is a function argument
107 MathData const & arg = (*pos)->asDelimInset()->cell(0);
108 MathData::const_iterator cur = arg.begin();
109 MathData::const_iterator end = arg.end();
111 ar.push_back(*cur++);
117 // if there's one, get following superscript only if this
118 // isn't a function argument
120 extractScript(ar, pos, last, true);
124 // always take the first thing, no matter what it is
127 // go ahead if possible
132 // if the next item is a super/subscript, it most certainly belongs
133 // to the thing we have
134 extractScript(ar, pos, last, false);
138 // but it might be more than that.
139 // FIXME: not implemented
140 //for (MathData::iterator it = pos + 1; it != last; ++it) {
141 // // always take the first thing, no matter
143 // ar.push_back(*it);
151 // returns sequence of char with same code starting at it up to end
152 // it might be less, though...
153 docstring charSequence
154 (MathData::const_iterator it, MathData::const_iterator end)
157 for (; it != end && (*it)->asCharInset(); ++it)
158 s += (*it)->getChar();
163 void extractStrings(MathData & ar)
165 //lyxerr << "\nStrings from: " << ar << endl;
166 for (size_t i = 0; i < ar.size(); ++i) {
167 if (!ar[i]->asCharInset())
169 docstring s = charSequence(ar.begin() + i, ar.end());
170 ar[i] = MathAtom(new InsetMathString(s));
171 ar.erase(i + 1, i + s.size());
173 //lyxerr << "\nStrings to: " << ar << endl;
177 void extractMatrices(MathData & ar)
179 //lyxerr << "\nMatrices from: " << ar << endl;
180 // first pass for explicitly delimited stuff
181 for (size_t i = 0; i < ar.size(); ++i) {
182 if (!ar[i]->asDelimInset())
184 MathData const & arr = ar[i]->asDelimInset()->cell(0);
187 if (!arr.front()->asGridInset())
189 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset())));
192 // second pass for AMS "pmatrix" etc
193 for (size_t i = 0; i < ar.size(); ++i)
194 if (ar[i]->asAMSArrayInset())
195 ar[i] = MathAtom(new InsetMathMatrix(*(ar[i]->asGridInset())));
196 //lyxerr << "\nMatrices to: " << ar << endl;
200 // convert this inset somehow to a string
201 bool extractString(MathAtom const & at, docstring & str)
204 str = docstring(1, at->getChar());
207 if (at->asStringInset()) {
208 str = at->asStringInset()->str();
215 // is this a known function?
216 bool isKnownFunction(docstring const & str)
218 for (int i = 0; function_names[i]; ++i) {
219 if (str == function_names[i])
226 // extract a function name from this inset
227 bool extractFunctionName(MathAtom const & at, docstring & str)
229 if (at->asSymbolInset()) {
230 str = at->asSymbolInset()->name();
231 return isKnownFunction(str);
233 if (at->asUnknownInset()) {
234 // assume it is well known...
238 if (at->asFontInset() && at->name() == "mathrm") {
239 // assume it is well known...
240 MathData const & ar = at->asFontInset()->cell(0);
241 str = charSequence(ar.begin(), ar.end());
242 return ar.size() == str.size();
248 // convert this inset somehow to a number
249 bool extractNumber(MathData const & ar, int & i)
251 idocstringstream is(charSequence(ar.begin(), ar.end()));
257 bool extractNumber(MathData const & ar, double & d)
259 idocstringstream is(charSequence(ar.begin(), ar.end()));
265 bool testString(MathAtom const & at, docstring const & str)
268 return extractString(at, s) && str == s;
272 bool testString(MathAtom const & at, char const * const str)
274 return testString(at, from_ascii(str));
277 // search end of nested sequence
278 MathData::iterator endNestSearch(
279 MathData::iterator it,
280 MathData::iterator last,
281 TestItemFunc testOpen,
282 TestItemFunc testClose
285 for (int level = 0; it != last; ++it) {
297 // replace nested sequences by a real Insets
300 TestItemFunc testOpen,
301 TestItemFunc testClose,
302 ReplaceArgumentFunc replaceArg
305 // use indices rather than iterators for the loop because we are going
306 // to modify the array.
307 for (size_t i = 0; i < ar.size(); ++i) {
308 // check whether this is the begin of the sequence
309 if (!testOpen(ar[i]))
312 // search end of sequence
313 MathData::iterator it = ar.begin() + i;
314 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
318 // replace the original stuff by the new inset
319 ar[i] = replaceArg(MathData(it + 1, jt));
320 ar.erase(it + 1, jt + 1);
327 // split scripts into seperate super- and subscript insets. sub goes in
331 void splitScripts(MathData & ar)
333 //lyxerr << "\nScripts from: " << ar << endl;
334 for (size_t i = 0; i < ar.size(); ++i) {
335 InsetMathScript const * script = ar[i]->asScriptInset();
337 // is this a script inset and do we also have a superscript?
338 if (!script || !script->hasUp())
341 // we must have a nucleus if we only have a superscript
342 if (!script->hasDown() && script->nuc().size() == 0)
345 if (script->nuc().size() == 1) {
346 // leave alone sums and integrals
347 InsetMathSymbol const * sym =
348 script->nuc().front()->asSymbolInset();
349 if (sym && (sym->name() == "sum" || sym->name() == "int"))
353 // create extra script inset and move superscript over
354 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
355 auto_ptr<InsetMathScript> q(new InsetMathScript(true));
356 swap(q->up(), p->up());
357 p->removeScript(true);
359 // if we don't have a subscript, get rid of the ScriptInset
360 if (!script->hasDown()) {
361 MathData arg(p->nuc());
362 MathData::const_iterator it = arg.begin();
363 MathData::const_iterator et = arg.end();
366 ar.insert(i++, *it++);
370 // insert new inset behind
371 ar.insert(i, MathAtom(q.release()));
373 //lyxerr << "\nScripts to: " << ar << endl;
381 void extractExps(MathData & ar)
383 //lyxerr << "\nExps from: " << ar << endl;
384 for (size_t i = 0; i + 1 < ar.size(); ++i) {
386 if (ar[i]->getChar() != 'e')
389 // we need an exponent but no subscript
390 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
391 if (!sup || sup->hasDown())
394 // create a proper exp-inset as replacement
395 ar[i] = MathAtom(new InsetMathExFunc(from_ascii("exp"), sup->cell(1)));
398 //lyxerr << "\nExps to: " << ar << endl;
403 // extract det(...) from |matrix|
405 void extractDets(MathData & ar)
407 //lyxerr << "\ndet from: " << ar << endl;
408 for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
409 InsetMathDelim const * del = (*it)->asDelimInset();
414 *it = MathAtom(new InsetMathExFunc(from_ascii("det"), del->cell(0)));
416 //lyxerr << "\ndet to: " << ar << endl;
424 bool isDigitOrSimilar(char_type c)
426 return ('0' <= c && c <= '9') || c == '.';
430 // returns sequence of digits
431 docstring digitSequence
432 (MathData::const_iterator it, MathData::const_iterator end)
435 for (; it != end && (*it)->asCharInset(); ++it) {
436 if (!isDigitOrSimilar((*it)->getChar()))
438 s += (*it)->getChar();
444 void extractNumbers(MathData & ar)
446 //lyxerr << "\nNumbers from: " << ar << endl;
447 for (size_t i = 0; i < ar.size(); ++i) {
448 if (!ar[i]->asCharInset())
450 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
453 docstring s = digitSequence(ar.begin() + i, ar.end());
455 ar[i] = MathAtom(new InsetMathNumber(s));
456 ar.erase(i + 1, i + s.size());
458 //lyxerr << "\nNumbers to: " << ar << endl;
467 bool testOpenParen(MathAtom const & at)
469 return testString(at, "(");
473 bool testCloseParen(MathAtom const & at)
475 return testString(at, ")");
479 MathAtom replaceParenDelims(const MathData & ar)
481 return MathAtom(new InsetMathDelim(from_ascii("("), from_ascii(")"), ar));
485 bool testOpenBracket(MathAtom const & at)
487 return testString(at, "[");
491 bool testCloseBracket(MathAtom const & at)
493 return testString(at, "]");
497 MathAtom replaceBracketDelims(const MathData & ar)
499 return MathAtom(new InsetMathDelim(from_ascii("["), from_ascii("]"), ar));
503 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
504 void extractDelims(MathData & ar)
506 //lyxerr << "\nDelims from: " << ar << endl;
507 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
508 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
509 //lyxerr << "\nDelims to: " << ar << endl;
515 // search well-known functions
519 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
520 // assume 'extractDelims' ran before
521 void extractFunctions(MathData & ar)
523 // we need at least two items...
527 //lyxerr << "\nFunctions from: " << ar << endl;
528 for (size_t i = 0; i + 1 < ar.size(); ++i) {
529 MathData::iterator it = ar.begin() + i;
530 MathData::iterator jt = it + 1;
534 // it certainly is if it is well known...
535 if (!extractFunctionName(*it, name)) {
536 // is this a user defined function?
537 // it it probably not, if it doesn't have a name.
538 if (!extractString(*it, name))
540 // it is not if it has no argument
543 // guess so, if this is followed by
544 // a DelimInset with a single item in the cell
545 InsetMathDelim const * del = (*jt)->asDelimInset();
546 if (!del || del->cell(0).size() != 1)
548 // fall trough into main branch
551 // do we have an exponent like in
552 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
554 extractScript(exp, jt, ar.end(), true);
556 // create a proper inset as replacement
557 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(name));
559 // jt points to the "argument". Get hold of this.
560 MathData::iterator st = extractArgument(p->cell(0), jt, ar.end(), true);
562 // replace the function name by a real function inset
563 *it = MathAtom(p.release());
565 // remove the source of the argument from the array
566 ar.erase(it + 1, st);
568 // re-insert exponent
569 ar.insert(i + 1, exp);
570 //lyxerr << "\nFunctions to: " << ar << endl;
579 bool testSymbol(MathAtom const & at, docstring const & name)
581 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
585 bool testSymbol(MathAtom const & at, char const * const name)
587 return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
591 bool testIntSymbol(MathAtom const & at)
593 return testSymbol(at, from_ascii("int"));
597 bool testIntegral(MathAtom const & at)
601 ( at->asScriptInset()
602 && at->asScriptInset()->nuc().size()
603 && testIntSymbol(at->asScriptInset()->nuc().back()) );
608 bool testIntDiff(MathAtom const & at)
610 return testString(at, "d");
614 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
615 // assume 'extractDelims' ran before
616 void extractIntegrals(MathData & ar)
618 // we need at least three items...
622 //lyxerr << "\nIntegrals from: " << ar << endl;
623 for (size_t i = 0; i + 1 < ar.size(); ++i) {
624 MathData::iterator it = ar.begin() + i;
627 MathData::iterator jt =
628 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
630 // something sensible found?
634 // is this a integral name?
635 if (!testIntegral(*it))
638 // core ist part from behind the scripts to the 'd'
639 auto_ptr<InsetMathExInt> p(new InsetMathExInt(from_ascii("int")));
641 // handle scripts if available
642 if (!testIntSymbol(*it)) {
643 p->cell(2) = (*it)->asScriptInset()->down();
644 p->cell(3) = (*it)->asScriptInset()->up();
646 p->cell(0) = MathData(it + 1, jt);
648 // use the "thing" behind the 'd' as differential
649 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
652 ar.erase(it + 1, tt);
653 *it = MathAtom(p.release());
655 //lyxerr << "\nIntegrals to: " << ar << endl;
659 bool testTermDelimiter(MathAtom const & at)
661 return testString(at, "+") || testString(at, "-");
665 // try to extract a "term", i.e., something delimited by '+' or '-'.
666 // returns position behind the term
667 MathData::iterator extractTerm(MathData & ar,
668 MathData::iterator pos, MathData::iterator last)
670 while (pos != last && !testTermDelimiter(*pos)) {
683 bool testEqualSign(MathAtom const & at)
685 return testString(at, "=");
689 bool testSumSymbol(MathAtom const & p)
691 return testSymbol(p, from_ascii("sum"));
695 bool testSum(MathAtom const & at)
699 ( at->asScriptInset()
700 && at->asScriptInset()->nuc().size()
701 && testSumSymbol(at->asScriptInset()->nuc().back()) );
705 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
706 // assume 'extractDelims' ran before
707 void extractSums(MathData & ar)
709 // we need at least two items...
713 //lyxerr << "\nSums from: " << ar << endl;
714 for (size_t i = 0; i + 1 < ar.size(); ++i) {
715 MathData::iterator it = ar.begin() + i;
717 // is this a sum name?
721 // create a proper inset as replacement
722 auto_ptr<InsetMathExInt> p(new InsetMathExInt(from_ascii("sum")));
724 // collect lower bound and summation index
725 InsetMathScript const * sub = ar[i]->asScriptInset();
726 if (sub && sub->hasDown()) {
727 // try to figure out the summation index from the subscript
728 MathData const & ar = sub->down();
729 MathData::const_iterator xt =
730 find_if(ar.begin(), ar.end(), &testEqualSign);
731 if (xt != ar.end()) {
732 // we found a '=', use everything in front of that as index,
733 // and everything behind as lower index
734 p->cell(1) = MathData(ar.begin(), xt);
735 p->cell(2) = MathData(xt + 1, ar.end());
737 // use everything as summation index, don't use scripts.
742 // collect upper bound
743 if (sub && sub->hasUp())
744 p->cell(3) = sub->up();
746 // use something behind the script as core
747 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
750 ar.erase(it + 1, tt);
751 *it = MathAtom(p.release());
753 //lyxerr << "\nSums to: " << ar << endl;
758 // search differential stuff
761 // tests for 'd' or '\partial'
762 bool testDiffItem(MathAtom const & at)
764 if (testString(at, "d") || testSymbol(at, "partial"))
767 // we may have d^n .../d and splitScripts() has not yet seen it
768 InsetMathScript const * sup = at->asScriptInset();
769 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
770 MathAtom const & ma = sup->nuc().front();
771 return testString(ma, "d") || testSymbol(ma, "partial");
777 bool testDiffArray(MathData const & ar)
779 return ar.size() && testDiffItem(ar.front());
783 bool testDiffFrac(MathAtom const & at)
787 && testDiffArray(at->asFracInset()->cell(0))
788 && testDiffArray(at->asFracInset()->cell(1));
792 void extractDiff(MathData & ar)
794 //lyxerr << "\nDiffs from: " << ar << endl;
795 for (size_t i = 0; i < ar.size(); ++i) {
796 MathData::iterator it = ar.begin() + i;
798 // is this a "differential fraction"?
799 if (!testDiffFrac(*it))
802 InsetMathFrac const * f = (*it)->asFracInset();
804 lyxerr << "should not happen" << endl;
808 // create a proper diff inset
809 auto_ptr<InsetMathDiff> diff(new InsetMathDiff);
811 // collect function, let jt point behind last used item
812 MathData::iterator jt = it + 1;
814 MathData numer(f->cell(0));
816 if (numer.size() > 1 && numer[1]->asScriptInset()) {
817 // this is something like d^n f(x) / d... or d^n / d...
820 if (numer.size() > 2)
821 diff->cell(0) = MathData(numer.begin() + 2, numer.end());
823 jt = extractTerm(diff->cell(0), jt, ar.end());
825 // simply d f(x) / d... or d/d...
826 if (numer.size() > 1)
827 diff->cell(0) = MathData(numer.begin() + 1, numer.end());
829 jt = extractTerm(diff->cell(0), jt, ar.end());
832 // collect denominator parts
833 MathData denom(f->cell(1));
835 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
837 MathData::iterator et
838 = find_if(dt + 1, denom.end(), &testDiffItem);
841 MathData::iterator st = et - 1;
842 InsetMathScript const * script = (*st)->asScriptInset();
843 if (script && script->hasUp()) {
844 // things like d.../dx^n
846 if (extractNumber(script->up(), mult)) {
847 //lyxerr << "mult: " << mult << endl;
848 for (int i = 0; i < mult; ++i)
849 diff->addDer(MathData(dt + 1, st));
853 diff->addDer(MathData(dt + 1, et));
859 ar.erase(it + 1, jt);
860 *it = MathAtom(diff.release());
862 //lyxerr << "\nDiffs to: " << ar << endl;
871 bool testRightArrow(MathAtom const & at)
873 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
878 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
879 // assume 'extractDelims' ran before
880 void extractLims(MathData & ar)
882 //lyxerr << "\nLimits from: " << ar << endl;
883 for (size_t i = 0; i < ar.size(); ++i) {
884 MathData::iterator it = ar.begin() + i;
886 // must be a script inset with a subscript (without superscript)
887 InsetMathScript const * sub = (*it)->asScriptInset();
888 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
891 // is this a limit function?
892 if (!testSymbol(sub->nuc().front(), "lim"))
895 // subscript must contain a -> symbol
896 MathData const & s = sub->down();
897 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
901 // the -> splits the subscript int x and x0
902 MathData x = MathData(s.begin(), st);
903 MathData x0 = MathData(st + 1, s.end());
905 // use something behind the script as core
907 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
910 ar.erase(it + 1, tt);
912 // create a proper inset as replacement
913 *it = MathAtom(new InsetMathLim(f, x, x0));
915 //lyxerr << "\nLimits to: " << ar << endl;
923 void extractStructure(MathData & ar)
925 //lyxerr << "\nStructure from: " << ar << endl;
928 extractIntegrals(ar);
932 extractFunctions(ar);
938 //lyxerr << "\nStructure to: " << ar << endl;
942 void write(MathData const & dat, WriteStream & wi)
946 wi.firstitem() = true;
947 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it) {
949 wi.firstitem() = false;
954 void normalize(MathData const & ar, NormalStream & os)
956 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
957 (*it)->normalize(os);
961 void octave(MathData const & dat, OctaveStream & os)
964 extractStructure(ar);
965 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
970 void maple(MathData const & dat, MapleStream & os)
973 extractStructure(ar);
974 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
979 void maxima(MathData const & dat, MaximaStream & os)
982 extractStructure(ar);
983 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
988 void mathematica(MathData const & dat, MathematicaStream & os)
991 extractStructure(ar);
992 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
993 (*it)->mathematica(os);
997 void mathmlize(MathData const & dat, MathStream & os)
1000 extractStructure(ar);
1003 else if (ar.size() == 1)
1007 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1008 (*it)->mathmlize(os);
1018 string captureOutput(string const & cmd, string const & data)
1020 // In order to avoid parsing problems with command interpreters
1021 // we pass input data through a file
1022 FileName const cas_tmpfile = FileName::tempName("casinput");
1023 if (cas_tmpfile.empty()) {
1024 lyxerr << "Warning: cannot create temporary file."
1028 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
1031 string command = cmd + " < "
1032 + quoteName(cas_tmpfile.toFilesystemEncoding());
1033 lyxerr << "calling: " << cmd
1034 << "\ninput: '" << data << "'" << endl;
1035 cmd_ret const ret = runCommand(command);
1036 cas_tmpfile.removeFile();
1040 size_t get_matching_brace(string const & str, size_t i)
1043 size_t n = str.size();
1045 i = str.find_first_of("{}", i+1);
1058 size_t get_matching_brace_back(string const & str, size_t i)
1062 i = str.find_last_of("{}", i-1);
1075 MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1077 odocstringstream os;
1078 MaximaStream ms(os);
1080 docstring expr = os.str();
1081 docstring const header = from_ascii("simpsum:true;");
1084 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1085 // try to fix missing '*' the hard way
1087 // > echo "2x;" | maxima
1089 // (C1) Incorrect syntax: x is not an infix operator
1093 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1094 docstring full = header + "tex(" + expr + ");";
1095 out = captureOutput("maxima", to_utf8(full));
1097 // leave loop if expression syntax is probably ok
1098 if (out.find("Incorrect syntax") == npos)
1101 // search line with "Incorrect syntax"
1102 istringstream is(out);
1106 if (line.find("Incorrect syntax") != npos)
1110 // 2nd next line is the one with caret
1113 size_t pos = line.find('^');
1114 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1115 if (pos == npos || pos < 4)
1116 break; // caret position not found
1117 pos -= 4; // skip the "tex(" part
1118 if (expr[pos] == '*')
1119 break; // two '*' in a row are definitely bad
1120 expr.insert(pos, from_ascii("*"));
1123 vector<string> tmp = getVectorFromString(out, "$$");
1127 out = subst(tmp[1], "\\>", string());
1128 lyxerr << "output: '" << out << "'" << endl;
1130 // Ugly code that tries to make the result prettier
1131 size_t i = out.find("\\mathchoice");
1133 size_t j = get_matching_brace(out, i + 12);
1134 size_t k = get_matching_brace(out, j + 1);
1135 k = get_matching_brace(out, k + 1);
1136 k = get_matching_brace(out, k + 1);
1137 string mid = out.substr(i + 13, j - i - 13);
1138 if (mid.find("\\over") != npos)
1139 mid = '{' + mid + '}';
1140 out = out.substr(0,i)
1142 + out.substr(k + 1);
1143 //lyxerr << "output: " << out << endl;
1144 i = out.find("\\mathchoice", i);
1148 i = out.find("\\over");
1150 size_t j = get_matching_brace_back(out, i - 1);
1151 if (j == npos || j == 0)
1153 size_t k = get_matching_brace(out, i + 5);
1154 if (k == npos || k + 1 == out.size())
1156 out = out.substr(0,j - 1)
1158 + out.substr(j,i - j)
1159 + out.substr(i + 5,k - i - 4)
1160 + out.substr(k + 2);
1161 //lyxerr << "output: " << out << endl;
1162 i = out.find("\\over", i + 4);
1165 mathed_parse_cell(res, from_utf8(out));
1170 MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1172 string header = "readlib(latex):\n";
1174 // remove the \\it for variable names
1175 //"#`latex/csname_font` := `\\it `:"
1177 "`latex/csname_font` := ``:\n";
1179 // export matrices in (...) instead of [...]
1181 "`latex/latex/matrix` := "
1182 "subs(`[`=`(`, `]`=`)`,"
1183 "eval(`latex/latex/matrix`)):\n";
1185 // replace \\cdots with proper '*'
1187 "`latex/latex/*` := "
1188 "subs(`\\,`=`\\cdot `,"
1189 "eval(`latex/latex/*`)):\n";
1191 // remove spurious \\noalign{\\medskip} in matrix output
1193 "`latex/latex/matrix`:= "
1194 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1195 "eval(`latex/latex/matrix`)):\n";
1197 //"#`latex/latex/symbol` "
1198 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1200 string trailer = "quit;";
1201 odocstringstream os;
1204 string expr = to_utf8(os.str());
1205 lyxerr << "ar: '" << ar << "'\n"
1206 << "ms: '" << expr << "'" << endl;
1208 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1209 // try to fix missing '*' the hard way by using mint
1211 // ... > echo "1A;" | mint -i 1 -S -s -q
1214 // Probably missing an operator such as * p
1216 lyxerr << "checking expr: '" << expr << "'" << endl;
1217 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1219 break; // expression syntax is ok
1220 istringstream is(out);
1223 if (line.find("on line") != 0)
1224 break; // error message not identified
1226 size_t pos = line.find('^');
1227 if (pos == string::npos || pos < 15)
1228 break; // caret position not found
1229 pos -= 15; // skip the "on line ..." part
1230 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1231 break; // two '*' in a row are definitely bad
1232 expr.insert(pos, 1, '*');
1235 // FIXME UNICODE Is utf8 encoding correct?
1236 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1237 string out = captureOutput("maple -q", header + full + trailer);
1243 mathed_parse_cell(res, from_utf8(out));
1248 MathData pipeThroughOctave(docstring const &, MathData const & ar)
1250 odocstringstream os;
1251 OctaveStream vs(os);
1253 string expr = to_utf8(os.str());
1256 lyxerr << "pipe: ar: '" << ar << "'\n"
1257 << "pipe: expr: '" << expr << "'" << endl;
1259 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1261 // try to fix missing '*' the hard way
1263 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1266 lyxerr << "checking expr: '" << expr << "'" << endl;
1267 out = captureOutput("octave -q 2>&1", expr);
1268 lyxerr << "output: '" << out << "'" << endl;
1270 // leave loop if expression syntax is probably ok
1271 if (out.find("parse error:") == string::npos)
1274 // search line with single caret
1275 istringstream is(out);
1279 lyxerr << "skipping line: '" << line << "'" << endl;
1280 if (line.find(">>> ") != string::npos)
1284 // found line with error, next line is the one with caret
1286 size_t pos = line.find('^');
1287 lyxerr << "caret line: '" << line << "'" << endl;
1288 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1289 if (pos == string::npos || pos < 4)
1290 break; // caret position not found
1291 pos -= 4; // skip the ">>> " part
1292 if (expr[pos] == '*')
1293 break; // two '*' in a row are definitely bad
1294 expr.insert(pos, 1, '*');
1297 // remove 'ans = ' taking into account that there may be an
1298 // ansi control sequence before, such as '\033[?1034hans = '
1299 size_t i = out.find("ans = ");
1300 if (i == string::npos)
1302 out = out.substr(i + 6);
1304 // parse output as matrix or single number
1305 MathAtom at(new InsetMathArray(from_ascii("array"), from_utf8(out)));
1306 InsetMathArray const * mat = at->asArrayInset();
1308 if (mat->ncols() == 1 && mat->nrows() == 1)
1309 res.append(mat->cell(0));
1311 res.push_back(MathAtom(new InsetMathDelim(from_ascii("("), from_ascii(")"))));
1312 res.back().nucleus()->cell(0).push_back(at);
1318 string fromMathematicaName(string const & name)
1320 if (name == "Sin") return "sin";
1321 if (name == "Sinh") return "sinh";
1322 if (name == "ArcSin") return "arcsin";
1323 if (name == "Cos") return "cos";
1324 if (name == "Cosh") return "cosh";
1325 if (name == "ArcCos") return "arccos";
1326 if (name == "Tan") return "tan";
1327 if (name == "Tanh") return "tanh";
1328 if (name == "ArcTan") return "arctan";
1329 if (name == "Cot") return "cot";
1330 if (name == "Coth") return "coth";
1331 if (name == "Csc") return "csc";
1332 if (name == "Sec") return "sec";
1333 if (name == "Exp") return "exp";
1334 if (name == "Log") return "log";
1335 if (name == "Arg" ) return "arg";
1336 if (name == "Det" ) return "det";
1337 if (name == "GCD" ) return "gcd";
1338 if (name == "Max" ) return "max";
1339 if (name == "Min" ) return "min";
1340 if (name == "Erf" ) return "erf";
1341 if (name == "Erfc" ) return "erfc";
1346 void prettifyMathematicaOutput(string & out, string const & macroName,
1347 bool roman, bool translate)
1349 string const macro = "\\" + macroName + "{";
1350 size_t const len = macro.length();
1351 size_t i = out.find(macro);
1354 size_t const j = get_matching_brace(out, i + len);
1355 string const name = out.substr(i + len, j - i - len);
1356 out = out.substr(0, i)
1357 + (roman ? "\\mathrm{" : "")
1358 + (translate ? fromMathematicaName(name) : name)
1359 + out.substr(roman ? j : j + 1);
1360 //lyxerr << "output: " << out << endl;
1361 i = out.find(macro, i);
1366 MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1368 odocstringstream os;
1369 MathematicaStream ms(os);
1371 // FIXME UNICODE Is utf8 encoding correct?
1372 string const expr = to_utf8(os.str());
1375 lyxerr << "expr: '" << expr << "'" << endl;
1377 string const full = "TeXForm[" + expr + "]";
1378 out = captureOutput("math", full);
1379 lyxerr << "output: '" << out << "'" << endl;
1381 size_t pos1 = out.find("Out[1]//TeXForm= ");
1382 size_t pos2 = out.find("In[2]:=");
1384 if (pos1 == string::npos || pos2 == string::npos)
1387 // get everything from pos1+17 to pos2
1388 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1389 out = subst(subst(out, '\r', ' '), '\n', ' ');
1391 // tries to make the result prettier
1392 prettifyMathematicaOutput(out, "Mfunction", true, true);
1393 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1394 prettifyMathematicaOutput(out, "Mvariable", false, false);
1397 mathed_parse_cell(res, from_utf8(out));
1404 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1405 MathData const & ar)
1407 if (lang == "octave")
1408 return pipeThroughOctave(extra, ar);
1410 if (lang == "maxima")
1411 return pipeThroughMaxima(extra, ar);
1413 if (lang == "maple")
1414 return pipeThroughMaple(extra, ar);
1416 if (lang == "mathematica")
1417 return pipeThroughMathematica(extra, ar);
1419 // create normalized expression
1420 odocstringstream os;
1421 NormalStream ns(os);
1422 os << '[' << extra << ' ';
1425 // FIXME UNICODE Is utf8 encoding correct?
1426 string data = to_utf8(os.str());
1428 // search external script
1429 FileName const file = libFileSearch("mathed", "extern_" + lang);
1431 lyxerr << "converter to '" << lang << "' not found" << endl;
1435 // run external sript
1436 string out = captureOutput(file.absFilename(), data);
1438 mathed_parse_cell(res, from_utf8(out));