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"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/FileName.h"
43 #include "support/filetools.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/TempFile.h"
47 #include "support/textutils.h"
48 #include "support/unique_ptr.h"
56 using namespace lyx::support;
72 static char const * function_names[] = {
73 "arccos", "arcsin", "arctan", "arg", "bmod",
74 "cos", "cosh", "cot", "coth", "csc", "deg",
75 "det", "dim", "exp", "gcd", "hom", "inf", "ker",
76 "lg", "lim", "liminf", "limsup", "ln", "log",
77 "max", "min", "sec", "sin", "sinh", "sup",
78 "tan", "tanh", "Pr", 0
81 static size_t const npos = lyx::docstring::npos;
83 // define a function for tests
84 typedef bool TestItemFunc(MathAtom const &);
86 // define a function for replacing subexpressions
87 typedef MathAtom ReplaceArgumentFunc(const MathData & ar);
91 // try to extract a super/subscript
92 // modify iterator position to point behind the thing
93 bool extractScript(MathData & ar,
94 MathData::iterator & pos, MathData::iterator last, bool superscript)
96 // nothing to get here
100 // is this a scriptinset?
101 if (!(*pos)->asScriptInset())
104 // do we want superscripts only?
105 if (superscript && !(*pos)->asScriptInset()->hasUp())
108 // it is a scriptinset, use it.
115 // try to extract an "argument" to some function.
116 // returns position behind the argument
117 MathData::iterator extractArgument(MathData & ar,
118 MathData::iterator pos, MathData::iterator last,
119 ExternalMath kind, bool function = false)
121 // nothing to get here
125 // something delimited _is_ an argument
126 if ((*pos)->asDelimInset()) {
127 // leave out delimiters if this is a function argument
128 // unless we are doing MathML, in which case we do want
130 if (function && kind != MATHML && kind != HTML) {
131 MathData const & arg = (*pos)->asDelimInset()->cell(0);
132 MathData::const_iterator cur = arg.begin();
133 MathData::const_iterator end = arg.end();
135 ar.push_back(*cur++);
141 // if there's one, get following superscript only if this
142 // isn't a function argument
144 extractScript(ar, pos, last, true);
148 // always take the first thing, no matter what it is
151 // go ahead if possible
156 // if the next item is a super/subscript, it most certainly belongs
157 // to the thing we have
158 extractScript(ar, pos, last, false);
162 // but it might be more than that.
163 // FIXME: not implemented
164 //for (MathData::iterator it = pos + 1; it != last; ++it) {
165 // // always take the first thing, no matter
167 // ar.push_back(*it);
175 // returns sequence of char with same code starting at it up to end
176 // it might be less, though...
177 docstring charSequence
178 (MathData::const_iterator it, MathData::const_iterator end)
181 for (; it != end && (*it)->asCharInset(); ++it)
182 s += (*it)->getChar();
187 void extractStrings(MathData & ar)
189 //lyxerr << "\nStrings from: " << ar << endl;
190 for (size_t i = 0; i < ar.size(); ++i) {
191 if (!ar[i]->asCharInset())
193 docstring s = charSequence(ar.begin() + i, ar.end());
194 ar[i] = MathAtom(new InsetMathString(s));
195 ar.erase(i + 1, i + s.size());
197 //lyxerr << "\nStrings to: " << ar << endl;
201 void extractMatrices(MathData & ar)
203 //lyxerr << "\nMatrices from: " << ar << endl;
204 // first pass for explicitly delimited stuff
205 for (size_t i = 0; i < ar.size(); ++i) {
206 InsetMathDelim const * const inset = ar[i]->asDelimInset();
209 MathData const & arr = inset->cell(0);
212 if (!arr.front()->asGridInset())
214 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset()),
215 inset->left_, inset->right_));
218 // second pass for AMS "pmatrix" etc
219 for (size_t i = 0; i < ar.size(); ++i) {
220 InsetMathAMSArray const * const inset = ar[i]->asAMSArrayInset();
222 string left = inset->name_left();
225 string right = inset->name_right();
228 ar[i] = MathAtom(new InsetMathMatrix(*inset, from_ascii(left), from_ascii(right)));
231 //lyxerr << "\nMatrices to: " << ar << endl;
235 // convert this inset somehow to a string
236 bool extractString(MathAtom const & at, docstring & str)
239 str = docstring(1, at->getChar());
242 if (at->asStringInset()) {
243 str = at->asStringInset()->str();
250 // is this a known function?
251 bool isKnownFunction(docstring const & str)
253 for (int i = 0; function_names[i]; ++i) {
254 if (str == function_names[i])
261 // extract a function name from this inset
262 bool extractFunctionName(MathAtom const & at, docstring & str)
264 if (at->asSymbolInset()) {
265 str = at->asSymbolInset()->name();
266 return isKnownFunction(str);
268 if (at->asUnknownInset()) {
269 // assume it is well known...
273 if (at->asFontInset() && at->name() == "mathrm") {
274 // assume it is well known...
275 MathData const & ar = at->asFontInset()->cell(0);
276 str = charSequence(ar.begin(), ar.end());
277 return ar.size() == str.size();
283 bool testString(MathAtom const & at, docstring const & str)
286 return extractString(at, s) && str == s;
290 bool testString(MathAtom const & at, char const * const str)
292 return testString(at, from_ascii(str));
295 // search end of nested sequence
296 MathData::iterator endNestSearch(
297 MathData::iterator it,
298 MathData::iterator last,
299 TestItemFunc testOpen,
300 TestItemFunc testClose
303 for (int level = 0; it != last; ++it) {
315 // replace nested sequences by a real Insets
318 TestItemFunc testOpen,
319 TestItemFunc testClose,
320 ReplaceArgumentFunc replaceArg)
322 Buffer * buf = ar.buffer();
323 // use indices rather than iterators for the loop because we are going
324 // to modify the array.
325 for (size_t i = 0; i < ar.size(); ++i) {
326 // check whether this is the begin of the sequence
327 if (!testOpen(ar[i]))
330 // search end of sequence
331 MathData::iterator it = ar.begin() + i;
332 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
336 // replace the original stuff by the new inset
337 ar[i] = replaceArg(MathData(buf, it + 1, jt));
338 ar.erase(it + 1, jt + 1);
345 // split scripts into seperate super- and subscript insets. sub goes in
349 void splitScripts(MathData & ar)
351 Buffer * buf = ar.buffer();
352 //lyxerr << "\nScripts from: " << ar << endl;
353 for (size_t i = 0; i < ar.size(); ++i) {
354 InsetMathScript const * script = ar[i]->asScriptInset();
356 // is this a script inset and do we also have a superscript?
357 if (!script || !script->hasUp())
360 // we must have a nucleus if we only have a superscript
361 if (!script->hasDown() && script->nuc().empty())
364 if (script->nuc().size() == 1) {
365 // leave alone sums and integrals
366 InsetMathSymbol const * sym =
367 script->nuc().front()->asSymbolInset();
368 if (sym && (sym->name() == "sum" || sym->name() == "int"))
372 // create extra script inset and move superscript over
373 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
374 auto q = make_unique<InsetMathScript>(buf, true);
375 swap(q->up(), p->up());
376 p->removeScript(true);
378 // if we don't have a subscript, get rid of the ScriptInset
379 if (!script->hasDown()) {
380 MathData arg(p->nuc());
381 MathData::const_iterator it = arg.begin();
382 MathData::const_iterator et = arg.end();
385 ar.insert(i++, *it++);
389 // insert new inset behind
390 ar.insert(i, MathAtom(q.release()));
392 //lyxerr << "\nScripts to: " << ar << endl;
400 void extractExps(MathData & ar)
402 Buffer * buf = ar.buffer();
403 //lyxerr << "\nExps from: " << ar << endl;
404 for (size_t i = 0; i + 1 < ar.size(); ++i) {
406 if (ar[i]->getChar() != 'e')
409 // we need an exponent but no subscript
410 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
411 if (!sup || sup->hasDown())
414 // create a proper exp-inset as replacement
415 ar[i] = MathAtom(new InsetMathExFunc(buf, from_ascii("exp"), sup->cell(1)));
418 //lyxerr << "\nExps to: " << ar << endl;
423 // extract det(...) from |matrix|
425 void extractDets(MathData & ar)
427 Buffer * buf = ar.buffer();
428 //lyxerr << "\ndet from: " << ar << endl;
429 for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
430 InsetMathDelim const * del = (*it)->asDelimInset();
435 *it = MathAtom(new InsetMathExFunc(buf, from_ascii("det"), del->cell(0)));
437 //lyxerr << "\ndet to: " << ar << endl;
445 bool isDigitOrSimilar(char_type c)
447 return ('0' <= c && c <= '9') || c == '.';
451 // returns sequence of digits
452 docstring digitSequence
453 (MathData::const_iterator it, MathData::const_iterator end)
456 for (; it != end && (*it)->asCharInset(); ++it) {
457 if (!isDigitOrSimilar((*it)->getChar()))
459 s += (*it)->getChar();
465 void extractNumbers(MathData & ar)
467 //lyxerr << "\nNumbers from: " << ar << endl;
468 for (size_t i = 0; i < ar.size(); ++i) {
469 if (!ar[i]->asCharInset())
471 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
474 docstring s = digitSequence(ar.begin() + i, ar.end());
476 ar[i] = MathAtom(new InsetMathNumber(s));
477 ar.erase(i + 1, i + s.size());
479 //lyxerr << "\nNumbers to: " << ar << endl;
488 bool testOpenParen(MathAtom const & at)
490 return testString(at, "(");
494 bool testCloseParen(MathAtom const & at)
496 return testString(at, ")");
500 MathAtom replaceParenDelims(const MathData & ar)
502 return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
503 from_ascii("("), from_ascii(")"), ar));
507 bool testOpenBracket(MathAtom const & at)
509 return testString(at, "[");
513 bool testCloseBracket(MathAtom const & at)
515 return testString(at, "]");
519 MathAtom replaceBracketDelims(const MathData & ar)
521 return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
522 from_ascii("["), from_ascii("]"), ar));
526 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
527 void extractDelims(MathData & ar)
529 //lyxerr << "\nDelims from: " << ar << endl;
530 replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
531 replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
532 //lyxerr << "\nDelims to: " << ar << endl;
538 // search well-known functions
542 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
543 // assume 'extractDelims' ran before
544 void extractFunctions(MathData & ar, ExternalMath kind)
546 // FIXME From what I can see, this is quite broken right now, for reasons
547 // I will note below. (RGH)
549 // we need at least two items...
553 Buffer * buf = ar.buffer();
555 //lyxerr << "\nFunctions from: " << ar << endl;
556 for (size_t i = 0; i + 1 < ar.size(); ++i) {
557 MathData::iterator it = ar.begin() + i;
558 MathData::iterator jt = it + 1;
562 // it certainly is if it is well known...
564 // FIXME This will never give us anything. When we get here, *it will
565 // never point at a string, but only at a character. I.e., if we are
566 // working on "sin(x)", then we are seeing:
567 // [char s mathalpha][char i mathalpha][char n mathalpha][delim ( ) [char x mathalpha]]
568 // and of course we will not find the function name "sin" in there, but
571 // It appears that we original ran extractStrings() before we ran
572 // extractFunctions(), but Andre changed this at f200be55, I think
573 // because this messed up what he was trying to do with "dx" in the
574 // context of integrals.
576 // This could be fixed by looking at a charSequence instead of just at
577 // the various characters, one by one. But I am not sure I understand
578 // exactly what we are trying to do here. And it involves a lot of
580 if (!extractFunctionName(*it, name)) {
581 // is this a user defined function?
582 // probably not, if it doesn't have a name.
583 if (!extractString(*it, name))
585 // it is not if it has no argument
588 // guess so, if this is followed by
589 // a DelimInset with a single item in the cell
590 InsetMathDelim const * del = (*jt)->asDelimInset();
591 if (!del || del->cell(0).size() != 1)
593 // fall through into main branch
596 // do we have an exponent like in
597 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
599 extractScript(exp, jt, ar.end(), true);
601 // create a proper inset as replacement
602 auto p = make_unique<InsetMathExFunc>(buf, name);
604 // jt points to the "argument". Get hold of this.
605 MathData::iterator st =
606 extractArgument(p->cell(0), jt, ar.end(), kind, true);
608 // replace the function name by a real function inset
609 *it = MathAtom(p.release());
611 // remove the source of the argument from the array
612 ar.erase(it + 1, st);
614 // re-insert exponent
615 ar.insert(i + 1, exp);
616 //lyxerr << "\nFunctions to: " << ar << endl;
625 bool testSymbol(MathAtom const & at, docstring const & name)
627 return at->asSymbolInset() && at->asSymbolInset()->name() == name;
631 bool testSymbol(MathAtom const & at, char const * const name)
633 return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
637 bool testIntSymbol(MathAtom const & at)
639 return testSymbol(at, from_ascii("int"));
643 bool testIntegral(MathAtom const & at)
647 ( at->asScriptInset()
648 && !at->asScriptInset()->nuc().empty()
649 && testIntSymbol(at->asScriptInset()->nuc().back()) );
654 bool testIntDiff(MathAtom const & at)
656 return testString(at, "d");
660 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
661 // assume 'extractDelims' ran before
662 void extractIntegrals(MathData & ar, ExternalMath kind)
664 // we need at least three items...
668 Buffer * buf = ar.buffer();
670 //lyxerr << "\nIntegrals from: " << ar << endl;
671 for (size_t i = 0; i + 1 < ar.size(); ++i) {
672 MathData::iterator it = ar.begin() + i;
675 MathData::iterator jt =
676 endNestSearch(it, ar.end(), testIntegral, testIntDiff);
678 // something sensible found?
682 // is this a integral name?
683 if (!testIntegral(*it))
686 // core ist part from behind the scripts to the 'd'
687 auto p = make_unique<InsetMathExInt>(buf, from_ascii("int"));
689 // handle scripts if available
690 if (!testIntSymbol(*it)) {
691 p->cell(2) = (*it)->asScriptInset()->down();
692 p->cell(3) = (*it)->asScriptInset()->up();
694 p->cell(0) = MathData(buf, it + 1, jt);
696 // use the "thing" behind the 'd' as differential
697 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end(), kind);
700 ar.erase(it + 1, tt);
701 *it = MathAtom(p.release());
703 //lyxerr << "\nIntegrals to: " << ar << endl;
707 bool testTermDelimiter(MathAtom const & at)
709 return testString(at, "+") || testString(at, "-");
713 // try to extract a "term", i.e., something delimited by '+' or '-'.
714 // returns position behind the term
715 MathData::iterator extractTerm(MathData & ar,
716 MathData::iterator pos, MathData::iterator last)
718 while (pos != last && !testTermDelimiter(*pos)) {
731 bool testEqualSign(MathAtom const & at)
733 return testString(at, "=");
737 bool testSumSymbol(MathAtom const & p)
739 return testSymbol(p, from_ascii("sum"));
743 bool testSum(MathAtom const & at)
747 ( at->asScriptInset()
748 && !at->asScriptInset()->nuc().empty()
749 && testSumSymbol(at->asScriptInset()->nuc().back()) );
753 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
754 // assume 'extractDelims' ran before
755 void extractSums(MathData & ar)
757 // we need at least two items...
761 Buffer * buf = ar.buffer();
763 //lyxerr << "\nSums from: " << ar << endl;
764 for (size_t i = 0; i + 1 < ar.size(); ++i) {
765 MathData::iterator it = ar.begin() + i;
767 // is this a sum name?
771 // create a proper inset as replacement
772 auto p = make_unique<InsetMathExInt>(buf, from_ascii("sum"));
774 // collect lower bound and summation index
775 InsetMathScript const * sub = ar[i]->asScriptInset();
776 if (sub && sub->hasDown()) {
777 // try to figure out the summation index from the subscript
778 MathData const & ar = sub->down();
779 MathData::const_iterator xt =
780 find_if(ar.begin(), ar.end(), &testEqualSign);
781 if (xt != ar.end()) {
782 // we found a '=', use everything in front of that as index,
783 // and everything behind as lower index
784 p->cell(1) = MathData(buf, ar.begin(), xt);
785 p->cell(2) = MathData(buf, xt + 1, ar.end());
787 // use everything as summation index, don't use scripts.
792 // collect upper bound
793 if (sub && sub->hasUp())
794 p->cell(3) = sub->up();
796 // use something behind the script as core
797 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
800 ar.erase(it + 1, tt);
801 *it = MathAtom(p.release());
803 //lyxerr << "\nSums to: " << ar << endl;
808 // search differential stuff
811 // tests for 'd' or '\partial'
812 bool testDiffItem(MathAtom const & at)
814 if (testString(at, "d") || testSymbol(at, "partial"))
817 // we may have d^n .../d and splitScripts() has not yet seen it
818 InsetMathScript const * sup = at->asScriptInset();
819 if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
820 MathAtom const & ma = sup->nuc().front();
821 return testString(ma, "d") || testSymbol(ma, "partial");
827 bool testDiffArray(MathData const & ar)
829 return !ar.empty() && testDiffItem(ar.front());
833 bool testDiffFrac(MathAtom const & at)
837 && testDiffArray(at->asFracInset()->cell(0))
838 && testDiffArray(at->asFracInset()->cell(1));
842 void extractDiff(MathData & ar)
844 Buffer * buf = ar.buffer();
845 //lyxerr << "\nDiffs from: " << ar << endl;
846 for (size_t i = 0; i < ar.size(); ++i) {
847 MathData::iterator it = ar.begin() + i;
849 // is this a "differential fraction"?
850 if (!testDiffFrac(*it))
853 InsetMathFrac const * f = (*it)->asFracInset();
855 lyxerr << "should not happen" << endl;
859 // create a proper diff inset
860 auto diff = make_unique<InsetMathDiff>(buf);
862 // collect function, let jt point behind last used item
863 MathData::iterator jt = it + 1;
865 MathData numer(f->cell(0));
867 if (numer.size() > 1 && numer[1]->asScriptInset()) {
868 // this is something like d^n f(x) / d... or d^n / d...
871 if (numer.size() > 2)
872 diff->cell(0) = MathData(buf, numer.begin() + 2, numer.end());
874 jt = extractTerm(diff->cell(0), jt, ar.end());
876 // simply d f(x) / d... or d/d...
877 if (numer.size() > 1)
878 diff->cell(0) = MathData(buf, numer.begin() + 1, numer.end());
880 jt = extractTerm(diff->cell(0), jt, ar.end());
883 // collect denominator parts
884 MathData denom(f->cell(1));
886 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
888 MathData::iterator et
889 = find_if(dt + 1, denom.end(), &testDiffItem);
892 MathData::iterator st = et - 1;
893 InsetMathScript const * script = (*st)->asScriptInset();
894 if (script && script->hasUp()) {
895 // things like d.../dx^n
897 if (extractNumber(script->up(), mult)) {
898 //lyxerr << "mult: " << mult << endl;
899 for (int i = 0; i < mult; ++i)
900 diff->addDer(MathData(buf, dt + 1, st));
904 diff->addDer(MathData(buf, dt + 1, et));
910 ar.erase(it + 1, jt);
911 *it = MathAtom(diff.release());
913 //lyxerr << "\nDiffs to: " << ar << endl;
922 bool testRightArrow(MathAtom const & at)
924 return testSymbol(at, "to") || testSymbol(at, "rightarrow");
929 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
930 // assume 'extractDelims' ran before
931 void extractLims(MathData & ar)
933 Buffer * buf = ar.buffer();
934 //lyxerr << "\nLimits from: " << ar << endl;
935 for (size_t i = 0; i < ar.size(); ++i) {
936 MathData::iterator it = ar.begin() + i;
938 // must be a script inset with a subscript (without superscript)
939 InsetMathScript const * sub = (*it)->asScriptInset();
940 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
943 // is this a limit function?
944 if (!testSymbol(sub->nuc().front(), "lim"))
947 // subscript must contain a -> symbol
948 MathData const & s = sub->down();
949 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
953 // the -> splits the subscript int x and x0
954 MathData x = MathData(buf, s.begin(), st);
955 MathData x0 = MathData(buf, st + 1, s.end());
957 // use something behind the script as core
959 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
962 ar.erase(it + 1, tt);
964 // create a proper inset as replacement
965 *it = MathAtom(new InsetMathLim(buf, f, x, x0));
967 //lyxerr << "\nLimits to: " << ar << endl;
975 void extractStructure(MathData & ar, ExternalMath kind)
977 //lyxerr << "\nStructure from: " << ar << endl;
978 if (kind != MATHML && kind != HTML)
981 extractIntegrals(ar, kind);
982 if (kind != MATHML && kind != HTML)
986 if (kind != MATHML && kind != HTML) {
987 extractFunctions(ar, kind);
994 //lyxerr << "\nStructure to: " << ar << endl;
1000 string captureOutput(string const & cmd, string const & data)
1002 // In order to avoid parsing problems with command interpreters
1003 // we pass input data through a file
1004 TempFile tempfile("casinput");
1005 FileName const cas_tmpfile = tempfile.name();
1006 if (cas_tmpfile.empty()) {
1007 lyxerr << "Warning: cannot create temporary file."
1011 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
1014 string command = cmd + " < "
1015 + quoteName(cas_tmpfile.toFilesystemEncoding());
1016 lyxerr << "calling: " << cmd
1017 << "\ninput: '" << data << "'" << endl;
1018 cmd_ret const ret = runCommand(command);
1022 size_t get_matching_brace(string const & str, size_t i)
1025 size_t n = str.size();
1027 i = str.find_first_of("{}", i+1);
1040 size_t get_matching_brace_back(string const & str, size_t i)
1044 i = str.find_last_of("{}", i-1);
1057 MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1059 odocstringstream os;
1060 MaximaStream ms(os);
1062 docstring expr = os.str();
1063 docstring const header = from_ascii("simpsum:true;");
1066 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1067 // try to fix missing '*' the hard way
1069 // > echo "2x;" | maxima
1071 // (C1) Incorrect syntax: x is not an infix operator
1075 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1076 docstring full = header + "tex(" + expr + ");";
1077 out = captureOutput("maxima", to_utf8(full));
1079 // leave loop if expression syntax is probably ok
1080 if (out.find("Incorrect syntax") == npos)
1083 // search line with "Incorrect syntax"
1084 istringstream is(out);
1088 if (line.find("Incorrect syntax") != npos)
1092 // 2nd next line is the one with caret
1095 size_t pos = line.find('^');
1096 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1097 if (pos == npos || pos < 4)
1098 break; // caret position not found
1099 pos -= 4; // skip the "tex(" part
1100 if (expr[pos] == '*')
1101 break; // two '*' in a row are definitely bad
1102 expr.insert(pos, from_ascii("*"));
1105 vector<string> tmp = getVectorFromString(out, "$$");
1109 out = subst(subst(tmp[1], "\\>", string()), "{\\it ", "\\mathit{");
1110 lyxerr << "output: '" << out << "'" << endl;
1112 // Ugly code that tries to make the result prettier
1113 size_t i = out.find("\\mathchoice");
1115 size_t j = get_matching_brace(out, i + 12);
1116 size_t k = get_matching_brace(out, j + 1);
1117 k = get_matching_brace(out, k + 1);
1118 k = get_matching_brace(out, k + 1);
1119 string mid = out.substr(i + 13, j - i - 13);
1120 if (mid.find("\\over") != npos)
1121 mid = '{' + mid + '}';
1122 out = out.substr(0, i)
1124 + out.substr(k + 1);
1125 //lyxerr << "output: " << out << endl;
1126 i = out.find("\\mathchoice", i);
1129 i = out.find("\\over");
1131 size_t j = get_matching_brace_back(out, i - 1);
1132 if (j == npos || j == 0)
1134 size_t k = get_matching_brace(out, i + 5);
1135 if (k == npos || k + 1 == out.size())
1137 out = out.substr(0, j - 1)
1139 + out.substr(j, i - j)
1140 + out.substr(i + 5, k - i - 4)
1141 + out.substr(k + 2);
1142 //lyxerr << "output: " << out << endl;
1143 i = out.find("\\over", i + 4);
1146 mathed_parse_cell(res, from_utf8(out));
1151 MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1153 string header = "readlib(latex):\n";
1155 // remove the \\it for variable names
1156 //"#`latex/csname_font` := `\\it `:"
1158 "`latex/csname_font` := ``:\n";
1160 // export matrices in (...) instead of [...]
1162 "`latex/latex/matrix` := "
1163 "subs(`[`=`(`, `]`=`)`,"
1164 "eval(`latex/latex/matrix`)):\n";
1166 // replace \\cdots with proper '*'
1168 "`latex/latex/*` := "
1169 "subs(`\\,`=`\\cdot `,"
1170 "eval(`latex/latex/*`)):\n";
1172 // remove spurious \\noalign{\\medskip} in matrix output
1174 "`latex/latex/matrix`:= "
1175 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1176 "eval(`latex/latex/matrix`)):\n";
1178 //"#`latex/latex/symbol` "
1179 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1181 string trailer = "quit;";
1182 odocstringstream os;
1185 string expr = to_utf8(os.str());
1186 lyxerr << "ar: '" << ar << "'\n"
1187 << "ms: '" << expr << "'" << endl;
1189 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1190 // try to fix missing '*' the hard way by using mint
1192 // ... > echo "1A;" | mint -i 1 -S -s -q
1195 // Probably missing an operator such as * p
1197 lyxerr << "checking expr: '" << expr << "'" << endl;
1198 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1200 break; // expression syntax is ok
1201 istringstream is(out);
1204 if (!prefixIs(line, "on line"))
1205 break; // error message not identified
1207 size_t pos = line.find('^');
1208 if (pos == string::npos || pos < 15)
1209 break; // caret position not found
1210 pos -= 15; // skip the "on line ..." part
1211 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1212 break; // two '*' in a row are definitely bad
1213 expr.insert(pos, 1, '*');
1216 // FIXME UNICODE Is utf8 encoding correct?
1217 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1218 string out = captureOutput("maple -q", header + full + trailer);
1224 mathed_parse_cell(res, from_utf8(out));
1229 MathData pipeThroughOctave(docstring const &, MathData const & ar)
1231 odocstringstream os;
1232 OctaveStream vs(os);
1234 string expr = to_utf8(os.str());
1237 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1238 lyxerr << "pipe: ar: '" << ar << "'\n"
1239 << "pipe: expr: '" << expr << "'" << endl;
1241 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1243 // try to fix missing '*' the hard way
1245 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1248 lyxerr << "checking expr: '" << expr << "'" << endl;
1249 out = captureOutput("octave -q 2>&1", expr);
1250 lyxerr << "output: '" << out << "'" << endl;
1252 // leave loop if expression syntax is probably ok
1253 if (out.find("parse error:") == string::npos)
1256 // search line with single caret
1257 istringstream is(out);
1261 lyxerr << "skipping line: '" << line << "'" << endl;
1262 if (line.find(">>> ") != string::npos)
1266 // found line with error, next line is the one with caret
1268 size_t pos = line.find('^');
1269 lyxerr << "caret line: '" << line << "'" << endl;
1270 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1271 if (pos == string::npos || pos < 4)
1272 break; // caret position not found
1273 pos -= 4; // skip the ">>> " part
1274 if (expr[pos] == '*')
1275 break; // two '*' in a row are definitely bad
1276 expr.insert(pos, 1, '*');
1279 // remove 'ans = ' taking into account that there may be an
1280 // ansi control sequence before, such as '\033[?1034hans = '
1281 size_t i = out.find("ans = ");
1282 if (i == string::npos)
1284 out = out.substr(i + 6);
1286 // parse output as matrix or single number
1287 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1288 InsetMathArray const * mat = at->asArrayInset();
1290 if (mat->ncols() == 1 && mat->nrows() == 1)
1291 res.append(mat->cell(0));
1293 res.push_back(MathAtom(
1294 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1295 res.back().nucleus()->cell(0).push_back(at);
1301 string fromMathematicaName(string const & name)
1303 if (name == "Sin") return "sin";
1304 if (name == "Sinh") return "sinh";
1305 if (name == "ArcSin") return "arcsin";
1306 if (name == "Cos") return "cos";
1307 if (name == "Cosh") return "cosh";
1308 if (name == "ArcCos") return "arccos";
1309 if (name == "Tan") return "tan";
1310 if (name == "Tanh") return "tanh";
1311 if (name == "ArcTan") return "arctan";
1312 if (name == "Cot") return "cot";
1313 if (name == "Coth") return "coth";
1314 if (name == "Csc") return "csc";
1315 if (name == "Sec") return "sec";
1316 if (name == "Exp") return "exp";
1317 if (name == "Log") return "log";
1318 if (name == "Arg" ) return "arg";
1319 if (name == "Det" ) return "det";
1320 if (name == "GCD" ) return "gcd";
1321 if (name == "Max" ) return "max";
1322 if (name == "Min" ) return "min";
1323 if (name == "Erf" ) return "erf";
1324 if (name == "Erfc" ) return "erfc";
1329 void prettifyMathematicaOutput(string & out, string const & macroName,
1330 bool roman, bool translate)
1332 string const macro = "\\" + macroName + "{";
1333 size_t const len = macro.length();
1334 size_t i = out.find(macro);
1337 size_t const j = get_matching_brace(out, i + len);
1338 string const name = out.substr(i + len, j - i - len);
1339 out = out.substr(0, i)
1340 + (roman ? "\\mathrm{" : "")
1341 + (translate ? fromMathematicaName(name) : name)
1342 + out.substr(roman ? j : j + 1);
1343 //lyxerr << "output: " << out << endl;
1344 i = out.find(macro, i);
1349 MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1351 odocstringstream os;
1352 MathematicaStream ms(os);
1354 // FIXME UNICODE Is utf8 encoding correct?
1355 string const expr = to_utf8(os.str());
1358 lyxerr << "expr: '" << expr << "'" << endl;
1360 string const full = "TeXForm[" + expr + "]";
1361 out = captureOutput("math", full);
1362 lyxerr << "output: '" << out << "'" << endl;
1364 size_t pos1 = out.find("Out[1]//TeXForm= ");
1365 size_t pos2 = out.find("In[2]:=");
1367 if (pos1 == string::npos || pos2 == string::npos)
1370 // get everything from pos1+17 to pos2
1371 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1372 out = subst(subst(out, '\r', ' '), '\n', ' ');
1374 // tries to make the result prettier
1375 prettifyMathematicaOutput(out, "Mfunction", true, true);
1376 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1377 prettifyMathematicaOutput(out, "Mvariable", false, false);
1380 mathed_parse_cell(res, from_utf8(out));
1388 void write(MathData const & dat, WriteStream & wi)
1390 wi.firstitem() = true;
1392 for (MathData::const_iterator it = dat.begin(); it != dat.end(); ++it) {
1393 InsetMathChar const * const c = (*it)->asCharInset();
1402 wi.firstitem() = false;
1407 wi.firstitem() = false;
1412 void writeString(docstring const & s, WriteStream & os)
1414 if (!os.latex() || os.lockedMode()) {
1415 os << (os.asciiOnly() ? escape(s) : s);
1419 docstring::const_iterator cit = s.begin();
1420 docstring::const_iterator end = s.end();
1422 // We may already be inside an \ensuremath command.
1423 bool in_forced_mode = os.pendingBrace();
1425 // We will take care of matching braces.
1426 os.pendingBrace(false);
1428 while (cit != end) {
1429 bool mathmode = in_forced_mode ? os.textMode() : !os.textMode();
1430 char_type const c = *cit;
1431 docstring command(1, c);
1433 bool termination = false;
1435 Encodings::latexMathChar(c, mathmode, os.encoding(), command, termination)) {
1436 if (os.textMode()) {
1437 if (in_forced_mode) {
1438 // we were inside \lyxmathsym
1441 in_forced_mode = false;
1443 if (!isASCII(c) && os.textMode()) {
1444 os << "\\ensuremath{";
1446 in_forced_mode = true;
1448 } else if (isASCII(c) && in_forced_mode) {
1449 // we were inside \ensuremath
1452 in_forced_mode = false;
1454 } else if (!os.textMode()) {
1455 if (in_forced_mode) {
1456 // we were inside \ensuremath
1458 in_forced_mode = false;
1460 os << "\\lyxmathsym{";
1461 in_forced_mode = true;
1466 // We may need a space if the command contains a macro
1467 // and the last char is ASCII.
1469 os.pendingSpace(true);
1470 } catch (EncodingException const & e) {
1471 switch (os.output()) {
1472 case WriteStream::wsDryrun: {
1473 os << "<" << _("LyX Warning: ")
1474 << _("uncodable character") << " '";
1475 os << docstring(1, e.failed_char);
1479 case WriteStream::wsPreview: {
1480 // indicate the encoding error by a boxed '?'
1481 os << "{\\fboxsep=1pt\\fbox{?}}";
1482 LYXERR0("Uncodable character" << " '"
1483 << docstring(1, e.failed_char)
1487 case WriteStream::wsDefault:
1496 if (in_forced_mode && os.textMode()) {
1497 // We have to care for closing \lyxmathsym
1501 os.pendingBrace(in_forced_mode);
1506 void normalize(MathData const & ar, NormalStream & os)
1508 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1509 (*it)->normalize(os);
1513 void octave(MathData const & dat, OctaveStream & os)
1516 extractStructure(ar, OCTAVE);
1517 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1522 void maple(MathData const & dat, MapleStream & os)
1525 extractStructure(ar, MAPLE);
1526 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1531 void maxima(MathData const & dat, MaximaStream & os)
1534 extractStructure(ar, MAXIMA);
1535 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1540 void mathematica(MathData const & dat, MathematicaStream & os)
1543 extractStructure(ar, MATHEMATICA);
1544 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1545 (*it)->mathematica(os);
1549 void mathmlize(MathData const & dat, MathStream & os)
1552 extractStructure(ar, MATHML);
1555 else if (ar.size() == 1)
1559 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1560 (*it)->mathmlize(os);
1566 void htmlize(MathData const & dat, HtmlStream & os)
1569 extractStructure(ar, HTML);
1572 if (ar.size() == 1) {
1576 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1581 // convert this inset somehow to a number
1582 bool extractNumber(MathData const & ar, int & i)
1584 idocstringstream is(charSequence(ar.begin(), ar.end()));
1586 // Do not convert is implicitly to bool, since that is forbidden in C++11.
1591 bool extractNumber(MathData const & ar, double & d)
1593 idocstringstream is(charSequence(ar.begin(), ar.end()));
1595 // Do not convert is implicitly to bool, since that is forbidden in C++11.
1600 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1601 MathData const & ar)
1603 if (lang == "octave")
1604 return pipeThroughOctave(extra, ar);
1606 if (lang == "maxima")
1607 return pipeThroughMaxima(extra, ar);
1609 if (lang == "maple")
1610 return pipeThroughMaple(extra, ar);
1612 if (lang == "mathematica")
1613 return pipeThroughMathematica(extra, ar);
1615 // create normalized expression
1616 odocstringstream os;
1617 NormalStream ns(os);
1618 os << '[' << extra << ' ';
1621 // FIXME UNICODE Is utf8 encoding correct?
1622 string data = to_utf8(os.str());
1624 // search external script
1625 FileName const file = libFileSearch("mathed", "extern_" + lang);
1627 lyxerr << "converter to '" << lang << "' not found" << endl;
1631 // run external sript
1632 string out = captureOutput(file.absFileName(), data);
1634 mathed_parse_cell(res, from_utf8(out));