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 "MathStream.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 "support/lyxlib.h"
39 #include "frontends/controllers/ControlMath.h"
48 using support::cmd_ret;
49 using support::getVectorFromString;
50 using support::libFileSearch;
51 using support::runCommand;
52 using support::FileName;
53 using support::quoteName;
54 using support::tempName;
55 using support::unlink;
58 using frontend::function_names;
63 using std::istringstream;
69 static size_t const npos = lyx::docstring::npos;
71 // define a function for tests
72 typedef bool TestItemFunc(MathAtom const &);
74 // define a function for replacing subexpressions
75 typedef MathAtom ReplaceArgumentFunc(const MathArray & ar);
79 // try to extract a super/subscript
80 // modify iterator position to point behind the thing
81 bool extractScript(MathArray & ar,
82 MathArray::iterator & pos, MathArray::iterator last, bool superscript)
84 // nothing to get here
88 // is this a scriptinset?
89 if (!(*pos)->asScriptInset())
92 // do we want superscripts only?
93 if (superscript && !(*pos)->asScriptInset()->hasUp())
96 // it is a scriptinset, use it.
103 // try to extract an "argument" to some function.
104 // returns position behind the argument
105 MathArray::iterator extractArgument(MathArray & ar,
106 MathArray::iterator pos, MathArray::iterator last, bool function = false)
108 // nothing to get here
112 // something delimited _is_ an argument
113 if ((*pos)->asDelimInset()) {
114 // leave out delimiters if this is a function argument
116 MathArray const & arg = (*pos)->asDelimInset()->cell(0);
117 MathArray::const_iterator cur = arg.begin();
118 MathArray::const_iterator end = arg.end();
120 ar.push_back(*cur++);
126 // if there's one, get following superscript only if this
127 // isn't a function argument
129 extractScript(ar, pos, last, true);
133 // always take the first thing, no matter what it is
136 // go ahead if possible
141 // if the next item is a super/subscript, it most certainly belongs
142 // to the thing we have
143 extractScript(ar, pos, last, false);
147 // but it might be more than that.
148 // FIXME: not implemented
149 //for (MathArray::iterator it = pos + 1; it != last; ++it) {
150 // // always take the first thing, no matter
152 // ar.push_back(*it);
160 // returns sequence of char with same code starting at it up to end
161 // it might be less, though...
162 docstring charSequence
163 (MathArray::const_iterator it, MathArray::const_iterator end)
166 for (; it != end && (*it)->asCharInset(); ++it)
167 s += (*it)->getChar();
172 void extractStrings(MathArray & ar)
174 //lyxerr << "\nStrings from: " << ar << endl;
175 for (size_t i = 0; i < ar.size(); ++i) {
176 if (!ar[i]->asCharInset())
178 docstring s = charSequence(ar.begin() + i, ar.end());
179 ar[i] = MathAtom(new InsetMathString(s));
180 ar.erase(i + 1, i + s.size());
182 //lyxerr << "\nStrings to: " << ar << endl;
186 void extractMatrices(MathArray & ar)
188 //lyxerr << "\nMatrices from: " << ar << endl;
189 // first pass for explicitly delimited stuff
190 for (size_t i = 0; i < ar.size(); ++i) {
191 if (!ar[i]->asDelimInset())
193 MathArray const & arr = ar[i]->asDelimInset()->cell(0);
196 if (!arr.front()->asGridInset())
198 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset())));
201 // second pass for AMS "pmatrix" etc
202 for (size_t i = 0; i < ar.size(); ++i)
203 if (ar[i]->asAMSArrayInset())
204 ar[i] = MathAtom(new InsetMathMatrix(*(ar[i]->asGridInset())));
205 //lyxerr << "\nMatrices to: " << ar << endl;
209 // convert this inset somehow to a string
210 bool extractString(MathAtom const & at, docstring & str)
213 str = docstring(1, at->getChar());
216 if (at->asStringInset()) {
217 str = at->asStringInset()->str();
224 // is this a known function?
225 bool isKnownFunction(docstring const & str)
227 for (int i = 0; *function_names[i]; ++i) {
228 if (str == function_names[i])
235 // extract a function name from this inset
236 bool extractFunctionName(MathAtom const & at, docstring & str)
238 if (at->asSymbolInset()) {
239 str = at->asSymbolInset()->name();
240 return isKnownFunction(str);
242 if (at->asUnknownInset()) {
243 // assume it is well known...
247 if (at->asFontInset() && at->name() == "mathrm") {
248 // assume it is well known...
249 MathArray const & ar = at->asFontInset()->cell(0);
250 str = charSequence(ar.begin(), ar.end());
251 return ar.size() == str.size();
257 // convert this inset somehow to a number
258 bool extractNumber(MathArray const & ar, int & i)
260 idocstringstream is(charSequence(ar.begin(), ar.end()));
266 bool extractNumber(MathArray const & ar, double & d)
268 idocstringstream is(charSequence(ar.begin(), ar.end()));
274 bool testString(MathAtom const & at, docstring const & str)
277 return extractString(at, s) && str == s;
281 bool testString(MathAtom const & at, char const * const str)
283 return testString(at, from_ascii(str));
286 // search end of nested sequence
287 MathArray::iterator endNestSearch(
288 MathArray::iterator it,
289 MathArray::iterator last,
290 TestItemFunc testOpen,
291 TestItemFunc testClose
294 for (int level = 0; it != last; ++it) {
306 // replace nested sequences by a real Insets
309 TestItemFunc testOpen,
310 TestItemFunc testClose,
311 ReplaceArgumentFunc replaceArg
314 // use indices rather than iterators for the loop because we are going
315 // to modify the array.
316 for (size_t i = 0; i < ar.size(); ++i) {
317 // check whether this is the begin of the sequence
318 if (!testOpen(ar[i]))
321 // search end of sequence
322 MathArray::iterator it = ar.begin() + i;
323 MathArray::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
327 // replace the original stuff by the new inset
328 ar[i] = replaceArg(MathArray(it + 1, jt));
329 ar.erase(it + 1, jt + 1);
336 // split scripts into seperate super- and subscript insets. sub goes in
340 void splitScripts(MathArray & ar)
342 //lyxerr << "\nScripts from: " << ar << endl;
343 for (size_t i = 0; i < ar.size(); ++i) {
344 InsetMathScript const * script = ar[i]->asScriptInset();
346 // is this a script inset and do we also have a superscript?
347 if (!script || !script->hasUp())
350 // we must have a nucleus if we only have a superscript
351 if (!script->hasDown() && script->nuc().size() == 0)
354 if (script->nuc().size() == 1) {
355 // leave alone sums and integrals
356 InsetMathSymbol const * sym =
357 script->nuc().front()->asSymbolInset();
358 if (sym && (sym->name() == "sum" || sym->name() == "int"))
362 // create extra script inset and move superscript over
363 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
364 auto_ptr<InsetMathScript> q(new InsetMathScript(true));
365 swap(q->up(), p->up());
366 p->removeScript(true);
368 // if we don't have a subscript, get rid of the ScriptInset
369 if (!script->hasDown()) {
370 MathArray arg(p->nuc());
371 MathArray::const_iterator it = arg.begin();
372 MathArray::const_iterator et = arg.end();
375 ar.insert(i++, *it++);
379 // insert new inset behind
380 ar.insert(i, MathAtom(q.release()));
382 //lyxerr << "\nScripts to: " << ar << endl;
390 void extractExps(MathArray & ar)
392 //lyxerr << "\nExps from: " << ar << endl;
393 for (size_t i = 0; i + 1 < ar.size(); ++i) {
395 if (ar[i]->getChar() != 'e')
398 // we need an exponent but no subscript
399 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
400 if (!sup || sup->hasDown())
403 // create a proper exp-inset as replacement
404 ar[i] = MathAtom(new InsetMathExFunc(from_ascii("exp"), sup->cell(1)));
407 //lyxerr << "\nExps to: " << ar << endl;
412 // extract det(...) from |matrix|
414 void extractDets(MathArray & ar)
416 //lyxerr << "\ndet from: " << ar << endl;
417 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it) {
418 InsetMathDelim const * del = (*it)->asDelimInset();
423 *it = MathAtom(new InsetMathExFunc(from_ascii("det"), del->cell(0)));
425 //lyxerr << "\ndet to: " << ar << endl;
433 bool isDigitOrSimilar(char_type c)
435 return ('0' <= c && c <= '9') || c == '.';
439 // returns sequence of digits
440 docstring digitSequence
441 (MathArray::const_iterator it, MathArray::const_iterator end)
444 for (; it != end && (*it)->asCharInset(); ++it) {
445 if (!isDigitOrSimilar((*it)->getChar()))
447 s += (*it)->getChar();
453 void extractNumbers(MathArray & ar)
455 //lyxerr << "\nNumbers from: " << ar << endl;
456 for (size_t i = 0; i < ar.size(); ++i) {
457 if (!ar[i]->asCharInset())
459 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
462 docstring s = digitSequence(ar.begin() + i, ar.end());
464 ar[i] = MathAtom(new InsetMathNumber(s));
465 ar.erase(i + 1, i + s.size());
467 //lyxerr << "\nNumbers to: " << ar << endl;
476 bool testOpenParen(MathAtom const & at)
478 return testString(at, "(");
482 bool testCloseParen(MathAtom const & at)
484 return testString(at, ")");
488 MathAtom replaceParenDelims(const MathArray & ar)
490 return MathAtom(new InsetMathDelim(from_ascii("("), from_ascii(")"), ar));
494 bool testOpenBracket(MathAtom const & at)
496 return testString(at, "[");
500 bool testCloseBracket(MathAtom const & at)
502 return testString(at, "]");
506 MathAtom replaceBracketDelims(const MathArray & ar)
508 return MathAtom(new InsetMathDelim(from_ascii("["), from_ascii("]"), ar));
512 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
513 void extractDelims(MathArray & ar)
515 //lyxerr << "\nDelims from: " << ar << endl;
516 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
517 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
518 //lyxerr << "\nDelims to: " << ar << endl;
524 // search well-known functions
528 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
529 // assume 'extractDelims' ran before
530 void extractFunctions(MathArray & ar)
532 // we need at least two items...
536 //lyxerr << "\nFunctions from: " << ar << endl;
537 for (size_t i = 0; i + 1 < ar.size(); ++i) {
538 MathArray::iterator it = ar.begin() + i;
539 MathArray::iterator jt = it + 1;
543 // it certainly is if it is well known...
544 if (!extractFunctionName(*it, name)) {
545 // is this a user defined function?
546 // it it probably not, if it doesn't have a name.
547 if (!extractString(*it, name))
549 // it is not if it has no argument
552 // guess so, if this is followed by
553 // a DelimInset with a single item in the cell
554 InsetMathDelim const * del = (*jt)->asDelimInset();
555 if (!del || del->cell(0).size() != 1)
557 // fall trough into main branch
560 // do we have an exponent like in
561 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
563 extractScript(exp, jt, ar.end(), true);
565 // create a proper inset as replacement
566 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(name));
568 // jt points to the "argument". Get hold of this.
569 MathArray::iterator st = extractArgument(p->cell(0), jt, ar.end(), true);
571 // replace the function name by a real function inset
572 *it = MathAtom(p.release());
574 // remove the source of the argument from the array
575 ar.erase(it + 1, st);
577 // re-insert exponent
578 ar.insert(i + 1, exp);
579 //lyxerr << "\nFunctions to: " << ar << endl;
588 bool testSymbol(MathAtom const & at, docstring const & name)
590 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
594 bool testSymbol(MathAtom const & at, char const * const name)
596 return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
600 bool testIntSymbol(MathAtom const & at)
602 return testSymbol(at, from_ascii("int"));
606 bool testIntegral(MathAtom const & at)
610 ( at->asScriptInset()
611 && at->asScriptInset()->nuc().size()
612 && testIntSymbol(at->asScriptInset()->nuc().back()) );
617 bool testIntDiff(MathAtom const & at)
619 return testString(at, "d");
623 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
624 // assume 'extractDelims' ran before
625 void extractIntegrals(MathArray & ar)
627 // we need at least three items...
631 //lyxerr << "\nIntegrals from: " << ar << endl;
632 for (size_t i = 0; i + 1 < ar.size(); ++i) {
633 MathArray::iterator it = ar.begin() + i;
636 MathArray::iterator jt =
637 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
639 // something sensible found?
643 // is this a integral name?
644 if (!testIntegral(*it))
647 // core ist part from behind the scripts to the 'd'
648 auto_ptr<InsetMathExInt> p(new InsetMathExInt(from_ascii("int")));
650 // handle scripts if available
651 if (!testIntSymbol(*it)) {
652 p->cell(2) = (*it)->asScriptInset()->down();
653 p->cell(3) = (*it)->asScriptInset()->up();
655 p->cell(0) = MathArray(it + 1, jt);
657 // use the "thing" behind the 'd' as differential
658 MathArray::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end());
661 ar.erase(it + 1, tt);
662 *it = MathAtom(p.release());
664 //lyxerr << "\nIntegrals to: " << ar << endl;
668 bool testTermDelimiter(MathAtom const & at)
670 return testString(at, "+") || testString(at, "-");
674 // try to extract a "term", i.e., something delimited by '+' or '-'.
675 // returns position behind the term
676 MathArray::iterator extractTerm(MathArray & ar,
677 MathArray::iterator pos, MathArray::iterator last)
679 while (pos != last && !testTermDelimiter(*pos)) {
692 bool testEqualSign(MathAtom const & at)
694 return testString(at, "=");
698 bool testSumSymbol(MathAtom const & p)
700 return testSymbol(p, from_ascii("sum"));
704 bool testSum(MathAtom const & at)
708 ( at->asScriptInset()
709 && at->asScriptInset()->nuc().size()
710 && testSumSymbol(at->asScriptInset()->nuc().back()) );
714 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
715 // assume 'extractDelims' ran before
716 void extractSums(MathArray & ar)
718 // we need at least two items...
722 //lyxerr << "\nSums from: " << ar << endl;
723 for (size_t i = 0; i + 1 < ar.size(); ++i) {
724 MathArray::iterator it = ar.begin() + i;
726 // is this a sum name?
730 // create a proper inset as replacement
731 auto_ptr<InsetMathExInt> p(new InsetMathExInt(from_ascii("sum")));
733 // collect lower bound and summation index
734 InsetMathScript const * sub = ar[i]->asScriptInset();
735 if (sub && sub->hasDown()) {
736 // try to figure out the summation index from the subscript
737 MathArray const & ar = sub->down();
738 MathArray::const_iterator xt =
739 find_if(ar.begin(), ar.end(), &testEqualSign);
740 if (xt != ar.end()) {
741 // we found a '=', use everything in front of that as index,
742 // and everything behind as lower index
743 p->cell(1) = MathArray(ar.begin(), xt);
744 p->cell(2) = MathArray(xt + 1, ar.end());
746 // use everything as summation index, don't use scripts.
751 // collect upper bound
752 if (sub && sub->hasUp())
753 p->cell(3) = sub->up();
755 // use something behind the script as core
756 MathArray::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
759 ar.erase(it + 1, tt);
760 *it = MathAtom(p.release());
762 //lyxerr << "\nSums to: " << ar << endl;
767 // search differential stuff
770 // tests for 'd' or '\partial'
771 bool testDiffItem(MathAtom const & at)
773 if (testString(at, "d") || testSymbol(at, "partial"))
776 // we may have d^n .../d and splitScripts() has not yet seen it
777 InsetMathScript const * sup = at->asScriptInset();
778 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
779 MathAtom const & ma = sup->nuc().front();
780 return testString(ma, "d") || testSymbol(ma, "partial");
786 bool testDiffArray(MathArray const & ar)
788 return ar.size() && testDiffItem(ar.front());
792 bool testDiffFrac(MathAtom const & at)
796 && testDiffArray(at->asFracInset()->cell(0))
797 && testDiffArray(at->asFracInset()->cell(1));
801 void extractDiff(MathArray & ar)
803 //lyxerr << "\nDiffs from: " << ar << endl;
804 for (size_t i = 0; i < ar.size(); ++i) {
805 MathArray::iterator it = ar.begin() + i;
807 // is this a "differential fraction"?
808 if (!testDiffFrac(*it))
811 InsetMathFrac const * f = (*it)->asFracInset();
813 lyxerr << "should not happen" << endl;
817 // create a proper diff inset
818 auto_ptr<InsetMathDiff> diff(new InsetMathDiff);
820 // collect function, let jt point behind last used item
821 MathArray::iterator jt = it + 1;
823 MathArray numer(f->cell(0));
825 if (numer.size() > 1 && numer[1]->asScriptInset()) {
826 // this is something like d^n f(x) / d... or d^n / d...
829 if (numer.size() > 2)
830 diff->cell(0) = MathArray(numer.begin() + 2, numer.end());
832 jt = extractTerm(diff->cell(0), jt, ar.end());
834 // simply d f(x) / d... or d/d...
835 if (numer.size() > 1)
836 diff->cell(0) = MathArray(numer.begin() + 1, numer.end());
838 jt = extractTerm(diff->cell(0), jt, ar.end());
841 // collect denominator parts
842 MathArray denom(f->cell(1));
844 for (MathArray::iterator dt = denom.begin(); dt != denom.end();) {
846 MathArray::iterator et
847 = find_if(dt + 1, denom.end(), &testDiffItem);
850 MathArray::iterator st = et - 1;
851 InsetMathScript const * script = (*st)->asScriptInset();
852 if (script && script->hasUp()) {
853 // things like d.../dx^n
855 if (extractNumber(script->up(), mult)) {
856 //lyxerr << "mult: " << mult << endl;
857 for (int i = 0; i < mult; ++i)
858 diff->addDer(MathArray(dt + 1, st));
862 diff->addDer(MathArray(dt + 1, et));
868 ar.erase(it + 1, jt);
869 *it = MathAtom(diff.release());
871 //lyxerr << "\nDiffs to: " << ar << endl;
880 bool testRightArrow(MathAtom const & at)
882 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
887 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
888 // assume 'extractDelims' ran before
889 void extractLims(MathArray & ar)
891 //lyxerr << "\nLimits from: " << ar << endl;
892 for (size_t i = 0; i < ar.size(); ++i) {
893 MathArray::iterator it = ar.begin() + i;
895 // must be a script inset with a subscript (without superscript)
896 InsetMathScript const * sub = (*it)->asScriptInset();
897 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
900 // is this a limit function?
901 if (!testSymbol(sub->nuc().front(), "lim"))
904 // subscript must contain a -> symbol
905 MathArray const & s = sub->down();
906 MathArray::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
910 // the -> splits the subscript int x and x0
911 MathArray x = MathArray(s.begin(), st);
912 MathArray x0 = MathArray(st + 1, s.end());
914 // use something behind the script as core
916 MathArray::iterator tt = extractTerm(f, it + 1, ar.end());
919 ar.erase(it + 1, tt);
921 // create a proper inset as replacement
922 *it = MathAtom(new InsetMathLim(f, x, x0));
924 //lyxerr << "\nLimits to: " << ar << endl;
932 void extractStructure(MathArray & ar)
934 //lyxerr << "\nStructure from: " << ar << endl;
937 extractIntegrals(ar);
941 extractFunctions(ar);
947 //lyxerr << "\nStructure to: " << ar << endl;
951 void write(MathArray const & dat, WriteStream & wi)
955 wi.firstitem() = true;
956 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it) {
958 wi.firstitem() = false;
963 void normalize(MathArray const & ar, NormalStream & os)
965 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
966 (*it)->normalize(os);
970 void octave(MathArray const & dat, OctaveStream & os)
973 extractStructure(ar);
974 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
979 void maple(MathArray const & dat, MapleStream & os)
982 extractStructure(ar);
983 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
988 void maxima(MathArray const & dat, MaximaStream & os)
991 extractStructure(ar);
992 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
997 void mathematica(MathArray const & dat, MathematicaStream & os)
1000 extractStructure(ar);
1001 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1002 (*it)->mathematica(os);
1006 void mathmlize(MathArray const & dat, MathStream & os)
1009 extractStructure(ar);
1012 else if (ar.size() == 1)
1016 for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1017 (*it)->mathmlize(os);
1027 std::string captureOutput(std::string const & cmd, std::string const & data)
1029 // In order to avoid parsing problems with command interpreters
1030 // we pass input data through a file
1031 FileName const cas_tmpfile(tempName(FileName(), "casinput"));
1032 if (cas_tmpfile.empty()) {
1033 lyxerr << "Warning: cannot create temporary file."
1035 return std::string();
1037 std::ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
1040 std::string command = cmd + " < "
1041 + quoteName(cas_tmpfile.toFilesystemEncoding());
1042 lyxerr << "calling: " << cmd
1043 << "\ninput: '" << data << "'" << endl;
1044 cmd_ret const ret = runCommand(command);
1045 unlink(cas_tmpfile);
1049 size_t get_matching_brace(std::string const & str, size_t i)
1052 size_t n = str.size();
1054 i = str.find_first_of("{}", i+1);
1067 size_t get_matching_brace_back(std::string const & str, size_t i)
1071 i = str.find_last_of("{}", i-1);
1084 MathArray pipeThroughMaxima(docstring const &, MathArray const & ar)
1086 odocstringstream os;
1087 MaximaStream ms(os);
1089 docstring expr = os.str();
1090 docstring const header = from_ascii("simpsum:true;");
1093 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1094 // try to fix missing '*' the hard way
1096 // > echo "2x;" | maxima
1098 // (C1) Incorrect syntax: x is not an infix operator
1102 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1103 docstring full = header + "tex(" + expr + ");";
1104 out = captureOutput("maxima", to_utf8(full));
1106 // leave loop if expression syntax is probably ok
1107 if (out.find("Incorrect syntax") == npos)
1110 // search line with "Incorrect syntax"
1111 istringstream is(out);
1115 if (line.find("Incorrect syntax") != npos)
1119 // 2nd next line is the one with caret
1122 size_t pos = line.find('^');
1123 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1124 if (pos == npos || pos < 4)
1125 break; // caret position not found
1126 pos -= 4; // skip the "tex(" part
1127 if (expr[pos] == '*')
1128 break; // two '*' in a row are definitely bad
1129 expr.insert(pos, from_ascii("*"));
1132 vector<std::string> tmp = getVectorFromString(out, "$$");
1136 out = subst(tmp[1], "\\>", std::string());
1137 lyxerr << "output: '" << out << "'" << endl;
1139 // Ugly code that tries to make the result prettier
1140 size_t i = out.find("\\mathchoice");
1142 size_t j = get_matching_brace(out, i + 12);
1143 size_t k = get_matching_brace(out, j + 1);
1144 k = get_matching_brace(out, k + 1);
1145 k = get_matching_brace(out, k + 1);
1146 std::string mid = out.substr(i + 13, j - i - 13);
1147 if (mid.find("\\over") != npos)
1148 mid = '{' + mid + '}';
1149 out = out.substr(0,i)
1151 + out.substr(k + 1);
1152 //lyxerr << "output: " << out << endl;
1153 i = out.find("\\mathchoice", i);
1157 i = out.find("\\over");
1159 size_t j = get_matching_brace_back(out, i - 1);
1160 if (j == npos || j == 0)
1162 size_t k = get_matching_brace(out, i + 5);
1163 if (k == npos || k + 1 == out.size())
1165 out = out.substr(0,j - 1)
1167 + out.substr(j,i - j)
1168 + out.substr(i + 5,k - i - 4)
1169 + out.substr(k + 2);
1170 //lyxerr << "output: " << out << endl;
1171 i = out.find("\\over", i + 4);
1174 mathed_parse_cell(res, from_utf8(out));
1179 MathArray pipeThroughMaple(docstring const & extra, MathArray const & ar)
1181 std::string header = "readlib(latex):\n";
1183 // remove the \\it for variable names
1184 //"#`latex/csname_font` := `\\it `:"
1186 "`latex/csname_font` := ``:\n";
1188 // export matrices in (...) instead of [...]
1190 "`latex/latex/matrix` := "
1191 "subs(`[`=`(`, `]`=`)`,"
1192 "eval(`latex/latex/matrix`)):\n";
1194 // replace \\cdots with proper '*'
1196 "`latex/latex/*` := "
1197 "subs(`\\,`=`\\cdot `,"
1198 "eval(`latex/latex/*`)):\n";
1200 // remove spurious \\noalign{\\medskip} in matrix output
1202 "`latex/latex/matrix`:= "
1203 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1204 "eval(`latex/latex/matrix`)):\n";
1206 //"#`latex/latex/symbol` "
1207 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1209 std::string trailer = "quit;";
1210 odocstringstream os;
1213 std::string expr = to_utf8(os.str());
1214 lyxerr << "ar: '" << ar << "'\n"
1215 << "ms: '" << expr << "'" << endl;
1217 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1218 // try to fix missing '*' the hard way by using mint
1220 // ... > echo "1A;" | mint -i 1 -S -s -q
1223 // Probably missing an operator such as * p
1225 lyxerr << "checking expr: '" << expr << "'" << endl;
1226 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1228 break; // expression syntax is ok
1229 istringstream is(out);
1232 if (line.find("on line") != 0)
1233 break; // error message not identified
1235 size_t pos = line.find('^');
1236 if (pos == string::npos || pos < 15)
1237 break; // caret position not found
1238 pos -= 15; // skip the "on line ..." part
1239 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1240 break; // two '*' in a row are definitely bad
1241 expr.insert(pos, 1, '*');
1244 // FIXME UNICODE Is utf8 encoding correct?
1245 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1246 string out = captureOutput("maple -q", header + full + trailer);
1252 mathed_parse_cell(res, from_utf8(out));
1257 MathArray pipeThroughOctave(docstring const &, MathArray const & ar)
1259 odocstringstream os;
1260 OctaveStream vs(os);
1262 string expr = to_utf8(os.str());
1265 lyxerr << "pipe: ar: '" << ar << "'\n"
1266 << "pipe: expr: '" << expr << "'" << endl;
1268 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1270 // try to fix missing '*' the hard way
1272 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1275 lyxerr << "checking expr: '" << expr << "'" << endl;
1276 out = captureOutput("octave -q 2>&1", expr);
1277 lyxerr << "output: '" << out << "'" << endl;
1279 // leave loop if expression syntax is probably ok
1280 if (out.find("parse error:") == string::npos)
1283 // search line with single caret
1284 istringstream is(out);
1288 lyxerr << "skipping line: '" << line << "'" << endl;
1289 if (line.find(">>> ") != string::npos)
1293 // found line with error, next line is the one with caret
1295 size_t pos = line.find('^');
1296 lyxerr << "caret line: '" << line << "'" << endl;
1297 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1298 if (pos == string::npos || pos < 4)
1299 break; // caret position not found
1300 pos -= 4; // skip the ">>> " part
1301 if (expr[pos] == '*')
1302 break; // two '*' in a row are definitely bad
1303 expr.insert(pos, 1, '*');
1306 // remove 'ans = ' taking into account that there may be an
1307 // ansi control sequence before, such as '\033[?1034hans = '
1308 size_t i = out.find("ans = ");
1309 if (i == string::npos)
1311 out = out.substr(i + 6);
1313 // parse output as matrix or single number
1314 MathAtom at(new InsetMathArray(from_ascii("array"), from_utf8(out)));
1315 InsetMathArray const * mat = at->asArrayInset();
1317 if (mat->ncols() == 1 && mat->nrows() == 1)
1318 res.append(mat->cell(0));
1320 res.push_back(MathAtom(new InsetMathDelim(from_ascii("("), from_ascii(")"))));
1321 res.back().nucleus()->cell(0).push_back(at);
1327 string fromMathematicaName(string const & name)
1329 if (name == "Sin") return "sin";
1330 if (name == "Sinh") return "sinh";
1331 if (name == "ArcSin") return "arcsin";
1332 if (name == "Cos") return "cos";
1333 if (name == "Cosh") return "cosh";
1334 if (name == "ArcCos") return "arccos";
1335 if (name == "Tan") return "tan";
1336 if (name == "Tanh") return "tanh";
1337 if (name == "ArcTan") return "arctan";
1338 if (name == "Cot") return "cot";
1339 if (name == "Coth") return "coth";
1340 if (name == "Csc") return "csc";
1341 if (name == "Sec") return "sec";
1342 if (name == "Exp") return "exp";
1343 if (name == "Log") return "log";
1344 if (name == "Arg" ) return "arg";
1345 if (name == "Det" ) return "det";
1346 if (name == "GCD" ) return "gcd";
1347 if (name == "Max" ) return "max";
1348 if (name == "Min" ) return "min";
1349 if (name == "Erf" ) return "erf";
1350 if (name == "Erfc" ) return "erfc";
1355 void prettifyMathematicaOutput(string & out, string const & macroName,
1356 bool roman, bool translate)
1358 string const macro = "\\" + macroName + "{";
1359 size_t const len = macro.length();
1360 size_t i = out.find(macro);
1363 size_t const j = get_matching_brace(out, i + len);
1364 string const name = out.substr(i + len, j - i - len);
1365 out = out.substr(0, i)
1366 + (roman ? "\\mathrm{" : "")
1367 + (translate ? fromMathematicaName(name) : name)
1368 + out.substr(roman ? j : j + 1);
1369 //lyxerr << "output: " << out << endl;
1370 i = out.find(macro, i);
1375 MathArray pipeThroughMathematica(docstring const &, MathArray const & ar)
1377 odocstringstream os;
1378 MathematicaStream ms(os);
1380 // FIXME UNICODE Is utf8 encoding correct?
1381 string const expr = to_utf8(os.str());
1384 lyxerr << "expr: '" << expr << "'" << endl;
1386 string const full = "TeXForm[" + expr + "]";
1387 out = captureOutput("math", full);
1388 lyxerr << "output: '" << out << "'" << endl;
1390 size_t pos1 = out.find("Out[1]//TeXForm= ");
1391 size_t pos2 = out.find("In[2]:=");
1393 if (pos1 == string::npos || pos2 == string::npos)
1396 // get everything from pos1+17 to pos2
1397 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1398 out = subst(subst(out, '\r', ' '), '\n', ' ');
1400 // tries to make the result prettier
1401 prettifyMathematicaOutput(out, "Mfunction", true, true);
1402 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1403 prettifyMathematicaOutput(out, "Mvariable", false, false);
1406 mathed_parse_cell(res, from_utf8(out));
1413 MathArray pipeThroughExtern(string const & lang, docstring const & extra,
1414 MathArray const & ar)
1416 if (lang == "octave")
1417 return pipeThroughOctave(extra, ar);
1419 if (lang == "maxima")
1420 return pipeThroughMaxima(extra, ar);
1422 if (lang == "maple")
1423 return pipeThroughMaple(extra, ar);
1425 if (lang == "mathematica")
1426 return pipeThroughMathematica(extra, ar);
1428 // create normalized expression
1429 odocstringstream os;
1430 NormalStream ns(os);
1431 os << '[' << extra << ' ';
1434 // FIXME UNICODE Is utf8 encoding correct?
1435 string data = to_utf8(os.str());
1437 // search external script
1438 support::FileName const file = libFileSearch("mathed", "extern_" + lang);
1440 lyxerr << "converter to '" << lang << "' not found" << endl;
1444 // run external sript
1445 string out = captureOutput(file.absFilename(), data);
1447 mathed_parse_cell(res, from_utf8(out));