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);
966 //lyxerr << "\nStructure to: " << ar << endl;
972 string captureOutput(string const & cmd, string const & data)
974 // In order to avoid parsing problems with command interpreters
975 // we pass input data through a file
976 FileName const cas_tmpfile = FileName::tempName("casinput");
977 if (cas_tmpfile.empty()) {
978 lyxerr << "Warning: cannot create temporary file."
982 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
985 string command = cmd + " < "
986 + quoteName(cas_tmpfile.toFilesystemEncoding());
987 lyxerr << "calling: " << cmd
988 << "\ninput: '" << data << "'" << endl;
989 cmd_ret const ret = runCommand(command);
990 cas_tmpfile.removeFile();
994 size_t get_matching_brace(string const & str, size_t i)
997 size_t n = str.size();
999 i = str.find_first_of("{}", i+1);
1012 size_t get_matching_brace_back(string const & str, size_t i)
1016 i = str.find_last_of("{}", i-1);
1029 MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1031 odocstringstream os;
1032 MaximaStream ms(os);
1034 docstring expr = os.str();
1035 docstring const header = from_ascii("simpsum:true;");
1038 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1039 // try to fix missing '*' the hard way
1041 // > echo "2x;" | maxima
1043 // (C1) Incorrect syntax: x is not an infix operator
1047 lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1048 docstring full = header + "tex(" + expr + ");";
1049 out = captureOutput("maxima", to_utf8(full));
1051 // leave loop if expression syntax is probably ok
1052 if (out.find("Incorrect syntax") == npos)
1055 // search line with "Incorrect syntax"
1056 istringstream is(out);
1060 if (line.find("Incorrect syntax") != npos)
1064 // 2nd next line is the one with caret
1067 size_t pos = line.find('^');
1068 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1069 if (pos == npos || pos < 4)
1070 break; // caret position not found
1071 pos -= 4; // skip the "tex(" part
1072 if (expr[pos] == '*')
1073 break; // two '*' in a row are definitely bad
1074 expr.insert(pos, from_ascii("*"));
1077 vector<string> tmp = getVectorFromString(out, "$$");
1081 out = subst(tmp[1], "\\>", string());
1082 lyxerr << "output: '" << out << "'" << endl;
1084 // Ugly code that tries to make the result prettier
1085 size_t i = out.find("\\mathchoice");
1087 size_t j = get_matching_brace(out, i + 12);
1088 size_t k = get_matching_brace(out, j + 1);
1089 k = get_matching_brace(out, k + 1);
1090 k = get_matching_brace(out, k + 1);
1091 string mid = out.substr(i + 13, j - i - 13);
1092 if (mid.find("\\over") != npos)
1093 mid = '{' + mid + '}';
1094 out = out.substr(0, i)
1096 + out.substr(k + 1);
1097 //lyxerr << "output: " << out << endl;
1098 i = out.find("\\mathchoice", i);
1102 i = out.find("\\over");
1104 size_t j = get_matching_brace_back(out, i - 1);
1105 if (j == npos || j == 0)
1107 size_t k = get_matching_brace(out, i + 5);
1108 if (k == npos || k + 1 == out.size())
1110 out = out.substr(0, j - 1)
1112 + out.substr(j, i - j)
1113 + out.substr(i + 5, k - i - 4)
1114 + out.substr(k + 2);
1115 //lyxerr << "output: " << out << endl;
1116 i = out.find("\\over", i + 4);
1119 mathed_parse_cell(res, from_utf8(out));
1124 MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1126 string header = "readlib(latex):\n";
1128 // remove the \\it for variable names
1129 //"#`latex/csname_font` := `\\it `:"
1131 "`latex/csname_font` := ``:\n";
1133 // export matrices in (...) instead of [...]
1135 "`latex/latex/matrix` := "
1136 "subs(`[`=`(`, `]`=`)`,"
1137 "eval(`latex/latex/matrix`)):\n";
1139 // replace \\cdots with proper '*'
1141 "`latex/latex/*` := "
1142 "subs(`\\,`=`\\cdot `,"
1143 "eval(`latex/latex/*`)):\n";
1145 // remove spurious \\noalign{\\medskip} in matrix output
1147 "`latex/latex/matrix`:= "
1148 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1149 "eval(`latex/latex/matrix`)):\n";
1151 //"#`latex/latex/symbol` "
1152 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1154 string trailer = "quit;";
1155 odocstringstream os;
1158 string expr = to_utf8(os.str());
1159 lyxerr << "ar: '" << ar << "'\n"
1160 << "ms: '" << expr << "'" << endl;
1162 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1163 // try to fix missing '*' the hard way by using mint
1165 // ... > echo "1A;" | mint -i 1 -S -s -q
1168 // Probably missing an operator such as * p
1170 lyxerr << "checking expr: '" << expr << "'" << endl;
1171 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1173 break; // expression syntax is ok
1174 istringstream is(out);
1177 if (line.find("on line") != 0)
1178 break; // error message not identified
1180 size_t pos = line.find('^');
1181 if (pos == string::npos || pos < 15)
1182 break; // caret position not found
1183 pos -= 15; // skip the "on line ..." part
1184 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1185 break; // two '*' in a row are definitely bad
1186 expr.insert(pos, 1, '*');
1189 // FIXME UNICODE Is utf8 encoding correct?
1190 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1191 string out = captureOutput("maple -q", header + full + trailer);
1197 mathed_parse_cell(res, from_utf8(out));
1202 MathData pipeThroughOctave(docstring const &, MathData const & ar)
1204 odocstringstream os;
1205 OctaveStream vs(os);
1207 string expr = to_utf8(os.str());
1210 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1211 lyxerr << "pipe: ar: '" << ar << "'\n"
1212 << "pipe: expr: '" << expr << "'" << endl;
1214 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1216 // try to fix missing '*' the hard way
1218 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1221 lyxerr << "checking expr: '" << expr << "'" << endl;
1222 out = captureOutput("octave -q 2>&1", expr);
1223 lyxerr << "output: '" << out << "'" << endl;
1225 // leave loop if expression syntax is probably ok
1226 if (out.find("parse error:") == string::npos)
1229 // search line with single caret
1230 istringstream is(out);
1234 lyxerr << "skipping line: '" << line << "'" << endl;
1235 if (line.find(">>> ") != string::npos)
1239 // found line with error, next line is the one with caret
1241 size_t pos = line.find('^');
1242 lyxerr << "caret line: '" << line << "'" << endl;
1243 lyxerr << "found caret at pos: '" << pos << "'" << endl;
1244 if (pos == string::npos || pos < 4)
1245 break; // caret position not found
1246 pos -= 4; // skip the ">>> " part
1247 if (expr[pos] == '*')
1248 break; // two '*' in a row are definitely bad
1249 expr.insert(pos, 1, '*');
1252 // remove 'ans = ' taking into account that there may be an
1253 // ansi control sequence before, such as '\033[?1034hans = '
1254 size_t i = out.find("ans = ");
1255 if (i == string::npos)
1257 out = out.substr(i + 6);
1259 // parse output as matrix or single number
1260 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1261 InsetMathArray const * mat = at->asArrayInset();
1263 if (mat->ncols() == 1 && mat->nrows() == 1)
1264 res.append(mat->cell(0));
1266 res.push_back(MathAtom(
1267 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1268 res.back().nucleus()->cell(0).push_back(at);
1274 string fromMathematicaName(string const & name)
1276 if (name == "Sin") return "sin";
1277 if (name == "Sinh") return "sinh";
1278 if (name == "ArcSin") return "arcsin";
1279 if (name == "Cos") return "cos";
1280 if (name == "Cosh") return "cosh";
1281 if (name == "ArcCos") return "arccos";
1282 if (name == "Tan") return "tan";
1283 if (name == "Tanh") return "tanh";
1284 if (name == "ArcTan") return "arctan";
1285 if (name == "Cot") return "cot";
1286 if (name == "Coth") return "coth";
1287 if (name == "Csc") return "csc";
1288 if (name == "Sec") return "sec";
1289 if (name == "Exp") return "exp";
1290 if (name == "Log") return "log";
1291 if (name == "Arg" ) return "arg";
1292 if (name == "Det" ) return "det";
1293 if (name == "GCD" ) return "gcd";
1294 if (name == "Max" ) return "max";
1295 if (name == "Min" ) return "min";
1296 if (name == "Erf" ) return "erf";
1297 if (name == "Erfc" ) return "erfc";
1302 void prettifyMathematicaOutput(string & out, string const & macroName,
1303 bool roman, bool translate)
1305 string const macro = "\\" + macroName + "{";
1306 size_t const len = macro.length();
1307 size_t i = out.find(macro);
1310 size_t const j = get_matching_brace(out, i + len);
1311 string const name = out.substr(i + len, j - i - len);
1312 out = out.substr(0, i)
1313 + (roman ? "\\mathrm{" : "")
1314 + (translate ? fromMathematicaName(name) : name)
1315 + out.substr(roman ? j : j + 1);
1316 //lyxerr << "output: " << out << endl;
1317 i = out.find(macro, i);
1322 MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1324 odocstringstream os;
1325 MathematicaStream ms(os);
1327 // FIXME UNICODE Is utf8 encoding correct?
1328 string const expr = to_utf8(os.str());
1331 lyxerr << "expr: '" << expr << "'" << endl;
1333 string const full = "TeXForm[" + expr + "]";
1334 out = captureOutput("math", full);
1335 lyxerr << "output: '" << out << "'" << endl;
1337 size_t pos1 = out.find("Out[1]//TeXForm= ");
1338 size_t pos2 = out.find("In[2]:=");
1340 if (pos1 == string::npos || pos2 == string::npos)
1343 // get everything from pos1+17 to pos2
1344 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1345 out = subst(subst(out, '\r', ' '), '\n', ' ');
1347 // tries to make the result prettier
1348 prettifyMathematicaOutput(out, "Mfunction", true, true);
1349 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1350 prettifyMathematicaOutput(out, "Mvariable", false, false);
1353 mathed_parse_cell(res, from_utf8(out));
1361 void write(MathData const & dat, WriteStream & wi)
1365 wi.firstitem() = true;
1366 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it) {
1368 wi.firstitem() = false;
1373 void normalize(MathData const & ar, NormalStream & os)
1375 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1376 (*it)->normalize(os);
1380 void octave(MathData const & dat, OctaveStream & os)
1383 extractStructure(ar, OCTAVE);
1384 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1389 void maple(MathData const & dat, MapleStream & os)
1392 extractStructure(ar, MAPLE);
1393 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1398 void maxima(MathData const & dat, MaximaStream & os)
1401 extractStructure(ar, MAXIMA);
1402 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1407 void mathematica(MathData const & dat, MathematicaStream & os)
1410 extractStructure(ar, MATHEMATICA);
1411 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1412 (*it)->mathematica(os);
1416 docstring mathmlize(MathData const & dat, MathStream & os)
1419 extractStructure(ar, MATHML);
1423 else if (ar.size() == 1)
1424 retval = ar.front()->mathmlize(os);
1427 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1428 retval += (*it)->mathmlize(os);
1434 // convert this inset somehow to a number
1435 bool extractNumber(MathData const & ar, int & i)
1437 idocstringstream is(charSequence(ar.begin(), ar.end()));
1443 bool extractNumber(MathData const & ar, double & d)
1445 idocstringstream is(charSequence(ar.begin(), ar.end()));
1451 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1452 MathData const & ar)
1454 if (lang == "octave")
1455 return pipeThroughOctave(extra, ar);
1457 if (lang == "maxima")
1458 return pipeThroughMaxima(extra, ar);
1460 if (lang == "maple")
1461 return pipeThroughMaple(extra, ar);
1463 if (lang == "mathematica")
1464 return pipeThroughMathematica(extra, ar);
1466 // create normalized expression
1467 odocstringstream os;
1468 NormalStream ns(os);
1469 os << '[' << extra << ' ';
1472 // FIXME UNICODE Is utf8 encoding correct?
1473 string data = to_utf8(os.str());
1475 // search external script
1476 FileName const file = libFileSearch("mathed", "extern_" + lang);
1478 lyxerr << "converter to '" << lang << "' not found" << endl;
1482 // run external sript
1483 string out = captureOutput(file.absFilename(), data);
1485 mathed_parse_cell(res, from_utf8(out));