2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
28 #include "bufferview_funcs.h"
32 #include "BufferParams.h"
33 #include "BufferView.h"
34 #include "CutAndPaste.h"
35 #include "FuncStatus.h"
37 #include "LaTeXFeatures.h"
40 #include "DispatchResult.h"
41 #include "FuncRequest.h"
44 #include "OutputParams.h"
46 #include "TextPainter.h"
49 #include "insets/RenderPreview.h"
50 #include "insets/InsetLabel.h"
52 #include "graphics/PreviewImage.h"
53 #include "graphics/PreviewLoader.h"
55 #include "frontends/Painter.h"
57 #include "support/lyxlib.h"
58 #include "support/lstrings.h"
60 #include <boost/bind.hpp>
67 using cap::grabAndEraseSelection;
68 using support::bformat;
74 using std::istringstream;
75 using std::ostringstream;
82 int getCols(HullType type)
99 // returns position of first relation operator in the array
100 // used for "intelligent splitting"
101 size_t firstRelOp(MathData const & ar)
103 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
104 if ((*it)->isRelOp())
105 return it - ar.begin();
110 char const * star(bool numbered)
112 return numbered ? "" : "*";
116 } // end anon namespace
119 HullType hullType(docstring const & s)
121 if (s == "none") return hullNone;
122 if (s == "simple") return hullSimple;
123 if (s == "equation") return hullEquation;
124 if (s == "eqnarray") return hullEqnArray;
125 if (s == "align") return hullAlign;
126 if (s == "alignat") return hullAlignAt;
127 if (s == "xalignat") return hullXAlignAt;
128 if (s == "xxalignat") return hullXXAlignAt;
129 if (s == "multline") return hullMultline;
130 if (s == "gather") return hullGather;
131 if (s == "flalign") return hullFlAlign;
132 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
137 docstring hullName(HullType type)
140 case hullNone: return from_ascii("none");
141 case hullSimple: return from_ascii("simple");
142 case hullEquation: return from_ascii("equation");
143 case hullEqnArray: return from_ascii("eqnarray");
144 case hullAlign: return from_ascii("align");
145 case hullAlignAt: return from_ascii("alignat");
146 case hullXAlignAt: return from_ascii("xalignat");
147 case hullXXAlignAt: return from_ascii("xxalignat");
148 case hullMultline: return from_ascii("multline");
149 case hullGather: return from_ascii("gather");
150 case hullFlAlign: return from_ascii("flalign");
152 lyxerr << "unknown hull type '" << type << "'" << endl;
153 return from_ascii("none");
158 InsetMathHull::InsetMathHull()
159 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
160 preview_(new RenderPreview(this))
162 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
163 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
164 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
165 //lyxerr << "sizeof Font: " << sizeof(Font) << endl;
171 InsetMathHull::InsetMathHull(HullType type)
172 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
173 preview_(new RenderPreview(this))
180 InsetMathHull::InsetMathHull(InsetMathHull const & other)
181 : InsetMathGrid(other),
182 type_(other.type_), nonum_(other.nonum_), label_(other.label_),
183 preview_(new RenderPreview(*other.preview_, this))
187 InsetMathHull::~InsetMathHull()
191 Inset * InsetMathHull::clone() const
193 return new InsetMathHull(*this);
197 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
201 *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
203 nonum_ = other.nonum_;
204 label_ = other.label_;
205 preview_.reset(new RenderPreview(*other.preview_, this));
211 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
217 return InsetMathNest::editXY(cur, x, y);
221 InsetMath::mode_type InsetMathHull::currentMode() const
223 if (type_ == hullNone)
224 return UNDECIDED_MODE;
225 // definitely math mode ...
230 bool InsetMathHull::idxFirst(Cursor & cur) const
238 bool InsetMathHull::idxLast(Cursor & cur) const
240 cur.idx() = nargs() - 1;
241 cur.pos() = cur.lastpos();
246 char InsetMathHull::defaultColAlign(col_type col)
248 if (type_ == hullEqnArray)
250 if (type_ >= hullAlign)
251 return "rl"[col & 1];
256 int InsetMathHull::defaultColSpace(col_type col)
258 if (type_ == hullAlign || type_ == hullAlignAt)
260 if (type_ == hullXAlignAt)
261 return (col & 1) ? 20 : 0;
262 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
263 return (col & 1) ? 40 : 0;
268 docstring InsetMathHull::standardFont() const
270 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
274 bool InsetMathHull::previewState(BufferView * bv) const
276 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
277 graphics::PreviewImage const * pimage =
278 preview_->getPreviewImage(bv->buffer());
279 return pimage && pimage->image();
285 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
287 if (previewState(mi.base.bv)) {
288 preview_->metrics(mi, dim);
289 // insert a one pixel gap in front of the formula
292 dim.des += displayMargin();
293 // Cache the inset dimension.
294 setDimCache(mi, dim);
298 FontSetChanger dummy1(mi.base, standardFont());
299 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
301 // let the cells adjust themselves
302 InsetMathGrid::metrics(mi, dim);
305 dim.asc += displayMargin();
306 dim.des += displayMargin();
309 if (numberedType()) {
310 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
312 for (row_type row = 0; row < nrows(); ++row)
313 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
319 // make it at least as high as the current font
322 math_font_max_dim(mi.base.font, asc, des);
323 dim.asc = max(dim.asc, asc);
324 dim.des = max(dim.des, des);
325 // Cache the inset dimension.
326 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
327 setDimCache(mi, dim);
331 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
333 use_preview_ = previewState(pi.base.bv);
334 Dimension const dim = dimension(*pi.base.bv);
336 // background of mathed under focus is not painted because
337 // selection at the top level of nested inset is difficult to handle.
338 if (!editing(pi.base.bv))
339 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
340 dim.asc + dim.des - 1, Color::mathbg);
343 // one pixel gap in front
344 preview_->draw(pi, x + 1, y);
345 setPosCache(pi, x, y);
349 FontSetChanger dummy1(pi.base, standardFont());
350 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
351 InsetMathGrid::draw(pi, x + 1, y);
353 if (numberedType()) {
354 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
355 for (row_type row = 0; row < nrows(); ++row) {
356 int const yy = y + rowinfo_[row].offset_;
357 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
358 docstring const nl = nicelabel(row);
362 setPosCache(pi, x, y);
366 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
369 InsetMathGrid::metricsT(mi, dim);
372 WriteStream wi(os, false, true);
374 dim.wid = os.str().size();
381 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
384 InsetMathGrid::drawT(pain, x, y);
387 WriteStream wi(os, false, true);
389 pain.draw(x, y, os.str().c_str());
396 docstring const latex_string(InsetMathHull const & inset)
399 WriteStream wi(ls, false, false);
407 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
409 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
410 docstring const snippet = latex_string(*this);
411 preview_->addPreview(snippet, ploader);
416 bool InsetMathHull::notifyCursorLeaves(Cursor & cur)
418 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
419 Buffer const & buffer = cur.buffer();
420 docstring const snippet = latex_string(*this);
421 preview_->addPreview(snippet, buffer);
422 preview_->startLoading(buffer);
423 cur.updateFlags(Update::Force);
429 docstring InsetMathHull::label(row_type row) const
431 BOOST_ASSERT(row < nrows());
436 void InsetMathHull::label(row_type row, docstring const & label)
438 //lyxerr << "setting label '" << label << "' for row " << row << endl;
443 void InsetMathHull::numbered(row_type row, bool num)
451 bool InsetMathHull::numbered(row_type row) const
457 bool InsetMathHull::ams() const
460 type_ == hullAlign ||
461 type_ == hullFlAlign ||
462 type_ == hullMultline ||
463 type_ == hullGather ||
464 type_ == hullAlignAt ||
465 type_ == hullXAlignAt ||
466 type_ == hullXXAlignAt;
470 Inset::DisplayType InsetMathHull::display() const
472 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
476 void InsetMathHull::getLabelList(Buffer const &, vector<docstring> & labels) const
478 for (row_type row = 0; row < nrows(); ++row)
479 if (!label_[row].empty() && nonum_[row] != 1)
480 labels.push_back(label_[row]);
484 bool InsetMathHull::numberedType() const
486 if (type_ == hullNone)
488 if (type_ == hullSimple)
490 if (type_ == hullXXAlignAt)
492 for (row_type row = 0; row < nrows(); ++row)
499 void InsetMathHull::validate(LaTeXFeatures & features) const
502 features.require("amsmath");
505 // Validation is necessary only if not using AMS math.
506 // To be safe, we will always run mathedvalidate.
507 //if (features.amsstyle)
510 features.require("boldsymbol");
511 //features.binom = true;
513 InsetMathGrid::validate(features);
517 void InsetMathHull::header_write(WriteStream & os) const
519 bool n = numberedType();
533 os << "\\begin{equation" << star(n) << "}\n";
543 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
548 os << "\\begin{" << hullName(type_) << star(n) << '}'
549 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
553 os << "\\begin{" << hullName(type_) << '}'
554 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
558 os << "\\begin{unknown" << star(n) << '}';
564 void InsetMathHull::footer_write(WriteStream & os) const
566 bool n = numberedType();
579 os << "\\end{equation" << star(n) << "}\n";
591 os << "\\end{" << hullName(type_) << star(n) << "}\n";
595 os << "\\end{" << hullName(type_) << "}\n";
599 os << "\\end{unknown" << star(n) << '}';
605 bool InsetMathHull::rowChangeOK() const
608 type_ == hullEqnArray || type_ == hullAlign ||
609 type_ == hullFlAlign || type_ == hullAlignAt ||
610 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
611 type_ == hullGather || type_ == hullMultline;
615 bool InsetMathHull::colChangeOK() const
618 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
619 type_ == hullXAlignAt || type_ == hullXXAlignAt;
623 void InsetMathHull::addRow(row_type row)
627 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
628 label_.insert(label_.begin() + row + 1, docstring());
629 InsetMathGrid::addRow(row);
633 void InsetMathHull::swapRow(row_type row)
637 if (row + 1 == nrows())
639 swap(nonum_[row], nonum_[row + 1]);
640 swap(label_[row], label_[row + 1]);
641 InsetMathGrid::swapRow(row);
645 void InsetMathHull::delRow(row_type row)
647 if (nrows() <= 1 || !rowChangeOK())
649 InsetMathGrid::delRow(row);
650 // The last dummy row has no number info nor a label.
651 // Test nrows() + 1 because we have already erased the row.
652 if (row == nrows() + 1)
654 nonum_.erase(nonum_.begin() + row);
655 label_.erase(label_.begin() + row);
659 void InsetMathHull::addCol(col_type col)
663 InsetMathGrid::addCol(col);
667 void InsetMathHull::delCol(col_type col)
669 if (ncols() <= 1 || !colChangeOK())
671 InsetMathGrid::delCol(col);
675 docstring InsetMathHull::nicelabel(row_type row) const
679 if (label_[row].empty())
680 return from_ascii("(#)");
681 return '(' + label_[row] + ')';
685 void InsetMathHull::glueall()
688 for (idx_type i = 0; i < nargs(); ++i)
690 *this = InsetMathHull(hullSimple);
696 void InsetMathHull::splitTo2Cols()
698 BOOST_ASSERT(ncols() == 1);
699 InsetMathGrid::addCol(1);
700 for (row_type row = 0; row < nrows(); ++row) {
701 idx_type const i = 2 * row;
702 pos_type pos = firstRelOp(cell(i));
703 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
704 cell(i).erase(pos, cell(i).size());
709 void InsetMathHull::splitTo3Cols()
711 BOOST_ASSERT(ncols() < 3);
714 InsetMathGrid::addCol(1);
715 for (row_type row = 0; row < nrows(); ++row) {
716 idx_type const i = 3 * row + 1;
717 if (cell(i).size()) {
718 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
719 cell(i).erase(1, cell(i).size());
725 void InsetMathHull::changeCols(col_type cols)
729 else if (ncols() < cols) {
735 while (ncols() < cols)
736 InsetMathGrid::addCol(ncols() - 1);
742 for (row_type row = 0; row < nrows(); ++row) {
743 idx_type const i = row * ncols();
744 for (col_type col = cols; col < ncols(); ++col) {
745 cell(i + cols - 1).append(cell(i + col));
749 while (ncols() > cols) {
750 InsetMathGrid::delCol(ncols() - 1);
755 HullType InsetMathHull::getType() const
761 void InsetMathHull::setType(HullType type)
768 void InsetMathHull::mutate(HullType newtype)
770 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
772 // we try to move along the chain
773 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
775 // +-------------------------------------+
776 // we use eqnarray as intermediate type for mutations that are not
777 // directly supported because it handles labels and numbering for
780 if (newtype == type_) {
784 else if (newtype < hullNone) {
789 else if (type_ == hullNone) {
795 else if (type_ == hullSimple) {
796 if (newtype == hullNone) {
800 setType(hullEquation);
806 else if (type_ == hullEquation) {
807 if (newtype < type_) {
811 } else if (newtype == hullEqnArray) {
812 // split it "nicely" on the first relop
814 setType(hullEqnArray);
815 } else if (newtype == hullMultline || newtype == hullGather) {
825 else if (type_ == hullEqnArray) {
826 if (newtype < type_) {
827 // set correct (no)numbering
828 bool allnonum = true;
829 for (row_type row = 0; row < nrows(); ++row)
833 // set first non-empty label
835 for (row_type row = 0; row < nrows(); ++row) {
836 if (!label_[row].empty()) {
843 nonum_[0] = allnonum;
846 } else { // align & Co.
853 else if (type_ == hullAlign || type_ == hullAlignAt ||
854 type_ == hullXAlignAt || type_ == hullFlAlign) {
855 if (newtype < hullAlign) {
857 setType(hullEqnArray);
859 } else if (newtype == hullGather || newtype == hullMultline) {
862 } else if (newtype == hullXXAlignAt) {
863 for (row_type row = 0; row < nrows(); ++row)
864 numbered(row, false);
871 else if (type_ == hullXXAlignAt) {
872 for (row_type row = 0; row < nrows(); ++row)
873 numbered(row, false);
874 if (newtype < hullAlign) {
876 setType(hullEqnArray);
878 } else if (newtype == hullGather || newtype == hullMultline) {
886 else if (type_ == hullMultline || type_ == hullGather) {
887 if (newtype == hullGather || newtype == hullMultline)
889 else if (newtype == hullAlign || newtype == hullFlAlign ||
890 newtype == hullAlignAt || newtype == hullXAlignAt) {
893 } else if (newtype == hullXXAlignAt) {
895 for (row_type row = 0; row < nrows(); ++row)
896 numbered(row, false);
900 setType(hullEqnArray);
906 lyxerr << "mutation from '" << to_utf8(hullName(type_))
907 << "' to '" << to_utf8(hullName(newtype))
908 << "' not implemented" << endl;
913 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
916 if (numberedType()) {
917 if (!label_[row].empty() && !nonum_[row])
918 res += "\\label{" + label_[row] + '}';
919 if (nonum_[row] && (type_ != hullMultline))
920 res += "\\nonumber ";
922 return res + InsetMathGrid::eolString(row, emptyline, fragile);
926 void InsetMathHull::write(WriteStream & os) const
929 InsetMathGrid::write(os);
934 void InsetMathHull::normalize(NormalStream & os) const
936 os << "[formula " << hullName(type_) << ' ';
937 InsetMathGrid::normalize(os);
942 void InsetMathHull::mathmlize(MathStream & os) const
944 InsetMathGrid::mathmlize(os);
948 void InsetMathHull::infoize(odocstream & os) const
950 os << "Type: " << hullName(type_);
954 void InsetMathHull::check() const
956 BOOST_ASSERT(nonum_.size() == nrows());
957 BOOST_ASSERT(label_.size() == nrows());
961 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
965 idocstringstream iss(func.argument());
966 iss >> dlang >> extra;
968 extra = from_ascii("noextra");
969 std::string const lang = to_ascii(dlang);
971 // FIXME: temporarily disabled
972 //if (cur.selection()) {
975 // lyxerr << "use selection: " << ar << endl;
976 // insert(pipeThroughExtern(lang, extra, ar));
981 eq.push_back(MathAtom(new InsetMathChar('=')));
983 // go to first item in line
984 cur.idx() -= cur.idx() % ncols();
987 if (getType() == hullSimple) {
988 size_type pos = cur.cell().find_last(eq);
990 if (cur.inMathed() && cur.selection()) {
991 asArray(grabAndEraseSelection(cur), ar);
992 } else if (pos == cur.cell().size()) {
994 lyxerr << "use whole cell: " << ar << endl;
996 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
997 lyxerr << "use partial cell form pos: " << pos << endl;
999 cur.cell().append(eq);
1000 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1001 cur.pos() = cur.lastpos();
1005 if (getType() == hullEquation) {
1006 lyxerr << "use equation inset" << endl;
1007 mutate(hullEqnArray);
1008 MathData & ar = cur.cell();
1009 lyxerr << "use cell: " << ar << endl;
1013 cur.cell() = pipeThroughExtern(lang, extra, ar);
1014 // move to end of line
1015 cur.pos() = cur.lastpos();
1020 lyxerr << "use eqnarray" << endl;
1021 cur.idx() += 2 - cur.idx() % ncols();
1023 MathData ar = cur.cell();
1024 lyxerr << "use cell: " << ar << endl;
1025 // FIXME: temporarily disabled
1031 cur.cell() = pipeThroughExtern(lang, extra, ar);
1032 cur.pos() = cur.lastpos();
1037 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1039 //lyxerr << "action: " << cmd.action << endl;
1040 switch (cmd.action) {
1042 case LFUN_FINISHED_LEFT:
1043 case LFUN_FINISHED_RIGHT:
1044 //lyxerr << "action: " << cmd.action << endl;
1045 InsetMathGrid::doDispatch(cur, cmd);
1046 notifyCursorLeaves(cur);
1050 case LFUN_BREAK_PARAGRAPH:
1051 // just swallow this
1054 case LFUN_BREAK_LINE:
1055 // some magic for the common case
1056 if (type_ == hullSimple || type_ == hullEquation) {
1057 recordUndoInset(cur);
1059 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1060 mutate(align ? hullAlign : hullEqnArray);
1062 cur.pos() = cur.lastpos();
1064 InsetMathGrid::doDispatch(cur, cmd);
1067 case LFUN_MATH_NUMBER:
1068 //lyxerr << "toggling all numbers" << endl;
1070 recordUndoInset(cur);
1071 bool old = numberedType();
1072 if (type_ == hullMultline)
1073 numbered(nrows() - 1, !old);
1075 for (row_type row = 0; row < nrows(); ++row)
1076 numbered(row, !old);
1078 cur.message(old ? _("No number") : _("Number"));
1082 case LFUN_MATH_NONUMBER:
1084 recordUndoInset(cur);
1085 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1086 bool old = numbered(r);
1087 cur.message(old ? _("No number") : _("Number"));
1092 case LFUN_LABEL_INSERT: {
1093 recordUndoInset(cur);
1094 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1095 docstring old_label = label(r);
1096 docstring const default_label = from_ascii(
1097 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1098 if (old_label.empty())
1099 old_label = default_label;
1101 InsetCommandParams p("label");
1102 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1103 std::string const data = InsetCommandMailer::params2string("label", p);
1105 if (cmd.argument().empty())
1106 cur.bv().showInsetDialog("label", data, 0);
1108 FuncRequest fr(LFUN_INSET_INSERT, data);
1114 case LFUN_INSET_INSERT: {
1115 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1116 std::string const name = cmd.getArg(0);
1117 if (name == "label") {
1118 InsetCommandParams p("label");
1119 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1120 docstring str = p["name"];
1121 recordUndoInset(cur);
1122 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1123 str = support::trim(str);
1126 docstring old = label(r);
1128 cur.bv().buffer().changeRefsIfUnique(old, str,
1134 InsetMathGrid::doDispatch(cur, cmd);
1138 case LFUN_MATH_EXTERN:
1139 recordUndoInset(cur);
1143 case LFUN_MATH_MUTATE: {
1144 recordUndoInset(cur);
1145 row_type row = cur.row();
1146 col_type col = cur.col();
1147 mutate(hullType(cmd.argument()));
1148 cur.idx() = row * ncols() + col;
1149 if (cur.idx() > cur.lastidx()) {
1150 cur.idx() = cur.lastidx();
1151 cur.pos() = cur.lastpos();
1153 if (cur.pos() > cur.lastpos())
1154 cur.pos() = cur.lastpos();
1155 //cur.dispatched(FINISHED);
1159 case LFUN_MATH_DISPLAY: {
1160 recordUndoInset(cur);
1161 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1163 cur.pos() = cur.lastpos();
1164 //cur.dispatched(FINISHED);
1169 InsetMathGrid::doDispatch(cur, cmd);
1175 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1176 FuncStatus & status) const
1178 switch (cmd.action) {
1179 case LFUN_FINISHED_LEFT:
1180 case LFUN_FINISHED_RIGHT:
1183 status.enabled(true);
1185 case LFUN_BREAK_LINE:
1186 case LFUN_MATH_NUMBER:
1187 case LFUN_MATH_NONUMBER:
1188 case LFUN_MATH_EXTERN:
1189 case LFUN_MATH_MUTATE:
1190 case LFUN_MATH_DISPLAY:
1192 status.enabled(true);
1194 case LFUN_LABEL_INSERT:
1195 status.enabled(type_ != hullSimple);
1197 case LFUN_INSET_INSERT:
1198 if (cmd.getArg(0) == "label") {
1199 status.enabled(type_ != hullSimple);
1202 return InsetMathGrid::getStatus(cur, cmd, status);
1203 case LFUN_TABULAR_FEATURE: {
1204 istringstream is(to_utf8(cmd.argument()));
1208 && (s == "append-row"
1209 || s == "delete-row"
1210 || s == "copy-row")) {
1211 status.message(bformat(
1212 from_utf8(N_("Can't change number of rows in '%1$s'")),
1214 status.enabled(false);
1218 && (s == "append-column"
1219 || s == "delete-column"
1220 || s == "copy-column")) {
1221 status.message(bformat(
1222 from_utf8(N_("Can't change number of columns in '%1$s'")),
1224 status.enabled(false);
1227 if ((type_ == hullSimple
1228 || type_ == hullEquation
1229 || type_ == hullNone) &&
1230 (s == "add-hline-above" || s == "add-hline-below")) {
1231 status.message(bformat(
1232 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1234 status.enabled(false);
1237 if (s == "add-vline-left" || s == "add-vline-right") {
1238 status.message(bformat(
1239 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1241 status.enabled(false);
1244 if (s == "valign-top" || s == "valign-middle"
1245 || s == "valign-bottom" || s == "align-left"
1246 || s == "align-center" || s == "align-right") {
1247 status.enabled(false);
1250 return InsetMathGrid::getStatus(cur, cmd, status);
1253 return InsetMathGrid::getStatus(cur, cmd, status);
1256 // This cannot really happen, but inserted to shut-up gcc
1257 return InsetMathGrid::getStatus(cur, cmd, status);
1261 /////////////////////////////////////////////////////////////////////
1265 // simply scrap this function if you want
1266 void InsetMathHull::mutateToText()
1269 // translate to latex
1271 latex(NULL, os, false, false);
1272 string str = os.str();
1275 Text * lt = view_->cursor().innerText();
1276 string::const_iterator cit = str.begin();
1277 string::const_iterator end = str.end();
1278 for (; cit != end; ++cit)
1279 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1282 //dispatch(LFUN_ESCAPE);
1287 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1288 docstring const & font)
1290 // this whole function is a hack and won't work for incremental font
1293 if (cur.inset().asInsetMath()->name() == font)
1294 cur.handleFont(to_utf8(font));
1296 cur.handleNest(createInsetMath(font));
1302 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1307 bv_funcs::string2font(to_utf8(arg), font, b);
1308 if (font.color() != Color::inherit) {
1309 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
1310 cur.handleNest(at, 0);
1315 void InsetMathHull::edit(Cursor & cur, bool left)
1318 left ? idxFirst(cur) : idxLast(cur);
1319 // The inset formula dimension is not necessarily the same as the
1320 // one of the instant preview image, so we have to indicate to the
1321 // BufferView that a metrics update is needed.
1322 cur.updateFlags(Update::Force);
1326 docstring const InsetMathHull::editMessage() const
1328 return _("Math editor mode");
1332 void InsetMathHull::revealCodes(Cursor & cur) const
1334 if (!cur.inMathed())
1336 odocstringstream os;
1338 cur.message(os.str());
1340 // write something to the minibuffer
1341 // translate to latex
1345 string str = os.str();
1347 string::size_type pos = 0;
1349 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1352 else if (*it == '\0') {
1354 pos = it - str.begin();
1360 res = res.substr(pos - 30);
1361 if (res.size() > 60)
1362 res = res.substr(0, 60);
1368 Inset::Code InsetMathHull::lyxCode() const
1374 /////////////////////////////////////////////////////////////////////
1378 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1381 // FIXME: completely broken
1382 static InsetMathHull * lastformula = 0;
1383 static CursorBase current = DocIterator(ibegin(nucleus()));
1385 static string laststr;
1387 if (lastformula != this || laststr != str) {
1388 //lyxerr << "reset lastformula to " << this << endl;
1391 current = ibegin(nucleus());
1393 mathed_parse_cell(ar, str);
1397 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1399 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1400 CursorSlice & top = it.back();
1401 MathData const & a = top.asInsetMath()->cell(top.idx_);
1402 if (a.matchpart(ar, top.pos_)) {
1403 bv->cursor().setSelection(it, ar.size());
1405 top.pos_ += ar.size();
1411 //lyxerr << "not found!" << endl;
1418 void InsetMathHull::write(Buffer const &, std::ostream & os) const
1420 odocstringstream oss;
1421 WriteStream wi(oss, false, false);
1424 os << to_utf8(oss.str());
1428 void InsetMathHull::read(Buffer const &, Lexer & lex)
1431 mathed_parse_normal(at, lex);
1432 operator=(*at->asHullInset());
1436 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1437 OutputParams const &) const
1439 if (0 && display()) {
1443 TextPainter tpain(dim.width(), dim.height());
1444 drawT(tpain, 0, dim.ascent());
1446 // reset metrics cache to "real" values
1448 return tpain.textheight();
1450 odocstringstream oss;
1451 WriteStream wi(oss, false, true);
1454 docstring const str = oss.str();
1461 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1462 OutputParams const & runparams) const
1467 if (getType() == hullSimple)
1468 name = from_ascii("inlineequation");
1470 name = from_ascii("informalequation");
1472 docstring bname = name;
1473 if (!label(0).empty())
1474 bname += " id='" + sgml::cleanID(buf, runparams, label(0)) + "'";
1477 odocstringstream ls;
1478 if (runparams.flavor == OutputParams::XML) {
1479 ms << MTag(from_ascii("alt role='tex' "));
1480 // Workaround for db2latex: db2latex always includes equations with
1481 // \ensuremath{} or \begin{display}\end{display}
1482 // so we strip LyX' math environment
1483 WriteStream wi(ls, false, false);
1484 InsetMathGrid::write(wi);
1485 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1486 ms << ETag(from_ascii("alt"));
1487 ms << MTag(from_ascii("math"));
1488 ms << ETag(from_ascii("alt"));
1489 ms << MTag(from_ascii("math"));
1490 InsetMathGrid::mathmlize(ms);
1491 ms << ETag(from_ascii("math"));
1493 ms << MTag(from_ascii("alt role='tex'"));
1494 res = latex(buf, ls, runparams);
1495 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1496 ms << ETag(from_ascii("alt"));
1499 ms << from_ascii("<graphic fileref=\"eqn/");
1500 if (!label(0).empty())
1501 ms << sgml::cleanID(buf, runparams, label(0));
1503 ms << sgml::uniqueID(from_ascii("anon"));
1505 if (runparams.flavor == OutputParams::XML)
1506 ms << from_ascii("\"/>");
1508 ms << from_ascii("\">");
1511 return ms.line() + res;
1515 void InsetMathHull::textString(Buffer const & buf, odocstream & os) const
1517 plaintext(buf, os, OutputParams(0));