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_matrixinset.h"
44 #include "mathed/support.h"
56 string captureOutput(string const & cmd, string const & data)
58 string outfile = lyx::tempName(string(), "mathextern");
59 string full = "echo '" + data + "' | (" + cmd + ") > " + outfile;
60 lyxerr << "calling: " << full << "\n";
61 Systemcalls dummy(Systemcalls::System, full, 0);
62 string out = GetFileContents(outfile);
63 lyxerr << "result: '" << out << "'\n";
68 MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
70 string header = "readlib(latex):\n";
72 // remove the \\it for variable names
73 //"#`latex/csname_font` := `\\it `:"
75 "`latex/csname_font` := ``:\n";
77 // export matrices in (...) instead of [...]
79 "`latex/latex/matrix` := "
80 "subs(`[`=`(`, `]`=`)`,"
81 "eval(`latex/latex/matrix`)):\n";
83 // replace \\cdots with proper '*'
86 "subs(`\\,`=`\\cdot `,"
87 "eval(`latex/latex/*`)):\n";
89 //"#`latex/latex/symbol` "
90 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
92 string trailer = "quit;";
96 string expr = os.str();
98 for (int i = 0; i < 100; ++i) { // at most 100 attempts
99 // try to fix missing '*' the hard way by using mint
101 // ... > echo "1A;" | mint -i 1 -S -s -q
104 // Probably missing an operator such as * p
106 lyxerr << "checking expr: '" << expr << "'\n";
107 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
109 break; // expression syntax is ok
110 istringstream is(out);
113 if (line.find("on line") != 0)
114 break; // error message not identified
116 string::size_type pos = line.find('^');
117 if (pos == string::npos || pos < 15)
118 break; // caret position not found
119 pos -= 15; // skip the "on line ..." part
120 if (expr[pos] == '*')
121 break; // two '*' in a row are definitely bad
122 expr.insert(pos, "*");
125 string full = "latex(" + extra + '(' + expr + "));";
126 string out = captureOutput("maple -q", header + full + trailer);
132 mathed_parse_cell(res, out);
137 MathArray pipeThroughOctave(string const &, MathArray const & ar)
142 string expr = os.str();
145 for (int i = 0; i < 100; ++i) { // at most 100 attempts
147 // try to fix missing '*' the hard way
149 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
152 lyxerr << "checking expr: '" << expr << "'\n";
153 out = captureOutput("octave -q 2>&1", expr);
154 lyxerr << "checking out: '" << out << "'\n";
156 // leave loop if expression syntax is probably ok
157 if (out.find("parse error:") == string::npos)
160 // search line with single caret
161 istringstream is(out);
165 lyxerr << "skipping line: '" << line << "'\n";
166 if (line.find(">>> ") != string::npos)
170 // found line with error, next line is the one with caret
172 string::size_type pos = line.find('^');
173 lyxerr << "caret line: '" << line << "'\n";
174 lyxerr << "found caret at pos: '" << pos << "'\n";
175 if (pos == string::npos || pos < 4)
176 break; // caret position not found
177 pos -= 4; // skip the ">>> " part
178 if (expr[pos] == '*')
179 break; // two '*' in a row are definitely bad
180 expr.insert(pos, "*");
189 // parse output as matrix or single number
190 MathAtom at(new MathArrayInset(out));
191 MathArrayInset const * mat = at.nucleus()->asArrayInset();
193 if (mat->ncols() == 1 && mat->nrows() == 1)
194 res.push_back(mat->cell(0));
196 res.push_back(MathAtom(new MathDelimInset("(", ")")));
197 res.back()->cell(0).push_back(at);
203 MathArray pipeThroughExtern(string const & arg, MathArray const & ar)
207 istringstream iss(arg.c_str());
208 iss >> lang >> extra;
212 if (lang == "octave")
213 return pipeThroughOctave(extra, ar);
216 return pipeThroughMaple(extra, ar);
218 // create normalized expression
220 os << "[" << extra << ' ';
223 string data = os.str().c_str();
225 // search external script
226 string file = LibFileSearch("mathed", "extern_" + lang);
228 lyxerr << "converter to '" << lang << "' not found\n";
232 // run external sript
233 string out = captureOutput(file, data);
235 mathed_parse_cell(res, out);
242 InsetFormula::InsetFormula()
243 : par_(MathAtom(new MathMatrixInset))
247 InsetFormula::InsetFormula(MathInsetTypes t)
248 : par_(MathAtom(new MathMatrixInset(t)))
252 InsetFormula::InsetFormula(string const & s)
255 bool res = mathed_parse_normal(par_, s);
258 res = mathed_parse_normal(par_, "$" + s + "$");
261 lyxerr << "cannot interpret '" << s << "' as math\n";
262 par_ = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
269 Inset * InsetFormula::clone(Buffer const &, bool) const
271 return new InsetFormula(*this);
275 void InsetFormula::write(Buffer const * buf, ostream & os) const
278 latex(buf, os, false, false);
282 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
285 MathWriteInfo wi(buf, os, fragil);
291 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
293 MathWriteInfo wi(buf, os, false);
299 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
301 return docbook(buf, os);
305 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
308 ms << "<equation><alt>";
309 int res = ascii(buf, ms.os_, 0);
310 ms << "</alt>\n<mml>" << par_.nucleus() << "<mml></equation>";
315 void InsetFormula::read(Buffer const *, LyXLex & lex)
317 mathed_parse_normal(par_, lex);
322 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
323 int y, float & xx, bool) const
328 Painter & pain = bv->painter();
331 int w = par_->width();
332 int h = par_->height();
333 int a = par_->ascent();
334 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
336 if (mathcursor && mathcursor->formula() == this) {
337 mathcursor->drawSelection(pain);
338 pain.rectangle(x, y - a, w, h, LColor::mathframe);
341 par_->draw(pain, x, y);
346 setCursorVisible(false);
350 vector<string> const InsetFormula::getLabelList() const
352 return mat()->getLabelList();
356 UpdatableInset::RESULT
357 InsetFormula::localDispatch(BufferView * bv, kb_action action,
360 RESULT result = DISPATCHED;
365 bv->lockedInsetStoreUndo(Undo::INSERT);
366 mathcursor->breakLine();
367 mathcursor->normalize();
368 updateLocal(bv, true);
371 case LFUN_MATH_NUMBER:
373 //lyxerr << "toggling all numbers\n";
375 bv->lockedInsetStoreUndo(Undo::INSERT);
376 bool old = mat()->numberedType();
377 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
378 mat()->numbered(row, !old);
379 bv->owner()->message(old ? _("No number") : _("Number"));
380 updateLocal(bv, true);
385 case LFUN_MATH_NONUMBER:
387 //lyxerr << "toggling line number\n";
389 bv->lockedInsetStoreUndo(Undo::INSERT);
390 MathCursor::row_type row = mathcursor->row();
391 bool old = mat()->numbered(row);
392 bv->owner()->message(old ? _("No number") : _("Number"));
393 mat()->numbered(row, !old);
394 updateLocal(bv, true);
399 case LFUN_INSERT_LABEL:
401 bv->lockedInsetStoreUndo(Undo::INSERT);
403 MathCursor::row_type row = mathcursor->row();
404 string old_label = mat()->label(row);
405 string new_label = arg;
407 if (new_label.empty()) {
408 string const default_label =
409 (lyxrc.label_init_length >= 0) ? "eq:" : "";
410 pair<bool, string> const res = old_label.empty()
411 ? askForText(_("Enter new label to insert:"), default_label)
412 : askForText(_("Enter label:"), old_label);
414 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
417 new_label = frontStrip(strip(res.second));
420 //if (new_label == old_label)
421 // break; // Nothing to do
423 if (!new_label.empty()) {
424 lyxerr << "setting label to '" << new_label << "'\n";
425 mat()->numbered(row, true);
428 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
431 mat()->label(row, new_label);
433 updateLocal(bv, true);
437 case LFUN_MATH_MUTATE:
439 bv->lockedInsetStoreUndo(Undo::EDIT);
442 mathcursor->getPos(x, y);
444 mathcursor->setPos(x, y);
445 mathcursor->normalize();
446 updateLocal(bv, true);
450 case LFUN_MATH_EXTERN:
452 bv->lockedInsetStoreUndo(Undo::EDIT);
454 // re-compute inset dimension
456 updateLocal(bv, true);
460 case LFUN_MATH_DISPLAY:
464 mathcursor->getPos(x, y);
465 if (mat()->getType() == LM_OT_SIMPLE)
466 mat()->mutate(LM_OT_EQUATION);
468 mat()->mutate(LM_OT_SIMPLE);
469 mathcursor->setPos(x, y);
470 mathcursor->normalize();
471 updateLocal(bv, true);
475 case LFUN_PASTESELECTION:
477 string const clip = bv->getClipboard();
479 mathed_parse_normal(par_, clip);
483 case LFUN_MATH_COLUMN_INSERT:
485 if (mat()->getType() == LM_OT_ALIGN)
486 mat()->mutate(LM_OT_ALIGNAT);
487 mat()->addCol(mat()->ncols());
488 mathcursor->normalize();
489 updateLocal(bv, true);
493 result = InsetFormulaBase::localDispatch(bv, action, arg);
500 void InsetFormula::handleExtern(const string & arg)
506 bool selected = mathcursor->selection();
510 mathcursor->selGet(ar);
511 lyxerr << "use selection: " << ar << "\n";
514 mathcursor->stripFromLastEqualSign();
515 ar = mathcursor->cursor().cell();
516 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
517 //lyxerr << "use whole cell: " << ar << "\n";
520 mathcursor->insert(pipeThroughExtern(arg, ar));
524 bool InsetFormula::display() const
526 return mat()->getType() != LM_OT_SIMPLE;
530 MathMatrixInset const * InsetFormula::mat() const
532 lyx::Assert(par_->asMatrixInset());
533 return par_->asMatrixInset();
537 MathMatrixInset * InsetFormula::mat()
539 lyx::Assert(par_->asMatrixInset());
540 return par_->asMatrixInset();
544 Inset::Code InsetFormula::lyxCode() const
546 return Inset::MATH_CODE;
550 void InsetFormula::validate(LaTeXFeatures & features) const
552 par_->validate(features);
556 bool InsetFormula::insetAllowed(Inset::Code code) const
558 return code == Inset::LABEL_CODE && display();
562 int InsetFormula::ascent(BufferView *, LyXFont const &) const
564 return par_->ascent() + 2;
568 int InsetFormula::descent(BufferView *, LyXFont const &) const
570 return par_->descent() - 2;
574 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
577 return par_->width();
581 MathInsetTypes InsetFormula::getType() const
583 return mat()->getType();