]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
add missing using's
[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/systemcall.h"
37 #include "support/filetools.h" // LibFileSearch
38 #include "frontends/LyXView.h"
39 #include "frontends/Painter.h"
40 #include "lyxrc.h"
41 #include "math_hullinset.h"
42 #include "math_support.h"
43 #include "math_mathmlstream.h"
44 #include "textpainter.h"
45 #include "preview.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                 Systemcall dummy;
64                 dummy.startscript(Systemcall::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 *, ostream & os) const
281 {
282         os << "Formula ";
283         WriteStream wi(os, false, false);
284         par_->write(wi);
285 }
286
287
288 int InsetFormula::latex(Buffer const *, ostream & os, bool fragile, bool) const
289 {
290         WriteStream wi(os, fragile, true);
291         par_->write(wi);
292         return wi.line();
293 }
294
295
296 int InsetFormula::ascii(Buffer const *, ostream & os, int) const
297 {
298 #if 0
299         TextMetricsInfo mi;
300         par()->metricsT(mi);
301         TextPainter tpain(par()->width(), par()->height());
302         par()->drawT(tpain, 0, par()->ascent());
303         tpain.show(os);
304         // reset metrics cache to "real" values
305         metrics();
306         return tpain.textheight();
307 #else
308         WriteStream wi(os, false, true);
309         par_->write(wi);
310         return wi.line();
311 #endif
312 }
313
314
315 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
316 {
317         return docbook(buf, os);
318 }
319
320
321 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
322 {
323         MathMLStream ms(os);
324         ms << MTag("equation") << MTag("alt");
325         int res = ascii(buf, ms.os(), 0);
326         ms << ETag("alt") << MTag("math");
327         ms << par_.nucleus();
328         ms << ETag("math") << ETag("equation");
329         return ms.line() + res;
330 }
331
332
333 void InsetFormula::read(Buffer const *, LyXLex & lex)
334 {
335         mathed_parse_normal(par_, lex);
336         metrics();
337 }
338
339
340 //ostream & operator<<(ostream & os, LyXCursor const & c)
341 //{
342 //      os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
343 //      return os;
344 //}
345
346
347 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
348                         int y, float & xx, bool) const
349 {
350         metrics(bv, font);
351
352         int x = int(xx);
353         int w = par_->width();
354         int h = par_->height();
355         int a = par_->ascent();
356         Painter & pain = bv->painter();
357
358         if (lcolor.getX11Name(LColor::mathbg)!=lcolor.getX11Name(LColor::background))
359                 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
360
361         if (mathcursor &&
362                         const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
363         {
364                 mathcursor->drawSelection(pain);
365                 pain.rectangle(x, y - a, w, h, LColor::mathframe);
366         }
367
368         par_->draw(pain, x, y);
369
370         // preview stuff
371 #if 0
372         ostringstream os;
373         WriteStream wi(os, false, false);
374         par_->write(wi);
375         if (grfx::ImagePtr image = preview(os.str()))
376                 pain.image(x, y, w, h, *image);
377 #endif
378         
379         xx += par_->width();
380         xo_ = x;
381         yo_ = y;
382
383         setCursorVisible(false);
384 }
385
386
387 vector<string> const InsetFormula::getLabelList() const
388 {
389         return hull()->getLabelList();
390 }
391
392
393 UpdatableInset::RESULT
394 InsetFormula::localDispatch(BufferView * bv, kb_action action,
395          string const & arg)
396 {
397         RESULT result = DISPATCHED;
398
399         switch (action) {
400
401                 case LFUN_BREAKLINE:
402                         bv->lockedInsetStoreUndo(Undo::INSERT);
403                         mathcursor->breakLine();
404                         mathcursor->normalize();
405                         updateLocal(bv, true);
406                         break;
407
408                 case LFUN_MATH_NUMBER:
409                 {
410                         //lyxerr << "toggling all numbers\n";
411                         if (display()) {
412                                 bv->lockedInsetStoreUndo(Undo::INSERT);
413                                 bool old = hull()->numberedType();
414                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
415                                         hull()->numbered(row, !old);
416                                 bv->owner()->message(old ? _("No number") : _("Number"));
417                                 updateLocal(bv, true);
418                         }
419                         break;
420                 }
421
422                 case LFUN_MATH_NONUMBER:
423                 {
424                         //lyxerr << "toggling line number\n";
425                         if (display()) {
426                                 bv->lockedInsetStoreUndo(Undo::INSERT);
427                                 MathCursor::row_type row = mathcursor->hullRow();
428                                 bool old = hull()->numbered(row);
429                                 bv->owner()->message(old ? _("No number") : _("Number"));
430                                 hull()->numbered(row, !old);
431                                 updateLocal(bv, true);
432                         }
433                         break;
434                 }
435
436                 case LFUN_INSERT_LABEL:
437                 {
438                         bv->lockedInsetStoreUndo(Undo::INSERT);
439
440                         MathCursor::row_type row = mathcursor->hullRow();
441                         string old_label = hull()->label(row);
442                         string new_label = arg;
443
444                         if (new_label.empty()) {
445                                 string const default_label =
446                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
447                                 pair<bool, string> const res = old_label.empty()
448                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
449                                         : Alert::askForText(_("Enter label:"), old_label);
450                                 if (!res.first)
451                                         break;
452                                 new_label = frontStrip(strip(res.second));
453                         }
454
455                         //if (new_label == old_label)
456                         //      break;  // Nothing to do
457
458                         if (!new_label.empty()) {
459                                 lyxerr << "setting label to '" << new_label << "'\n";
460                                 hull()->numbered(row, true);
461                         }
462
463                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
464                                 bv->redraw();
465
466                         hull()->label(row, new_label);
467
468                         updateLocal(bv, true);
469                         break;
470                 }
471
472                 case LFUN_MATH_MUTATE:
473                 {
474                         bv->lockedInsetStoreUndo(Undo::EDIT);
475                         int x;
476                         int y;
477                         mathcursor->getPos(x, y);
478                         hull()->mutate(arg);
479                         mathcursor->setPos(x, y);
480                         mathcursor->normalize();
481                         updateLocal(bv, true);
482                         break;
483                 }
484
485                 case LFUN_MATH_EXTERN:
486                 {
487                         bv->lockedInsetStoreUndo(Undo::EDIT);
488                         handleExtern(arg);
489                         // re-compute inset dimension
490                         metrics(bv);
491                         updateLocal(bv, true);
492                         break;
493                 }
494
495                 case LFUN_MATH_DISPLAY:
496                 {
497                         int x = 0;
498                         int y = 0;
499                         mathcursor->getPos(x, y);
500                         if (hull()->getType() == LM_OT_SIMPLE)
501                                 hull()->mutate(LM_OT_EQUATION);
502                         else
503                                 hull()->mutate(LM_OT_SIMPLE);
504                         mathcursor->setPos(x, y);
505                         mathcursor->normalize();
506                         updateLocal(bv, true);
507                         break;
508                 }
509
510                 case LFUN_PASTESELECTION:
511                 {
512                         string const clip = bv->getClipboard();
513                 if (!clip.empty())
514                                 mathed_parse_normal(par_, clip);
515                         break;
516                 }
517
518                 default:
519                         result = InsetFormulaBase::localDispatch(bv, action, arg);
520         }
521
522         return result;
523 }
524
525
526 bool needEqnArray(string const & extra)
527 {
528         return extra == "dsolve";
529 }
530
531
532 void InsetFormula::handleExtern(const string & arg)
533 {
534         // where are we?
535         if (!mathcursor)
536                 return;
537
538         string lang;
539         string extra;
540         istringstream iss(arg.c_str());
541         iss >> lang >> extra;
542         if (extra.empty())
543                 extra = "noextra";
544
545         bool selected = mathcursor->selection();
546
547         MathArray ar;
548         if (needEqnArray(extra)) {
549                 mathcursor->last();
550                 //mathcursor->readLine(ar);
551                 mathcursor->breakLine();
552         } else if (selected) {
553                 mathcursor->selGet(ar);
554                 //lyxerr << "use selection: " << ar << "\n";
555         } else {
556                 mathcursor->last();
557                 mathcursor->stripFromLastEqualSign();
558                 ar = mathcursor->cursor().cell();
559                 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
560                 //lyxerr << "use whole cell: " << ar << "\n";
561         }
562
563         mathcursor->insert(pipeThroughExtern(lang, extra, ar));
564 }
565
566
567 bool InsetFormula::display() const
568 {
569         return hull()->getType() != LM_OT_SIMPLE;
570 }
571
572
573 MathHullInset const * InsetFormula::hull() const
574 {
575         lyx::Assert(par_->asHullInset());
576         return par_->asHullInset();
577 }
578
579
580 MathHullInset * InsetFormula::hull()
581 {
582         lyx::Assert(par_->asHullInset());
583         return par_->asHullInset();
584 }
585
586
587 Inset::Code InsetFormula::lyxCode() const
588 {
589         return Inset::MATH_CODE;
590 }
591
592
593 void InsetFormula::validate(LaTeXFeatures & features) const
594 {
595         par_->validate(features);
596 }
597
598
599 bool InsetFormula::insetAllowed(Inset::Code code) const
600 {
601         return
602                 (code == Inset::LABEL_CODE && display())
603                 || code == Inset::ERT_CODE;
604 }
605
606
607 int InsetFormula::ascent(BufferView *, LyXFont const &) const
608 {
609         return par_->ascent() + 1;
610 }
611
612
613 int InsetFormula::descent(BufferView *, LyXFont const &) const
614 {
615         return par_->descent() + 1;
616 }
617
618
619 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
620 {
621         metrics(bv, font);
622         return par_->width();
623 }
624
625
626 MathInsetTypes InsetFormula::getType() const
627 {
628         return hull()->getType();
629 }