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 "lyx_gui_misc.h"
35 #include "support/LOstream.h"
36 #include "support/LAssert.h"
37 #include "support/lyxlib.h"
38 #include "support/syscall.h"
39 #include "support/lstrings.h"
40 #include "support/filetools.h" // LibFileSearch
44 #include "math_hullinset.h"
45 #include "math_support.h"
46 #include "math_mathmlstream.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";
63 Systemcalls dummy(Systemcalls::System, full, 0);
64 string out = GetFileContents(outfile);
66 lyxerr << "result: '" << out << "'\n";
71 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
73 string header = "readlib(latex):\n";
75 // remove the \\it for variable names
76 //"#`latex/csname_font` := `\\it `:"
78 "`latex/csname_font` := ``:\n";
80 // export matrices in (...) instead of [...]
82 "`latex/latex/matrix` := "
83 "subs(`[`=`(`, `]`=`)`,"
84 "eval(`latex/latex/matrix`)):\n";
86 // replace \\cdots with proper '*'
89 "subs(`\\,`=`\\cdot `,"
90 "eval(`latex/latex/*`)):\n";
92 // remove spurious \\noalign{\\medskip} in matrix output
94 "`latex/latex/matrix`:= "
95 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
96 "eval(`latex/latex/matrix`)):\n";
98 //"#`latex/latex/symbol` "
99 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
101 string trailer = "quit;";
105 string expr = os.str().c_str();
107 for (int i = 0; i < 100; ++i) { // at most 100 attempts
108 // try to fix missing '*' the hard way by using mint
110 // ... > echo "1A;" | mint -i 1 -S -s -q
113 // Probably missing an operator such as * p
115 lyxerr << "checking expr: '" << expr << "'\n";
116 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
118 break; // expression syntax is ok
119 istringstream is(out.c_str());
122 if (line.find("on line") != 0)
123 break; // error message not identified
125 string::size_type pos = line.find('^');
126 if (pos == string::npos || pos < 15)
127 break; // caret position not found
128 pos -= 15; // skip the "on line ..." part
129 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
130 break; // two '*' in a row are definitely bad
131 expr.insert(pos, "*");
134 string full = "latex(" + extra + '(' + expr + "));";
135 string out = captureOutput("maple -q", header + full + trailer);
141 mathed_parse_cell(res, out);
146 MathArray pipeThroughOctave(string const &, MathArray const & ar)
151 string expr = os.str().c_str();
154 for (int i = 0; i < 100; ++i) { // at most 100 attempts
156 // try to fix missing '*' the hard way
158 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
161 lyxerr << "checking expr: '" << expr << "'\n";
162 out = captureOutput("octave -q 2>&1", expr);
163 lyxerr << "checking out: '" << out << "'\n";
165 // leave loop if expression syntax is probably ok
166 if (out.find("parse error:") == string::npos)
169 // search line with single caret
170 istringstream is(out.c_str());
174 lyxerr << "skipping line: '" << line << "'\n";
175 if (line.find(">>> ") != string::npos)
179 // found line with error, next line is the one with caret
181 string::size_type pos = line.find('^');
182 lyxerr << "caret line: '" << line << "'\n";
183 lyxerr << "found caret at pos: '" << pos << "'\n";
184 if (pos == string::npos || pos < 4)
185 break; // caret position not found
186 pos -= 4; // skip the ">>> " part
187 if (expr[pos] == '*')
188 break; // two '*' in a row are definitely bad
189 expr.insert(pos, "*");
198 // parse output as matrix or single number
199 MathAtom at(new MathArrayInset(out));
200 MathArrayInset const * mat = at.nucleus()->asArrayInset();
202 if (mat->ncols() == 1 && mat->nrows() == 1)
203 res.push_back(mat->cell(0));
205 res.push_back(MathAtom(new MathDelimInset("(", ")")));
206 res.back()->cell(0).push_back(at);
212 MathArray pipeThroughExtern(string const & lang, string const & extra,
213 MathArray const & ar)
215 if (lang == "octave")
216 return pipeThroughOctave(extra, ar);
219 return pipeThroughMaple(extra, ar);
221 // create normalized expression
224 os << "[" << extra << ' ';
227 string data = os.str().c_str();
229 // search external script
230 string file = LibFileSearch("mathed", "extern_" + lang);
232 lyxerr << "converter to '" << lang << "' not found\n";
236 // run external sript
237 string out = captureOutput(file, data);
239 mathed_parse_cell(res, out);
246 InsetFormula::InsetFormula()
247 : par_(MathAtom(new MathHullInset))
251 InsetFormula::InsetFormula(MathInsetTypes t)
252 : par_(MathAtom(new MathHullInset(t)))
256 InsetFormula::InsetFormula(string const & s)
259 bool res = mathed_parse_normal(par_, s);
262 res = mathed_parse_normal(par_, "$" + s + "$");
265 lyxerr << "cannot interpret '" << s << "' as math\n";
266 par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
273 Inset * InsetFormula::clone(Buffer const &, bool) const
275 return new InsetFormula(*this);
279 void InsetFormula::write(Buffer const * buf, ostream & os) const
282 latex(buf, os, false, false);
286 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
289 WriteStream wi(buf, os, fragil);
295 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
297 WriteStream wi(buf, os, false);
303 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
305 return docbook(buf, os);
309 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
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;
321 void InsetFormula::read(Buffer const *, LyXLex & lex)
323 mathed_parse_normal(par_, lex);
328 //std::ostream & operator<<(std::ostream & os, LyXCursor const & c)
330 // os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
335 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
336 int y, float & xx, bool) const
341 Painter & pain = bv->painter();
344 int w = par_->width();
345 int h = par_->height();
346 int a = par_->ascent();
350 if (LyXText * t = bv->getLyXText()) {
351 LyXText::Selection & sel = t->selection;
352 lyxerr << "sel.start: " << sel.start << "\n";
353 lyxerr << "sel.end: " << sel.end << "\n";
354 lyxerr << "t->cursor: " << t->cursor << "\n";
355 if (sel.set() && sel.start < t->cursor && t->cursor < sel.end) {
356 pain.fillRectangle(x, y - a, w, h, LColor::selection);
363 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
364 if (mathcursor && mathcursor->formula() == this) {
365 mathcursor->drawSelection(pain);
366 pain.rectangle(x, y - a, w, h, LColor::mathframe);
370 par_->draw(pain, x, y);
375 setCursorVisible(false);
379 vector<string> const InsetFormula::getLabelList() const
381 return mat()->getLabelList();
385 UpdatableInset::RESULT
386 InsetFormula::localDispatch(BufferView * bv, kb_action action,
389 RESULT result = DISPATCHED;
394 bv->lockedInsetStoreUndo(Undo::INSERT);
395 mathcursor->breakLine();
396 mathcursor->normalize();
397 updateLocal(bv, true);
400 case LFUN_MATH_NUMBER:
402 //lyxerr << "toggling all numbers\n";
404 bv->lockedInsetStoreUndo(Undo::INSERT);
405 bool old = mat()->numberedType();
406 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
407 mat()->numbered(row, !old);
408 bv->owner()->message(old ? _("No number") : _("Number"));
409 updateLocal(bv, true);
414 case LFUN_MATH_NONUMBER:
416 //lyxerr << "toggling line number\n";
418 bv->lockedInsetStoreUndo(Undo::INSERT);
419 MathCursor::row_type row = mathcursor->row();
420 bool old = mat()->numbered(row);
421 bv->owner()->message(old ? _("No number") : _("Number"));
422 mat()->numbered(row, !old);
423 updateLocal(bv, true);
428 case LFUN_INSERT_LABEL:
430 bv->lockedInsetStoreUndo(Undo::INSERT);
432 MathCursor::row_type row = mathcursor->row();
433 string old_label = mat()->label(row);
434 string new_label = arg;
436 if (new_label.empty()) {
437 string const default_label =
438 (lyxrc.label_init_length >= 0) ? "eq:" : "";
439 pair<bool, string> const res = old_label.empty()
440 ? askForText(_("Enter new label to insert:"), default_label)
441 : askForText(_("Enter label:"), old_label);
443 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
446 new_label = frontStrip(strip(res.second));
449 //if (new_label == old_label)
450 // break; // Nothing to do
452 if (!new_label.empty()) {
453 lyxerr << "setting label to '" << new_label << "'\n";
454 mat()->numbered(row, true);
457 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
460 mat()->label(row, new_label);
462 updateLocal(bv, true);
466 case LFUN_MATH_MUTATE:
468 bv->lockedInsetStoreUndo(Undo::EDIT);
471 mathcursor->getPos(x, y);
473 mathcursor->setPos(x, y);
474 mathcursor->normalize();
475 updateLocal(bv, true);
479 case LFUN_MATH_EXTERN:
481 bv->lockedInsetStoreUndo(Undo::EDIT);
483 // re-compute inset dimension
485 updateLocal(bv, true);
489 case LFUN_MATH_DISPLAY:
493 mathcursor->getPos(x, y);
494 if (mat()->getType() == LM_OT_SIMPLE)
495 mat()->mutate(LM_OT_EQUATION);
497 mat()->mutate(LM_OT_SIMPLE);
498 mathcursor->setPos(x, y);
499 mathcursor->normalize();
500 updateLocal(bv, true);
504 case LFUN_PASTESELECTION:
506 string const clip = bv->getClipboard();
508 mathed_parse_normal(par_, clip);
512 case LFUN_MATH_COLUMN_INSERT:
514 if (mat()->getType() == LM_OT_ALIGN)
515 mat()->mutate(LM_OT_ALIGNAT);
516 mat()->addCol(mat()->ncols());
517 mathcursor->normalize();
518 updateLocal(bv, true);
523 result = InsetFormulaBase::localDispatch(bv, action, arg);
530 bool needEqnArray(string const & extra)
533 return extra == "dsolve";
537 void InsetFormula::handleExtern(const string & arg)
545 istringstream iss(arg.c_str());
546 iss >> lang >> extra;
550 bool selected = mathcursor->selection();
553 if (needEqnArray(extra)) {
555 mathcursor->readLine(ar);
556 mathcursor->breakLine();
557 } else if (selected) {
558 mathcursor->selGet(ar);
559 //lyxerr << "use selection: " << ar << "\n";
562 mathcursor->stripFromLastEqualSign();
563 ar = mathcursor->cursor().cell();
564 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
565 //lyxerr << "use whole cell: " << ar << "\n";
568 mathcursor->insert(pipeThroughExtern(lang, extra, ar));
572 bool InsetFormula::display() const
574 return mat()->getType() != LM_OT_SIMPLE;
578 MathHullInset const * InsetFormula::mat() const
580 lyx::Assert(par_->asHullInset());
581 return par_->asHullInset();
585 MathHullInset * InsetFormula::mat()
587 lyx::Assert(par_->asHullInset());
588 return par_->asHullInset();
592 Inset::Code InsetFormula::lyxCode() const
594 return Inset::MATH_CODE;
598 void InsetFormula::validate(LaTeXFeatures & features) const
600 par_->validate(features);
604 bool InsetFormula::insetAllowed(Inset::Code code) const
607 (code == Inset::LABEL_CODE && display())
608 || code == Inset::ERT_CODE;
612 int InsetFormula::ascent(BufferView *, LyXFont const &) const
614 return par_->ascent() + 2;
618 int InsetFormula::descent(BufferView *, LyXFont const &) const
620 return par_->descent() - 2;
624 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
627 return par_->width();
631 MathInsetTypes InsetFormula::getType() const
633 return mat()->getType();