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)
72 "`latex/csname_font` := ``:\n"
73 "`latex/latex/*` := subs(`\\,`=`\\cdot `,eval(`latex/latex/*`)):\n";
74 //"#`latex/csname_font` := `\\it `:"
75 //"#`latex/latex/symbol` "
76 // " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
78 string trailer = "quit;";
79 string expr = ar.maplize();
81 for (int i = 0; i < 100; ++i) { // at most 100 attempts
82 // try to fix missing '*' the hard way by using mint
84 // ... > echo "1A;" | mint -i 1 -S -s -q
87 // Probably missing an operator such as * p
89 lyxerr << "checking expr: '" << expr << "'\n";
90 string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
92 break; // expression syntax is ok
93 istringstream is(out);
96 if (line.find("on line") != 0)
97 break; // error message not identified
99 string::size_type pos = line.find('^');
100 if (pos == string::npos || pos < 15)
101 break; // caret position not found
102 pos -= 15; // skip the "on line ..." part
103 if (expr[pos] == '*')
104 break; // two '*' in a row are definitely bad
105 expr.insert(pos, "*");
108 string full = "latex(" + extra + '(' + expr + "));";
109 string out = captureOutput("maple -q", header + full + trailer);
115 mathed_parse_cell(res, out);
120 MathArray pipeThroughOctave(string const &, MathArray const & ar)
122 string expr = ar.octavize();
125 for (int i = 0; i < 100; ++i) { // at most 100 attempts
127 // try to fix missing '*' the hard way
129 // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
132 lyxerr << "checking expr: '" << expr << "'\n";
133 out = captureOutput("octave -q 2>&1", expr);
134 lyxerr << "checking out: '" << out << "'\n";
136 // leave loop if expression syntax is probably ok
137 if (out.find("parse error:") == string::npos)
140 // search line with single caret
141 istringstream is(out);
145 lyxerr << "skipping line: '" << line << "'\n";
146 if (line.find(">>> ") != string::npos)
150 // found line with error, next line is the one with caret
152 string::size_type pos = line.find('^');
153 lyxerr << "caret line: '" << line << "'\n";
154 lyxerr << "found caret at pos: '" << pos << "'\n";
155 if (pos == string::npos || pos < 4)
156 break; // caret position not found
157 pos -= 4; // skip the ">>> " part
158 if (expr[pos] == '*')
159 break; // two '*' in a row are definitely bad
160 expr.insert(pos, "*");
169 // parse output as matrix or single number
170 MathAtom at(new MathArrayInset(out));
171 MathArrayInset const * mat = at.nucleus()->asArrayInset();
173 if (mat->ncols() == 1 && mat->nrows() == 1)
174 res.push_back(mat->cell(0));
176 res.push_back(MathAtom(new MathDelimInset("(", ")")));
177 res.back()->cell(0).push_back(at);
183 MathArray pipeThroughExtern(string const & arg, MathArray const & ar)
187 istringstream iss(arg.c_str());
188 iss >> lang >> extra;
192 if (lang == "octave")
193 return pipeThroughOctave(extra, ar);
196 return pipeThroughMaple(extra, ar);
198 // create normalized expression
200 os << "[" << extra << ' ';
203 string data = os.str().c_str();
205 // search external script
206 string file = LibFileSearch("mathed", "extern_" + lang);
208 lyxerr << "converter to '" << lang << "' not found\n";
212 // run external sript
213 string out = captureOutput(file, data);
215 mathed_parse_cell(res, out);
222 InsetFormula::InsetFormula()
223 : par_(MathAtom(new MathMatrixInset))
227 InsetFormula::InsetFormula(MathInsetTypes t)
228 : par_(MathAtom(new MathMatrixInset(t)))
232 InsetFormula::InsetFormula(string const & s)
235 bool res = mathed_parse_normal(par_, s);
238 res = mathed_parse_normal(par_, "$" + s + "$");
241 lyxerr << "cannot interpret '" << s << "' as math\n";
242 par_ = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
249 Inset * InsetFormula::clone(Buffer const &, bool) const
251 return new InsetFormula(*this);
255 void InsetFormula::write(Buffer const * buf, ostream & os) const
258 latex(buf, os, false, false);
262 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
265 MathWriteInfo wi(buf, os, fragil);
271 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
273 MathWriteInfo wi(buf, os, false);
279 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
281 return ascii(buf, os, 0);
285 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
287 return ascii(buf, os, 0);
291 void InsetFormula::read(Buffer const *, LyXLex & lex)
293 mathed_parse_normal(par_, lex);
298 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
299 int y, float & xx, bool) const
304 Painter & pain = bv->painter();
307 int w = par_->width();
308 int h = par_->height();
309 int a = par_->ascent();
310 pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
312 if (mathcursor && mathcursor->formula() == this) {
313 mathcursor->drawSelection(pain);
314 pain.rectangle(x, y - a, w, h, LColor::mathframe);
317 par_->draw(pain, x, y);
322 setCursorVisible(false);
326 vector<string> const InsetFormula::getLabelList() const
328 return mat()->getLabelList();
332 UpdatableInset::RESULT
333 InsetFormula::localDispatch(BufferView * bv, kb_action action,
336 RESULT result = DISPATCHED;
341 bv->lockedInsetStoreUndo(Undo::INSERT);
342 mathcursor->breakLine();
343 mathcursor->normalize();
344 updateLocal(bv, true);
347 case LFUN_MATH_NUMBER:
349 //lyxerr << "toggling all numbers\n";
351 bv->lockedInsetStoreUndo(Undo::INSERT);
352 bool old = mat()->numberedType();
353 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
354 mat()->numbered(row, !old);
355 bv->owner()->message(old ? _("No number") : _("Number"));
356 updateLocal(bv, true);
361 case LFUN_MATH_NONUMBER:
363 //lyxerr << "toggling line number\n";
365 bv->lockedInsetStoreUndo(Undo::INSERT);
366 MathCursor::row_type row = mathcursor->row();
367 bool old = mat()->numbered(row);
368 bv->owner()->message(old ? _("No number") : _("Number"));
369 mat()->numbered(row, !old);
370 updateLocal(bv, true);
375 case LFUN_INSERT_LABEL:
377 bv->lockedInsetStoreUndo(Undo::INSERT);
379 MathCursor::row_type row = mathcursor->row();
380 string old_label = mat()->label(row);
381 string new_label = arg;
383 if (new_label.empty()) {
384 string const default_label =
385 (lyxrc.label_init_length >= 0) ? "eq:" : "";
386 pair<bool, string> const res = old_label.empty()
387 ? askForText(_("Enter new label to insert:"), default_label)
388 : askForText(_("Enter label:"), old_label);
390 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
393 new_label = frontStrip(strip(res.second));
396 //if (new_label == old_label)
397 // break; // Nothing to do
399 if (!new_label.empty()) {
400 lyxerr << "setting label to '" << new_label << "'\n";
401 mat()->numbered(row, true);
404 if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
407 mat()->label(row, new_label);
409 updateLocal(bv, true);
413 case LFUN_MATH_MUTATE:
415 bv->lockedInsetStoreUndo(Undo::EDIT);
418 mathcursor->getPos(x, y);
420 mathcursor->setPos(x, y);
421 mathcursor->normalize();
422 updateLocal(bv, true);
426 case LFUN_MATH_EXTERN:
428 bv->lockedInsetStoreUndo(Undo::EDIT);
430 // re-compute inset dimension
432 updateLocal(bv, true);
436 case LFUN_MATH_DISPLAY:
440 mathcursor->getPos(x, y);
441 if (mat()->getType() == LM_OT_SIMPLE)
442 mat()->mutate(LM_OT_EQUATION);
444 mat()->mutate(LM_OT_SIMPLE);
445 mathcursor->setPos(x, y);
446 mathcursor->normalize();
447 updateLocal(bv, true);
451 case LFUN_PASTESELECTION:
453 string const clip = bv->getClipboard();
455 mathed_parse_normal(par_, clip);
459 case LFUN_MATH_COLUMN_INSERT:
461 if (mat()->getType() == LM_OT_ALIGN)
462 mat()->mutate(LM_OT_ALIGNAT);
463 mat()->addCol(mat()->ncols());
464 mathcursor->normalize();
465 updateLocal(bv, true);
469 result = InsetFormulaBase::localDispatch(bv, action, arg);
476 void InsetFormula::handleExtern(const string & arg)
482 bool selected = mathcursor->selection();
486 mathcursor->selGet(ar);
487 lyxerr << "use selection: " << ar << "\n";
490 mathcursor->stripFromLastEqualSign();
491 ar = mathcursor->cursor().cell();
492 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
493 //lyxerr << "use whole cell: " << ar << "\n";
496 mathcursor->insert(pipeThroughExtern(arg, ar));
500 bool InsetFormula::display() const
502 return mat()->getType() != LM_OT_SIMPLE;
506 MathMatrixInset const * InsetFormula::mat() const
508 lyx::Assert(par_->asMatrixInset());
509 return par_->asMatrixInset();
513 MathMatrixInset * InsetFormula::mat()
515 lyx::Assert(par_->asMatrixInset());
516 return par_->asMatrixInset();
520 Inset::Code InsetFormula::lyxCode() const
522 return Inset::MATH_CODE;
526 void InsetFormula::validate(LaTeXFeatures & features) const
528 par_->validate(features);
532 bool InsetFormula::insetAllowed(Inset::Code code) const
534 return code == Inset::LABEL_CODE && display();
538 int InsetFormula::ascent(BufferView *, LyXFont const &) const
540 return par_->ascent() + 2;
544 int InsetFormula::descent(BufferView *, LyXFont const &) const
546 return par_->descent() - 2;
550 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
553 return par_->width();
557 MathInsetTypes InsetFormula::getType() const
559 return mat()->getType();