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