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);
64 lyxerr << "result: '" << out << "'\n";
69 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
71 string header = "readlib(latex):\n";
73 // remove the \\it for variable names
74 //"#`latex/csname_font` := `\\it `:"
76 "`latex/csname_font` := ``:\n";
78 // export matrices in (...) instead of [...]
80 "`latex/latex/matrix` := "
81 "subs(`[`=`(`, `]`=`)`,"
82 "eval(`latex/latex/matrix`)):\n";
84 // replace \\cdots with proper '*'
87 "subs(`\\,`=`\\cdot `,"
88 "eval(`latex/latex/*`)):\n";
90 // remove spurious \\noalign{\\medskip} in matrix output
92 "`latex/latex/matrix`:= "
93 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
94 "eval(`latex/latex/matrix`)):\n";
96 //"#`latex/latex/symbol` "
97 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
99 string trailer = "quit;";
103 string expr = os.str().c_str();
105 for (int i = 0; i < 100; ++i) { // at most 100 attempts
106 // try to fix missing '*' the hard way by using mint
108 // ... > echo "1A;" | mint -i 1 -S -s -q
111 // Probably missing an operator such as * p
113 lyxerr << "checking expr: '" << expr << "'\n";
114 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
116 break; // expression syntax is ok
117 istringstream is(out.c_str());
120 if (line.find("on line") != 0)
121 break; // error message not identified
123 string::size_type pos = line.find('^');
124 if (pos == string::npos || pos < 15)
125 break; // caret position not found
126 pos -= 15; // skip the "on line ..." part
127 if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
128 break; // two '*' in a row are definitely bad
129 expr.insert(pos, "*");
132 string full = "latex(" + extra + '(' + expr + "));";
133 string out = captureOutput("maple -q", header + full + trailer);
139 mathed_parse_cell(res, out);
144 MathArray pipeThroughOctave(string const &, MathArray const & ar)
149 string expr = os.str().c_str();
152 for (int i = 0; i < 100; ++i) { // at most 100 attempts
154 // try to fix missing '*' the hard way
156 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
159 lyxerr << "checking expr: '" << expr << "'\n";
160 out = captureOutput("octave -q 2>&1", expr);
161 lyxerr << "checking out: '" << out << "'\n";
163 // leave loop if expression syntax is probably ok
164 if (out.find("parse error:") == string::npos)
167 // search line with single caret
168 istringstream is(out.c_str());
172 lyxerr << "skipping line: '" << line << "'\n";
173 if (line.find(">>> ") != string::npos)
177 // found line with error, next line is the one with caret
179 string::size_type pos = line.find('^');
180 lyxerr << "caret line: '" << line << "'\n";
181 lyxerr << "found caret at pos: '" << pos << "'\n";
182 if (pos == string::npos || pos < 4)
183 break; // caret position not found
184 pos -= 4; // skip the ">>> " part
185 if (expr[pos] == '*')
186 break; // two '*' in a row are definitely bad
187 expr.insert(pos, "*");
196 // parse output as matrix or single number
197 MathAtom at(new MathArrayInset(out));
198 MathArrayInset const * mat = at.nucleus()->asArrayInset();
200 if (mat->ncols() == 1 && mat->nrows() == 1)
201 res.push_back(mat->cell(0));
203 res.push_back(MathAtom(new MathDelimInset("(", ")")));
204 res.back()->cell(0).push_back(at);
210 MathArray pipeThroughExtern(string const & lang, string const & extra,
211 MathArray const & ar)
213 if (lang == "octave")
214 return pipeThroughOctave(extra, ar);
217 return pipeThroughMaple(extra, ar);
219 // create normalized expression
222 os << "[" << extra << ' ';
225 string data = os.str().c_str();
227 // search external script
228 string file = LibFileSearch("mathed", "extern_" + lang);
230 lyxerr << "converter to '" << lang << "' not found\n";
234 // run external sript
235 string out = captureOutput(file, data);
237 mathed_parse_cell(res, out);
244 InsetFormula::InsetFormula()
245 : par_(MathAtom(new MathHullInset))
249 InsetFormula::InsetFormula(MathInsetTypes t)
250 : par_(MathAtom(new MathHullInset(t)))
254 InsetFormula::InsetFormula(string const & s)
257 bool res = mathed_parse_normal(par_, s);
260 res = mathed_parse_normal(par_, "$" + s + "$");
263 lyxerr << "cannot interpret '" << s << "' as math\n";
264 par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
271 Inset * InsetFormula::clone(Buffer const &, bool) const
273 return new InsetFormula(*this);
277 void InsetFormula::write(Buffer const * buf, ostream & os) const
280 latex(buf, os, false, false);
284 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
287 WriteStream wi(buf, os, fragil);
293 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
295 WriteStream wi(buf, os, false);
301 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
303 return docbook(buf, os);
307 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
310 ms << MTag("equation") << MTag("alt");
311 int res = ascii(buf, ms.os_, 0);
312 ms << ETag("alt") << MTag("math");
313 ms << par_.nucleus();
314 ms << ETag("math") << ETag("equation");
315 return ms.line_ + res;
319 void InsetFormula::read(Buffer const *, LyXLex & lex)
321 mathed_parse_normal(par_, lex);
326 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
327 int y, float & xx, bool) const
332 Painter & pain = bv->painter();
335 int w = par_->width();
336 int h = par_->height();
337 int a = par_->ascent();
338 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
340 if (mathcursor && mathcursor->formula() == this) {
341 mathcursor->drawSelection(pain);
342 pain.rectangle(x, y - a, w, h, LColor::mathframe);
345 par_->draw(pain, x, y);
350 setCursorVisible(false);
354 vector<string> const InsetFormula::getLabelList() const
356 return mat()->getLabelList();
360 UpdatableInset::RESULT
361 InsetFormula::localDispatch(BufferView * bv, kb_action action,
364 RESULT result = DISPATCHED;
369 bv->lockedInsetStoreUndo(Undo::INSERT);
370 mathcursor->breakLine();
371 mathcursor->normalize();
372 updateLocal(bv, true);
375 case LFUN_MATH_NUMBER:
377 //lyxerr << "toggling all numbers\n";
379 bv->lockedInsetStoreUndo(Undo::INSERT);
380 bool old = mat()->numberedType();
381 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
382 mat()->numbered(row, !old);
383 bv->owner()->message(old ? _("No number") : _("Number"));
384 updateLocal(bv, true);
389 case LFUN_MATH_NONUMBER:
391 //lyxerr << "toggling line number\n";
393 bv->lockedInsetStoreUndo(Undo::INSERT);
394 MathCursor::row_type row = mathcursor->row();
395 bool old = mat()->numbered(row);
396 bv->owner()->message(old ? _("No number") : _("Number"));
397 mat()->numbered(row, !old);
398 updateLocal(bv, true);
403 case LFUN_INSERT_LABEL:
405 bv->lockedInsetStoreUndo(Undo::INSERT);
407 MathCursor::row_type row = mathcursor->row();
408 string old_label = mat()->label(row);
409 string new_label = arg;
411 if (new_label.empty()) {
412 string const default_label =
413 (lyxrc.label_init_length >= 0) ? "eq:" : "";
414 pair<bool, string> const res = old_label.empty()
415 ? askForText(_("Enter new label to insert:"), default_label)
416 : askForText(_("Enter label:"), old_label);
418 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
421 new_label = frontStrip(strip(res.second));
424 //if (new_label == old_label)
425 // break; // Nothing to do
427 if (!new_label.empty()) {
428 lyxerr << "setting label to '" << new_label << "'\n";
429 mat()->numbered(row, true);
432 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
435 mat()->label(row, new_label);
437 updateLocal(bv, true);
441 case LFUN_MATH_MUTATE:
443 bv->lockedInsetStoreUndo(Undo::EDIT);
446 mathcursor->getPos(x, y);
448 mathcursor->setPos(x, y);
449 mathcursor->normalize();
450 updateLocal(bv, true);
454 case LFUN_MATH_EXTERN:
456 bv->lockedInsetStoreUndo(Undo::EDIT);
458 // re-compute inset dimension
460 updateLocal(bv, true);
464 case LFUN_MATH_DISPLAY:
468 mathcursor->getPos(x, y);
469 if (mat()->getType() == LM_OT_SIMPLE)
470 mat()->mutate(LM_OT_EQUATION);
472 mat()->mutate(LM_OT_SIMPLE);
473 mathcursor->setPos(x, y);
474 mathcursor->normalize();
475 updateLocal(bv, true);
479 case LFUN_PASTESELECTION:
481 string const clip = bv->getClipboard();
483 mathed_parse_normal(par_, clip);
487 case LFUN_MATH_COLUMN_INSERT:
489 if (mat()->getType() == LM_OT_ALIGN)
490 mat()->mutate(LM_OT_ALIGNAT);
491 mat()->addCol(mat()->ncols());
492 mathcursor->normalize();
493 updateLocal(bv, true);
498 result = InsetFormulaBase::localDispatch(bv, action, arg);
505 bool needEqnArray(string const & extra)
507 return extra == "dsolve";
511 void InsetFormula::handleExtern(const string & arg)
519 istringstream iss(arg.c_str());
520 iss >> lang >> extra;
524 bool selected = mathcursor->selection();
527 if (needEqnArray(extra)) {
529 mathcursor->readLine(ar);
530 mathcursor->breakLine();
531 } else if (selected) {
532 mathcursor->selGet(ar);
533 //lyxerr << "use selection: " << ar << "\n";
536 mathcursor->stripFromLastEqualSign();
537 ar = mathcursor->cursor().cell();
538 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
539 //lyxerr << "use whole cell: " << ar << "\n";
542 mathcursor->insert(pipeThroughExtern(lang, extra, ar));
546 bool InsetFormula::display() const
548 return mat()->getType() != LM_OT_SIMPLE;
552 MathHullInset const * InsetFormula::mat() const
554 lyx::Assert(par_->asHullInset());
555 return par_->asHullInset();
559 MathHullInset * InsetFormula::mat()
561 lyx::Assert(par_->asHullInset());
562 return par_->asHullInset();
566 Inset::Code InsetFormula::lyxCode() const
568 return Inset::MATH_CODE;
572 void InsetFormula::validate(LaTeXFeatures & features) const
574 par_->validate(features);
578 bool InsetFormula::insetAllowed(Inset::Code code) const
581 (code == Inset::LABEL_CODE && display())
582 || code == Inset::ERT_CODE;
586 int InsetFormula::ascent(BufferView *, LyXFont const &) const
588 return par_->ascent() + 2;
592 int InsetFormula::descent(BufferView *, LyXFont const &) const
594 return par_->descent() - 2;
598 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
601 return par_->width();
605 MathInsetTypes InsetFormula::getType() const
607 return mat()->getType();