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"
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"
41 #include "support/lyxlib.h"
50 using support::cmd_ret;
51 using support::getVectorFromString;
52 using support::libFileSearch;
53 using support::runCommand;
54 using support::FileName;
55 using support::quoteName;
56 using support::tempName;
57 using support::unlink;
63 using std::istringstream;
69 static char const * function_names[] = {
70 "arccos", "arcsin", "arctan", "arg", "bmod",
71 "cos", "cosh", "cot", "coth", "csc", "deg",
72 "det", "dim", "exp", "gcd", "hom", "inf", "ker",
73 "lg", "lim", "liminf", "limsup", "ln", "log",
74 "max", "min", "sec", "sin", "sinh", "sup",
75 "tan", "tanh", "Pr", 0
78 static size_t const npos = lyx::docstring::npos;
80 // define a function for tests
81 typedef bool TestItemFunc(MathAtom const &);
83 // define a function for replacing subexpressions
84 typedef MathAtom ReplaceArgumentFunc(const MathData & ar);
88 // try to extract a super/subscript
89 // modify iterator position to point behind the thing
90 bool extractScript(MathData & ar,
91 MathData::iterator & pos, MathData::iterator last, bool superscript)
93 // nothing to get here
97 // is this a scriptinset?
98 if (!(*pos)->asScriptInset())
101 // do we want superscripts only?
102 if (superscript && !(*pos)->asScriptInset()->hasUp())
105 // it is a scriptinset, use it.
112 // try to extract an "argument" to some function.
113 // returns position behind the argument
114 MathData::iterator extractArgument(MathData & ar,
115 MathData::iterator pos, MathData::iterator last, bool function = false)
117 // nothing to get here
121 // something delimited _is_ an argument
122 if ((*pos)->asDelimInset()) {
123 // leave out delimiters if this is a function argument
125 MathData const & arg = (*pos)->asDelimInset()->cell(0);
126 MathData::const_iterator cur = arg.begin();
127 MathData::const_iterator end = arg.end();
129 ar.push_back(*cur++);
135 // if there's one, get following superscript only if this
136 // isn't a function argument
138 extractScript(ar, pos, last, true);
142 // always take the first thing, no matter what it is
145 // go ahead if possible
150 // if the next item is a super/subscript, it most certainly belongs
151 // to the thing we have
152 extractScript(ar, pos, last, false);
156 // but it might be more than that.
157 // FIXME: not implemented
158 //for (MathData::iterator it = pos + 1; it != last; ++it) {
159 // // always take the first thing, no matter
161 // ar.push_back(*it);
169 // returns sequence of char with same code starting at it up to end
170 // it might be less, though...
171 docstring charSequence
172 (MathData::const_iterator it, MathData::const_iterator end)
175 for (; it != end && (*it)->asCharInset(); ++it)
176 s += (*it)->getChar();
181 void extractStrings(MathData & ar)
183 //lyxerr << "\nStrings from: " << ar << endl;
184 for (size_t i = 0; i < ar.size(); ++i) {
185 if (!ar[i]->asCharInset())
187 docstring s = charSequence(ar.begin() + i, ar.end());
188 ar[i] = MathAtom(new InsetMathString(s));
189 ar.erase(i + 1, i + s.size());
191 //lyxerr << "\nStrings to: " << ar << endl;
195 void extractMatrices(MathData & ar)
197 //lyxerr << "\nMatrices from: " << ar << endl;
198 // first pass for explicitly delimited stuff
199 for (size_t i = 0; i < ar.size(); ++i) {
200 if (!ar[i]->asDelimInset())
202 MathData const & arr = ar[i]->asDelimInset()->cell(0);
205 if (!arr.front()->asGridInset())
207 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset())));
210 // second pass for AMS "pmatrix" etc
211 for (size_t i = 0; i < ar.size(); ++i)
212 if (ar[i]->asAMSArrayInset())
213 ar[i] = MathAtom(new InsetMathMatrix(*(ar[i]->asGridInset())));
214 //lyxerr << "\nMatrices to: " << ar << endl;
218 // convert this inset somehow to a string
219 bool extractString(MathAtom const & at, docstring & str)
222 str = docstring(1, at->getChar());
225 if (at->asStringInset()) {
226 str = at->asStringInset()->str();
233 // is this a known function?
234 bool isKnownFunction(docstring const & str)
236 for (int i = 0; function_names[i]; ++i) {
237 if (str == function_names[i])
244 // extract a function name from this inset
245 bool extractFunctionName(MathAtom const & at, docstring & str)
247 if (at->asSymbolInset()) {
248 str = at->asSymbolInset()->name();
249 return isKnownFunction(str);
251 if (at->asUnknownInset()) {
252 // assume it is well known...
256 if (at->asFontInset() && at->name() == "mathrm") {
257 // assume it is well known...
258 MathData const & ar = at->asFontInset()->cell(0);
259 str = charSequence(ar.begin(), ar.end());
260 return ar.size() == str.size();
266 // convert this inset somehow to a number
267 bool extractNumber(MathData const & ar, int & i)
269 idocstringstream is(charSequence(ar.begin(), ar.end()));
275 bool extractNumber(MathData const & ar, double & d)
277 idocstringstream is(charSequence(ar.begin(), ar.end()));
283 bool testString(MathAtom const & at, docstring const & str)
286 return extractString(at, s) && str == s;
290 bool testString(MathAtom const & at, char const * const str)
292 return testString(at, from_ascii(str));
295 // search end of nested sequence
296 MathData::iterator endNestSearch(
297 MathData::iterator it,
298 MathData::iterator last,
299 TestItemFunc testOpen,
300 TestItemFunc testClose
303 for (int level = 0; it != last; ++it) {
315 // replace nested sequences by a real Insets
318 TestItemFunc testOpen,
319 TestItemFunc testClose,
320 ReplaceArgumentFunc replaceArg
323 // use indices rather than iterators for the loop because we are going
324 // to modify the array.
325 for (size_t i = 0; i < ar.size(); ++i) {
326 // check whether this is the begin of the sequence
327 if (!testOpen(ar[i]))
330 // search end of sequence
331 MathData::iterator it = ar.begin() + i;
332 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
336 // replace the original stuff by the new inset
337 ar[i] = replaceArg(MathData(it + 1, jt));
338 ar.erase(it + 1, jt + 1);
345 // split scripts into seperate super- and subscript insets. sub goes in
349 void splitScripts(MathData & ar)
351 //lyxerr << "\nScripts from: " << ar << endl;
352 for (size_t i = 0; i < ar.size(); ++i) {
353 InsetMathScript const * script = ar[i]->asScriptInset();
355 // is this a script inset and do we also have a superscript?
356 if (!script || !script->hasUp())
359 // we must have a nucleus if we only have a superscript
360 if (!script->hasDown() && script->nuc().size() == 0)
363 if (script->nuc().size() == 1) {
364 // leave alone sums and integrals
365 InsetMathSymbol const * sym =
366 script->nuc().front()->asSymbolInset();
367 if (sym && (sym->name() == "sum" || sym->name() == "int"))
371 // create extra script inset and move superscript over
372 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
373 std::auto_ptr<InsetMathScript> q(new InsetMathScript(true));
374 swap(q->up(), p->up());
375 p->removeScript(true);
377 // if we don't have a subscript, get rid of the ScriptInset
378 if (!script->hasDown()) {
379 MathData arg(p->nuc());
380 MathData::const_iterator it = arg.begin();
381 MathData::const_iterator et = arg.end();
384 ar.insert(i++, *it++);
388 // insert new inset behind
389 ar.insert(i, MathAtom(q.release()));
391 //lyxerr << "\nScripts to: " << ar << endl;
399 void extractExps(MathData & ar)
401 //lyxerr << "\nExps from: " << ar << endl;
402 for (size_t i = 0; i + 1 < ar.size(); ++i) {
404 if (ar[i]->getChar() != 'e')
407 // we need an exponent but no subscript
408 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
409 if (!sup || sup->hasDown())
412 // create a proper exp-inset as replacement
413 ar[i] = MathAtom(new InsetMathExFunc(from_ascii("exp"), sup->cell(1)));
416 //lyxerr << "\nExps to: " << ar << endl;
421 // extract det(...) from |matrix|
423 void extractDets(MathData & ar)
425 //lyxerr << "\ndet from: " << ar << endl;
426 for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
427 InsetMathDelim const * del = (*it)->asDelimInset();
432 *it = MathAtom(new InsetMathExFunc(from_ascii("det"), del->cell(0)));
434 //lyxerr << "\ndet to: " << ar << endl;
442 bool isDigitOrSimilar(char_type c)
444 return ('0' <= c && c <= '9') || c == '.';
448 // returns sequence of digits
449 docstring digitSequence
450 (MathData::const_iterator it, MathData::const_iterator end)
453 for (; it != end && (*it)->asCharInset(); ++it) {
454 if (!isDigitOrSimilar((*it)->getChar()))
456 s += (*it)->getChar();
462 void extractNumbers(MathData & ar)
464 //lyxerr << "\nNumbers from: " << ar << endl;
465 for (size_t i = 0; i < ar.size(); ++i) {
466 if (!ar[i]->asCharInset())
468 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
471 docstring s = digitSequence(ar.begin() + i, ar.end());
473 ar[i] = MathAtom(new InsetMathNumber(s));
474 ar.erase(i + 1, i + s.size());
476 //lyxerr << "\nNumbers to: " << ar << endl;
485 bool testOpenParen(MathAtom const & at)
487 return testString(at, "(");
491 bool testCloseParen(MathAtom const & at)
493 return testString(at, ")");
497 MathAtom replaceParenDelims(const MathData & ar)
499 return MathAtom(new InsetMathDelim(from_ascii("("), from_ascii(")"), ar));
503 bool testOpenBracket(MathAtom const & at)
505 return testString(at, "[");
509 bool testCloseBracket(MathAtom const & at)
511 return testString(at, "]");
515 MathAtom replaceBracketDelims(const MathData & ar)
517 return MathAtom(new InsetMathDelim(from_ascii("["), from_ascii("]"), ar));
521 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
522 void extractDelims(MathData & ar)
524 //lyxerr << "\nDelims from: " << ar << endl;
525 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
526 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
527 //lyxerr << "\nDelims to: " << ar << endl;
533 // search well-known functions
537 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
538 // assume 'extractDelims' ran before
539 void extractFunctions(MathData & ar)
541 // we need at least two items...
545 //lyxerr << "\nFunctions from: " << ar << endl;
546 for (size_t i = 0; i + 1 < ar.size(); ++i) {
547 MathData::iterator it = ar.begin() + i;
548 MathData::iterator jt = it + 1;
552 // it certainly is if it is well known...
553 if (!extractFunctionName(*it, name)) {
554 // is this a user defined function?
555 // it it probably not, if it doesn't have a name.
556 if (!extractString(*it, name))
558 // it is not if it has no argument
561 // guess so, if this is followed by
562 // a DelimInset with a single item in the cell
563 InsetMathDelim const * del = (*jt)->asDelimInset();
564 if (!del || del->cell(0).size() != 1)
566 // fall trough into main branch
569 // do we have an exponent like in
570 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
572 extractScript(exp, jt, ar.end(), true);
574 // create a proper inset as replacement
575 std::auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(name));
577 // jt points to the "argument". Get hold of this.
578 MathData::iterator st = extractArgument(p->cell(0), jt, ar.end(), true);
580 // replace the function name by a real function inset
581 *it = MathAtom(p.release());
583 // remove the source of the argument from the array
584 ar.erase(it + 1, st);
586 // re-insert exponent
587 ar.insert(i + 1, exp);
588 //lyxerr << "\nFunctions to: " << ar << endl;
597 bool testSymbol(MathAtom const & at, docstring const & name)
599 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
603 bool testSymbol(MathAtom const & at, char const * const name)
605 return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
609 bool testIntSymbol(MathAtom const & at)
611 return testSymbol(at, from_ascii("int"));
615 bool testIntegral(MathAtom const & at)
619 ( at->asScriptInset()
620 && at->asScriptInset()->nuc().size()
621 && testIntSymbol(at->asScriptInset()->nuc().back()) );
626 bool testIntDiff(MathAtom const & at)
628 return testString(at, "d");
632 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
633 // assume 'extractDelims' ran before
634 void extractIntegrals(MathData & ar)
636 // we need at least three items...
640 //lyxerr << "\nIntegrals from: " << ar << endl;
641 for (size_t i = 0; i + 1 < ar.size(); ++i) {
642 MathData::iterator it = ar.begin() + i;
645 MathData::iterator jt =
646 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
648 // something sensible found?
652 // is this a integral name?
653 if (!testIntegral(*it))
656 // core ist part from behind the scripts to the 'd'
657 auto_ptr<InsetMathExInt> p(new InsetMathExInt(from_ascii("int")));
659 // handle scripts if available
660 if (!testIntSymbol(*it)) {
661 p->cell(2) = (*it)->asScriptInset()->down();
662 p->cell(3) = (*it)->asScriptInset()->up();
664 p->cell(0) = MathData(it + 1, jt);
666 // use the "thing" behind the 'd' as differential
667 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
670 ar.erase(it + 1, tt);
671 *it = MathAtom(p.release());
673 //lyxerr << "\nIntegrals to: " << ar << endl;
677 bool testTermDelimiter(MathAtom const & at)
679 return testString(at, "+") || testString(at, "-");
683 // try to extract a "term", i.e., something delimited by '+' or '-'.
684 // returns position behind the term
685 MathData::iterator extractTerm(MathData & ar,
686 MathData::iterator pos, MathData::iterator last)
688 while (pos != last && !testTermDelimiter(*pos)) {
701 bool testEqualSign(MathAtom const & at)
703 return testString(at, "=");
707 bool testSumSymbol(MathAtom const & p)
709 return testSymbol(p, from_ascii("sum"));
713 bool testSum(MathAtom const & at)
717 ( at->asScriptInset()
718 && at->asScriptInset()->nuc().size()
719 && testSumSymbol(at->asScriptInset()->nuc().back()) );
723 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
724 // assume 'extractDelims' ran before
725 void extractSums(MathData & ar)
727 // we need at least two items...
731 //lyxerr << "\nSums from: " << ar << endl;
732 for (size_t i = 0; i + 1 < ar.size(); ++i) {
733 MathData::iterator it = ar.begin() + i;
735 // is this a sum name?
739 // create a proper inset as replacement
740 auto_ptr<InsetMathExInt> p(new InsetMathExInt(from_ascii("sum")));
742 // collect lower bound and summation index
743 InsetMathScript const * sub = ar[i]->asScriptInset();
744 if (sub && sub->hasDown()) {
745 // try to figure out the summation index from the subscript
746 MathData const & ar = sub->down();
747 MathData::const_iterator xt =
748 find_if(ar.begin(), ar.end(), &testEqualSign);
749 if (xt != ar.end()) {
750 // we found a '=', use everything in front of that as index,
751 // and everything behind as lower index
752 p->cell(1) = MathData(ar.begin(), xt);
753 p->cell(2) = MathData(xt + 1, ar.end());
755 // use everything as summation index, don't use scripts.
760 // collect upper bound
761 if (sub && sub->hasUp())
762 p->cell(3) = sub->up();
764 // use something behind the script as core
765 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
768 ar.erase(it + 1, tt);
769 *it = MathAtom(p.release());
771 //lyxerr << "\nSums to: " << ar << endl;
776 // search differential stuff
779 // tests for 'd' or '\partial'
780 bool testDiffItem(MathAtom const & at)
782 if (testString(at, "d") || testSymbol(at, "partial"))
785 // we may have d^n .../d and splitScripts() has not yet seen it
786 InsetMathScript const * sup = at->asScriptInset();
787 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
788 MathAtom const & ma = sup->nuc().front();
789 return testString(ma, "d") || testSymbol(ma, "partial");
795 bool testDiffArray(MathData const & ar)
797 return ar.size() && testDiffItem(ar.front());
801 bool testDiffFrac(MathAtom const & at)
805 && testDiffArray(at->asFracInset()->cell(0))
806 && testDiffArray(at->asFracInset()->cell(1));
810 void extractDiff(MathData & ar)
812 //lyxerr << "\nDiffs from: " << ar << endl;
813 for (size_t i = 0; i < ar.size(); ++i) {
814 MathData::iterator it = ar.begin() + i;
816 // is this a "differential fraction"?
817 if (!testDiffFrac(*it))
820 InsetMathFrac const * f = (*it)->asFracInset();
822 lyxerr << "should not happen" << endl;
826 // create a proper diff inset
827 std::auto_ptr<InsetMathDiff> diff(new InsetMathDiff);
829 // collect function, let jt point behind last used item
830 MathData::iterator jt = it + 1;
832 MathData numer(f->cell(0));
834 if (numer.size() > 1 && numer[1]->asScriptInset()) {
835 // this is something like d^n f(x) / d... or d^n / d...
838 if (numer.size() > 2)
839 diff->cell(0) = MathData(numer.begin() + 2, numer.end());
841 jt = extractTerm(diff->cell(0), jt, ar.end());
843 // simply d f(x) / d... or d/d...
844 if (numer.size() > 1)
845 diff->cell(0) = MathData(numer.begin() + 1, numer.end());
847 jt = extractTerm(diff->cell(0), jt, ar.end());
850 // collect denominator parts
851 MathData denom(f->cell(1));
853 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
855 MathData::iterator et
856 = find_if(dt + 1, denom.end(), &testDiffItem);
859 MathData::iterator st = et - 1;
860 InsetMathScript const * script = (*st)->asScriptInset();
861 if (script && script->hasUp()) {
862 // things like d.../dx^n
864 if (extractNumber(script->up(), mult)) {
865 //lyxerr << "mult: " << mult << endl;
866 for (int i = 0; i < mult; ++i)
867 diff->addDer(MathData(dt + 1, st));
871 diff->addDer(MathData(dt + 1, et));
877 ar.erase(it + 1, jt);
878 *it = MathAtom(diff.release());
880 //lyxerr << "\nDiffs to: " << ar << endl;
889 bool testRightArrow(MathAtom const & at)
891 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
896 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
897 // assume 'extractDelims' ran before
898 void extractLims(MathData & ar)
900 //lyxerr << "\nLimits from: " << ar << endl;
901 for (size_t i = 0; i < ar.size(); ++i) {
902 MathData::iterator it = ar.begin() + i;
904 // must be a script inset with a subscript (without superscript)
905 InsetMathScript const * sub = (*it)->asScriptInset();
906 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
909 // is this a limit function?
910 if (!testSymbol(sub->nuc().front(), "lim"))
913 // subscript must contain a -> symbol
914 MathData const & s = sub->down();
915 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
919 // the -> splits the subscript int x and x0
920 MathData x = MathData(s.begin(), st);
921 MathData x0 = MathData(st + 1, s.end());
923 // use something behind the script as core
925 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
928 ar.erase(it + 1, tt);
930 // create a proper inset as replacement
931 *it = MathAtom(new InsetMathLim(f, x, x0));
933 //lyxerr << "\nLimits to: " << ar << endl;
941 void extractStructure(MathData & ar)
943 //lyxerr << "\nStructure from: " << ar << endl;
946 extractIntegrals(ar);
950 extractFunctions(ar);
956 //lyxerr << "\nStructure to: " << ar << endl;
960 void write(MathData const & dat, WriteStream & wi)
964 wi.firstitem() = true;
965 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it) {
967 wi.firstitem() = false;
972 void normalize(MathData const & ar, NormalStream & os)
974 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
975 (*it)->normalize(os);
979 void octave(MathData const & dat, OctaveStream & os)
982 extractStructure(ar);
983 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
988 void maple(MathData const & dat, MapleStream & os)
991 extractStructure(ar);
992 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
997 void maxima(MathData const & dat, MaximaStream & os)
1000 extractStructure(ar);
1001 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1006 void mathematica(MathData const & dat, MathematicaStream & os)
1009 extractStructure(ar);
1010 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1011 (*it)->mathematica(os);
1015 void mathmlize(MathData const & dat, MathStream & os)
1018 extractStructure(ar);
1021 else if (ar.size() == 1)
1025 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1026 (*it)->mathmlize(os);
1036 std::string captureOutput(std::string const & cmd, std::string const & data)
1038 // In order to avoid parsing problems with command interpreters
1039 // we pass input data through a file
1040 FileName const cas_tmpfile(tempName(FileName(), "casinput"));
1041 if (cas_tmpfile.empty()) {
1042 lyxerr << "Warning: cannot create temporary file."
1044 return std::string();
1046 std::ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
1049 std::string command = cmd + " < "
1050 + quoteName(cas_tmpfile.toFilesystemEncoding());
1051 lyxerr << "calling: " << cmd
1052 << "\ninput: '" << data << "'" << endl;
1053 cmd_ret const ret = runCommand(command);
1054 unlink(cas_tmpfile);
1058 size_t get_matching_brace(std::string const & str, size_t i)
1061 size_t n = str.size();
1063 i = str.find_first_of("{}", i+1);
1076 size_t get_matching_brace_back(std::string const & str, size_t i)
1080 i = str.find_last_of("{}", i-1);
1093 MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1095 odocstringstream os;
1096 MaximaStream ms(os);
1098 docstring expr = os.str();
1099 docstring const header = from_ascii("simpsum:true;");
1102 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1103 // try to fix missing '*' the hard way
1105 // > echo "2x;" | maxima
1107 // (C1) Incorrect syntax: x is not an infix operator
1111 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1112 docstring full = header + "tex(" + expr + ");";
1113 out = captureOutput("maxima", to_utf8(full));
1115 // leave loop if expression syntax is probably ok
1116 if (out.find("Incorrect syntax") == npos)
1119 // search line with "Incorrect syntax"
1120 istringstream is(out);
1124 if (line.find("Incorrect syntax") != npos)
1128 // 2nd next line is the one with caret
1131 size_t pos = line.find('^');
1132 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1133 if (pos == npos || pos < 4)
1134 break; // caret position not found
1135 pos -= 4; // skip the "tex(" part
1136 if (expr[pos] == '*')
1137 break; // two '*' in a row are definitely bad
1138 expr.insert(pos, from_ascii("*"));
1141 vector<std::string> tmp = getVectorFromString(out, "$$");
1145 out = subst(tmp[1], "\\>", std::string());
1146 lyxerr << "output: '" << out << "'" << endl;
1148 // Ugly code that tries to make the result prettier
1149 size_t i = out.find("\\mathchoice");
1151 size_t j = get_matching_brace(out, i + 12);
1152 size_t k = get_matching_brace(out, j + 1);
1153 k = get_matching_brace(out, k + 1);
1154 k = get_matching_brace(out, k + 1);
1155 std::string mid = out.substr(i + 13, j - i - 13);
1156 if (mid.find("\\over") != npos)
1157 mid = '{' + mid + '}';
1158 out = out.substr(0,i)
1160 + out.substr(k + 1);
1161 //lyxerr << "output: " << out << endl;
1162 i = out.find("\\mathchoice", i);
1166 i = out.find("\\over");
1168 size_t j = get_matching_brace_back(out, i - 1);
1169 if (j == npos || j == 0)
1171 size_t k = get_matching_brace(out, i + 5);
1172 if (k == npos || k + 1 == out.size())
1174 out = out.substr(0,j - 1)
1176 + out.substr(j,i - j)
1177 + out.substr(i + 5,k - i - 4)
1178 + out.substr(k + 2);
1179 //lyxerr << "output: " << out << endl;
1180 i = out.find("\\over", i + 4);
1183 mathed_parse_cell(res, from_utf8(out));
1188 MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1190 std::string header = "readlib(latex):\n";
1192 // remove the \\it for variable names
1193 //"#`latex/csname_font` := `\\it `:"
1195 "`latex/csname_font` := ``:\n";
1197 // export matrices in (...) instead of [...]
1199 "`latex/latex/matrix` := "
1200 "subs(`[`=`(`, `]`=`)`,"
1201 "eval(`latex/latex/matrix`)):\n";
1203 // replace \\cdots with proper '*'
1205 "`latex/latex/*` := "
1206 "subs(`\\,`=`\\cdot `,"
1207 "eval(`latex/latex/*`)):\n";
1209 // remove spurious \\noalign{\\medskip} in matrix output
1211 "`latex/latex/matrix`:= "
1212 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1213 "eval(`latex/latex/matrix`)):\n";
1215 //"#`latex/latex/symbol` "
1216 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1218 std::string trailer = "quit;";
1219 odocstringstream os;
1222 std::string expr = to_utf8(os.str());
1223 lyxerr << "ar: '" << ar << "'\n"
1224 << "ms: '" << expr << "'" << endl;
1226 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1227 // try to fix missing '*' the hard way by using mint
1229 // ... > echo "1A;" | mint -i 1 -S -s -q
1232 // Probably missing an operator such as * p
1234 lyxerr << "checking expr: '" << expr << "'" << endl;
1235 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1237 break; // expression syntax is ok
1238 istringstream is(out);
1241 if (line.find("on line") != 0)
1242 break; // error message not identified
1244 size_t pos = line.find('^');
1245 if (pos == string::npos || pos < 15)
1246 break; // caret position not found
1247 pos -= 15; // skip the "on line ..." part
1248 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1249 break; // two '*' in a row are definitely bad
1250 expr.insert(pos, 1, '*');
1253 // FIXME UNICODE Is utf8 encoding correct?
1254 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1255 string out = captureOutput("maple -q", header + full + trailer);
1261 mathed_parse_cell(res, from_utf8(out));
1266 MathData pipeThroughOctave(docstring const &, MathData const & ar)
1268 odocstringstream os;
1269 OctaveStream vs(os);
1271 string expr = to_utf8(os.str());
1274 lyxerr << "pipe: ar: '" << ar << "'\n"
1275 << "pipe: expr: '" << expr << "'" << endl;
1277 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1279 // try to fix missing '*' the hard way
1281 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1284 lyxerr << "checking expr: '" << expr << "'" << endl;
1285 out = captureOutput("octave -q 2>&1", expr);
1286 lyxerr << "output: '" << out << "'" << endl;
1288 // leave loop if expression syntax is probably ok
1289 if (out.find("parse error:") == string::npos)
1292 // search line with single caret
1293 istringstream is(out);
1297 lyxerr << "skipping line: '" << line << "'" << endl;
1298 if (line.find(">>> ") != string::npos)
1302 // found line with error, next line is the one with caret
1304 size_t pos = line.find('^');
1305 lyxerr << "caret line: '" << line << "'" << endl;
1306 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1307 if (pos == string::npos || pos < 4)
1308 break; // caret position not found
1309 pos -= 4; // skip the ">>> " part
1310 if (expr[pos] == '*')
1311 break; // two '*' in a row are definitely bad
1312 expr.insert(pos, 1, '*');
1315 // remove 'ans = ' taking into account that there may be an
1316 // ansi control sequence before, such as '\033[?1034hans = '
1317 size_t i = out.find("ans = ");
1318 if (i == string::npos)
1320 out = out.substr(i + 6);
1322 // parse output as matrix or single number
1323 MathAtom at(new InsetMathArray(from_ascii("array"), from_utf8(out)));
1324 InsetMathArray const * mat = at->asArrayInset();
1326 if (mat->ncols() == 1 && mat->nrows() == 1)
1327 res.append(mat->cell(0));
1329 res.push_back(MathAtom(new InsetMathDelim(from_ascii("("), from_ascii(")"))));
1330 res.back().nucleus()->cell(0).push_back(at);
1336 string fromMathematicaName(string const & name)
1338 if (name == "Sin") return "sin";
1339 if (name == "Sinh") return "sinh";
1340 if (name == "ArcSin") return "arcsin";
1341 if (name == "Cos") return "cos";
1342 if (name == "Cosh") return "cosh";
1343 if (name == "ArcCos") return "arccos";
1344 if (name == "Tan") return "tan";
1345 if (name == "Tanh") return "tanh";
1346 if (name == "ArcTan") return "arctan";
1347 if (name == "Cot") return "cot";
1348 if (name == "Coth") return "coth";
1349 if (name == "Csc") return "csc";
1350 if (name == "Sec") return "sec";
1351 if (name == "Exp") return "exp";
1352 if (name == "Log") return "log";
1353 if (name == "Arg" ) return "arg";
1354 if (name == "Det" ) return "det";
1355 if (name == "GCD" ) return "gcd";
1356 if (name == "Max" ) return "max";
1357 if (name == "Min" ) return "min";
1358 if (name == "Erf" ) return "erf";
1359 if (name == "Erfc" ) return "erfc";
1364 void prettifyMathematicaOutput(string & out, string const & macroName,
1365 bool roman, bool translate)
1367 string const macro = "\\" + macroName + "{";
1368 size_t const len = macro.length();
1369 size_t i = out.find(macro);
1372 size_t const j = get_matching_brace(out, i + len);
1373 string const name = out.substr(i + len, j - i - len);
1374 out = out.substr(0, i)
1375 + (roman ? "\\mathrm{" : "")
1376 + (translate ? fromMathematicaName(name) : name)
1377 + out.substr(roman ? j : j + 1);
1378 //lyxerr << "output: " << out << endl;
1379 i = out.find(macro, i);
1384 MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1386 odocstringstream os;
1387 MathematicaStream ms(os);
1389 // FIXME UNICODE Is utf8 encoding correct?
1390 string const expr = to_utf8(os.str());
1393 lyxerr << "expr: '" << expr << "'" << endl;
1395 string const full = "TeXForm[" + expr + "]";
1396 out = captureOutput("math", full);
1397 lyxerr << "output: '" << out << "'" << endl;
1399 size_t pos1 = out.find("Out[1]//TeXForm= ");
1400 size_t pos2 = out.find("In[2]:=");
1402 if (pos1 == string::npos || pos2 == string::npos)
1405 // get everything from pos1+17 to pos2
1406 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1407 out = subst(subst(out, '\r', ' '), '\n', ' ');
1409 // tries to make the result prettier
1410 prettifyMathematicaOutput(out, "Mfunction", true, true);
1411 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1412 prettifyMathematicaOutput(out, "Mvariable", false, false);
1415 mathed_parse_cell(res, from_utf8(out));
1422 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1423 MathData const & ar)
1425 if (lang == "octave")
1426 return pipeThroughOctave(extra, ar);
1428 if (lang == "maxima")
1429 return pipeThroughMaxima(extra, ar);
1431 if (lang == "maple")
1432 return pipeThroughMaple(extra, ar);
1434 if (lang == "mathematica")
1435 return pipeThroughMathematica(extra, ar);
1437 // create normalized expression
1438 odocstringstream os;
1439 NormalStream ns(os);
1440 os << '[' << extra << ' ';
1443 // FIXME UNICODE Is utf8 encoding correct?
1444 string data = to_utf8(os.str());
1446 // search external script
1447 support::FileName const file = libFileSearch("mathed", "extern_" + lang);
1449 lyxerr << "converter to '" << lang << "' not found" << endl;
1453 // run external sript
1454 string out = captureOutput(file.absFilename(), data);
1456 mathed_parse_cell(res, from_utf8(out));