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 // unless we are doing MathML, in which case we do want
123 if (function && kind != MATHML) {
124 MathData const & arg = (*pos)->asDelimInset()->cell(0);
125 MathData::const_iterator cur = arg.begin();
126 MathData::const_iterator end = arg.end();
128 ar.push_back(*cur++);
134 // if there's one, get following superscript only if this
135 // isn't a function argument
137 extractScript(ar, pos, last, true);
141 // always take the first thing, no matter what it is
144 // go ahead if possible
149 // if the next item is a super/subscript, it most certainly belongs
150 // to the thing we have
151 extractScript(ar, pos, last, false);
155 // but it might be more than that.
156 // FIXME: not implemented
157 //for (MathData::iterator it = pos + 1; it != last; ++it) {
158 // // always take the first thing, no matter
160 // ar.push_back(*it);
168 // returns sequence of char with same code starting at it up to end
169 // it might be less, though...
170 docstring charSequence
171 (MathData::const_iterator it, MathData::const_iterator end)
174 for (; it != end && (*it)->asCharInset(); ++it)
175 s += (*it)->getChar();
180 void extractStrings(MathData & ar)
182 //lyxerr << "\nStrings from: " << ar << endl;
183 for (size_t i = 0; i < ar.size(); ++i) {
184 if (!ar[i]->asCharInset())
186 docstring s = charSequence(ar.begin() + i, ar.end());
187 ar[i] = MathAtom(new InsetMathString(s));
188 ar.erase(i + 1, i + s.size());
190 //lyxerr << "\nStrings to: " << ar << endl;
194 void extractMatrices(MathData & ar)
196 //lyxerr << "\nMatrices from: " << ar << endl;
197 // first pass for explicitly delimited stuff
198 for (size_t i = 0; i < ar.size(); ++i) {
199 InsetMathDelim const * const inset = ar[i]->asDelimInset();
202 MathData const & arr = inset->cell(0);
205 if (!arr.front()->asGridInset())
207 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset()),
208 inset->left_, inset->right_));
211 // second pass for AMS "pmatrix" etc
212 for (size_t i = 0; i < ar.size(); ++i) {
213 InsetMathAMSArray const * const inset = ar[i]->asAMSArrayInset();
215 string left = inset->name_left();
218 string right = inset->name_right();
221 ar[i] = MathAtom(new InsetMathMatrix(*inset, from_ascii(left), from_ascii(right)));
224 //lyxerr << "\nMatrices to: " << ar << endl;
228 // convert this inset somehow to a string
229 bool extractString(MathAtom const & at, docstring & str)
232 str = docstring(1, at->getChar());
235 if (at->asStringInset()) {
236 str = at->asStringInset()->str();
243 // is this a known function?
244 bool isKnownFunction(docstring const & str)
246 for (int i = 0; function_names[i]; ++i) {
247 if (str == function_names[i])
254 // extract a function name from this inset
255 bool extractFunctionName(MathAtom const & at, docstring & str)
257 if (at->asSymbolInset()) {
258 str = at->asSymbolInset()->name();
259 return isKnownFunction(str);
261 if (at->asUnknownInset()) {
262 // assume it is well known...
266 if (at->asFontInset() && at->name() == "mathrm") {
267 // assume it is well known...
268 MathData const & ar = at->asFontInset()->cell(0);
269 str = charSequence(ar.begin(), ar.end());
270 return ar.size() == str.size();
276 bool testString(MathAtom const & at, docstring const & str)
279 return extractString(at, s) && str == s;
283 bool testString(MathAtom const & at, char const * const str)
285 return testString(at, from_ascii(str));
288 // search end of nested sequence
289 MathData::iterator endNestSearch(
290 MathData::iterator it,
291 MathData::iterator last,
292 TestItemFunc testOpen,
293 TestItemFunc testClose
296 for (int level = 0; it != last; ++it) {
308 // replace nested sequences by a real Insets
311 TestItemFunc testOpen,
312 TestItemFunc testClose,
313 ReplaceArgumentFunc replaceArg)
315 Buffer * buf = ar.buffer();
316 // use indices rather than iterators for the loop because we are going
317 // to modify the array.
318 for (size_t i = 0; i < ar.size(); ++i) {
319 // check whether this is the begin of the sequence
320 if (!testOpen(ar[i]))
323 // search end of sequence
324 MathData::iterator it = ar.begin() + i;
325 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
329 // replace the original stuff by the new inset
330 ar[i] = replaceArg(MathData(buf, it + 1, jt));
331 ar.erase(it + 1, jt + 1);
338 // split scripts into seperate super- and subscript insets. sub goes in
342 void splitScripts(MathData & ar)
344 Buffer * buf = ar.buffer();
345 //lyxerr << "\nScripts from: " << ar << endl;
346 for (size_t i = 0; i < ar.size(); ++i) {
347 InsetMathScript const * script = ar[i]->asScriptInset();
349 // is this a script inset and do we also have a superscript?
350 if (!script || !script->hasUp())
353 // we must have a nucleus if we only have a superscript
354 if (!script->hasDown() && script->nuc().size() == 0)
357 if (script->nuc().size() == 1) {
358 // leave alone sums and integrals
359 InsetMathSymbol const * sym =
360 script->nuc().front()->asSymbolInset();
361 if (sym && (sym->name() == "sum" || sym->name() == "int"))
365 // create extra script inset and move superscript over
366 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
367 auto_ptr<InsetMathScript> q(new InsetMathScript(buf, true));
368 swap(q->up(), p->up());
369 p->removeScript(true);
371 // if we don't have a subscript, get rid of the ScriptInset
372 if (!script->hasDown()) {
373 MathData arg(p->nuc());
374 MathData::const_iterator it = arg.begin();
375 MathData::const_iterator et = arg.end();
378 ar.insert(i++, *it++);
382 // insert new inset behind
383 ar.insert(i, MathAtom(q.release()));
385 //lyxerr << "\nScripts to: " << ar << endl;
393 void extractExps(MathData & ar)
395 Buffer * buf = ar.buffer();
396 //lyxerr << "\nExps from: " << ar << endl;
397 for (size_t i = 0; i + 1 < ar.size(); ++i) {
399 if (ar[i]->getChar() != 'e')
402 // we need an exponent but no subscript
403 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
404 if (!sup || sup->hasDown())
407 // create a proper exp-inset as replacement
408 ar[i] = MathAtom(new InsetMathExFunc(buf, from_ascii("exp"), sup->cell(1)));
411 //lyxerr << "\nExps to: " << ar << endl;
416 // extract det(...) from |matrix|
418 void extractDets(MathData & ar)
420 Buffer * buf = ar.buffer();
421 //lyxerr << "\ndet from: " << ar << endl;
422 for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
423 InsetMathDelim const * del = (*it)->asDelimInset();
428 *it = MathAtom(new InsetMathExFunc(buf, from_ascii("det"), del->cell(0)));
430 //lyxerr << "\ndet to: " << ar << endl;
438 bool isDigitOrSimilar(char_type c)
440 return ('0' <= c && c <= '9') || c == '.';
444 // returns sequence of digits
445 docstring digitSequence
446 (MathData::const_iterator it, MathData::const_iterator end)
449 for (; it != end && (*it)->asCharInset(); ++it) {
450 if (!isDigitOrSimilar((*it)->getChar()))
452 s += (*it)->getChar();
458 void extractNumbers(MathData & ar)
460 //lyxerr << "\nNumbers from: " << ar << endl;
461 for (size_t i = 0; i < ar.size(); ++i) {
462 if (!ar[i]->asCharInset())
464 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
467 docstring s = digitSequence(ar.begin() + i, ar.end());
469 ar[i] = MathAtom(new InsetMathNumber(s));
470 ar.erase(i + 1, i + s.size());
472 //lyxerr << "\nNumbers to: " << ar << endl;
481 bool testOpenParen(MathAtom const & at)
483 return testString(at, "(");
487 bool testCloseParen(MathAtom const & at)
489 return testString(at, ")");
493 MathAtom replaceParenDelims(const MathData & ar)
495 return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
496 from_ascii("("), from_ascii(")"), ar));
500 bool testOpenBracket(MathAtom const & at)
502 return testString(at, "[");
506 bool testCloseBracket(MathAtom const & at)
508 return testString(at, "]");
512 MathAtom replaceBracketDelims(const MathData & ar)
514 return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
515 from_ascii("["), from_ascii("]"), ar));
519 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
520 void extractDelims(MathData & ar)
522 //lyxerr << "\nDelims from: " << ar << endl;
523 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
524 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
525 //lyxerr << "\nDelims to: " << ar << endl;
531 // search well-known functions
535 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
536 // assume 'extractDelims' ran before
537 void extractFunctions(MathData & ar, ExternalMath kind)
539 // we need at least two items...
543 Buffer * buf = ar.buffer();
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 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(buf, name));
577 // jt points to the "argument". Get hold of this.
578 MathData::iterator st =
579 extractArgument(p->cell(0), jt, ar.end(), kind, true);
581 // replace the function name by a real function inset
582 *it = MathAtom(p.release());
584 // remove the source of the argument from the array
585 ar.erase(it + 1, st);
587 // re-insert exponent
588 ar.insert(i + 1, exp);
589 //lyxerr << "\nFunctions to: " << ar << endl;
598 bool testSymbol(MathAtom const & at, docstring const & name)
600 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
604 bool testSymbol(MathAtom const & at, char const * const name)
606 return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
610 bool testIntSymbol(MathAtom const & at)
612 return testSymbol(at, from_ascii("int"));
616 bool testIntegral(MathAtom const & at)
620 ( at->asScriptInset()
621 && at->asScriptInset()->nuc().size()
622 && testIntSymbol(at->asScriptInset()->nuc().back()) );
627 bool testIntDiff(MathAtom const & at)
629 return testString(at, "d");
633 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
634 // assume 'extractDelims' ran before
635 void extractIntegrals(MathData & ar, ExternalMath kind)
637 // we need at least three items...
641 Buffer * buf = ar.buffer();
643 //lyxerr << "\nIntegrals from: " << ar << endl;
644 for (size_t i = 0; i + 1 < ar.size(); ++i) {
645 MathData::iterator it = ar.begin() + i;
648 MathData::iterator jt =
649 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
651 // something sensible found?
655 // is this a integral name?
656 if (!testIntegral(*it))
659 // core ist part from behind the scripts to the 'd'
660 auto_ptr<InsetMathExInt> p(new InsetMathExInt(buf, from_ascii("int")));
662 // handle scripts if available
663 if (!testIntSymbol(*it)) {
664 p->cell(2) = (*it)->asScriptInset()->down();
665 p->cell(3) = (*it)->asScriptInset()->up();
667 p->cell(0) = MathData(buf, it + 1, jt);
669 // use the "thing" behind the 'd' as differential
670 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end(), kind);
673 ar.erase(it + 1, tt);
674 *it = MathAtom(p.release());
676 //lyxerr << "\nIntegrals to: " << ar << endl;
680 bool testTermDelimiter(MathAtom const & at)
682 return testString(at, "+") || testString(at, "-");
686 // try to extract a "term", i.e., something delimited by '+' or '-'.
687 // returns position behind the term
688 MathData::iterator extractTerm(MathData & ar,
689 MathData::iterator pos, MathData::iterator last)
691 while (pos != last && !testTermDelimiter(*pos)) {
704 bool testEqualSign(MathAtom const & at)
706 return testString(at, "=");
710 bool testSumSymbol(MathAtom const & p)
712 return testSymbol(p, from_ascii("sum"));
716 bool testSum(MathAtom const & at)
720 ( at->asScriptInset()
721 && at->asScriptInset()->nuc().size()
722 && testSumSymbol(at->asScriptInset()->nuc().back()) );
726 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
727 // assume 'extractDelims' ran before
728 void extractSums(MathData & ar)
730 // we need at least two items...
734 Buffer * buf = ar.buffer();
736 //lyxerr << "\nSums from: " << ar << endl;
737 for (size_t i = 0; i + 1 < ar.size(); ++i) {
738 MathData::iterator it = ar.begin() + i;
740 // is this a sum name?
744 // create a proper inset as replacement
745 auto_ptr<InsetMathExInt> p(new InsetMathExInt(buf, from_ascii("sum")));
747 // collect lower bound and summation index
748 InsetMathScript const * sub = ar[i]->asScriptInset();
749 if (sub && sub->hasDown()) {
750 // try to figure out the summation index from the subscript
751 MathData const & ar = sub->down();
752 MathData::const_iterator xt =
753 find_if(ar.begin(), ar.end(), &testEqualSign);
754 if (xt != ar.end()) {
755 // we found a '=', use everything in front of that as index,
756 // and everything behind as lower index
757 p->cell(1) = MathData(buf, ar.begin(), xt);
758 p->cell(2) = MathData(buf, xt + 1, ar.end());
760 // use everything as summation index, don't use scripts.
765 // collect upper bound
766 if (sub && sub->hasUp())
767 p->cell(3) = sub->up();
769 // use something behind the script as core
770 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
773 ar.erase(it + 1, tt);
774 *it = MathAtom(p.release());
776 //lyxerr << "\nSums to: " << ar << endl;
781 // search differential stuff
784 // tests for 'd' or '\partial'
785 bool testDiffItem(MathAtom const & at)
787 if (testString(at, "d") || testSymbol(at, "partial"))
790 // we may have d^n .../d and splitScripts() has not yet seen it
791 InsetMathScript const * sup = at->asScriptInset();
792 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
793 MathAtom const & ma = sup->nuc().front();
794 return testString(ma, "d") || testSymbol(ma, "partial");
800 bool testDiffArray(MathData const & ar)
802 return ar.size() && testDiffItem(ar.front());
806 bool testDiffFrac(MathAtom const & at)
810 && testDiffArray(at->asFracInset()->cell(0))
811 && testDiffArray(at->asFracInset()->cell(1));
815 void extractDiff(MathData & ar)
817 Buffer * buf = ar.buffer();
818 //lyxerr << "\nDiffs from: " << ar << endl;
819 for (size_t i = 0; i < ar.size(); ++i) {
820 MathData::iterator it = ar.begin() + i;
822 // is this a "differential fraction"?
823 if (!testDiffFrac(*it))
826 InsetMathFrac const * f = (*it)->asFracInset();
828 lyxerr << "should not happen" << endl;
832 // create a proper diff inset
833 auto_ptr<InsetMathDiff> diff(new InsetMathDiff(buf));
835 // collect function, let jt point behind last used item
836 MathData::iterator jt = it + 1;
838 MathData numer(f->cell(0));
840 if (numer.size() > 1 && numer[1]->asScriptInset()) {
841 // this is something like d^n f(x) / d... or d^n / d...
844 if (numer.size() > 2)
845 diff->cell(0) = MathData(buf, numer.begin() + 2, numer.end());
847 jt = extractTerm(diff->cell(0), jt, ar.end());
849 // simply d f(x) / d... or d/d...
850 if (numer.size() > 1)
851 diff->cell(0) = MathData(buf, numer.begin() + 1, numer.end());
853 jt = extractTerm(diff->cell(0), jt, ar.end());
856 // collect denominator parts
857 MathData denom(f->cell(1));
859 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
861 MathData::iterator et
862 = find_if(dt + 1, denom.end(), &testDiffItem);
865 MathData::iterator st = et - 1;
866 InsetMathScript const * script = (*st)->asScriptInset();
867 if (script && script->hasUp()) {
868 // things like d.../dx^n
870 if (extractNumber(script->up(), mult)) {
871 //lyxerr << "mult: " << mult << endl;
872 for (int i = 0; i < mult; ++i)
873 diff->addDer(MathData(buf, dt + 1, st));
877 diff->addDer(MathData(buf, dt + 1, et));
883 ar.erase(it + 1, jt);
884 *it = MathAtom(diff.release());
886 //lyxerr << "\nDiffs to: " << ar << endl;
895 bool testRightArrow(MathAtom const & at)
897 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
902 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
903 // assume 'extractDelims' ran before
904 void extractLims(MathData & ar)
906 Buffer * buf = ar.buffer();
907 //lyxerr << "\nLimits from: " << ar << endl;
908 for (size_t i = 0; i < ar.size(); ++i) {
909 MathData::iterator it = ar.begin() + i;
911 // must be a script inset with a subscript (without superscript)
912 InsetMathScript const * sub = (*it)->asScriptInset();
913 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
916 // is this a limit function?
917 if (!testSymbol(sub->nuc().front(), "lim"))
920 // subscript must contain a -> symbol
921 MathData const & s = sub->down();
922 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
926 // the -> splits the subscript int x and x0
927 MathData x = MathData(buf, s.begin(), st);
928 MathData x0 = MathData(buf, st + 1, s.end());
930 // use something behind the script as core
932 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
935 ar.erase(it + 1, tt);
937 // create a proper inset as replacement
938 *it = MathAtom(new InsetMathLim(buf, f, x, x0));
940 //lyxerr << "\nLimits to: " << ar << endl;
948 void extractStructure(MathData & ar, ExternalMath kind)
950 //lyxerr << "\nStructure from: " << ar << endl;
954 extractIntegrals(ar, kind);
959 extractFunctions(ar, kind);
960 if (kind != MATHML) {
965 if (kind != MATHML) {
969 //lyxerr << "\nStructure to: " << ar << endl;
975 string captureOutput(string const & cmd, string const & data)
977 // In order to avoid parsing problems with command interpreters
978 // we pass input data through a file
979 FileName const cas_tmpfile = FileName::tempName("casinput");
980 if (cas_tmpfile.empty()) {
981 lyxerr << "Warning: cannot create temporary file."
985 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
988 string command = cmd + " < "
989 + quoteName(cas_tmpfile.toFilesystemEncoding());
990 lyxerr << "calling: " << cmd
991 << "\ninput: '" << data << "'" << endl;
992 cmd_ret const ret = runCommand(command);
993 cas_tmpfile.removeFile();
997 size_t get_matching_brace(string const & str, size_t i)
1000 size_t n = str.size();
1002 i = str.find_first_of("{}", i+1);
1015 size_t get_matching_brace_back(string const & str, size_t i)
1019 i = str.find_last_of("{}", i-1);
1032 MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1034 odocstringstream os;
1035 MaximaStream ms(os);
1037 docstring expr = os.str();
1038 docstring const header = from_ascii("simpsum:true;");
1041 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1042 // try to fix missing '*' the hard way
1044 // > echo "2x;" | maxima
1046 // (C1) Incorrect syntax: x is not an infix operator
1050 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1051 docstring full = header + "tex(" + expr + ");";
1052 out = captureOutput("maxima", to_utf8(full));
1054 // leave loop if expression syntax is probably ok
1055 if (out.find("Incorrect syntax") == npos)
1058 // search line with "Incorrect syntax"
1059 istringstream is(out);
1063 if (line.find("Incorrect syntax") != npos)
1067 // 2nd next line is the one with caret
1070 size_t pos = line.find('^');
1071 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1072 if (pos == npos || pos < 4)
1073 break; // caret position not found
1074 pos -= 4; // skip the "tex(" part
1075 if (expr[pos] == '*')
1076 break; // two '*' in a row are definitely bad
1077 expr.insert(pos, from_ascii("*"));
1080 vector<string> tmp = getVectorFromString(out, "$$");
1084 out = subst(tmp[1], "\\>", string());
1085 lyxerr << "output: '" << out << "'" << endl;
1087 // Ugly code that tries to make the result prettier
1088 size_t i = out.find("\\mathchoice");
1090 size_t j = get_matching_brace(out, i + 12);
1091 size_t k = get_matching_brace(out, j + 1);
1092 k = get_matching_brace(out, k + 1);
1093 k = get_matching_brace(out, k + 1);
1094 string mid = out.substr(i + 13, j - i - 13);
1095 if (mid.find("\\over") != npos)
1096 mid = '{' + mid + '}';
1097 out = out.substr(0, i)
1099 + out.substr(k + 1);
1100 //lyxerr << "output: " << out << endl;
1101 i = out.find("\\mathchoice", i);
1105 i = out.find("\\over");
1107 size_t j = get_matching_brace_back(out, i - 1);
1108 if (j == npos || j == 0)
1110 size_t k = get_matching_brace(out, i + 5);
1111 if (k == npos || k + 1 == out.size())
1113 out = out.substr(0, j - 1)
1115 + out.substr(j, i - j)
1116 + out.substr(i + 5, k - i - 4)
1117 + out.substr(k + 2);
1118 //lyxerr << "output: " << out << endl;
1119 i = out.find("\\over", i + 4);
1122 mathed_parse_cell(res, from_utf8(out));
1127 MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1129 string header = "readlib(latex):\n";
1131 // remove the \\it for variable names
1132 //"#`latex/csname_font` := `\\it `:"
1134 "`latex/csname_font` := ``:\n";
1136 // export matrices in (...) instead of [...]
1138 "`latex/latex/matrix` := "
1139 "subs(`[`=`(`, `]`=`)`,"
1140 "eval(`latex/latex/matrix`)):\n";
1142 // replace \\cdots with proper '*'
1144 "`latex/latex/*` := "
1145 "subs(`\\,`=`\\cdot `,"
1146 "eval(`latex/latex/*`)):\n";
1148 // remove spurious \\noalign{\\medskip} in matrix output
1150 "`latex/latex/matrix`:= "
1151 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1152 "eval(`latex/latex/matrix`)):\n";
1154 //"#`latex/latex/symbol` "
1155 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1157 string trailer = "quit;";
1158 odocstringstream os;
1161 string expr = to_utf8(os.str());
1162 lyxerr << "ar: '" << ar << "'\n"
1163 << "ms: '" << expr << "'" << endl;
1165 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1166 // try to fix missing '*' the hard way by using mint
1168 // ... > echo "1A;" | mint -i 1 -S -s -q
1171 // Probably missing an operator such as * p
1173 lyxerr << "checking expr: '" << expr << "'" << endl;
1174 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1176 break; // expression syntax is ok
1177 istringstream is(out);
1180 if (line.find("on line") != 0)
1181 break; // error message not identified
1183 size_t pos = line.find('^');
1184 if (pos == string::npos || pos < 15)
1185 break; // caret position not found
1186 pos -= 15; // skip the "on line ..." part
1187 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1188 break; // two '*' in a row are definitely bad
1189 expr.insert(pos, 1, '*');
1192 // FIXME UNICODE Is utf8 encoding correct?
1193 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1194 string out = captureOutput("maple -q", header + full + trailer);
1200 mathed_parse_cell(res, from_utf8(out));
1205 MathData pipeThroughOctave(docstring const &, MathData const & ar)
1207 odocstringstream os;
1208 OctaveStream vs(os);
1210 string expr = to_utf8(os.str());
1213 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1214 lyxerr << "pipe: ar: '" << ar << "'\n"
1215 << "pipe: expr: '" << expr << "'" << endl;
1217 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1219 // try to fix missing '*' the hard way
1221 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1224 lyxerr << "checking expr: '" << expr << "'" << endl;
1225 out = captureOutput("octave -q 2>&1", expr);
1226 lyxerr << "output: '" << out << "'" << endl;
1228 // leave loop if expression syntax is probably ok
1229 if (out.find("parse error:") == string::npos)
1232 // search line with single caret
1233 istringstream is(out);
1237 lyxerr << "skipping line: '" << line << "'" << endl;
1238 if (line.find(">>> ") != string::npos)
1242 // found line with error, next line is the one with caret
1244 size_t pos = line.find('^');
1245 lyxerr << "caret line: '" << line << "'" << endl;
1246 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1247 if (pos == string::npos || pos < 4)
1248 break; // caret position not found
1249 pos -= 4; // skip the ">>> " part
1250 if (expr[pos] == '*')
1251 break; // two '*' in a row are definitely bad
1252 expr.insert(pos, 1, '*');
1255 // remove 'ans = ' taking into account that there may be an
1256 // ansi control sequence before, such as '\033[?1034hans = '
1257 size_t i = out.find("ans = ");
1258 if (i == string::npos)
1260 out = out.substr(i + 6);
1262 // parse output as matrix or single number
1263 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1264 InsetMathArray const * mat = at->asArrayInset();
1266 if (mat->ncols() == 1 && mat->nrows() == 1)
1267 res.append(mat->cell(0));
1269 res.push_back(MathAtom(
1270 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1271 res.back().nucleus()->cell(0).push_back(at);
1277 string fromMathematicaName(string const & name)
1279 if (name == "Sin") return "sin";
1280 if (name == "Sinh") return "sinh";
1281 if (name == "ArcSin") return "arcsin";
1282 if (name == "Cos") return "cos";
1283 if (name == "Cosh") return "cosh";
1284 if (name == "ArcCos") return "arccos";
1285 if (name == "Tan") return "tan";
1286 if (name == "Tanh") return "tanh";
1287 if (name == "ArcTan") return "arctan";
1288 if (name == "Cot") return "cot";
1289 if (name == "Coth") return "coth";
1290 if (name == "Csc") return "csc";
1291 if (name == "Sec") return "sec";
1292 if (name == "Exp") return "exp";
1293 if (name == "Log") return "log";
1294 if (name == "Arg" ) return "arg";
1295 if (name == "Det" ) return "det";
1296 if (name == "GCD" ) return "gcd";
1297 if (name == "Max" ) return "max";
1298 if (name == "Min" ) return "min";
1299 if (name == "Erf" ) return "erf";
1300 if (name == "Erfc" ) return "erfc";
1305 void prettifyMathematicaOutput(string & out, string const & macroName,
1306 bool roman, bool translate)
1308 string const macro = "\\" + macroName + "{";
1309 size_t const len = macro.length();
1310 size_t i = out.find(macro);
1313 size_t const j = get_matching_brace(out, i + len);
1314 string const name = out.substr(i + len, j - i - len);
1315 out = out.substr(0, i)
1316 + (roman ? "\\mathrm{" : "")
1317 + (translate ? fromMathematicaName(name) : name)
1318 + out.substr(roman ? j : j + 1);
1319 //lyxerr << "output: " << out << endl;
1320 i = out.find(macro, i);
1325 MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1327 odocstringstream os;
1328 MathematicaStream ms(os);
1330 // FIXME UNICODE Is utf8 encoding correct?
1331 string const expr = to_utf8(os.str());
1334 lyxerr << "expr: '" << expr << "'" << endl;
1336 string const full = "TeXForm[" + expr + "]";
1337 out = captureOutput("math", full);
1338 lyxerr << "output: '" << out << "'" << endl;
1340 size_t pos1 = out.find("Out[1]//TeXForm= ");
1341 size_t pos2 = out.find("In[2]:=");
1343 if (pos1 == string::npos || pos2 == string::npos)
1346 // get everything from pos1+17 to pos2
1347 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1348 out = subst(subst(out, '\r', ' '), '\n', ' ');
1350 // tries to make the result prettier
1351 prettifyMathematicaOutput(out, "Mfunction", true, true);
1352 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1353 prettifyMathematicaOutput(out, "Mvariable", false, false);
1356 mathed_parse_cell(res, from_utf8(out));
1364 void write(MathData const & dat, WriteStream & wi)
1368 wi.firstitem() = true;
1369 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it) {
1371 wi.firstitem() = false;
1376 void normalize(MathData const & ar, NormalStream & os)
1378 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1379 (*it)->normalize(os);
1383 void octave(MathData const & dat, OctaveStream & os)
1386 extractStructure(ar, OCTAVE);
1387 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1392 void maple(MathData const & dat, MapleStream & os)
1395 extractStructure(ar, MAPLE);
1396 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1401 void maxima(MathData const & dat, MaximaStream & os)
1404 extractStructure(ar, MAXIMA);
1405 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1410 void mathematica(MathData const & dat, MathematicaStream & os)
1413 extractStructure(ar, MATHEMATICA);
1414 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1415 (*it)->mathematica(os);
1419 void mathmlize(MathData const & dat, MathStream & os)
1422 extractStructure(ar, MATHML);
1423 if (ar.size() == 0) {
1426 } else if (ar.size() == 1)
1431 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1432 (*it)->mathmlize(os);
1439 // convert this inset somehow to a number
1440 bool extractNumber(MathData const & ar, int & i)
1442 idocstringstream is(charSequence(ar.begin(), ar.end()));
1448 bool extractNumber(MathData const & ar, double & d)
1450 idocstringstream is(charSequence(ar.begin(), ar.end()));
1456 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1457 MathData const & ar)
1459 if (lang == "octave")
1460 return pipeThroughOctave(extra, ar);
1462 if (lang == "maxima")
1463 return pipeThroughMaxima(extra, ar);
1465 if (lang == "maple")
1466 return pipeThroughMaple(extra, ar);
1468 if (lang == "mathematica")
1469 return pipeThroughMathematica(extra, ar);
1471 // create normalized expression
1472 odocstringstream os;
1473 NormalStream ns(os);
1474 os << '[' << extra << ' ';
1477 // FIXME UNICODE Is utf8 encoding correct?
1478 string data = to_utf8(os.str());
1480 // search external script
1481 FileName const file = libFileSearch("mathed", "extern_" + lang);
1483 lyxerr << "converter to '" << lang << "' not found" << endl;
1487 // run external sript
1488 string out = captureOutput(file.absFilename(), data);
1490 mathed_parse_cell(res, from_utf8(out));