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();
108 for (int i = 0; i < 100; ++i) { // at most 100 attempts
109 // try to fix missing '*' the hard way by using mint
111 // ... > echo "1A;" | mint -i 1 -S -s -q
114 // Probably missing an operator such as * p
116 lyxerr << "checking expr: '" << expr << "'\n";
117 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
119 break; // expression syntax is ok
120 istringstream is(out.c_str());
123 if (line.find("on line") != 0)
124 break; // error message not identified
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, "*");
135 string full = "latex(" + extra + '(' + expr + "));";
136 string out = captureOutput("maple -q", header + full + trailer);
142 mathed_parse_cell(res, out);
147 MathArray pipeThroughOctave(string const &, MathArray const & ar)
152 string expr = os.str().c_str();
155 for (int i = 0; i < 100; ++i) { // at most 100 attempts
157 // try to fix missing '*' the hard way
159 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
162 lyxerr << "checking expr: '" << expr << "'\n";
163 out = captureOutput("octave -q 2>&1", expr);
164 lyxerr << "checking out: '" << out << "'\n";
166 // leave loop if expression syntax is probably ok
167 if (out.find("parse error:") == string::npos)
170 // search line with single caret
171 istringstream is(out.c_str());
175 lyxerr << "skipping line: '" << line << "'\n";
176 if (line.find(">>> ") != string::npos)
180 // found line with error, next line is the one with caret
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, "*");
199 // parse output as matrix or single number
200 MathAtom at(new MathArrayInset("array", out));
201 MathArrayInset const * mat = at.nucleus()->asArrayInset();
203 if (mat->ncols() == 1 && mat->nrows() == 1)
204 res.push_back(mat->cell(0));
206 res.push_back(MathAtom(new MathDelimInset("(", ")")));
207 res.back()->cell(0).push_back(at);
213 MathArray pipeThroughExtern(string const & lang, string const & extra,
214 MathArray const & ar)
216 if (lang == "octave")
217 return pipeThroughOctave(extra, ar);
220 return pipeThroughMaple(extra, ar);
222 // create normalized expression
225 os << "[" << extra << ' ';
228 string data = os.str().c_str();
230 // search external script
231 string file = LibFileSearch("mathed", "extern_" + lang);
233 lyxerr << "converter to '" << lang << "' not found\n";
237 // run external sript
238 string out = captureOutput(file, data);
240 mathed_parse_cell(res, out);
247 InsetFormula::InsetFormula()
248 : par_(MathAtom(new MathHullInset))
252 InsetFormula::InsetFormula(MathInsetTypes t)
253 : par_(MathAtom(new MathHullInset(t)))
257 InsetFormula::InsetFormula(string const & s)
260 bool res = mathed_parse_normal(par_, s);
263 res = mathed_parse_normal(par_, "$" + s + "$");
266 lyxerr << "cannot interpret '" << s << "' as math\n";
267 par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
274 Inset * InsetFormula::clone(Buffer const &, bool) const
276 return new InsetFormula(*this);
280 void InsetFormula::write(Buffer const *, ostream & os) const
283 WriteStream wi(os, false, false);
288 int InsetFormula::latex(Buffer const *, ostream & os, bool fragile, bool) const
290 WriteStream wi(os, fragile, true);
296 int InsetFormula::ascii(Buffer const *, ostream & os, int) const
301 TextPainter tpain(par()->width(), par()->height());
302 par()->drawT(tpain, 0, par()->ascent());
304 // reset metrics cache to "real" values
306 return tpain.textheight();
308 WriteStream wi(os, false, true);
315 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
317 return docbook(buf, os);
321 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
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;
333 void InsetFormula::read(Buffer const *, LyXLex & lex)
335 mathed_parse_normal(par_, lex);
340 //ostream & operator<<(ostream & os, LyXCursor const & c)
342 // os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
347 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
348 int y, float & xx, bool) const
353 int w = par_->width();
354 int h = par_->height();
355 int a = par_->ascent();
357 MathPainterInfo pi(bv->painter());
359 pi.base.font.setColor(LColor::math);
360 pi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
362 if (lcolor.getX11Name(LColor::mathbg)!=lcolor.getX11Name(LColor::background))
363 pi.pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
366 const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
368 mathcursor->drawSelection(pi);
369 pi.pain.rectangle(x, y - a, w, h, LColor::mathframe);
372 par_->draw(pi, x, y);
377 WriteStream wi(os, false, false);
379 if (grfx::ImagePtr image = preview(os.str()))
380 pain.image(x, y, w, h, *image);
387 setCursorVisible(false);
391 vector<string> const InsetFormula::getLabelList() const
393 return hull()->getLabelList();
397 UpdatableInset::RESULT
398 InsetFormula::localDispatch(BufferView * bv, kb_action action,
401 RESULT result = DISPATCHED;
406 bv->lockedInsetStoreUndo(Undo::INSERT);
407 mathcursor->breakLine();
408 mathcursor->normalize();
409 updateLocal(bv, true);
412 case LFUN_MATH_NUMBER:
414 //lyxerr << "toggling all numbers\n";
416 bv->lockedInsetStoreUndo(Undo::INSERT);
417 bool old = hull()->numberedType();
418 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
419 hull()->numbered(row, !old);
420 bv->owner()->message(old ? _("No number") : _("Number"));
421 updateLocal(bv, true);
426 case LFUN_MATH_NONUMBER:
428 //lyxerr << "toggling line number\n";
430 bv->lockedInsetStoreUndo(Undo::INSERT);
431 MathCursor::row_type row = mathcursor->hullRow();
432 bool old = hull()->numbered(row);
433 bv->owner()->message(old ? _("No number") : _("Number"));
434 hull()->numbered(row, !old);
435 updateLocal(bv, true);
440 case LFUN_INSERT_LABEL:
442 bv->lockedInsetStoreUndo(Undo::INSERT);
444 MathCursor::row_type row = mathcursor->hullRow();
445 string old_label = hull()->label(row);
446 string new_label = arg;
448 if (new_label.empty()) {
449 string const default_label =
450 (lyxrc.label_init_length >= 0) ? "eq:" : "";
451 pair<bool, string> const res = old_label.empty()
452 ? Alert::askForText(_("Enter new label to insert:"), default_label)
453 : Alert::askForText(_("Enter label:"), old_label);
456 new_label = frontStrip(strip(res.second));
459 //if (new_label == old_label)
460 // break; // Nothing to do
462 if (!new_label.empty()) {
463 lyxerr << "setting label to '" << new_label << "'\n";
464 hull()->numbered(row, true);
467 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
470 hull()->label(row, new_label);
472 updateLocal(bv, true);
476 case LFUN_MATH_MUTATE:
478 bv->lockedInsetStoreUndo(Undo::EDIT);
481 mathcursor->getPos(x, y);
483 mathcursor->setPos(x, y);
484 mathcursor->normalize();
485 updateLocal(bv, true);
489 case LFUN_MATH_EXTERN:
491 bv->lockedInsetStoreUndo(Undo::EDIT);
493 // re-compute inset dimension
495 updateLocal(bv, true);
499 case LFUN_MATH_DISPLAY:
503 mathcursor->getPos(x, y);
504 if (hull()->getType() == LM_OT_SIMPLE)
505 hull()->mutate(LM_OT_EQUATION);
507 hull()->mutate(LM_OT_SIMPLE);
508 mathcursor->setPos(x, y);
509 mathcursor->normalize();
510 updateLocal(bv, true);
514 case LFUN_PASTESELECTION:
516 string const clip = bv->getClipboard();
518 mathed_parse_normal(par_, clip);
523 result = InsetFormulaBase::localDispatch(bv, action, arg);
530 bool needEqnArray(string const & extra)
532 return extra == "dsolve";
536 void InsetFormula::handleExtern(const string & arg)
544 istringstream iss(arg.c_str());
545 iss >> lang >> extra;
549 bool selected = mathcursor->selection();
552 if (needEqnArray(extra)) {
554 //mathcursor->readLine(ar);
555 mathcursor->breakLine();
556 } else if (selected) {
557 mathcursor->selGet(ar);
558 //lyxerr << "use selection: " << ar << "\n";
561 mathcursor->stripFromLastEqualSign();
562 ar = mathcursor->cursor().cell();
563 mathcursor->insert('=');
564 //lyxerr << "use whole cell: " << ar << "\n";
567 mathcursor->insert(pipeThroughExtern(lang, extra, ar));
571 bool InsetFormula::display() const
573 return hull()->getType() != LM_OT_SIMPLE;
577 MathHullInset const * InsetFormula::hull() const
579 lyx::Assert(par_->asHullInset());
580 return par_->asHullInset();
584 MathHullInset * InsetFormula::hull()
586 lyx::Assert(par_->asHullInset());
587 return par_->asHullInset();
591 Inset::Code InsetFormula::lyxCode() const
593 return Inset::MATH_CODE;
597 void InsetFormula::validate(LaTeXFeatures & features) const
599 par_->validate(features);
603 bool InsetFormula::insetAllowed(Inset::Code code) const
606 (code == Inset::LABEL_CODE && display())
607 || code == Inset::ERT_CODE;
611 int InsetFormula::ascent(BufferView *, LyXFont const &) const
613 return par_->ascent() + 1;
617 int InsetFormula::descent(BufferView *, LyXFont const &) const
619 return par_->descent() + 1;
623 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
626 return par_->width();
630 MathInsetTypes InsetFormula::getType() const
632 return hull()->getType();