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] == '*')
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 & arg, MathArray const & ar)
214 istringstream iss(arg.c_str());
215 iss >> lang >> extra;
219 if (lang == "octave")
220 return pipeThroughOctave(extra, ar);
223 return pipeThroughMaple(extra, ar);
225 // create normalized expression
228 os << "[" << extra << ' ';
231 string data = os.str().c_str();
233 // search external script
234 string file = LibFileSearch("mathed", "extern_" + lang);
236 lyxerr << "converter to '" << lang << "' not found\n";
240 // run external sript
241 string out = captureOutput(file, data);
243 mathed_parse_cell(res, out);
250 InsetFormula::InsetFormula()
251 : par_(MathAtom(new MathHullInset))
255 InsetFormula::InsetFormula(MathInsetTypes t)
256 : par_(MathAtom(new MathHullInset(t)))
260 InsetFormula::InsetFormula(string const & s)
263 bool res = mathed_parse_normal(par_, s);
266 res = mathed_parse_normal(par_, "$" + s + "$");
269 lyxerr << "cannot interpret '" << s << "' as math\n";
270 par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
277 Inset * InsetFormula::clone(Buffer const &, bool) const
279 return new InsetFormula(*this);
283 void InsetFormula::write(Buffer const * buf, ostream & os) const
286 latex(buf, os, false, false);
290 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
293 WriteStream wi(buf, os, fragil);
299 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
301 WriteStream wi(buf, os, false);
307 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
309 return docbook(buf, os);
313 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
316 ms << MTag("equation") << MTag("alt");
317 int res = ascii(buf, ms.os_, 0);
318 ms << ETag("alt") << MTag("math");
319 ms << par_.nucleus();
320 ms << ETag("math") << ETag("equation");
321 return ms.line_ + res;
325 void InsetFormula::read(Buffer const *, LyXLex & lex)
327 mathed_parse_normal(par_, lex);
332 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
333 int y, float & xx, bool) const
338 Painter & pain = bv->painter();
341 int w = par_->width();
342 int h = par_->height();
343 int a = par_->ascent();
344 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
346 if (mathcursor && mathcursor->formula() == this) {
347 mathcursor->drawSelection(pain);
348 pain.rectangle(x, y - a, w, h, LColor::mathframe);
351 par_->draw(pain, x, y);
356 setCursorVisible(false);
360 vector<string> const InsetFormula::getLabelList() const
362 return mat()->getLabelList();
366 UpdatableInset::RESULT
367 InsetFormula::localDispatch(BufferView * bv, kb_action action,
370 RESULT result = DISPATCHED;
375 bv->lockedInsetStoreUndo(Undo::INSERT);
376 mathcursor->breakLine();
377 mathcursor->normalize();
378 updateLocal(bv, true);
381 case LFUN_MATH_NUMBER:
383 //lyxerr << "toggling all numbers\n";
385 bv->lockedInsetStoreUndo(Undo::INSERT);
386 bool old = mat()->numberedType();
387 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
388 mat()->numbered(row, !old);
389 bv->owner()->message(old ? _("No number") : _("Number"));
390 updateLocal(bv, true);
395 case LFUN_MATH_NONUMBER:
397 //lyxerr << "toggling line number\n";
399 bv->lockedInsetStoreUndo(Undo::INSERT);
400 MathCursor::row_type row = mathcursor->row();
401 bool old = mat()->numbered(row);
402 bv->owner()->message(old ? _("No number") : _("Number"));
403 mat()->numbered(row, !old);
404 updateLocal(bv, true);
409 case LFUN_INSERT_LABEL:
411 bv->lockedInsetStoreUndo(Undo::INSERT);
413 MathCursor::row_type row = mathcursor->row();
414 string old_label = mat()->label(row);
415 string new_label = arg;
417 if (new_label.empty()) {
418 string const default_label =
419 (lyxrc.label_init_length >= 0) ? "eq:" : "";
420 pair<bool, string> const res = old_label.empty()
421 ? askForText(_("Enter new label to insert:"), default_label)
422 : askForText(_("Enter label:"), old_label);
424 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
427 new_label = frontStrip(strip(res.second));
430 //if (new_label == old_label)
431 // break; // Nothing to do
433 if (!new_label.empty()) {
434 lyxerr << "setting label to '" << new_label << "'\n";
435 mat()->numbered(row, true);
438 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
441 mat()->label(row, new_label);
443 updateLocal(bv, true);
447 case LFUN_MATH_MUTATE:
449 bv->lockedInsetStoreUndo(Undo::EDIT);
452 mathcursor->getPos(x, y);
454 mathcursor->setPos(x, y);
455 mathcursor->normalize();
456 updateLocal(bv, true);
460 case LFUN_MATH_EXTERN:
462 bv->lockedInsetStoreUndo(Undo::EDIT);
464 // re-compute inset dimension
466 updateLocal(bv, true);
470 case LFUN_MATH_DISPLAY:
474 mathcursor->getPos(x, y);
475 if (mat()->getType() == LM_OT_SIMPLE)
476 mat()->mutate(LM_OT_EQUATION);
478 mat()->mutate(LM_OT_SIMPLE);
479 mathcursor->setPos(x, y);
480 mathcursor->normalize();
481 updateLocal(bv, true);
485 case LFUN_PASTESELECTION:
487 string const clip = bv->getClipboard();
489 mathed_parse_normal(par_, clip);
493 case LFUN_MATH_COLUMN_INSERT:
495 if (mat()->getType() == LM_OT_ALIGN)
496 mat()->mutate(LM_OT_ALIGNAT);
497 mat()->addCol(mat()->ncols());
498 mathcursor->normalize();
499 updateLocal(bv, true);
503 result = InsetFormulaBase::localDispatch(bv, action, arg);
510 void InsetFormula::handleExtern(const string & arg)
516 bool selected = mathcursor->selection();
520 mathcursor->selGet(ar);
521 //lyxerr << "use selection: " << ar << "\n";
524 mathcursor->stripFromLastEqualSign();
525 ar = mathcursor->cursor().cell();
526 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
527 //lyxerr << "use whole cell: " << ar << "\n";
530 mathcursor->insert(pipeThroughExtern(arg, ar));
534 bool InsetFormula::display() const
536 return mat()->getType() != LM_OT_SIMPLE;
540 MathHullInset const * InsetFormula::mat() const
542 lyx::Assert(par_->asHullInset());
543 return par_->asHullInset();
547 MathHullInset * InsetFormula::mat()
549 lyx::Assert(par_->asHullInset());
550 return par_->asHullInset();
554 Inset::Code InsetFormula::lyxCode() const
556 return Inset::MATH_CODE;
560 void InsetFormula::validate(LaTeXFeatures & features) const
562 par_->validate(features);
566 bool InsetFormula::insetAllowed(Inset::Code code) const
568 return code == Inset::LABEL_CODE && display();
572 int InsetFormula::ascent(BufferView *, LyXFont const &) const
574 return par_->ascent() + 2;
578 int InsetFormula::descent(BufferView *, LyXFont const &) const
580 return par_->descent() - 2;
584 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
587 return par_->width();
591 MathInsetTypes InsetFormula::getType() const
593 return mat()->getType();