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.
8 * Copyright: 1996-1998 Alejandro Aguilar Sierra
10 * Version: 0.4, Lyx project.
12 * You are free to use and modify this code under the terms of
13 * the GNU General Public Licence version 2 or later.
17 #pragma implementation
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"
30 #include "BufferView.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"
41 #include "math_hullinset.h"
42 #include "math_support.h"
43 #include "math_mathmlstream.h"
44 #include "textpainter.h"
58 string captureOutput(string const & cmd, string const & data)
60 string outfile = lyx::tempName(string(), "mathextern");
61 string full = "echo '" + data + "' | (" + cmd + ") > " + outfile;
62 lyxerr << "calling: " << full << "\n";
64 dummy.startscript(Systemcall::Wait, full);
65 string out = GetFileContents(outfile);
67 lyxerr << "result: '" << out << "'\n";
72 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
74 string header = "readlib(latex):\n";
76 // remove the \\it for variable names
77 //"#`latex/csname_font` := `\\it `:"
79 "`latex/csname_font` := ``:\n";
81 // export matrices in (...) instead of [...]
83 "`latex/latex/matrix` := "
84 "subs(`[`=`(`, `]`=`)`,"
85 "eval(`latex/latex/matrix`)):\n";
87 // replace \\cdots with proper '*'
90 "subs(`\\,`=`\\cdot `,"
91 "eval(`latex/latex/*`)):\n";
93 // remove spurious \\noalign{\\medskip} in matrix output
95 "`latex/latex/matrix`:= "
96 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
97 "eval(`latex/latex/matrix`)):\n";
99 //"#`latex/latex/symbol` "
100 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
102 string trailer = "quit;";
106 string expr = os.str().c_str();
107 lyxerr << "ar: '" << ar << "'\n";
109 for (int i = 0; i < 100; ++i) { // at most 100 attempts
110 // try to fix missing '*' the hard way by using mint
112 // ... > echo "1A;" | mint -i 1 -S -s -q
115 // Probably missing an operator such as * p
117 lyxerr << "checking expr: '" << expr << "'\n";
118 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
120 break; // expression syntax is ok
121 istringstream is(out.c_str());
124 if (line.find("on line") != 0)
125 break; // error message not identified
127 string::size_type pos = line.find('^');
128 if (pos == string::npos || pos < 15)
129 break; // caret position not found
130 pos -= 15; // skip the "on line ..." part
131 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
132 break; // two '*' in a row are definitely bad
133 expr.insert(pos, "*");
136 string full = "latex(" + extra + '(' + expr + "));";
137 string out = captureOutput("maple -q", header + full + trailer);
143 mathed_parse_cell(res, out);
148 MathArray pipeThroughOctave(string const &, MathArray const & ar)
153 string expr = os.str().c_str();
156 for (int i = 0; i < 100; ++i) { // at most 100 attempts
158 // try to fix missing '*' the hard way
160 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
163 lyxerr << "checking expr: '" << expr << "'\n";
164 out = captureOutput("octave -q 2>&1", expr);
165 lyxerr << "checking out: '" << out << "'\n";
167 // leave loop if expression syntax is probably ok
168 if (out.find("parse error:") == string::npos)
171 // search line with single caret
172 istringstream is(out.c_str());
176 lyxerr << "skipping line: '" << line << "'\n";
177 if (line.find(">>> ") != string::npos)
181 // found line with error, next line is the one with caret
183 string::size_type pos = line.find('^');
184 lyxerr << "caret line: '" << line << "'\n";
185 lyxerr << "found caret at pos: '" << pos << "'\n";
186 if (pos == string::npos || pos < 4)
187 break; // caret position not found
188 pos -= 4; // skip the ">>> " part
189 if (expr[pos] == '*')
190 break; // two '*' in a row are definitely bad
191 expr.insert(pos, "*");
200 // parse output as matrix or single number
201 MathAtom at(new MathArrayInset("array", out));
202 MathArrayInset const * mat = at.nucleus()->asArrayInset();
204 if (mat->ncols() == 1 && mat->nrows() == 1)
205 res.push_back(mat->cell(0));
207 res.push_back(MathAtom(new MathDelimInset("(", ")")));
208 res.back()->cell(0).push_back(at);
214 MathArray pipeThroughExtern(string const & lang, string const & extra,
215 MathArray const & ar)
217 if (lang == "octave")
218 return pipeThroughOctave(extra, ar);
221 return pipeThroughMaple(extra, ar);
223 // create normalized expression
226 os << "[" << extra << ' ';
229 string data = os.str().c_str();
231 // search external script
232 string file = LibFileSearch("mathed", "extern_" + lang);
234 lyxerr << "converter to '" << lang << "' not found\n";
238 // run external sript
239 string out = captureOutput(file, data);
241 mathed_parse_cell(res, out);
248 InsetFormula::InsetFormula()
249 : par_(MathAtom(new MathHullInset))
253 InsetFormula::InsetFormula(MathInsetTypes t)
254 : par_(MathAtom(new MathHullInset(t)))
258 InsetFormula::InsetFormula(string const & s)
261 bool res = mathed_parse_normal(par_, s);
264 res = mathed_parse_normal(par_, "$" + s + "$");
267 lyxerr << "cannot interpret '" << s << "' as math\n";
268 par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
275 Inset * InsetFormula::clone(Buffer const &, bool) const
277 return new InsetFormula(*this);
281 void InsetFormula::write(Buffer const *, ostream & os) const
284 WriteStream wi(os, false, false);
289 int InsetFormula::latex(Buffer const *, ostream & os, bool fragile, bool) const
291 WriteStream wi(os, fragile, true);
297 int InsetFormula::ascii(Buffer const *, ostream & os, int) const
302 TextPainter tpain(par()->width(), par()->height());
303 par()->drawT(tpain, 0, par()->ascent());
305 // reset metrics cache to "real" values
307 return tpain.textheight();
309 WriteStream wi(os, false, true);
316 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
318 return docbook(buf, os);
322 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
325 ms << MTag("equation") << MTag("alt");
326 int res = ascii(buf, ms.os(), 0);
327 ms << ETag("alt") << MTag("math");
328 ms << par_.nucleus();
329 ms << ETag("math") << ETag("equation");
330 return ms.line() + res;
334 void InsetFormula::read(Buffer const *, LyXLex & lex)
336 mathed_parse_normal(par_, lex);
341 //ostream & operator<<(ostream & os, LyXCursor const & c)
343 // os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
348 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
349 int y, float & xx, bool) const
354 int w = par_->width();
355 int h = par_->height();
356 int a = par_->ascent();
358 MathPainterInfo pi(bv->painter());
360 pi.base.font.setColor(LColor::math);
361 pi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
363 if (lcolor.getX11Name(LColor::mathbg)!=lcolor.getX11Name(LColor::background))
364 pi.pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
367 const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
369 mathcursor->drawSelection(pi);
370 pi.pain.rectangle(x, y - a, w, h, LColor::mathframe);
373 par_->draw(pi, x, y);
378 WriteStream wi(os, false, false);
380 if (grfx::ImagePtr image = preview(os.str()))
381 pain.image(x, y, w, h, *image);
388 setCursorVisible(false);
392 vector<string> const InsetFormula::getLabelList() const
394 return hull()->getLabelList();
398 UpdatableInset::RESULT
399 InsetFormula::localDispatch(BufferView * bv, kb_action action,
402 RESULT result = DISPATCHED;
407 bv->lockedInsetStoreUndo(Undo::INSERT);
408 mathcursor->breakLine();
409 mathcursor->normalize();
410 updateLocal(bv, true);
413 case LFUN_MATH_NUMBER:
415 //lyxerr << "toggling all numbers\n";
417 bv->lockedInsetStoreUndo(Undo::INSERT);
418 bool old = hull()->numberedType();
419 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
420 hull()->numbered(row, !old);
421 bv->owner()->message(old ? _("No number") : _("Number"));
422 updateLocal(bv, true);
427 case LFUN_MATH_NONUMBER:
429 //lyxerr << "toggling line number\n";
431 bv->lockedInsetStoreUndo(Undo::INSERT);
432 MathCursor::row_type row = mathcursor->hullRow();
433 bool old = hull()->numbered(row);
434 bv->owner()->message(old ? _("No number") : _("Number"));
435 hull()->numbered(row, !old);
436 updateLocal(bv, true);
441 case LFUN_INSERT_LABEL:
443 bv->lockedInsetStoreUndo(Undo::INSERT);
445 MathCursor::row_type row = mathcursor->hullRow();
446 string old_label = hull()->label(row);
447 string new_label = arg;
449 if (new_label.empty()) {
450 string const default_label =
451 (lyxrc.label_init_length >= 0) ? "eq:" : "";
452 pair<bool, string> const res = old_label.empty()
453 ? Alert::askForText(_("Enter new label to insert:"), default_label)
454 : Alert::askForText(_("Enter label:"), old_label);
457 new_label = frontStrip(strip(res.second));
460 //if (new_label == old_label)
461 // break; // Nothing to do
463 if (!new_label.empty()) {
464 lyxerr << "setting label to '" << new_label << "'\n";
465 hull()->numbered(row, true);
468 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
471 hull()->label(row, new_label);
473 updateLocal(bv, true);
477 case LFUN_MATH_MUTATE:
479 bv->lockedInsetStoreUndo(Undo::EDIT);
482 mathcursor->getPos(x, y);
484 mathcursor->setPos(x, y);
485 mathcursor->normalize();
486 updateLocal(bv, true);
490 case LFUN_MATH_EXTERN:
492 bv->lockedInsetStoreUndo(Undo::EDIT);
494 // re-compute inset dimension
496 updateLocal(bv, true);
500 case LFUN_MATH_DISPLAY:
504 mathcursor->getPos(x, y);
505 if (hull()->getType() == LM_OT_SIMPLE)
506 hull()->mutate(LM_OT_EQUATION);
508 hull()->mutate(LM_OT_SIMPLE);
509 mathcursor->setPos(x, y);
510 mathcursor->normalize();
511 updateLocal(bv, true);
515 case LFUN_PASTESELECTION:
517 string const clip = bv->getClipboard();
519 mathed_parse_normal(par_, clip);
524 result = InsetFormulaBase::localDispatch(bv, action, arg);
531 void InsetFormula::handleExtern(const string & arg)
539 istringstream iss(arg.c_str());
540 iss >> lang >> extra;
544 bool selected = mathcursor->selection();
548 mathcursor->selGet(ar);
549 //lyxerr << "use selection: " << ar << "\n";
552 mathcursor->stripFromLastEqualSign();
553 ar = mathcursor->cursor().cell();
554 mathcursor->insert('=');
555 //lyxerr << "use whole cell: " << ar << "\n";
558 mathcursor->insert(pipeThroughExtern(lang, extra, ar));
562 bool InsetFormula::display() const
564 return hull()->getType() != LM_OT_SIMPLE;
568 MathHullInset const * InsetFormula::hull() const
570 lyx::Assert(par_->asHullInset());
571 return par_->asHullInset();
575 MathHullInset * InsetFormula::hull()
577 lyx::Assert(par_->asHullInset());
578 return par_->asHullInset();
582 Inset::Code InsetFormula::lyxCode() const
584 return Inset::MATH_CODE;
588 void InsetFormula::validate(LaTeXFeatures & features) const
590 par_->validate(features);
594 bool InsetFormula::insetAllowed(Inset::Code code) const
597 (code == Inset::LABEL_CODE && display())
598 || code == Inset::ERT_CODE;
602 int InsetFormula::ascent(BufferView *, LyXFont const &) const
604 return par_->ascent() + 1;
608 int InsetFormula::descent(BufferView *, LyXFont const &) const
610 return par_->descent() + 1;
614 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
617 return par_->width();
621 MathInsetTypes InsetFormula::getType() const
623 return hull()->getType();