]> git.lyx.org Git - lyx.git/blob - src/mathed/MathExtern.cpp
Revert r32566 and r32568.
[lyx.git] / src / mathed / MathExtern.cpp
1 /**
2  * \file MathExtern.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 // This file contains most of the magic that extracts "context
12 // information" from the unstructered layout-oriented stuff in
13 // MathData.
14
15 #include <config.h>
16
17 #include "MathExtern.h"
18
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"
34 #include "MathData.h"
35 #include "MathParser.h"
36 #include "MathStream.h"
37
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"
43
44 #include <algorithm>
45 #include <sstream>
46 #include <fstream>
47 #include <memory>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53
54 namespace {
55
56 enum ExternalMath {
57         MAPLE,
58         MAXIMA,
59         MATHEMATICA,
60         MATHML,
61         OCTAVE
62 };
63
64
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
72 };
73
74 static size_t const npos = lyx::docstring::npos;
75
76 // define a function for tests
77 typedef bool TestItemFunc(MathAtom const &);
78
79 // define a function for replacing subexpressions
80 typedef MathAtom ReplaceArgumentFunc(const MathData & ar);
81
82
83
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)
88 {
89         // nothing to get here
90         if (pos == last)
91                 return false;
92
93         // is this a scriptinset?
94         if (!(*pos)->asScriptInset())
95                 return false;
96
97         // do we want superscripts only?
98         if (superscript && !(*pos)->asScriptInset()->hasUp())
99                 return false;
100
101         // it is a scriptinset, use it.
102         ar.push_back(*pos);
103         ++pos;
104         return true;
105 }
106
107
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)
113 {
114         // nothing to get here
115         if (pos == last)
116                 return pos;
117
118         // something delimited _is_ an argument
119         if ((*pos)->asDelimInset()) {
120                 // leave out delimiters if this is a function argument
121                 if (function && kind != MATHML) {
122                         MathData const & arg = (*pos)->asDelimInset()->cell(0);
123                         MathData::const_iterator cur = arg.begin();
124                         MathData::const_iterator end = arg.end();
125                         while (cur != end)
126                                 ar.push_back(*cur++);
127                 } else
128                         ar.push_back(*pos);
129                 ++pos;
130                 if (pos == last)
131                         return pos;
132                 // if there's one, get following superscript only if this
133                 // isn't a function argument
134                 if (!function)
135                         extractScript(ar, pos, last, true);
136                 return pos;
137         }
138
139         // always take the first thing, no matter what it is
140         ar.push_back(*pos);
141
142         // go ahead if possible
143         ++pos;
144         if (pos == last)
145                 return pos;
146
147         // if the next item is a super/subscript, it most certainly belongs
148         // to the thing we have
149         extractScript(ar, pos, last, false);
150         if (pos == last)
151                 return pos;
152
153         // but it might be more than that.
154         // FIXME: not implemented
155         //for (MathData::iterator it = pos + 1; it != last; ++it) {
156         //      // always take the first thing, no matter
157         //      if (it == pos) {
158         //              ar.push_back(*it);
159         //              continue;
160         //      }
161         //}
162         return pos;
163 }
164
165
166 // returns sequence of char with same code starting at it up to end
167 // it might be less, though...
168 docstring charSequence
169         (MathData::const_iterator it, MathData::const_iterator end)
170 {
171         docstring s;
172         for (; it != end && (*it)->asCharInset(); ++it)
173                 s += (*it)->getChar();
174         return s;
175 }
176
177
178 void extractStrings(MathData & ar)
179 {
180         //lyxerr << "\nStrings from: " << ar << endl;
181         for (size_t i = 0; i < ar.size(); ++i) {
182                 if (!ar[i]->asCharInset())
183                         continue;
184                 docstring s = charSequence(ar.begin() + i, ar.end());
185                 ar[i] = MathAtom(new InsetMathString(s));
186                 ar.erase(i + 1, i + s.size());
187         }
188         //lyxerr << "\nStrings to: " << ar << endl;
189 }
190
191
192 void extractMatrices(MathData & ar)
193 {
194         //lyxerr << "\nMatrices from: " << ar << endl;
195         // first pass for explicitly delimited stuff
196         for (size_t i = 0; i < ar.size(); ++i) {
197                 InsetMathDelim const * const inset = ar[i]->asDelimInset();
198                 if (!inset)
199                         continue;
200                 MathData const & arr = inset->cell(0);
201                 if (arr.size() != 1)
202                         continue;
203                 if (!arr.front()->asGridInset())
204                         continue;
205                 ar[i] = MathAtom(new InsetMathMatrix(*(arr.front()->asGridInset()), 
206                                  inset->left_, inset->right_));
207         }
208
209         // second pass for AMS "pmatrix" etc
210         for (size_t i = 0; i < ar.size(); ++i) {
211                 InsetMathAMSArray const * const inset = ar[i]->asAMSArrayInset();
212                 if (inset) {
213                         string left = inset->name_left();
214                         if (left == "Vert")
215                                 left = "[";
216                         string right = inset->name_right();
217                         if (right == "Vert")
218                                 right = "]";
219                         ar[i] = MathAtom(new InsetMathMatrix(*inset, from_ascii(left), from_ascii(right)));
220                 }
221         }
222         //lyxerr << "\nMatrices to: " << ar << endl;
223 }
224
225
226 // convert this inset somehow to a string
227 bool extractString(MathAtom const & at, docstring & str)
228 {
229         if (at->getChar()) {
230                 str = docstring(1, at->getChar());
231                 return true;
232         }
233         if (at->asStringInset()) {
234                 str = at->asStringInset()->str();
235                 return true;
236         }
237         return false;
238 }
239
240
241 // is this a known function?
242 bool isKnownFunction(docstring const & str)
243 {
244         for (int i = 0; function_names[i]; ++i) {
245                 if (str == function_names[i])
246                         return true;
247         }
248         return false;
249 }
250
251
252 // extract a function name from this inset
253 bool extractFunctionName(MathAtom const & at, docstring & str)
254 {
255         if (at->asSymbolInset()) {
256                 str = at->asSymbolInset()->name();
257                 return isKnownFunction(str);
258         }
259         if (at->asUnknownInset()) {
260                 // assume it is well known...
261                 str = at->name();
262                 return true;
263         }
264         if (at->asFontInset() && at->name() == "mathrm") {
265                 // assume it is well known...
266                 MathData const & ar = at->asFontInset()->cell(0);
267                 str = charSequence(ar.begin(), ar.end());
268                 return ar.size() == str.size();
269         }
270         return false;
271 }
272
273
274 bool testString(MathAtom const & at, docstring const & str)
275 {
276         docstring s;
277         return extractString(at, s) && str == s;
278 }
279
280
281 bool testString(MathAtom const & at, char const * const str)
282 {
283         return testString(at, from_ascii(str));
284 }
285
286 // search end of nested sequence
287 MathData::iterator endNestSearch(
288         MathData::iterator it,
289         MathData::iterator last,
290         TestItemFunc testOpen,
291         TestItemFunc testClose
292 )
293 {
294         for (int level = 0; it != last; ++it) {
295                 if (testOpen(*it))
296                         ++level;
297                 if (testClose(*it))
298                         --level;
299                 if (level == 0)
300                         break;
301         }
302         return it;
303 }
304
305
306 // replace nested sequences by a real Insets
307 void replaceNested(
308         MathData & ar,
309         TestItemFunc testOpen,
310         TestItemFunc testClose,
311         ReplaceArgumentFunc replaceArg)
312 {
313         Buffer * buf = ar.buffer();
314         // use indices rather than iterators for the loop  because we are going
315         // to modify the array.
316         for (size_t i = 0; i < ar.size(); ++i) {
317                 // check whether this is the begin of the sequence
318                 if (!testOpen(ar[i]))
319                         continue;
320
321                 // search end of sequence
322                 MathData::iterator it = ar.begin() + i;
323                 MathData::iterator jt = endNestSearch(it, ar.end(), testOpen, testClose);
324                 if (jt == ar.end())
325                         continue;
326
327                 // replace the original stuff by the new inset
328                 ar[i] = replaceArg(MathData(buf, it + 1, jt));
329                 ar.erase(it + 1, jt + 1);
330         }
331 }
332
333
334
335 //
336 // split scripts into seperate super- and subscript insets. sub goes in
337 // front of super...
338 //
339
340 void splitScripts(MathData & ar)
341 {
342         Buffer * buf = ar.buffer();
343         //lyxerr << "\nScripts from: " << ar << endl;
344         for (size_t i = 0; i < ar.size(); ++i) {
345                 InsetMathScript const * script = ar[i]->asScriptInset();
346
347                 // is this a script inset and do we also have a superscript?
348                 if (!script || !script->hasUp())
349                         continue;
350
351                 // we must have a nucleus if we only have a superscript
352                 if (!script->hasDown() && script->nuc().size() == 0)
353                         continue;
354
355                 if (script->nuc().size() == 1) {
356                         // leave alone sums and integrals
357                         InsetMathSymbol const * sym =
358                                 script->nuc().front()->asSymbolInset();
359                         if (sym && (sym->name() == "sum" || sym->name() == "int"))
360                                 continue;
361                 }
362
363                 // create extra script inset and move superscript over
364                 InsetMathScript * p = ar[i].nucleus()->asScriptInset();
365                 auto_ptr<InsetMathScript> q(new InsetMathScript(buf, true));
366                 swap(q->up(), p->up());
367                 p->removeScript(true);
368
369                 // if we don't have a subscript, get rid of the ScriptInset
370                 if (!script->hasDown()) {
371                         MathData arg(p->nuc());
372                         MathData::const_iterator it = arg.begin();
373                         MathData::const_iterator et = arg.end();
374                         ar.erase(i);
375                         while (it != et)
376                                 ar.insert(i++, *it++);
377                 } else
378                         ++i;
379
380                 // insert new inset behind
381                 ar.insert(i, MathAtom(q.release()));
382         }
383         //lyxerr << "\nScripts to: " << ar << endl;
384 }
385
386
387 //
388 // extract exp(...)
389 //
390
391 void extractExps(MathData & ar)
392 {
393         Buffer * buf = ar.buffer();
394         //lyxerr << "\nExps from: " << ar << endl;
395         for (size_t i = 0; i + 1 < ar.size(); ++i) {
396                 // is this 'e'?
397                 if (ar[i]->getChar() != 'e')
398                         continue;
399
400                 // we need an exponent but no subscript
401                 InsetMathScript const * sup = ar[i + 1]->asScriptInset();
402                 if (!sup || sup->hasDown())
403                         continue;
404
405                 // create a proper exp-inset as replacement
406                 ar[i] = MathAtom(new InsetMathExFunc(buf, from_ascii("exp"), sup->cell(1)));
407                 ar.erase(i + 1);
408         }
409         //lyxerr << "\nExps to: " << ar << endl;
410 }
411
412
413 //
414 // extract det(...)  from |matrix|
415 //
416 void extractDets(MathData & ar)
417 {
418         Buffer * buf = ar.buffer();
419         //lyxerr << "\ndet from: " << ar << endl;
420         for (MathData::iterator it = ar.begin(); it != ar.end(); ++it) {
421                 InsetMathDelim const * del = (*it)->asDelimInset();
422                 if (!del)
423                         continue;
424                 if (!del->isAbs())
425                         continue;
426                 *it = MathAtom(new InsetMathExFunc(buf, from_ascii("det"), del->cell(0)));
427         }
428         //lyxerr << "\ndet to: " << ar << endl;
429 }
430
431
432 //
433 // search numbers
434 //
435
436 bool isDigitOrSimilar(char_type c)
437 {
438         return ('0' <= c && c <= '9') || c == '.';
439 }
440
441
442 // returns sequence of digits
443 docstring digitSequence
444         (MathData::const_iterator it, MathData::const_iterator end)
445 {
446         docstring s;
447         for (; it != end && (*it)->asCharInset(); ++it) {
448                 if (!isDigitOrSimilar((*it)->getChar()))
449                         break;
450                 s += (*it)->getChar();
451         }
452         return s;
453 }
454
455
456 void extractNumbers(MathData & ar)
457 {
458         //lyxerr << "\nNumbers from: " << ar << endl;
459         for (size_t i = 0; i < ar.size(); ++i) {
460                 if (!ar[i]->asCharInset())
461                         continue;
462                 if (!isDigitOrSimilar(ar[i]->asCharInset()->getChar()))
463                         continue;
464
465                 docstring s = digitSequence(ar.begin() + i, ar.end());
466
467                 ar[i] = MathAtom(new InsetMathNumber(s));
468                 ar.erase(i + 1, i + s.size());
469         }
470         //lyxerr << "\nNumbers to: " << ar << endl;
471 }
472
473
474
475 //
476 // search delimiters
477 //
478
479 bool testOpenParen(MathAtom const & at)
480 {
481         return testString(at, "(");
482 }
483
484
485 bool testCloseParen(MathAtom const & at)
486 {
487         return testString(at, ")");
488 }
489
490
491 MathAtom replaceParenDelims(const MathData & ar)
492 {
493         return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
494                 from_ascii("("), from_ascii(")"), ar));
495 }
496
497
498 bool testOpenBracket(MathAtom const & at)
499 {
500         return testString(at, "[");
501 }
502
503
504 bool testCloseBracket(MathAtom const & at)
505 {
506         return testString(at, "]");
507 }
508
509
510 MathAtom replaceBracketDelims(const MathData & ar)
511 {
512         return MathAtom(new InsetMathDelim(const_cast<Buffer *>(ar.buffer()),
513                 from_ascii("["), from_ascii("]"), ar));
514 }
515
516
517 // replace '('...')' and '['...']' sequences by a real InsetMathDelim
518 void extractDelims(MathData & ar)
519 {
520         //lyxerr << "\nDelims from: " << ar << endl;
521         replaceNested(ar, testOpenParen, testCloseParen, replaceParenDelims);
522         replaceNested(ar, testOpenBracket, testCloseBracket, replaceBracketDelims);
523         //lyxerr << "\nDelims to: " << ar << endl;
524 }
525
526
527
528 //
529 // search well-known functions
530 //
531
532
533 // replace 'f' '(...)' and 'f' '^n' '(...)' sequences by a real InsetMathExFunc
534 // assume 'extractDelims' ran before
535 void extractFunctions(MathData & ar, ExternalMath kind)
536 {
537         // we need at least two items...
538         if (ar.size() < 2)
539                 return;
540
541         Buffer * buf = ar.buffer();
542
543         //lyxerr << "\nFunctions from: " << ar << endl;
544         for (size_t i = 0; i + 1 < ar.size(); ++i) {
545                 MathData::iterator it = ar.begin() + i;
546                 MathData::iterator jt = it + 1;
547
548                 docstring name;
549                 // is it a function?
550                 // it certainly is if it is well known...
551                 if (!extractFunctionName(*it, name)) {
552                         // is this a user defined function?
553                         // it it probably not, if it doesn't have a name.
554                         if (!extractString(*it, name))
555                                 continue;
556                         // it is not if it has no argument
557                         if (jt == ar.end())
558                                 continue;
559                         // guess so, if this is followed by
560                         // a DelimInset with a single item in the cell
561                         InsetMathDelim const * del = (*jt)->asDelimInset();
562                         if (!del || del->cell(0).size() != 1)
563                                 continue;
564                         // fall trough into main branch
565                 }
566
567                 // do we have an exponent like in
568                 // 'sin' '^2' 'x' -> 'sin(x)' '^2'
569                 MathData exp;
570                 extractScript(exp, jt, ar.end(), true);
571
572                 // create a proper inset as replacement
573                 auto_ptr<InsetMathExFunc> p(new InsetMathExFunc(buf, name));
574
575                 // jt points to the "argument". Get hold of this.
576                 MathData::iterator st = 
577                                 extractArgument(p->cell(0), jt, ar.end(), kind, true);
578
579                 // replace the function name by a real function inset
580                 *it = MathAtom(p.release());
581
582                 // remove the source of the argument from the array
583                 ar.erase(it + 1, st);
584
585                 // re-insert exponent
586                 ar.insert(i + 1, exp);
587                 //lyxerr << "\nFunctions to: " << ar << endl;
588         }
589 }
590
591
592 //
593 // search integrals
594 //
595
596 bool testSymbol(MathAtom const & at, docstring const & name)
597 {
598         return at->asSymbolInset() && at->asSymbolInset()->name() == name;
599 }
600
601
602 bool testSymbol(MathAtom const & at, char const * const name)
603 {
604         return at->asSymbolInset() && at->asSymbolInset()->name() == from_ascii(name);
605 }
606
607
608 bool testIntSymbol(MathAtom const & at)
609 {
610         return testSymbol(at, from_ascii("int"));
611 }
612
613
614 bool testIntegral(MathAtom const & at)
615 {
616         return
617          testIntSymbol(at) ||
618                 ( at->asScriptInset()
619                   && at->asScriptInset()->nuc().size()
620                         && testIntSymbol(at->asScriptInset()->nuc().back()) );
621 }
622
623
624
625 bool testIntDiff(MathAtom const & at)
626 {
627         return testString(at, "d");
628 }
629
630
631 // replace '\int' ['_^'] x 'd''x'(...)' sequences by a real InsetMathExInt
632 // assume 'extractDelims' ran before
633 void extractIntegrals(MathData & ar, ExternalMath kind)
634 {
635         // we need at least three items...
636         if (ar.size() < 3)
637                 return;
638
639         Buffer * buf = ar.buffer();
640
641         //lyxerr << "\nIntegrals from: " << ar << endl;
642         for (size_t i = 0; i + 1 < ar.size(); ++i) {
643                 MathData::iterator it = ar.begin() + i;
644
645                 // search 'd'
646                 MathData::iterator jt =
647                         endNestSearch(it, ar.end(), testIntegral, testIntDiff);
648
649                 // something sensible found?
650                 if (jt == ar.end())
651                         continue;
652
653                 // is this a integral name?
654                 if (!testIntegral(*it))
655                         continue;
656
657                 // core ist part from behind the scripts to the 'd'
658                 auto_ptr<InsetMathExInt> p(new InsetMathExInt(buf, from_ascii("int")));
659
660                 // handle scripts if available
661                 if (!testIntSymbol(*it)) {
662                         p->cell(2) = (*it)->asScriptInset()->down();
663                         p->cell(3) = (*it)->asScriptInset()->up();
664                 }
665                 p->cell(0) = MathData(buf, it + 1, jt);
666
667                 // use the "thing" behind the 'd' as differential
668                 MathData::iterator tt = extractArgument(p->cell(1), jt + 1, ar.end(), kind);
669
670                 // remove used parts
671                 ar.erase(it + 1, tt);
672                 *it = MathAtom(p.release());
673         }
674         //lyxerr << "\nIntegrals to: " << ar << endl;
675 }
676
677
678 bool testTermDelimiter(MathAtom const & at)
679 {
680         return testString(at, "+") || testString(at, "-");
681 }
682
683
684 // try to extract a "term", i.e., something delimited by '+' or '-'.
685 // returns position behind the term
686 MathData::iterator extractTerm(MathData & ar,
687         MathData::iterator pos, MathData::iterator last)
688 {
689         while (pos != last && !testTermDelimiter(*pos)) {
690                 ar.push_back(*pos);
691                 ++pos;
692         }
693         return pos;
694 }
695
696
697 //
698 // search sums
699 //
700
701
702 bool testEqualSign(MathAtom const & at)
703 {
704         return testString(at, "=");
705 }
706
707
708 bool testSumSymbol(MathAtom const & p)
709 {
710         return testSymbol(p, from_ascii("sum"));
711 }
712
713
714 bool testSum(MathAtom const & at)
715 {
716         return
717          testSumSymbol(at) ||
718                 ( at->asScriptInset()
719                   && at->asScriptInset()->nuc().size()
720                         && testSumSymbol(at->asScriptInset()->nuc().back()) );
721 }
722
723
724 // replace '\sum' ['_^'] f(x) sequences by a real InsetMathExInt
725 // assume 'extractDelims' ran before
726 void extractSums(MathData & ar)
727 {
728         // we need at least two items...
729         if (ar.size() < 2)
730                 return;
731
732         Buffer * buf = ar.buffer();
733
734         //lyxerr << "\nSums from: " << ar << endl;
735         for (size_t i = 0; i + 1 < ar.size(); ++i) {
736                 MathData::iterator it = ar.begin() + i;
737
738                 // is this a sum name?
739                 if (!testSum(ar[i]))
740                         continue;
741
742                 // create a proper inset as replacement
743                 auto_ptr<InsetMathExInt> p(new InsetMathExInt(buf, from_ascii("sum")));
744
745                 // collect lower bound and summation index
746                 InsetMathScript const * sub = ar[i]->asScriptInset();
747                 if (sub && sub->hasDown()) {
748                         // try to figure out the summation index from the subscript
749                         MathData const & ar = sub->down();
750                         MathData::const_iterator xt =
751                                 find_if(ar.begin(), ar.end(), &testEqualSign);
752                         if (xt != ar.end()) {
753                                 // we found a '=', use everything in front of that as index,
754                                 // and everything behind as lower index
755                                 p->cell(1) = MathData(buf, ar.begin(), xt);
756                                 p->cell(2) = MathData(buf, xt + 1, ar.end());
757                         } else {
758                                 // use everything as summation index, don't use scripts.
759                                 p->cell(1) = ar;
760                         }
761                 }
762
763                 // collect upper bound
764                 if (sub && sub->hasUp())
765                         p->cell(3) = sub->up();
766
767                 // use something  behind the script as core
768                 MathData::iterator tt = extractTerm(p->cell(0), it + 1, ar.end());
769
770                 // cleanup
771                 ar.erase(it + 1, tt);
772                 *it = MathAtom(p.release());
773         }
774         //lyxerr << "\nSums to: " << ar << endl;
775 }
776
777
778 //
779 // search differential stuff
780 //
781
782 // tests for 'd' or '\partial'
783 bool testDiffItem(MathAtom const & at)
784 {
785         if (testString(at, "d") || testSymbol(at, "partial"))
786                 return true;
787
788         // we may have d^n .../d and splitScripts() has not yet seen it
789         InsetMathScript const * sup = at->asScriptInset();
790         if (sup && !sup->hasDown() && sup->hasUp() && sup->nuc().size() == 1) {
791                 MathAtom const & ma = sup->nuc().front();
792                 return testString(ma, "d") || testSymbol(ma, "partial");
793         }
794         return false;
795 }
796
797
798 bool testDiffArray(MathData const & ar)
799 {
800         return ar.size() && testDiffItem(ar.front());
801 }
802
803
804 bool testDiffFrac(MathAtom const & at)
805 {
806         return
807                 at->asFracInset()
808                         && testDiffArray(at->asFracInset()->cell(0))
809                         && testDiffArray(at->asFracInset()->cell(1));
810 }
811
812
813 void extractDiff(MathData & ar)
814 {
815         Buffer * buf = ar.buffer();
816         //lyxerr << "\nDiffs from: " << ar << endl;
817         for (size_t i = 0; i < ar.size(); ++i) {
818                 MathData::iterator it = ar.begin() + i;
819
820                 // is this a "differential fraction"?
821                 if (!testDiffFrac(*it))
822                         continue;
823
824                 InsetMathFrac const * f = (*it)->asFracInset();
825                 if (!f) {
826                         lyxerr << "should not happen" << endl;
827                         continue;
828                 }
829
830                 // create a proper diff inset
831                 auto_ptr<InsetMathDiff> diff(new InsetMathDiff(buf));
832
833                 // collect function, let jt point behind last used item
834                 MathData::iterator jt = it + 1;
835                 //int n = 1;
836                 MathData numer(f->cell(0));
837                 splitScripts(numer);
838                 if (numer.size() > 1 && numer[1]->asScriptInset()) {
839                         // this is something like  d^n f(x) / d... or  d^n / d...
840                         // FIXME
841                         //n = 1;
842                         if (numer.size() > 2)
843                                 diff->cell(0) = MathData(buf, numer.begin() + 2, numer.end());
844                         else
845                                 jt = extractTerm(diff->cell(0), jt, ar.end());
846                 } else {
847                         // simply d f(x) / d... or  d/d...
848                         if (numer.size() > 1)
849                                 diff->cell(0) = MathData(buf, numer.begin() + 1, numer.end());
850                         else
851                                 jt = extractTerm(diff->cell(0), jt, ar.end());
852                 }
853
854                 // collect denominator parts
855                 MathData denom(f->cell(1));
856                 splitScripts(denom);
857                 for (MathData::iterator dt = denom.begin(); dt != denom.end();) {
858                         // find the next 'd'
859                         MathData::iterator et
860                                 = find_if(dt + 1, denom.end(), &testDiffItem);
861
862                         // point before this
863                         MathData::iterator st = et - 1;
864                         InsetMathScript const * script = (*st)->asScriptInset();
865                         if (script && script->hasUp()) {
866                                 // things like   d.../dx^n
867                                 int mult = 1;
868                                 if (extractNumber(script->up(), mult)) {
869                                         //lyxerr << "mult: " << mult << endl;
870                                         for (int i = 0; i < mult; ++i)
871                                                 diff->addDer(MathData(buf, dt + 1, st));
872                                 }
873                         } else {
874                                 // just  d.../dx
875                                 diff->addDer(MathData(buf, dt + 1, et));
876                         }
877                         dt = et;
878                 }
879
880                 // cleanup
881                 ar.erase(it + 1, jt);
882                 *it = MathAtom(diff.release());
883         }
884         //lyxerr << "\nDiffs to: " << ar << endl;
885 }
886
887
888 //
889 // search limits
890 //
891
892
893 bool testRightArrow(MathAtom const & at)
894 {
895         return testSymbol(at, "to") || testSymbol(at, "rightarrow");
896 }
897
898
899
900 // replace '\lim_{x->x0} f(x)' sequences by a real InsetMathLim
901 // assume 'extractDelims' ran before
902 void extractLims(MathData & ar)
903 {
904         Buffer * buf = ar.buffer();
905         //lyxerr << "\nLimits from: " << ar << endl;
906         for (size_t i = 0; i < ar.size(); ++i) {
907                 MathData::iterator it = ar.begin() + i;
908
909                 // must be a script inset with a subscript (without superscript)
910                 InsetMathScript const * sub = (*it)->asScriptInset();
911                 if (!sub || !sub->hasDown() || sub->hasUp() || sub->nuc().size() != 1)
912                         continue;
913
914                 // is this a limit function?
915                 if (!testSymbol(sub->nuc().front(), "lim"))
916                         continue;
917
918                 // subscript must contain a -> symbol
919                 MathData const & s = sub->down();
920                 MathData::const_iterator st = find_if(s.begin(), s.end(), &testRightArrow);
921                 if (st == s.end())
922                         continue;
923
924                 // the -> splits the subscript int x and x0
925                 MathData x  = MathData(buf, s.begin(), st);
926                 MathData x0 = MathData(buf, st + 1, s.end());
927
928                 // use something behind the script as core
929                 MathData f;
930                 MathData::iterator tt = extractTerm(f, it + 1, ar.end());
931
932                 // cleanup
933                 ar.erase(it + 1, tt);
934
935                 // create a proper inset as replacement
936                 *it = MathAtom(new InsetMathLim(buf, f, x, x0));
937         }
938         //lyxerr << "\nLimits to: " << ar << endl;
939 }
940
941
942 //
943 // combine searches
944 //
945
946 void extractStructure(MathData & ar, ExternalMath kind)
947 {
948         //lyxerr << "\nStructure from: " << ar << endl;
949         splitScripts(ar);
950         extractDelims(ar);
951         extractIntegrals(ar, kind);
952         extractSums(ar);
953         extractNumbers(ar);
954         extractMatrices(ar);
955         extractFunctions(ar, kind);
956         extractDets(ar);
957         extractDiff(ar);
958         extractExps(ar);
959         extractLims(ar);
960         if (kind != MATHML)
961                 extractStrings(ar);
962         //lyxerr << "\nStructure to: " << ar << endl;
963 }
964
965
966 namespace {
967
968         string captureOutput(string const & cmd, string const & data)
969         {
970                 // In order to avoid parsing problems with command interpreters
971                 // we pass input data through a file
972                 FileName const cas_tmpfile = FileName::tempName("casinput");
973                 if (cas_tmpfile.empty()) {
974                         lyxerr << "Warning: cannot create temporary file."
975                                << endl;
976                         return string();
977                 }
978                 ofstream os(cas_tmpfile.toFilesystemEncoding().c_str());
979                 os << data << endl;
980                 os.close();
981                 string command =  cmd + " < "
982                         + quoteName(cas_tmpfile.toFilesystemEncoding());
983                 lyxerr << "calling: " << cmd
984                        << "\ninput: '" << data << "'" << endl;
985                 cmd_ret const ret = runCommand(command);
986                 cas_tmpfile.removeFile();
987                 return ret.second;
988         }
989
990         size_t get_matching_brace(string const & str, size_t i)
991         {
992                 int count = 1;
993                 size_t n = str.size();
994                 while (i < n) {
995                         i = str.find_first_of("{}", i+1);
996                         if (i == npos)
997                                 return i;
998                         if (str[i] == '{')
999                                 ++count;
1000                         else
1001                                 --count;
1002                         if (count == 0)
1003                                 return i;
1004                 }
1005                 return npos;
1006         }
1007
1008         size_t get_matching_brace_back(string const & str, size_t i)
1009         {
1010                 int count = 1;
1011                 while (i > 0) {
1012                         i = str.find_last_of("{}", i-1);
1013                         if (i == npos)
1014                                 return i;
1015                         if (str[i] == '}')
1016                                 ++count;
1017                         else
1018                                 --count;
1019                         if (count == 0)
1020                                 return i;
1021                 }
1022                 return npos;
1023         }
1024
1025         MathData pipeThroughMaxima(docstring const &, MathData const & ar)
1026         {
1027                 odocstringstream os;
1028                 MaximaStream ms(os);
1029                 ms << ar;
1030                 docstring expr = os.str();
1031                 docstring const header = from_ascii("simpsum:true;");
1032
1033                 string out;
1034                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1035                         // try to fix missing '*' the hard way
1036                         //
1037                         // > echo "2x;" | maxima
1038                         // ...
1039                         // (C1) Incorrect syntax: x is not an infix operator
1040                         // 2x;
1041                         //  ^
1042                         //
1043                         lyxerr << "checking expr: '" << to_utf8(expr) << "'" << endl;
1044                         docstring full = header + "tex(" + expr + ");";
1045                         out = captureOutput("maxima", to_utf8(full));
1046
1047                         // leave loop if expression syntax is probably ok
1048                         if (out.find("Incorrect syntax") == npos)
1049                                 break;
1050
1051                         // search line with "Incorrect syntax"
1052                         istringstream is(out);
1053                         string line;
1054                         while (is) {
1055                                 getline(is, line);
1056                                 if (line.find("Incorrect syntax") != npos)
1057                                         break;
1058                         }
1059
1060                         // 2nd next line is the one with caret
1061                         getline(is, line);
1062                         getline(is, line);
1063                         size_t pos = line.find('^');
1064                         lyxerr << "found caret at pos: '" << pos << "'" << endl;
1065                         if (pos == npos || pos < 4)
1066                                 break; // caret position not found
1067                         pos -= 4; // skip the "tex(" part
1068                         if (expr[pos] == '*')
1069                                 break; // two '*' in a row are definitely bad
1070                         expr.insert(pos, from_ascii("*"));
1071                 }
1072
1073                 vector<string> tmp = getVectorFromString(out, "$$");
1074                 if (tmp.size() < 2)
1075                         return MathData();
1076
1077                 out = subst(tmp[1], "\\>", string());
1078                 lyxerr << "output: '" << out << "'" << endl;
1079
1080                 // Ugly code that tries to make the result prettier
1081                 size_t i = out.find("\\mathchoice");
1082                 while (i != npos) {
1083                         size_t j = get_matching_brace(out, i + 12);
1084                         size_t k = get_matching_brace(out, j + 1);
1085                         k = get_matching_brace(out, k + 1);
1086                         k = get_matching_brace(out, k + 1);
1087                         string mid = out.substr(i + 13, j - i - 13);
1088                         if (mid.find("\\over") != npos)
1089                                 mid = '{' + mid + '}';
1090                         out = out.substr(0, i)
1091                                 + mid
1092                                 + out.substr(k + 1);
1093                         //lyxerr << "output: " << out << endl;
1094                         i = out.find("\\mathchoice", i);
1095                         break;
1096                 }
1097
1098                 i = out.find("\\over");
1099                 while (i != npos) {
1100                         size_t j = get_matching_brace_back(out, i - 1);
1101                         if (j == npos || j == 0)
1102                                 break;
1103                         size_t k = get_matching_brace(out, i + 5);
1104                         if (k == npos || k + 1 == out.size())
1105                                 break;
1106                         out = out.substr(0, j - 1)
1107                                 + "\\frac"
1108                                 + out.substr(j, i - j)
1109                                 + out.substr(i + 5, k - i - 4)
1110                                 + out.substr(k + 2);
1111                         //lyxerr << "output: " << out << endl;
1112                         i = out.find("\\over", i + 4);
1113                 }
1114                 MathData res;
1115                 mathed_parse_cell(res, from_utf8(out));
1116                 return res;
1117         }
1118
1119
1120         MathData pipeThroughMaple(docstring const & extra, MathData const & ar)
1121         {
1122                 string header = "readlib(latex):\n";
1123
1124                 // remove the \\it for variable names
1125                 //"#`latex/csname_font` := `\\it `:"
1126                 header +=
1127                         "`latex/csname_font` := ``:\n";
1128
1129                 // export matrices in (...) instead of [...]
1130                 header +=
1131                         "`latex/latex/matrix` := "
1132                                 "subs(`[`=`(`, `]`=`)`,"
1133                                         "eval(`latex/latex/matrix`)):\n";
1134
1135                 // replace \\cdots with proper '*'
1136                 header +=
1137                         "`latex/latex/*` := "
1138                                 "subs(`\\,`=`\\cdot `,"
1139                                         "eval(`latex/latex/*`)):\n";
1140
1141                 // remove spurious \\noalign{\\medskip} in matrix output
1142                 header +=
1143                         "`latex/latex/matrix`:= "
1144                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
1145                                         "eval(`latex/latex/matrix`)):\n";
1146
1147                 //"#`latex/latex/symbol` "
1148                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
1149
1150                 string trailer = "quit;";
1151                 odocstringstream os;
1152                 MapleStream ms(os);
1153                 ms << ar;
1154                 string expr = to_utf8(os.str());
1155                 lyxerr << "ar: '" << ar << "'\n"
1156                        << "ms: '" << expr << "'" << endl;
1157
1158                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1159                         // try to fix missing '*' the hard way by using mint
1160                         //
1161                         // ... > echo "1A;" | mint -i 1 -S -s -q
1162                         // on line     1: 1A;
1163                         //                 ^ syntax error -
1164                         //                   Probably missing an operator such as * p
1165                         //
1166                         lyxerr << "checking expr: '" << expr << "'" << endl;
1167                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ';');
1168                         if (out.empty())
1169                                 break; // expression syntax is ok
1170                         istringstream is(out);
1171                         string line;
1172                         getline(is, line);
1173                         if (line.find("on line") != 0)
1174                                 break; // error message not identified
1175                         getline(is, line);
1176                         size_t pos = line.find('^');
1177                         if (pos == string::npos || pos < 15)
1178                                 break; // caret position not found
1179                         pos -= 15; // skip the "on line ..." part
1180                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
1181                                 break; // two '*' in a row are definitely bad
1182                         expr.insert(pos, 1, '*');
1183                 }
1184
1185                 // FIXME UNICODE Is utf8 encoding correct?
1186                 string full = "latex(" + to_utf8(extra) + '(' + expr + "));";
1187                 string out = captureOutput("maple -q", header + full + trailer);
1188
1189                 // change \_ into _
1190
1191                 //
1192                 MathData res;
1193                 mathed_parse_cell(res, from_utf8(out));
1194                 return res;
1195         }
1196
1197
1198         MathData pipeThroughOctave(docstring const &, MathData const & ar)
1199         {
1200                 odocstringstream os;
1201                 OctaveStream vs(os);
1202                 vs << ar;
1203                 string expr = to_utf8(os.str());
1204                 string out;
1205                 // FIXME const cast
1206                 Buffer * buf = const_cast<Buffer *>(ar.buffer());
1207                 lyxerr << "pipe: ar: '" << ar << "'\n"
1208                        << "pipe: expr: '" << expr << "'" << endl;
1209
1210                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
1211                         //
1212                         // try to fix missing '*' the hard way
1213                         // parse error:
1214                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
1215                         //                                   ^
1216                         //
1217                         lyxerr << "checking expr: '" << expr << "'" << endl;
1218                         out = captureOutput("octave -q 2>&1", expr);
1219                         lyxerr << "output: '" << out << "'" << endl;
1220
1221                         // leave loop if expression syntax is probably ok
1222                         if (out.find("parse error:") == string::npos)
1223                                 break;
1224
1225                         // search line with single caret
1226                         istringstream is(out);
1227                         string line;
1228                         while (is) {
1229                                 getline(is, line);
1230                                 lyxerr << "skipping line: '" << line << "'" << endl;
1231                                 if (line.find(">>> ") != string::npos)
1232                                         break;
1233                         }
1234
1235                         // found line with error, next line is the one with caret
1236                         getline(is, line);
1237                         size_t pos = line.find('^');
1238                         lyxerr << "caret line: '" << line << "'" << endl;
1239                         lyxerr << "found caret at pos: '" << pos << "'" << endl;
1240                         if (pos == string::npos || pos < 4)
1241                                 break; // caret position not found
1242                         pos -= 4; // skip the ">>> " part
1243                         if (expr[pos] == '*')
1244                                 break; // two '*' in a row are definitely bad
1245                         expr.insert(pos, 1, '*');
1246                 }
1247
1248                 // remove 'ans = ' taking into account that there may be an
1249                 // ansi control sequence before, such as '\033[?1034hans = '
1250                 size_t i = out.find("ans = ");
1251                 if (i == string::npos)
1252                         return MathData();
1253                 out = out.substr(i + 6);
1254
1255                 // parse output as matrix or single number
1256                 MathAtom at(new InsetMathArray(buf, from_ascii("array"), from_utf8(out)));
1257                 InsetMathArray const * mat = at->asArrayInset();
1258                 MathData res(buf);
1259                 if (mat->ncols() == 1 && mat->nrows() == 1)
1260                         res.append(mat->cell(0));
1261                 else {
1262                         res.push_back(MathAtom(
1263                                 new InsetMathDelim(buf, from_ascii("("), from_ascii(")"))));
1264                         res.back().nucleus()->cell(0).push_back(at);
1265                 }
1266                 return res;
1267         }
1268
1269
1270         string fromMathematicaName(string const & name)
1271         {
1272                 if (name == "Sin")    return "sin";
1273                 if (name == "Sinh")   return "sinh";
1274                 if (name == "ArcSin") return "arcsin";
1275                 if (name == "Cos")    return "cos";
1276                 if (name == "Cosh")   return "cosh";
1277                 if (name == "ArcCos") return "arccos";
1278                 if (name == "Tan")    return "tan";
1279                 if (name == "Tanh")   return "tanh";
1280                 if (name == "ArcTan") return "arctan";
1281                 if (name == "Cot")    return "cot";
1282                 if (name == "Coth")   return "coth";
1283                 if (name == "Csc")    return "csc";
1284                 if (name == "Sec")    return "sec";
1285                 if (name == "Exp")    return "exp";
1286                 if (name == "Log")    return "log";
1287                 if (name == "Arg" )   return "arg";
1288                 if (name == "Det" )   return "det";
1289                 if (name == "GCD" )   return "gcd";
1290                 if (name == "Max" )   return "max";
1291                 if (name == "Min" )   return "min";
1292                 if (name == "Erf" )   return "erf";
1293                 if (name == "Erfc" )  return "erfc";
1294                 return name;
1295         }
1296
1297
1298         void prettifyMathematicaOutput(string & out, string const & macroName,
1299                         bool roman, bool translate)
1300         {
1301                 string const macro = "\\" + macroName + "{";
1302                 size_t const len = macro.length();
1303                 size_t i = out.find(macro);
1304
1305                 while (i != npos) {
1306                         size_t const j = get_matching_brace(out, i + len);
1307                         string const name = out.substr(i + len, j - i - len);
1308                         out = out.substr(0, i)
1309                                 + (roman ? "\\mathrm{" : "")
1310                                 + (translate ? fromMathematicaName(name) : name)
1311                                 + out.substr(roman ? j : j + 1);
1312                         //lyxerr << "output: " << out << endl;
1313                         i = out.find(macro, i);
1314                 }
1315         }
1316
1317
1318         MathData pipeThroughMathematica(docstring const &, MathData const & ar)
1319         {
1320                 odocstringstream os;
1321                 MathematicaStream ms(os);
1322                 ms << ar;
1323                 // FIXME UNICODE Is utf8 encoding correct?
1324                 string const expr = to_utf8(os.str());
1325                 string out;
1326
1327                 lyxerr << "expr: '" << expr << "'" << endl;
1328
1329                 string const full = "TeXForm[" + expr + "]";
1330                 out = captureOutput("math", full);
1331                 lyxerr << "output: '" << out << "'" << endl;
1332
1333                 size_t pos1 = out.find("Out[1]//TeXForm= ");
1334                 size_t pos2 = out.find("In[2]:=");
1335
1336                 if (pos1 == string::npos || pos2 == string::npos)
1337                         return MathData();
1338
1339                 // get everything from pos1+17 to pos2
1340                 out = out.substr(pos1 + 17, pos2 - pos1 - 17);
1341                 out = subst(subst(out, '\r', ' '), '\n', ' ');
1342
1343                 // tries to make the result prettier
1344                 prettifyMathematicaOutput(out, "Mfunction", true, true);
1345                 prettifyMathematicaOutput(out, "Muserfunction", true, false);
1346                 prettifyMathematicaOutput(out, "Mvariable", false, false);
1347
1348                 MathData res;
1349                 mathed_parse_cell(res, from_utf8(out));
1350                 return res;
1351         }
1352
1353 }
1354
1355 } // anon namespace
1356
1357 void write(MathData const & dat, WriteStream & wi)
1358 {
1359         MathData ar = dat;
1360         extractStrings(ar);
1361         wi.firstitem() = true;
1362         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it) {
1363                 (*it)->write(wi);
1364                 wi.firstitem() = false;
1365         }
1366 }
1367
1368
1369 void normalize(MathData const & ar, NormalStream & os)
1370 {
1371         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1372                 (*it)->normalize(os);
1373 }
1374
1375
1376 void octave(MathData const & dat, OctaveStream & os)
1377 {
1378         MathData ar = dat;
1379         extractStructure(ar, OCTAVE);
1380         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1381                 (*it)->octave(os);
1382 }
1383
1384
1385 void maple(MathData const & dat, MapleStream & os)
1386 {
1387         MathData ar = dat;
1388         extractStructure(ar, MAPLE);
1389         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1390                 (*it)->maple(os);
1391 }
1392
1393
1394 void maxima(MathData const & dat, MaximaStream & os)
1395 {
1396         MathData ar = dat;
1397         extractStructure(ar, MAXIMA);
1398         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1399                 (*it)->maxima(os);
1400 }
1401
1402
1403 void mathematica(MathData const & dat, MathematicaStream & os)
1404 {
1405         MathData ar = dat;
1406         extractStructure(ar, MATHEMATICA);
1407         for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1408                 (*it)->mathematica(os);
1409 }
1410
1411
1412 void mathmlize(MathData const & dat, MathStream & os)
1413 {
1414         MathData ar = dat;
1415         extractStructure(ar, MATHML);
1416         if (ar.size() == 0)
1417                 os << "<mrow/>";
1418         else if (ar.size() == 1)
1419                 os << ar.front();
1420         else {
1421                 os << MTag("mrow");
1422                 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
1423                         (*it)->mathmlize(os);
1424                 os << ETag("mrow");
1425         }
1426 }
1427
1428 // convert this inset somehow to a number
1429 bool extractNumber(MathData const & ar, int & i)
1430 {
1431         idocstringstream is(charSequence(ar.begin(), ar.end()));
1432         is >> i;
1433         return is;
1434 }
1435
1436
1437 bool extractNumber(MathData const & ar, double & d)
1438 {
1439         idocstringstream is(charSequence(ar.begin(), ar.end()));
1440         is >> d;
1441         return is;
1442 }
1443
1444
1445 MathData pipeThroughExtern(string const & lang, docstring const & extra,
1446         MathData const & ar)
1447 {
1448         if (lang == "octave")
1449                 return pipeThroughOctave(extra, ar);
1450
1451         if (lang == "maxima")
1452                 return pipeThroughMaxima(extra, ar);
1453
1454         if (lang == "maple")
1455                 return pipeThroughMaple(extra, ar);
1456
1457         if (lang == "mathematica")
1458                 return pipeThroughMathematica(extra, ar);
1459
1460         // create normalized expression
1461         odocstringstream os;
1462         NormalStream ns(os);
1463         os << '[' << extra << ' ';
1464         ns << ar;
1465         os << ']';
1466         // FIXME UNICODE Is utf8 encoding correct?
1467         string data = to_utf8(os.str());
1468
1469         // search external script
1470         FileName const file = libFileSearch("mathed", "extern_" + lang);
1471         if (file.empty()) {
1472                 lyxerr << "converter to '" << lang << "' not found" << endl;
1473                 return MathData();
1474         }
1475
1476         // run external sript
1477         string out = captureOutput(file.absFilename(), data);
1478         MathData res;
1479         mathed_parse_cell(res, from_utf8(out));
1480         return res;
1481 }
1482
1483
1484 } // namespace lyx