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 "InsetMathAMSArray.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/debug.h"
39 #include "support/docstream.h"
40 #include "support/FileName.h"
41 #include "support/filetools.h"
42 #include "support/lstrings.h"
50 using namespace lyx::support;
65 static char const * function_names[] = {
66 "arccos", "arcsin", "arctan", "arg", "bmod",
67 "cos", "cosh", "cot", "coth", "csc", "deg",
68 "det", "dim", "exp", "gcd", "hom", "inf", "ker",
69 "lg", "lim", "liminf", "limsup", "ln", "log",
70 "max", "min", "sec", "sin", "sinh", "sup",
71 "tan", "tanh", "Pr", 0
74 static size_t const npos = lyx::docstring::npos;
76 // define a function for tests
77 typedef bool TestItemFunc(MathAtom const &);
79 // define a function for replacing subexpressions
80 typedef MathAtom ReplaceArgumentFunc(const MathData & ar);
84 // try to extract a super/subscript
85 // modify iterator position to point behind the thing
86 bool extractScript(MathData & ar,
87 MathData::iterator & pos, MathData::iterator last, bool superscript)
89 // nothing to get here
93 // is this a scriptinset?
94 if (!(*pos)->asScriptInset())
97 // do we want superscripts only?
98 if (superscript && !(*pos)->asScriptInset()->hasUp())
101 // it is a scriptinset, use it.
108 // try to extract an "argument" to some function.
109 // returns position behind the argument
110 MathData::iterator extractArgument(MathData & ar,
111 MathData::iterator pos, MathData::iterator last,
112 ExternalMath kind, bool function = false)
114 // nothing to get here
118 // something delimited _is_ an argument
119 if ((*pos)->asDelimInset()) {
120 // leave out delimiters if this is a function argument
121 if (function && kind != MATHML) {
122 MathData const & arg = (*pos)->asDelimInset()->cell(0);
123 MathData::const_iterator cur = arg.begin();
124 MathData::const_iterator end = arg.end();
126 ar.push_back(*cur++);
132 // if there's one, get following superscript only if this
133 // isn't a function argument
135 extractScript(ar, pos, last, true);
139 // always take the first thing, no matter what it is
142 // go ahead if possible
147 // if the next item is a super/subscript, it most certainly belongs
148 // to the thing we have
149 extractScript(ar, pos, last, false);
153 // but it might be more than that.
154 // FIXME: not implemented
155 //for (MathData::iterator it = pos + 1; it != last; ++it) {
156 // // always take the first thing, no matter
158 // ar.push_back(*it);
166 // returns sequence of char with same code starting at it up to end
167 // it might be less, though...
168 docstring charSequence
169 (MathData::const_iterator it, MathData::const_iterator end)
172 for (; it != end && (*it)->asCharInset(); ++it)
173 s += (*it)->getChar();
178 void extractStrings(MathData & ar)
180 //lyxerr << "\nStrings from: " << ar << endl;
181 for (size_t i = 0; i < ar.size(); ++i) {
182 if (!ar[i]->asCharInset())
184 docstring s = charSequence(ar.begin() + i, ar.end());
185 ar[i] = MathAtom(new InsetMathString(s));
186 ar.erase(i + 1, i + s.size());
188 //lyxerr << "\nStrings to: " << ar << endl;
192 void extractMatrices(MathData & ar)
194 //lyxerr << "\nMatrices from: " << ar << endl;
195 // first pass for explicitly delimited stuff
196 for (size_t i = 0; i < ar.size(); ++i) {
197 InsetMathDelim const * const inset = ar[i]->asDelimInset();
200 MathData const & arr = inset->cell(0);
203 if (!arr.front()->asGridInset())
205 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset()),
206 inset->left_, inset->right_));
209 // second pass for AMS "pmatrix" etc
210 for (size_t i = 0; i < ar.size(); ++i) {
211 InsetMathAMSArray const * const inset = ar[i]->asAMSArrayInset();
213 string left = inset->name_left();
216 string right = inset->name_right();
219 ar[i] = MathAtom(new InsetMathMatrix(*inset, from_ascii(left), from_ascii(right)));
222 //lyxerr << "\nMatrices to: " << ar << endl;
226 // convert this inset somehow to a string
227 bool extractString(MathAtom const & at, docstring & str)
230 str = docstring(1, at->getChar());
233 if (at->asStringInset()) {
234 str = at->asStringInset()->str();
241 // is this a known function?
242 bool isKnownFunction(docstring const & str)
244 for (int i = 0; function_names[i]; ++i) {
245 if (str == function_names[i])
252 // extract a function name from this inset
253 bool extractFunctionName(MathAtom const & at, docstring & str)
255 if (at->asSymbolInset()) {
256 str = at->asSymbolInset()->name();
257 return isKnownFunction(str);
259 if (at->asUnknownInset()) {
260 // assume it is well known...
264 if (at->asFontInset() && at->name() == "mathrm") {
265 // assume it is well known...
266 MathData const & ar = at->asFontInset()->cell(0);
267 str = charSequence(ar.begin(), ar.end());
268 return ar.size() == str.size();
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 MathData::iterator endNestSearch(
288 MathData::iterator it,
289 MathData::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)
313 Buffer * buf = ar.buffer();
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 MathData::iterator it = ar.begin() + i;
323 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
327 // replace the original stuff by the new inset
328 ar[i] = replaceArg(MathData(buf, 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(MathData & ar)
342 Buffer * buf = ar.buffer();
343 //lyxerr << "\nScripts from: " << ar << endl;
344 for (size_t i = 0; i < ar.size(); ++i) {
345 InsetMathScript const * script = ar[i]->asScriptInset();
347 // is this a script inset and do we also have a superscript?
348 if (!script || !script->hasUp())
351 // we must have a nucleus if we only have a superscript
352 if (!script->hasDown() && script->nuc().size() == 0)
355 if (script->nuc().size() == 1) {
356 // leave alone sums and integrals
357 InsetMathSymbol const * sym =
358 script->nuc().front()->asSymbolInset();
359 if (sym && (sym->name() == "sum" || sym->name() == "int"))
363 // create extra script inset and move superscript over
364 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
365 auto_ptr<InsetMathScript> q(new InsetMathScript(buf, true));
366 swap(q->up(), p->up());
367 p->removeScript(true);
369 // if we don't have a subscript, get rid of the ScriptInset
370 if (!script->hasDown()) {
371 MathData arg(p->nuc());
372 MathData::const_iterator it = arg.begin();
373 MathData::const_iterator et = arg.end();
376 ar.insert(i++, *it++);
380 // insert new inset behind
381 ar.insert(i, MathAtom(q.release()));
383 //lyxerr << "\nScripts to: " << ar << endl;
391 void extractExps(MathData & ar)
393 Buffer * buf = ar.buffer();
394 //lyxerr << "\nExps from: " << ar << endl;
395 for (size_t i = 0; i + 1 < ar.size(); ++i) {
397 if (ar[i]->getChar() != 'e')
400 // we need an exponent but no subscript
401 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
402 if (!sup || sup->hasDown())
405 // create a proper exp-inset as replacement
406 ar[i] = MathAtom(new InsetMathExFunc(buf, from_ascii("exp"), sup->cell(1)));
409 //lyxerr << "\nExps to: " << ar << endl;
414 // extract det(...) from |matrix|
416 void extractDets(MathData & ar)
418 Buffer * buf = ar.buffer();
419 //lyxerr << "\ndet from: " << ar << endl;
420 for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
421 InsetMathDelim const * del = (*it)->asDelimInset();
426 *it = MathAtom(new InsetMathExFunc(buf, from_ascii("det"), del->cell(0)));
428 //lyxerr << "\ndet to: " << ar << endl;
436 bool isDigitOrSimilar(char_type c)
438 return ('0' <= c && c <= '9') || c == '.';
442 // returns sequence of digits
443 docstring digitSequence
444 (MathData::const_iterator it, MathData::const_iterator end)
447 for (; it != end && (*it)->asCharInset(); ++it) {
448 if (!isDigitOrSimilar((*it)->getChar()))
450 s += (*it)->getChar();
456 void extractNumbers(MathData & ar)
458 //lyxerr << "\nNumbers from: " << ar << endl;
459 for (size_t i = 0; i < ar.size(); ++i) {
460 if (!ar[i]->asCharInset())
462 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
465 docstring s = digitSequence(ar.begin() + i, ar.end());
467 ar[i] = MathAtom(new InsetMathNumber(s));
468 ar.erase(i + 1, i + s.size());
470 //lyxerr << "\nNumbers to: " << ar << endl;
479 bool testOpenParen(MathAtom const & at)
481 return testString(at, "(");
485 bool testCloseParen(MathAtom const & at)
487 return testString(at, ")");
491 MathAtom replaceParenDelims(const MathData & ar)
493 return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
494 from_ascii("("), from_ascii(")"), ar));
498 bool testOpenBracket(MathAtom const & at)
500 return testString(at, "[");
504 bool testCloseBracket(MathAtom const & at)
506 return testString(at, "]");
510 MathAtom replaceBracketDelims(const MathData & ar)
512 return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
513 from_ascii("["), from_ascii("]"), ar));
517 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
518 void extractDelims(MathData & ar)
520 //lyxerr << "\nDelims from: " << ar << endl;
521 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
522 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
523 //lyxerr << "\nDelims to: " << ar << endl;
529 // search well-known functions
533 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
534 // assume 'extractDelims' ran before
535 void extractFunctions(MathData & ar, ExternalMath kind)
537 // we need at least two items...
541 Buffer * buf = ar.buffer();
543 //lyxerr << "\nFunctions from: " << ar << endl;
544 for (size_t i = 0; i + 1 < ar.size(); ++i) {
545 MathData::iterator it = ar.begin() + i;
546 MathData::iterator jt = it + 1;
550 // it certainly is if it is well known...
551 if (!extractFunctionName(*it, name)) {
552 // is this a user defined function?
553 // it it probably not, if it doesn't have a name.
554 if (!extractString(*it, name))
556 // it is not if it has no argument
559 // guess so, if this is followed by
560 // a DelimInset with a single item in the cell
561 InsetMathDelim const * del = (*jt)->asDelimInset();
562 if (!del || del->cell(0).size() != 1)
564 // fall trough into main branch
567 // do we have an exponent like in
568 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
570 extractScript(exp, jt, ar.end(), true);
572 // create a proper inset as replacement
573 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(buf, name));
575 // jt points to the "argument". Get hold of this.
576 MathData::iterator st =
577 extractArgument(p->cell(0), jt, ar.end(), kind, true);
579 // replace the function name by a real function inset
580 *it = MathAtom(p.release());
582 // remove the source of the argument from the array
583 ar.erase(it + 1, st);
585 // re-insert exponent
586 ar.insert(i + 1, exp);
587 //lyxerr << "\nFunctions to: " << ar << endl;
596 bool testSymbol(MathAtom const & at, docstring const & name)
598 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
602 bool testSymbol(MathAtom const & at, char const * const name)
604 return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
608 bool testIntSymbol(MathAtom const & at)
610 return testSymbol(at, from_ascii("int"));
614 bool testIntegral(MathAtom const & at)
618 ( at->asScriptInset()
619 && at->asScriptInset()->nuc().size()
620 && testIntSymbol(at->asScriptInset()->nuc().back()) );
625 bool testIntDiff(MathAtom const & at)
627 return testString(at, "d");
631 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
632 // assume 'extractDelims' ran before
633 void extractIntegrals(MathData & ar, ExternalMath kind)
635 // we need at least three items...
639 Buffer * buf = ar.buffer();
641 //lyxerr << "\nIntegrals from: " << ar << endl;
642 for (size_t i = 0; i + 1 < ar.size(); ++i) {
643 MathData::iterator it = ar.begin() + i;
646 MathData::iterator jt =
647 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
649 // something sensible found?
653 // is this a integral name?
654 if (!testIntegral(*it))
657 // core ist part from behind the scripts to the 'd'
658 auto_ptr<InsetMathExInt> p(new InsetMathExInt(buf, from_ascii("int")));
660 // handle scripts if available
661 if (!testIntSymbol(*it)) {
662 p->cell(2) = (*it)->asScriptInset()->down();
663 p->cell(3) = (*it)->asScriptInset()->up();
665 p->cell(0) = MathData(buf, it + 1, jt);
667 // use the "thing" behind the 'd' as differential
668 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end(), kind);
671 ar.erase(it + 1, tt);
672 *it = MathAtom(p.release());
674 //lyxerr << "\nIntegrals to: " << ar << endl;
678 bool testTermDelimiter(MathAtom const & at)
680 return testString(at, "+") || testString(at, "-");
684 // try to extract a "term", i.e., something delimited by '+' or '-'.
685 // returns position behind the term
686 MathData::iterator extractTerm(MathData & ar,
687 MathData::iterator pos, MathData::iterator last)
689 while (pos != last && !testTermDelimiter(*pos)) {
702 bool testEqualSign(MathAtom const & at)
704 return testString(at, "=");
708 bool testSumSymbol(MathAtom const & p)
710 return testSymbol(p, from_ascii("sum"));
714 bool testSum(MathAtom const & at)
718 ( at->asScriptInset()
719 && at->asScriptInset()->nuc().size()
720 && testSumSymbol(at->asScriptInset()->nuc().back()) );
724 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
725 // assume 'extractDelims' ran before
726 void extractSums(MathData & ar)
728 // we need at least two items...
732 Buffer * buf = ar.buffer();
734 //lyxerr << "\nSums from: " << ar << endl;
735 for (size_t i = 0; i + 1 < ar.size(); ++i) {
736 MathData::iterator it = ar.begin() + i;
738 // is this a sum name?
742 // create a proper inset as replacement
743 auto_ptr<InsetMathExInt> p(new InsetMathExInt(buf, from_ascii("sum")));
745 // collect lower bound and summation index
746 InsetMathScript const * sub = ar[i]->asScriptInset();
747 if (sub && sub->hasDown()) {
748 // try to figure out the summation index from the subscript
749 MathData const & ar = sub->down();
750 MathData::const_iterator xt =
751 find_if(ar.begin(), ar.end(), &testEqualSign);
752 if (xt != ar.end()) {
753 // we found a '=', use everything in front of that as index,
754 // and everything behind as lower index
755 p->cell(1) = MathData(buf, ar.begin(), xt);
756 p->cell(2) = MathData(buf, xt + 1, ar.end());
758 // use everything as summation index, don't use scripts.
763 // collect upper bound
764 if (sub && sub->hasUp())
765 p->cell(3) = sub->up();
767 // use something behind the script as core
768 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
771 ar.erase(it + 1, tt);
772 *it = MathAtom(p.release());
774 //lyxerr << "\nSums to: " << ar << endl;
779 // search differential stuff
782 // tests for 'd' or '\partial'
783 bool testDiffItem(MathAtom const & at)
785 if (testString(at, "d") || testSymbol(at, "partial"))
788 // we may have d^n .../d and splitScripts() has not yet seen it
789 InsetMathScript const * sup = at->asScriptInset();
790 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
791 MathAtom const & ma = sup->nuc().front();
792 return testString(ma, "d") || testSymbol(ma, "partial");
798 bool testDiffArray(MathData const & ar)
800 return ar.size() && testDiffItem(ar.front());
804 bool testDiffFrac(MathAtom const & at)
808 && testDiffArray(at->asFracInset()->cell(0))
809 && testDiffArray(at->asFracInset()->cell(1));
813 void extractDiff(MathData & ar)
815 Buffer * buf = ar.buffer();
816 //lyxerr << "\nDiffs from: " << ar << endl;
817 for (size_t i = 0; i < ar.size(); ++i) {
818 MathData::iterator it = ar.begin() + i;
820 // is this a "differential fraction"?
821 if (!testDiffFrac(*it))
824 InsetMathFrac const * f = (*it)->asFracInset();
826 lyxerr << "should not happen" << endl;
830 // create a proper diff inset
831 auto_ptr<InsetMathDiff> diff(new InsetMathDiff(buf));
833 // collect function, let jt point behind last used item
834 MathData::iterator jt = it + 1;
836 MathData numer(f->cell(0));
838 if (numer.size() > 1 && numer[1]->asScriptInset()) {
839 // this is something like d^n f(x) / d... or d^n / d...
842 if (numer.size() > 2)
843 diff->cell(0) = MathData(buf, numer.begin() + 2, numer.end());
845 jt = extractTerm(diff->cell(0), jt, ar.end());
847 // simply d f(x) / d... or d/d...
848 if (numer.size() > 1)
849 diff->cell(0) = MathData(buf, numer.begin() + 1, numer.end());
851 jt = extractTerm(diff->cell(0), jt, ar.end());
854 // collect denominator parts
855 MathData denom(f->cell(1));
857 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
859 MathData::iterator et
860 = find_if(dt + 1, denom.end(), &testDiffItem);
863 MathData::iterator st = et - 1;
864 InsetMathScript const * script = (*st)->asScriptInset();
865 if (script && script->hasUp()) {
866 // things like d.../dx^n
868 if (extractNumber(script->up(), mult)) {
869 //lyxerr << "mult: " << mult << endl;
870 for (int i = 0; i < mult; ++i)
871 diff->addDer(MathData(buf, dt + 1, st));
875 diff->addDer(MathData(buf, dt + 1, et));
881 ar.erase(it + 1, jt);
882 *it = MathAtom(diff.release());
884 //lyxerr << "\nDiffs to: " << ar << endl;
893 bool testRightArrow(MathAtom const & at)
895 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
900 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
901 // assume 'extractDelims' ran before
902 void extractLims(MathData & ar)
904 Buffer * buf = ar.buffer();
905 //lyxerr << "\nLimits from: " << ar << endl;
906 for (size_t i = 0; i < ar.size(); ++i) {
907 MathData::iterator it = ar.begin() + i;
909 // must be a script inset with a subscript (without superscript)
910 InsetMathScript const * sub = (*it)->asScriptInset();
911 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
914 // is this a limit function?
915 if (!testSymbol(sub->nuc().front(), "lim"))
918 // subscript must contain a -> symbol
919 MathData const & s = sub->down();
920 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
924 // the -> splits the subscript int x and x0
925 MathData x = MathData(buf, s.begin(), st);
926 MathData x0 = MathData(buf, st + 1, s.end());
928 // use something behind the script as core
930 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
933 ar.erase(it + 1, tt);
935 // create a proper inset as replacement
936 *it = MathAtom(new InsetMathLim(buf, f, x, x0));
938 //lyxerr << "\nLimits to: " << ar << endl;
946 void extractStructure(MathData & ar, ExternalMath kind)
948 //lyxerr << "\nStructure from: " << ar << endl;
951 extractIntegrals(ar, kind);
955 extractFunctions(ar, kind);
962 //lyxerr << "\nStructure to: " << ar << endl;
968 string captureOutput(string const & cmd, string const & data)
970 // In order to avoid parsing problems with command interpreters
971 // we pass input data through a file
972 FileName const cas_tmpfile = FileName::tempName("casinput");
973 if (cas_tmpfile.empty()) {
974 lyxerr << "Warning: cannot create temporary file."
978 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
981 string command = cmd + " < "
982 + quoteName(cas_tmpfile.toFilesystemEncoding());
983 lyxerr << "calling: " << cmd
984 << "\ninput: '" << data << "'" << endl;
985 cmd_ret const ret = runCommand(command);
986 cas_tmpfile.removeFile();
990 size_t get_matching_brace(string const & str, size_t i)
993 size_t n = str.size();
995 i = str.find_first_of("{}", i+1);
1008 size_t get_matching_brace_back(string const & str, size_t i)
1012 i = str.find_last_of("{}", i-1);
1025 MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1027 odocstringstream os;
1028 MaximaStream ms(os);
1030 docstring expr = os.str();
1031 docstring const header = from_ascii("simpsum:true;");
1034 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1035 // try to fix missing '*' the hard way
1037 // > echo "2x;" | maxima
1039 // (C1) Incorrect syntax: x is not an infix operator
1043 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1044 docstring full = header + "tex(" + expr + ");";
1045 out = captureOutput("maxima", to_utf8(full));
1047 // leave loop if expression syntax is probably ok
1048 if (out.find("Incorrect syntax") == npos)
1051 // search line with "Incorrect syntax"
1052 istringstream is(out);
1056 if (line.find("Incorrect syntax") != npos)
1060 // 2nd next line is the one with caret
1063 size_t pos = line.find('^');
1064 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1065 if (pos == npos || pos < 4)
1066 break; // caret position not found
1067 pos -= 4; // skip the "tex(" part
1068 if (expr[pos] == '*')
1069 break; // two '*' in a row are definitely bad
1070 expr.insert(pos, from_ascii("*"));
1073 vector<string> tmp = getVectorFromString(out, "$$");
1077 out = subst(tmp[1], "\\>", string());
1078 lyxerr << "output: '" << out << "'" << endl;
1080 // Ugly code that tries to make the result prettier
1081 size_t i = out.find("\\mathchoice");
1083 size_t j = get_matching_brace(out, i + 12);
1084 size_t k = get_matching_brace(out, j + 1);
1085 k = get_matching_brace(out, k + 1);
1086 k = get_matching_brace(out, k + 1);
1087 string mid = out.substr(i + 13, j - i - 13);
1088 if (mid.find("\\over") != npos)
1089 mid = '{' + mid + '}';
1090 out = out.substr(0, i)
1092 + out.substr(k + 1);
1093 //lyxerr << "output: " << out << endl;
1094 i = out.find("\\mathchoice", i);
1098 i = out.find("\\over");
1100 size_t j = get_matching_brace_back(out, i - 1);
1101 if (j == npos || j == 0)
1103 size_t k = get_matching_brace(out, i + 5);
1104 if (k == npos || k + 1 == out.size())
1106 out = out.substr(0, j - 1)
1108 + out.substr(j, i - j)
1109 + out.substr(i + 5, k - i - 4)
1110 + out.substr(k + 2);
1111 //lyxerr << "output: " << out << endl;
1112 i = out.find("\\over", i + 4);
1115 mathed_parse_cell(res, from_utf8(out));
1120 MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1122 string header = "readlib(latex):\n";
1124 // remove the \\it for variable names
1125 //"#`latex/csname_font` := `\\it `:"
1127 "`latex/csname_font` := ``:\n";
1129 // export matrices in (...) instead of [...]
1131 "`latex/latex/matrix` := "
1132 "subs(`[`=`(`, `]`=`)`,"
1133 "eval(`latex/latex/matrix`)):\n";
1135 // replace \\cdots with proper '*'
1137 "`latex/latex/*` := "
1138 "subs(`\\,`=`\\cdot `,"
1139 "eval(`latex/latex/*`)):\n";
1141 // remove spurious \\noalign{\\medskip} in matrix output
1143 "`latex/latex/matrix`:= "
1144 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1145 "eval(`latex/latex/matrix`)):\n";
1147 //"#`latex/latex/symbol` "
1148 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1150 string trailer = "quit;";
1151 odocstringstream os;
1154 string expr = to_utf8(os.str());
1155 lyxerr << "ar: '" << ar << "'\n"
1156 << "ms: '" << expr << "'" << endl;
1158 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1159 // try to fix missing '*' the hard way by using mint
1161 // ... > echo "1A;" | mint -i 1 -S -s -q
1164 // Probably missing an operator such as * p
1166 lyxerr << "checking expr: '" << expr << "'" << endl;
1167 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1169 break; // expression syntax is ok
1170 istringstream is(out);
1173 if (line.find("on line") != 0)
1174 break; // error message not identified
1176 size_t pos = line.find('^');
1177 if (pos == string::npos || pos < 15)
1178 break; // caret position not found
1179 pos -= 15; // skip the "on line ..." part
1180 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1181 break; // two '*' in a row are definitely bad
1182 expr.insert(pos, 1, '*');
1185 // FIXME UNICODE Is utf8 encoding correct?
1186 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1187 string out = captureOutput("maple -q", header + full + trailer);
1193 mathed_parse_cell(res, from_utf8(out));
1198 MathData pipeThroughOctave(docstring const &, MathData const & ar)
1200 odocstringstream os;
1201 OctaveStream vs(os);
1203 string expr = to_utf8(os.str());
1206 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1207 lyxerr << "pipe: ar: '" << ar << "'\n"
1208 << "pipe: expr: '" << expr << "'" << endl;
1210 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1212 // try to fix missing '*' the hard way
1214 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1217 lyxerr << "checking expr: '" << expr << "'" << endl;
1218 out = captureOutput("octave -q 2>&1", expr);
1219 lyxerr << "output: '" << out << "'" << endl;
1221 // leave loop if expression syntax is probably ok
1222 if (out.find("parse error:") == string::npos)
1225 // search line with single caret
1226 istringstream is(out);
1230 lyxerr << "skipping line: '" << line << "'" << endl;
1231 if (line.find(">>> ") != string::npos)
1235 // found line with error, next line is the one with caret
1237 size_t pos = line.find('^');
1238 lyxerr << "caret line: '" << line << "'" << endl;
1239 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1240 if (pos == string::npos || pos < 4)
1241 break; // caret position not found
1242 pos -= 4; // skip the ">>> " part
1243 if (expr[pos] == '*')
1244 break; // two '*' in a row are definitely bad
1245 expr.insert(pos, 1, '*');
1248 // remove 'ans = ' taking into account that there may be an
1249 // ansi control sequence before, such as '\033[?1034hans = '
1250 size_t i = out.find("ans = ");
1251 if (i == string::npos)
1253 out = out.substr(i + 6);
1255 // parse output as matrix or single number
1256 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1257 InsetMathArray const * mat = at->asArrayInset();
1259 if (mat->ncols() == 1 && mat->nrows() == 1)
1260 res.append(mat->cell(0));
1262 res.push_back(MathAtom(
1263 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1264 res.back().nucleus()->cell(0).push_back(at);
1270 string fromMathematicaName(string const & name)
1272 if (name == "Sin") return "sin";
1273 if (name == "Sinh") return "sinh";
1274 if (name == "ArcSin") return "arcsin";
1275 if (name == "Cos") return "cos";
1276 if (name == "Cosh") return "cosh";
1277 if (name == "ArcCos") return "arccos";
1278 if (name == "Tan") return "tan";
1279 if (name == "Tanh") return "tanh";
1280 if (name == "ArcTan") return "arctan";
1281 if (name == "Cot") return "cot";
1282 if (name == "Coth") return "coth";
1283 if (name == "Csc") return "csc";
1284 if (name == "Sec") return "sec";
1285 if (name == "Exp") return "exp";
1286 if (name == "Log") return "log";
1287 if (name == "Arg" ) return "arg";
1288 if (name == "Det" ) return "det";
1289 if (name == "GCD" ) return "gcd";
1290 if (name == "Max" ) return "max";
1291 if (name == "Min" ) return "min";
1292 if (name == "Erf" ) return "erf";
1293 if (name == "Erfc" ) return "erfc";
1298 void prettifyMathematicaOutput(string & out, string const & macroName,
1299 bool roman, bool translate)
1301 string const macro = "\\" + macroName + "{";
1302 size_t const len = macro.length();
1303 size_t i = out.find(macro);
1306 size_t const j = get_matching_brace(out, i + len);
1307 string const name = out.substr(i + len, j - i - len);
1308 out = out.substr(0, i)
1309 + (roman ? "\\mathrm{" : "")
1310 + (translate ? fromMathematicaName(name) : name)
1311 + out.substr(roman ? j : j + 1);
1312 //lyxerr << "output: " << out << endl;
1313 i = out.find(macro, i);
1318 MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1320 odocstringstream os;
1321 MathematicaStream ms(os);
1323 // FIXME UNICODE Is utf8 encoding correct?
1324 string const expr = to_utf8(os.str());
1327 lyxerr << "expr: '" << expr << "'" << endl;
1329 string const full = "TeXForm[" + expr + "]";
1330 out = captureOutput("math", full);
1331 lyxerr << "output: '" << out << "'" << endl;
1333 size_t pos1 = out.find("Out[1]//TeXForm= ");
1334 size_t pos2 = out.find("In[2]:=");
1336 if (pos1 == string::npos || pos2 == string::npos)
1339 // get everything from pos1+17 to pos2
1340 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1341 out = subst(subst(out, '\r', ' '), '\n', ' ');
1343 // tries to make the result prettier
1344 prettifyMathematicaOutput(out, "Mfunction", true, true);
1345 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1346 prettifyMathematicaOutput(out, "Mvariable", false, false);
1349 mathed_parse_cell(res, from_utf8(out));
1357 void write(MathData const & dat, WriteStream & wi)
1361 wi.firstitem() = true;
1362 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it) {
1364 wi.firstitem() = false;
1369 void normalize(MathData const & ar, NormalStream & os)
1371 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1372 (*it)->normalize(os);
1376 void octave(MathData const & dat, OctaveStream & os)
1379 extractStructure(ar, OCTAVE);
1380 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1385 void maple(MathData const & dat, MapleStream & os)
1388 extractStructure(ar, MAPLE);
1389 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1394 void maxima(MathData const & dat, MaximaStream & os)
1397 extractStructure(ar, MAXIMA);
1398 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1403 void mathematica(MathData const & dat, MathematicaStream & os)
1406 extractStructure(ar, MATHEMATICA);
1407 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1408 (*it)->mathematica(os);
1412 void mathmlize(MathData const & dat, MathStream & os)
1415 extractStructure(ar, MATHML);
1418 else if (ar.size() == 1)
1422 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1423 (*it)->mathmlize(os);
1428 // convert this inset somehow to a number
1429 bool extractNumber(MathData const & ar, int & i)
1431 idocstringstream is(charSequence(ar.begin(), ar.end()));
1437 bool extractNumber(MathData const & ar, double & d)
1439 idocstringstream is(charSequence(ar.begin(), ar.end()));
1445 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1446 MathData const & ar)
1448 if (lang == "octave")
1449 return pipeThroughOctave(extra, ar);
1451 if (lang == "maxima")
1452 return pipeThroughMaxima(extra, ar);
1454 if (lang == "maple")
1455 return pipeThroughMaple(extra, ar);
1457 if (lang == "mathematica")
1458 return pipeThroughMathematica(extra, ar);
1460 // create normalized expression
1461 odocstringstream os;
1462 NormalStream ns(os);
1463 os << '[' << extra << ' ';
1466 // FIXME UNICODE Is utf8 encoding correct?
1467 string data = to_utf8(os.str());
1469 // search external script
1470 FileName const file = libFileSearch("mathed", "extern_" + lang);
1472 lyxerr << "converter to '" << lang << "' not found" << endl;
1476 // run external sript
1477 string out = captureOutput(file.absFilename(), data);
1479 mathed_parse_cell(res, from_utf8(out));