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"
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
43 #include "math_hullinset.h"
44 #include "math_support.h"
45 #include "math_mathmlstream.h"
57 string captureOutput(string const & cmd, string const & data)
59 string outfile = lyx::tempName(string(), "mathextern");
60 string full = "echo '" + data + "' | (" + cmd + ") > " + outfile;
61 lyxerr << "calling: " << full << "\n";
62 Systemcalls dummy(Systemcalls::System, full, 0);
63 string out = GetFileContents(outfile);
65 lyxerr << "result: '" << out << "'\n";
70 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
72 string header = "readlib(latex):\n";
74 // remove the \\it for variable names
75 //"#`latex/csname_font` := `\\it `:"
77 "`latex/csname_font` := ``:\n";
79 // export matrices in (...) instead of [...]
81 "`latex/latex/matrix` := "
82 "subs(`[`=`(`, `]`=`)`,"
83 "eval(`latex/latex/matrix`)):\n";
85 // replace \\cdots with proper '*'
88 "subs(`\\,`=`\\cdot `,"
89 "eval(`latex/latex/*`)):\n";
91 // remove spurious \\noalign{\\medskip} in matrix output
93 "`latex/latex/matrix`:= "
94 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
95 "eval(`latex/latex/matrix`)):\n";
97 //"#`latex/latex/symbol` "
98 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
100 string trailer = "quit;";
104 string expr = os.str().c_str();
106 for (int i = 0; i < 100; ++i) { // at most 100 attempts
107 // try to fix missing '*' the hard way by using mint
109 // ... > echo "1A;" | mint -i 1 -S -s -q
112 // Probably missing an operator such as * p
114 lyxerr << "checking expr: '" << expr << "'\n";
115 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
117 break; // expression syntax is ok
118 istringstream is(out.c_str());
121 if (line.find("on line") != 0)
122 break; // error message not identified
124 string::size_type pos = line.find('^');
125 if (pos == string::npos || pos < 15)
126 break; // caret position not found
127 pos -= 15; // skip the "on line ..." part
128 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
129 break; // two '*' in a row are definitely bad
130 expr.insert(pos, "*");
133 string full = "latex(" + extra + '(' + expr + "));";
134 string out = captureOutput("maple -q", header + full + trailer);
140 mathed_parse_cell(res, out);
145 MathArray pipeThroughOctave(string const &, MathArray const & ar)
150 string expr = os.str().c_str();
153 for (int i = 0; i < 100; ++i) { // at most 100 attempts
155 // try to fix missing '*' the hard way
157 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
160 lyxerr << "checking expr: '" << expr << "'\n";
161 out = captureOutput("octave -q 2>&1", expr);
162 lyxerr << "checking out: '" << out << "'\n";
164 // leave loop if expression syntax is probably ok
165 if (out.find("parse error:") == string::npos)
168 // search line with single caret
169 istringstream is(out.c_str());
173 lyxerr << "skipping line: '" << line << "'\n";
174 if (line.find(">>> ") != string::npos)
178 // found line with error, next line is the one with caret
180 string::size_type pos = line.find('^');
181 lyxerr << "caret line: '" << line << "'\n";
182 lyxerr << "found caret at pos: '" << pos << "'\n";
183 if (pos == string::npos || pos < 4)
184 break; // caret position not found
185 pos -= 4; // skip the ">>> " part
186 if (expr[pos] == '*')
187 break; // two '*' in a row are definitely bad
188 expr.insert(pos, "*");
197 // parse output as matrix or single number
198 MathAtom at(new MathArrayInset(out));
199 MathArrayInset const * mat = at.nucleus()->asArrayInset();
201 if (mat->ncols() == 1 && mat->nrows() == 1)
202 res.push_back(mat->cell(0));
204 res.push_back(MathAtom(new MathDelimInset("(", ")")));
205 res.back()->cell(0).push_back(at);
211 MathArray pipeThroughExtern(string const & lang, string const & extra,
212 MathArray const & ar)
214 if (lang == "octave")
215 return pipeThroughOctave(extra, ar);
218 return pipeThroughMaple(extra, ar);
220 // create normalized expression
223 os << "[" << extra << ' ';
226 string data = os.str().c_str();
228 // search external script
229 string file = LibFileSearch("mathed", "extern_" + lang);
231 lyxerr << "converter to '" << lang << "' not found\n";
235 // run external sript
236 string out = captureOutput(file, data);
238 mathed_parse_cell(res, out);
245 InsetFormula::InsetFormula()
246 : par_(MathAtom(new MathHullInset))
250 InsetFormula::InsetFormula(MathInsetTypes t)
251 : par_(MathAtom(new MathHullInset(t)))
255 InsetFormula::InsetFormula(string const & s)
258 bool res = mathed_parse_normal(par_, s);
261 res = mathed_parse_normal(par_, "$" + s + "$");
264 lyxerr << "cannot interpret '" << s << "' as math\n";
265 par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
272 Inset * InsetFormula::clone(Buffer const &, bool) const
274 return new InsetFormula(*this);
278 void InsetFormula::write(Buffer const * buf, ostream & os) const
281 latex(buf, os, false, false);
285 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
288 WriteStream wi(buf, os, fragil);
294 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
296 WriteStream wi(buf, os, false);
302 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
304 return docbook(buf, os);
308 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
311 ms << MTag("equation") << MTag("alt");
312 int res = ascii(buf, ms.os_, 0);
313 ms << ETag("alt") << MTag("math");
314 ms << par_.nucleus();
315 ms << ETag("math") << ETag("equation");
316 return ms.line_ + res;
320 void InsetFormula::read(Buffer const *, LyXLex & lex)
322 mathed_parse_normal(par_, lex);
327 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
328 int y, float & xx, bool) const
333 Painter & pain = bv->painter();
336 int w = par_->width();
337 int h = par_->height();
338 int a = par_->ascent();
339 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
341 if (mathcursor && mathcursor->formula() == this) {
342 mathcursor->drawSelection(pain);
343 pain.rectangle(x, y - a, w, h, LColor::mathframe);
346 par_->draw(pain, x, y);
351 setCursorVisible(false);
355 vector<string> const InsetFormula::getLabelList() const
357 return mat()->getLabelList();
361 UpdatableInset::RESULT
362 InsetFormula::localDispatch(BufferView * bv, kb_action action,
365 RESULT result = DISPATCHED;
370 bv->lockedInsetStoreUndo(Undo::INSERT);
371 mathcursor->breakLine();
372 mathcursor->normalize();
373 updateLocal(bv, true);
376 case LFUN_MATH_NUMBER:
378 //lyxerr << "toggling all numbers\n";
380 bv->lockedInsetStoreUndo(Undo::INSERT);
381 bool old = mat()->numberedType();
382 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
383 mat()->numbered(row, !old);
384 bv->owner()->message(old ? _("No number") : _("Number"));
385 updateLocal(bv, true);
390 case LFUN_MATH_NONUMBER:
392 //lyxerr << "toggling line number\n";
394 bv->lockedInsetStoreUndo(Undo::INSERT);
395 MathCursor::row_type row = mathcursor->row();
396 bool old = mat()->numbered(row);
397 bv->owner()->message(old ? _("No number") : _("Number"));
398 mat()->numbered(row, !old);
399 updateLocal(bv, true);
404 case LFUN_INSERT_LABEL:
406 bv->lockedInsetStoreUndo(Undo::INSERT);
408 MathCursor::row_type row = mathcursor->row();
409 string old_label = mat()->label(row);
410 string new_label = arg;
412 if (new_label.empty()) {
413 string const default_label =
414 (lyxrc.label_init_length >= 0) ? "eq:" : "";
415 pair<bool, string> const res = old_label.empty()
416 ? askForText(_("Enter new label to insert:"), default_label)
417 : askForText(_("Enter label:"), old_label);
419 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
422 new_label = frontStrip(strip(res.second));
425 //if (new_label == old_label)
426 // break; // Nothing to do
428 if (!new_label.empty()) {
429 lyxerr << "setting label to '" << new_label << "'\n";
430 mat()->numbered(row, true);
433 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
436 mat()->label(row, new_label);
438 updateLocal(bv, true);
442 case LFUN_MATH_MUTATE:
444 bv->lockedInsetStoreUndo(Undo::EDIT);
447 mathcursor->getPos(x, y);
449 mathcursor->setPos(x, y);
450 mathcursor->normalize();
451 updateLocal(bv, true);
455 case LFUN_MATH_EXTERN:
457 bv->lockedInsetStoreUndo(Undo::EDIT);
459 // re-compute inset dimension
461 updateLocal(bv, true);
465 case LFUN_MATH_DISPLAY:
469 mathcursor->getPos(x, y);
470 if (mat()->getType() == LM_OT_SIMPLE)
471 mat()->mutate(LM_OT_EQUATION);
473 mat()->mutate(LM_OT_SIMPLE);
474 mathcursor->setPos(x, y);
475 mathcursor->normalize();
476 updateLocal(bv, true);
480 case LFUN_PASTESELECTION:
482 string const clip = bv->getClipboard();
484 mathed_parse_normal(par_, clip);
488 case LFUN_MATH_COLUMN_INSERT:
490 if (mat()->getType() == LM_OT_ALIGN)
491 mat()->mutate(LM_OT_ALIGNAT);
492 mat()->addCol(mat()->ncols());
493 mathcursor->normalize();
494 updateLocal(bv, true);
499 result = InsetFormulaBase::localDispatch(bv, action, arg);
506 bool needEqnArray(string const & extra)
509 return extra == "dsolve";
513 void InsetFormula::handleExtern(const string & arg)
521 istringstream iss(arg.c_str());
522 iss >> lang >> extra;
526 bool selected = mathcursor->selection();
529 if (needEqnArray(extra)) {
531 mathcursor->readLine(ar);
532 mathcursor->breakLine();
533 } else if (selected) {
534 mathcursor->selGet(ar);
535 //lyxerr << "use selection: " << ar << "\n";
538 mathcursor->stripFromLastEqualSign();
539 ar = mathcursor->cursor().cell();
540 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
541 //lyxerr << "use whole cell: " << ar << "\n";
544 mathcursor->insert(pipeThroughExtern(lang, extra, ar));
548 bool InsetFormula::display() const
550 return mat()->getType() != LM_OT_SIMPLE;
554 MathHullInset const * InsetFormula::mat() const
556 lyx::Assert(par_->asHullInset());
557 return par_->asHullInset();
561 MathHullInset * InsetFormula::mat()
563 lyx::Assert(par_->asHullInset());
564 return par_->asHullInset();
568 Inset::Code InsetFormula::lyxCode() const
570 return Inset::MATH_CODE;
574 void InsetFormula::validate(LaTeXFeatures & features) const
576 par_->validate(features);
580 bool InsetFormula::insetAllowed(Inset::Code code) const
583 (code == Inset::LABEL_CODE && display())
584 || code == Inset::ERT_CODE;
588 int InsetFormula::ascent(BufferView *, LyXFont const &) const
590 return par_->ascent() + 2;
594 int InsetFormula::descent(BufferView *, LyXFont const &) const
596 return par_->descent() - 2;
600 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
603 return par_->width();
607 MathInsetTypes InsetFormula::getType() const
609 return mat()->getType();