]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
more mathml stuff
[lyx.git] / src / mathed / formula.C
1 /*
2 *  File:        formula.C
3 *  Purpose:     Implementation of formula inset
4 *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 *  Created:     January 1996
6 *  Description: Allows the edition of math paragraphs inside Lyx.
7 *
8 *  Copyright: 1996-1998 Alejandro Aguilar Sierra
9 *
10 *  Version: 0.4, Lyx project.
11 *
12 *   You are free to use and modify this code under the terms of
13 *   the GNU General Public Licence version 2 or later.
14 */
15
16 #ifdef __GNUG__
17 #pragma implementation
18 #endif
19
20 #include <config.h>
21
22 #include "formula.h"
23 #include "commandtags.h"
24 #include "math_cursor.h"
25 #include "math_parser.h"
26 #include "math_charinset.h"
27 #include "math_arrayinset.h"
28 #include "math_deliminset.h"
29 #include "lyx_main.h"
30 #include "BufferView.h"
31 #include "gettext.h"
32 #include "debug.h"
33 #include "lyx_gui_misc.h"
34 #include "support/LOstream.h"
35 #include "support/LAssert.h"
36 #include "support/lyxlib.h"
37 #include "support/syscall.h"
38 #include "support/lstrings.h"
39 #include "support/filetools.h" // LibFileSearch
40 #include "LyXView.h"
41 #include "Painter.h"
42 #include "lyxrc.h"
43 #include "math_matrixinset.h"
44 #include "mathed/support.h"
45
46 using std::ostream;
47 using std::ifstream;
48 using std::istream;
49 using std::pair;
50 using std::endl;
51 using std::vector;
52
53
54 namespace {
55
56         string captureOutput(string const & cmd, string const & data)
57         {
58                 string outfile = lyx::tempName(string(), "mathextern");
59                 string full =  "echo '" + data + "' | (" + cmd + ") > " + outfile;
60                 lyxerr << "calling: " << full << "\n";
61                 Systemcalls dummy(Systemcalls::System, full, 0);
62                 string out = GetFileContents(outfile);
63                 lyxerr << "result: '" << out << "'\n";
64                 return out;
65         }
66
67
68         MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
69         {
70                 string header = "readlib(latex):\n";
71
72                 // remove the \\it for variable names
73                 //"#`latex/csname_font` := `\\it `:"
74                 header +=
75                         "`latex/csname_font` := ``:\n";
76
77                 // export matrices in (...) instead of [...]
78                 header +=
79                         "`latex/latex/matrix` := "
80                                 "subs(`[`=`(`, `]`=`)`,"
81                                         "eval(`latex/latex/matrix`)):\n";
82
83                 // replace \\cdots with proper '*'
84                 header +=
85                         "`latex/latex/*` := "
86                                 "subs(`\\,`=`\\cdot `,"
87                                         "eval(`latex/latex/*`)):\n";
88
89                 //"#`latex/latex/symbol` "
90                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
91
92                 string trailer = "quit;";
93                 ostringstream os;
94                 MapleStream ms(os);
95                 ms << ar;
96                 string expr = os.str();
97
98                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
99                         // try to fix missing '*' the hard way by using mint
100                         //
101                         // ... > echo "1A;" | mint -i 1 -S -s -q
102                         // on line     1: 1A;
103                         //                 ^ syntax error - 
104                         //                   Probably missing an operator such as * p
105                         //
106                         lyxerr << "checking expr: '" << expr << "'\n";
107                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
108                         if (out.empty())
109                                 break; // expression syntax is ok
110                         istringstream is(out);
111                         string line;
112                         getline(is, line);
113                         if (line.find("on line") != 0)
114                                 break; // error message not identified
115                         getline(is, line);
116                         string::size_type pos = line.find('^');
117                         if (pos == string::npos || pos < 15)
118                                 break; // caret position not found
119                         pos -= 15; // skip the "on line ..." part
120                         if (expr[pos] == '*')
121                                 break; // two '*' in a row are definitely bad
122                         expr.insert(pos,  "*");
123                 }
124
125                 string full = "latex(" +  extra + '(' + expr + "));";
126                 string out = captureOutput("maple -q", header + full + trailer);
127
128                 // change \_ into _
129
130                 //
131                 MathArray res;
132                 mathed_parse_cell(res, out);
133                 return res;
134         }
135                 
136         
137         MathArray pipeThroughOctave(string const &, MathArray const & ar)
138         {
139                 ostringstream os;
140                 OctaveStream vs(os);
141                 vs << ar;
142                 string expr = os.str();
143                 string out;
144
145                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
146                         //
147                         // try to fix missing '*' the hard way 
148                         // parse error:
149                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
150                         //                                   ^
151                         //
152                         lyxerr << "checking expr: '" << expr << "'\n";
153                         out = captureOutput("octave -q 2>&1", expr);
154                         lyxerr << "checking out: '" << out << "'\n";
155
156                         // leave loop if expression syntax is probably ok
157                         if (out.find("parse error:") == string::npos)
158                                 break;
159
160                         // search line with single caret
161                         istringstream is(out);
162                         string line;
163                         while (is) {
164                                 getline(is, line);
165                                 lyxerr << "skipping line: '" << line << "'\n";
166                                 if (line.find(">>> ") != string::npos)
167                                         break;
168                         }
169
170                         // found line with error, next line is the one with caret
171                         getline(is, line);
172                         string::size_type pos = line.find('^');
173                         lyxerr << "caret line: '" << line << "'\n";
174                         lyxerr << "found caret at pos: '" << pos << "'\n";
175                         if (pos == string::npos || pos < 4)
176                                 break; // caret position not found
177                         pos -= 4; // skip the ">>> " part
178                         if (expr[pos] == '*')
179                                 break; // two '*' in a row are definitely bad
180                         expr.insert(pos,  "*");
181                 }
182
183                 if (out.size() < 6)
184                         return MathArray();
185
186                 // remove 'ans = '
187                 out = out.substr(6);
188
189                 // parse output as matrix or single number
190                 MathAtom at(new MathArrayInset(out));
191                 MathArrayInset const * mat = at.nucleus()->asArrayInset();
192                 MathArray res;
193                 if (mat->ncols() == 1 && mat->nrows() == 1)
194                         res.push_back(mat->cell(0));
195                 else {
196                         res.push_back(MathAtom(new MathDelimInset("(", ")")));
197                         res.back()->cell(0).push_back(at);
198                 }
199                 return res;
200         }
201
202
203         MathArray pipeThroughExtern(string const & arg, MathArray const & ar)
204         {
205                 string lang;
206                 string extra;
207                 istringstream iss(arg.c_str());
208                 iss >> lang >> extra;
209                 if (extra.empty())
210                         extra = "noextra";      
211
212                 if (lang == "octave")
213                         return pipeThroughOctave(extra, ar);
214
215                 if (lang == "maple")
216                         return pipeThroughMaple(extra, ar);
217
218                 // create normalized expression
219                 ostringstream os;
220                 os << "[" << extra << ' ';
221                 ar.writeNormal(os); 
222                 os << "]";
223                 string data = os.str().c_str();
224
225                 // search external script
226                 string file = LibFileSearch("mathed", "extern_" + lang);
227                 if (file.empty()) {
228                         lyxerr << "converter to '" << lang << "' not found\n";
229                         return MathArray();
230                 }
231                 
232                 // run external sript
233                 string out = captureOutput(file, data);
234                 MathArray res;
235                 mathed_parse_cell(res, out);
236                 return res;
237         }
238
239 }
240
241
242 InsetFormula::InsetFormula()
243         : par_(MathAtom(new MathMatrixInset))
244 {}
245
246
247 InsetFormula::InsetFormula(MathInsetTypes t)
248         : par_(MathAtom(new MathMatrixInset(t)))
249 {}
250
251
252 InsetFormula::InsetFormula(string const & s) 
253 {
254         if (s.size()) {
255                 bool res = mathed_parse_normal(par_, s);
256
257                 if (!res)
258                         res = mathed_parse_normal(par_, "$" + s + "$");
259
260                 if (!res) {
261                         lyxerr << "cannot interpret '" << s << "' as math\n";
262                         par_ = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
263                 }
264         }
265         metrics();
266 }
267
268
269 Inset * InsetFormula::clone(Buffer const &, bool) const
270 {
271         return new InsetFormula(*this);
272 }
273
274
275 void InsetFormula::write(Buffer const * buf, ostream & os) const
276 {
277         os << "Formula ";
278         latex(buf, os, false, false);
279 }
280
281
282 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
283         const
284 {
285         MathWriteInfo wi(buf, os, fragil);
286         par_->write(wi);
287         return 1;
288 }
289
290
291 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
292 {
293         MathWriteInfo wi(buf, os, false);
294         par_->write(wi);
295         return 1;
296 }
297
298
299 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
300 {
301         return docbook(buf, os);
302 }
303
304
305 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
306 {
307         MathMLStream ms(os);
308         ms << "<equation><alt>";
309         int res = ascii(buf, ms.os_, 0);
310         ms << "</alt>\n<math>" << par_.nucleus() << "<math></equation>";
311         return res + 1;
312 }
313
314
315 void InsetFormula::read(Buffer const *, LyXLex & lex)
316 {
317         mathed_parse_normal(par_, lex);
318         metrics();
319 }
320
321
322 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
323                         int y, float & xx, bool) const
324 {
325         int x = int(xx) - 1;
326         y -= 2;
327
328         Painter & pain = bv->painter();
329
330         metrics(bv, font);
331         int w = par_->width();
332         int h = par_->height();
333         int a = par_->ascent();
334         pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
335
336         if (mathcursor && mathcursor->formula() == this) {
337                 mathcursor->drawSelection(pain);
338                 pain.rectangle(x, y - a, w, h, LColor::mathframe);
339         }
340
341         par_->draw(pain, x, y);
342         xx += par_->width();
343         xo_ = x;
344         yo_ = y;
345
346         setCursorVisible(false);
347 }
348
349
350 vector<string> const InsetFormula::getLabelList() const
351 {
352         return mat()->getLabelList();
353 }
354
355
356 UpdatableInset::RESULT
357 InsetFormula::localDispatch(BufferView * bv, kb_action action,
358          string const & arg)
359 {
360         RESULT result = DISPATCHED;
361
362         switch (action) {
363
364                 case LFUN_BREAKLINE: 
365                         bv->lockedInsetStoreUndo(Undo::INSERT);
366                         mathcursor->breakLine();
367                         mathcursor->normalize();
368                         updateLocal(bv, true);
369                         break;
370
371                 case LFUN_MATH_NUMBER:
372                 {
373                         //lyxerr << "toggling all numbers\n";
374                         if (display()) {
375                                 bv->lockedInsetStoreUndo(Undo::INSERT);
376                                 bool old = mat()->numberedType();
377                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
378                                         mat()->numbered(row, !old);
379                                 bv->owner()->message(old ? _("No number") : _("Number"));
380                                 updateLocal(bv, true);
381                         }
382                         break;
383                 }
384
385                 case LFUN_MATH_NONUMBER:
386                 {
387                         //lyxerr << "toggling line number\n";
388                         if (display()) {
389                                 bv->lockedInsetStoreUndo(Undo::INSERT);
390                                 MathCursor::row_type row = mathcursor->row();
391                                 bool old = mat()->numbered(row);
392                                 bv->owner()->message(old ? _("No number") : _("Number"));
393                                 mat()->numbered(row, !old);
394                                 updateLocal(bv, true);
395                         }
396                         break;
397                 }
398
399                 case LFUN_INSERT_LABEL:
400                 {
401                         bv->lockedInsetStoreUndo(Undo::INSERT);
402
403                         MathCursor::row_type row = mathcursor->row();
404                         string old_label = mat()->label(row);
405                         string new_label = arg;
406
407                         if (new_label.empty()) {
408                                 string const default_label =
409                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
410                                 pair<bool, string> const res = old_label.empty()
411                                         ? askForText(_("Enter new label to insert:"), default_label)
412                                         : askForText(_("Enter label:"), old_label);
413                                 
414                                 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
415                                 if (!res.first)
416                                         break;
417                                 new_label = frontStrip(strip(res.second));
418                         }
419
420                         //if (new_label == old_label)
421                         //      break;  // Nothing to do
422
423                         if (!new_label.empty()) {
424                                 lyxerr << "setting label to '" << new_label << "'\n";
425                                 mat()->numbered(row, true);
426                         }
427
428                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
429                                 bv->redraw();
430
431                         mat()->label(row, new_label);
432
433                         updateLocal(bv, true);
434                         break;
435                 }
436
437                 case LFUN_MATH_MUTATE:
438                 {
439                         bv->lockedInsetStoreUndo(Undo::EDIT);
440                         int x;
441                         int y;
442                         mathcursor->getPos(x, y);
443                         mat()->mutate(arg);
444                         mathcursor->setPos(x, y);
445                         mathcursor->normalize();
446                         updateLocal(bv, true);
447                         break;
448                 }
449
450                 case LFUN_MATH_EXTERN:
451                 {
452                         bv->lockedInsetStoreUndo(Undo::EDIT);
453                         handleExtern(arg);
454                         // re-compute inset dimension
455                         metrics(bv);
456                         updateLocal(bv, true);
457                         break;
458                 }
459
460                 case LFUN_MATH_DISPLAY:
461                 {
462                         int x;
463                         int y;
464                         mathcursor->getPos(x, y);
465                         if (mat()->getType() == LM_OT_SIMPLE)
466                                 mat()->mutate(LM_OT_EQUATION);
467                         else
468                                 mat()->mutate(LM_OT_SIMPLE);
469                         mathcursor->setPos(x, y);
470                         mathcursor->normalize();
471                         updateLocal(bv, true);
472                         break;
473                 }
474                 
475                 case LFUN_PASTESELECTION:
476                 {
477                         string const clip = bv->getClipboard();
478                 if (!clip.empty())
479                                 mathed_parse_normal(par_, clip);
480                         break;
481                 }
482
483                 case LFUN_MATH_COLUMN_INSERT:
484                 {
485                         if (mat()->getType() == LM_OT_ALIGN)
486                                 mat()->mutate(LM_OT_ALIGNAT);
487                         mat()->addCol(mat()->ncols());
488                         mathcursor->normalize();
489                         updateLocal(bv, true);
490                 }
491
492                 default:
493                         result = InsetFormulaBase::localDispatch(bv, action, arg);
494         }
495
496         return result;
497 }
498
499
500 void InsetFormula::handleExtern(const string & arg)
501 {
502         // where are we?
503         if (!mathcursor)
504                 return; 
505
506         bool selected = mathcursor->selection();
507
508         MathArray ar;
509         if (selected) {
510                 mathcursor->selGet(ar);
511                 lyxerr << "use selection: " << ar << "\n";
512         } else {
513                 mathcursor->end();
514                 mathcursor->stripFromLastEqualSign();
515                 ar = mathcursor->cursor().cell();
516                 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
517                 //lyxerr << "use whole cell: " << ar << "\n";
518         }
519
520         mathcursor->insert(pipeThroughExtern(arg, ar));
521 }
522
523
524 bool InsetFormula::display() const
525 {
526         return mat()->getType() != LM_OT_SIMPLE;
527 }
528
529
530 MathMatrixInset const * InsetFormula::mat() const
531 {
532         lyx::Assert(par_->asMatrixInset());
533         return par_->asMatrixInset();
534 }
535
536
537 MathMatrixInset * InsetFormula::mat()
538 {
539         lyx::Assert(par_->asMatrixInset());
540         return par_->asMatrixInset();
541 }
542
543
544 Inset::Code InsetFormula::lyxCode() const
545 {
546         return Inset::MATH_CODE;
547 }
548
549
550 void InsetFormula::validate(LaTeXFeatures & features) const
551 {
552         par_->validate(features);
553 }
554
555
556 bool InsetFormula::insetAllowed(Inset::Code code) const
557 {
558         return code == Inset::LABEL_CODE && display(); 
559 }
560
561
562 int InsetFormula::ascent(BufferView *, LyXFont const &) const
563 {
564         return par_->ascent() + 2;
565 }
566
567
568 int InsetFormula::descent(BufferView *, LyXFont const &) const
569 {
570         return par_->descent() - 2;
571 }
572
573
574 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
575 {
576         metrics(bv, font);
577         return par_->width();
578 }
579
580
581 MathInsetTypes InsetFormula::getType() const
582 {
583         return mat()->getType();
584 }