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"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CutAndPaste.h"
32 #include "FuncStatus.h"
33 #include "LaTeXFeatures.h"
35 #include "DispatchResult.h"
36 #include "FuncRequest.h"
38 #include "OutputParams.h"
39 #include "ParIterator.h"
42 #include "TextPainter.h"
43 #include "TocBackend.h"
45 #include "insets/RenderPreview.h"
46 #include "insets/InsetLabel.h"
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
51 #include "frontends/Painter.h"
53 #include "support/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
60 using namespace lyx::support;
64 using cap::grabAndEraseSelection;
68 int getCols(HullType type)
85 // returns position of first relation operator in the array
86 // used for "intelligent splitting"
87 size_t firstRelOp(MathData const & ar)
89 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
91 return it - ar.begin();
96 char const * star(bool numbered)
98 return numbered ? "" : "*";
102 } // end anon namespace
105 HullType hullType(docstring const & s)
107 if (s == "none") return hullNone;
108 if (s == "simple") return hullSimple;
109 if (s == "equation") return hullEquation;
110 if (s == "eqnarray") return hullEqnArray;
111 if (s == "align") return hullAlign;
112 if (s == "alignat") return hullAlignAt;
113 if (s == "xalignat") return hullXAlignAt;
114 if (s == "xxalignat") return hullXXAlignAt;
115 if (s == "multline") return hullMultline;
116 if (s == "gather") return hullGather;
117 if (s == "flalign") return hullFlAlign;
118 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
123 docstring hullName(HullType type)
126 case hullNone: return from_ascii("none");
127 case hullSimple: return from_ascii("simple");
128 case hullEquation: return from_ascii("equation");
129 case hullEqnArray: return from_ascii("eqnarray");
130 case hullAlign: return from_ascii("align");
131 case hullAlignAt: return from_ascii("alignat");
132 case hullXAlignAt: return from_ascii("xalignat");
133 case hullXXAlignAt: return from_ascii("xxalignat");
134 case hullMultline: return from_ascii("multline");
135 case hullGather: return from_ascii("gather");
136 case hullFlAlign: return from_ascii("flalign");
138 lyxerr << "unknown hull type '" << type << "'" << endl;
139 return from_ascii("none");
144 InsetMathHull::InsetMathHull()
145 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
146 preview_(new RenderPreview(this))
148 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
149 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
150 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
151 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
157 InsetMathHull::InsetMathHull(HullType type)
158 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
159 preview_(new RenderPreview(this))
166 InsetMathHull::InsetMathHull(InsetMathHull const & other)
167 : InsetMathGrid(other),
168 type_(other.type_), nonum_(other.nonum_), label_(other.label_),
169 preview_(new RenderPreview(*other.preview_, this))
173 InsetMathHull::~InsetMathHull()
177 Inset * InsetMathHull::clone() const
179 return new InsetMathHull(*this);
183 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
187 *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
189 nonum_ = other.nonum_;
190 label_ = other.label_;
191 preview_.reset(new RenderPreview(*other.preview_, this));
197 void InsetMathHull::addToToc(Buffer const & buf,
198 ParConstIterator const & pit) const
200 vector<docstring> labels;
201 getLabelList(buf, labels);
205 Toc & toc = buf.tocBackend().toc("equation");
206 toc.push_back(TocItem(pit, 0, labels[0]));
210 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
216 return InsetMathNest::editXY(cur, x, y);
220 InsetMath::mode_type InsetMathHull::currentMode() const
222 if (type_ == hullNone)
223 return UNDECIDED_MODE;
224 // definitely math mode ...
229 bool InsetMathHull::idxFirst(Cursor & cur) const
237 bool InsetMathHull::idxLast(Cursor & cur) const
239 cur.idx() = nargs() - 1;
240 cur.pos() = cur.lastpos();
245 char InsetMathHull::defaultColAlign(col_type col)
247 if (type_ == hullEqnArray)
249 if (type_ == hullGather)
251 if (type_ >= hullAlign)
252 return "rl"[col & 1];
257 int InsetMathHull::defaultColSpace(col_type col)
259 if (type_ == hullAlign || type_ == hullAlignAt)
261 if (type_ == hullXAlignAt)
262 return (col & 1) ? 20 : 0;
263 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
264 return (col & 1) ? 40 : 0;
269 docstring InsetMathHull::standardFont() const
271 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
275 bool InsetMathHull::previewState(BufferView * bv) const
277 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
278 graphics::PreviewImage const * pimage =
279 preview_->getPreviewImage(bv->buffer());
280 return pimage && pimage->image();
286 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
288 if (previewState(mi.base.bv)) {
289 preview_->metrics(mi, dim);
290 // insert a one pixel gap in front of the formula
293 dim.des += displayMargin();
294 // Cache the inset dimension.
295 setDimCache(mi, dim);
299 FontSetChanger dummy1(mi.base, standardFont());
300 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
302 // let the cells adjust themselves
303 InsetMathGrid::metrics(mi, dim);
306 dim.asc += displayMargin();
307 dim.des += displayMargin();
310 if (numberedType()) {
311 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
313 for (row_type row = 0; row < nrows(); ++row)
314 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
320 // make it at least as high as the current font
323 math_font_max_dim(mi.base.font, asc, des);
324 dim.asc = max(dim.asc, asc);
325 dim.des = max(dim.des, des);
326 // Cache the inset dimension.
327 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
328 setDimCache(mi, dim);
332 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
334 use_preview_ = previewState(pi.base.bv);
335 Dimension const dim = dimension(*pi.base.bv);
337 // background of mathed under focus is not painted because
338 // selection at the top level of nested inset is difficult to handle.
339 if (!editing(pi.base.bv))
340 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
341 dim.asc + dim.des - 1, Color_mathbg);
344 // one pixel gap in front
345 preview_->draw(pi, x + 1, y);
346 setPosCache(pi, x, y);
350 FontSetChanger dummy1(pi.base, standardFont());
351 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
352 InsetMathGrid::draw(pi, x + 1, y);
354 if (numberedType()) {
355 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
356 for (row_type row = 0; row < nrows(); ++row) {
357 int const yy = y + rowinfo_[row].offset_;
358 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
359 docstring const nl = nicelabel(row);
363 setPosCache(pi, x, y);
367 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
370 InsetMathGrid::metricsT(mi, dim);
373 WriteStream wi(os, false, true);
375 dim.wid = os.str().size();
382 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
385 InsetMathGrid::drawT(pain, x, y);
388 WriteStream wi(os, false, true);
390 pain.draw(x, y, os.str().c_str());
397 docstring const latex_string(InsetMathHull const & inset)
400 WriteStream wi(ls, false, false);
408 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
410 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
411 docstring const snippet = latex_string(*this);
412 preview_->addPreview(snippet, ploader);
417 bool InsetMathHull::notifyCursorLeaves(Cursor & cur)
419 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
420 Buffer const & buffer = cur.buffer();
421 docstring const snippet = latex_string(*this);
422 preview_->addPreview(snippet, buffer);
423 preview_->startLoading(buffer);
424 cur.updateFlags(Update::Force);
430 docstring InsetMathHull::label(row_type row) const
432 BOOST_ASSERT(row < nrows());
437 void InsetMathHull::label(row_type row, docstring const & label)
439 //lyxerr << "setting label '" << label << "' for row " << row << endl;
444 void InsetMathHull::numbered(row_type row, bool num)
452 bool InsetMathHull::numbered(row_type row) const
458 bool InsetMathHull::ams() const
461 type_ == hullAlign ||
462 type_ == hullFlAlign ||
463 type_ == hullMultline ||
464 type_ == hullGather ||
465 type_ == hullAlignAt ||
466 type_ == hullXAlignAt ||
467 type_ == hullXXAlignAt;
471 Inset::DisplayType InsetMathHull::display() const
473 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
477 void InsetMathHull::getLabelList(Buffer const &, vector<docstring> & labels) const
479 for (row_type row = 0; row < nrows(); ++row)
480 if (!label_[row].empty() && nonum_[row] != 1)
481 labels.push_back(label_[row]);
485 bool InsetMathHull::numberedType() const
487 if (type_ == hullNone)
489 if (type_ == hullSimple)
491 if (type_ == hullXXAlignAt)
493 for (row_type row = 0; row < nrows(); ++row)
500 void InsetMathHull::validate(LaTeXFeatures & features) const
503 features.require("amsmath");
506 // Validation is necessary only if not using AMS math.
507 // To be safe, we will always run mathedvalidate.
508 //if (features.amsstyle)
511 features.require("boldsymbol");
512 //features.binom = true;
514 InsetMathGrid::validate(features);
518 void InsetMathHull::header_write(WriteStream & os) const
520 bool n = numberedType();
534 os << "\\begin{equation" << star(n) << "}\n";
544 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
549 os << "\\begin{" << hullName(type_) << star(n) << '}'
550 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
554 os << "\\begin{" << hullName(type_) << '}'
555 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
559 os << "\\begin{unknown" << star(n) << '}';
565 void InsetMathHull::footer_write(WriteStream & os) const
567 bool n = numberedType();
580 os << "\\end{equation" << star(n) << "}\n";
592 os << "\\end{" << hullName(type_) << star(n) << "}\n";
596 os << "\\end{" << hullName(type_) << "}\n";
600 os << "\\end{unknown" << star(n) << '}';
606 bool InsetMathHull::rowChangeOK() const
609 type_ == hullEqnArray || type_ == hullAlign ||
610 type_ == hullFlAlign || type_ == hullAlignAt ||
611 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
612 type_ == hullGather || type_ == hullMultline;
616 bool InsetMathHull::colChangeOK() const
619 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
620 type_ == hullXAlignAt || type_ == hullXXAlignAt;
624 void InsetMathHull::addRow(row_type row)
628 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
629 label_.insert(label_.begin() + row + 1, docstring());
630 InsetMathGrid::addRow(row);
634 void InsetMathHull::swapRow(row_type row)
638 if (row + 1 == nrows())
640 swap(nonum_[row], nonum_[row + 1]);
641 swap(label_[row], label_[row + 1]);
642 InsetMathGrid::swapRow(row);
646 void InsetMathHull::delRow(row_type row)
648 if (nrows() <= 1 || !rowChangeOK())
650 InsetMathGrid::delRow(row);
651 // The last dummy row has no number info nor a label.
652 // Test nrows() + 1 because we have already erased the row.
653 if (row == nrows() + 1)
655 nonum_.erase(nonum_.begin() + row);
656 label_.erase(label_.begin() + row);
660 void InsetMathHull::addCol(col_type col)
664 InsetMathGrid::addCol(col);
668 void InsetMathHull::delCol(col_type col)
670 if (ncols() <= 1 || !colChangeOK())
672 InsetMathGrid::delCol(col);
676 docstring InsetMathHull::nicelabel(row_type row) const
680 if (label_[row].empty())
681 return from_ascii("(#)");
682 return '(' + label_[row] + ')';
686 void InsetMathHull::glueall()
689 for (idx_type i = 0; i < nargs(); ++i)
691 *this = InsetMathHull(hullSimple);
697 void InsetMathHull::splitTo2Cols()
699 BOOST_ASSERT(ncols() == 1);
700 InsetMathGrid::addCol(1);
701 for (row_type row = 0; row < nrows(); ++row) {
702 idx_type const i = 2 * row;
703 pos_type pos = firstRelOp(cell(i));
704 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
705 cell(i).erase(pos, cell(i).size());
710 void InsetMathHull::splitTo3Cols()
712 BOOST_ASSERT(ncols() < 3);
715 InsetMathGrid::addCol(2);
716 for (row_type row = 0; row < nrows(); ++row) {
717 idx_type const i = 3 * row + 1;
718 if (cell(i).size()) {
719 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
720 cell(i).erase(1, cell(i).size());
726 void InsetMathHull::changeCols(col_type cols)
730 else if (ncols() < cols) {
736 while (ncols() < cols)
737 InsetMathGrid::addCol(ncols());
743 for (row_type row = 0; row < nrows(); ++row) {
744 idx_type const i = row * ncols();
745 for (col_type col = cols; col < ncols(); ++col) {
746 cell(i + cols - 1).append(cell(i + col));
750 while (ncols() > cols) {
751 InsetMathGrid::delCol(ncols() - 1);
756 HullType InsetMathHull::getType() const
762 void InsetMathHull::setType(HullType type)
769 void InsetMathHull::mutate(HullType newtype)
771 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
773 // we try to move along the chain
774 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
776 // +-------------------------------------+
777 // we use eqnarray as intermediate type for mutations that are not
778 // directly supported because it handles labels and numbering for
781 if (newtype == type_) {
785 else if (newtype < hullNone) {
790 else if (type_ == hullNone) {
796 else if (type_ == hullSimple) {
797 if (newtype == hullNone) {
801 setType(hullEquation);
807 else if (type_ == hullEquation) {
808 if (newtype < type_) {
812 } else if (newtype == hullEqnArray) {
813 // split it "nicely" on the first relop
815 setType(hullEqnArray);
816 } else if (newtype == hullMultline || newtype == hullGather) {
826 else if (type_ == hullEqnArray) {
827 if (newtype < type_) {
828 // set correct (no)numbering
829 bool allnonum = true;
830 for (row_type row = 0; row < nrows(); ++row)
834 // set first non-empty label
836 for (row_type row = 0; row < nrows(); ++row) {
837 if (!label_[row].empty()) {
844 nonum_[0] = allnonum;
847 } else { // align & Co.
854 else if (type_ == hullAlign || type_ == hullAlignAt ||
855 type_ == hullXAlignAt || type_ == hullFlAlign) {
856 if (newtype < hullAlign) {
858 setType(hullEqnArray);
860 } else if (newtype == hullGather || newtype == hullMultline) {
863 } else if (newtype == hullXXAlignAt) {
864 for (row_type row = 0; row < nrows(); ++row)
865 numbered(row, false);
872 else if (type_ == hullXXAlignAt) {
873 for (row_type row = 0; row < nrows(); ++row)
874 numbered(row, false);
875 if (newtype < hullAlign) {
877 setType(hullEqnArray);
879 } else if (newtype == hullGather || newtype == hullMultline) {
887 else if (type_ == hullMultline || type_ == hullGather) {
888 if (newtype == hullGather || newtype == hullMultline)
890 else if (newtype == hullAlign || newtype == hullFlAlign ||
891 newtype == hullAlignAt || newtype == hullXAlignAt) {
894 } else if (newtype == hullXXAlignAt) {
896 for (row_type row = 0; row < nrows(); ++row)
897 numbered(row, false);
901 setType(hullEqnArray);
907 lyxerr << "mutation from '" << to_utf8(hullName(type_))
908 << "' to '" << to_utf8(hullName(newtype))
909 << "' not implemented" << endl;
914 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
917 if (numberedType()) {
918 if (!label_[row].empty() && !nonum_[row])
919 res += "\\label{" + label_[row] + '}';
920 if (nonum_[row] && (type_ != hullMultline))
921 res += "\\nonumber ";
923 return res + InsetMathGrid::eolString(row, emptyline, fragile);
927 void InsetMathHull::write(WriteStream & os) const
930 InsetMathGrid::write(os);
935 void InsetMathHull::normalize(NormalStream & os) const
937 os << "[formula " << hullName(type_) << ' ';
938 InsetMathGrid::normalize(os);
943 void InsetMathHull::mathmlize(MathStream & os) const
945 InsetMathGrid::mathmlize(os);
949 void InsetMathHull::infoize(odocstream & os) const
951 os << "Type: " << hullName(type_);
955 void InsetMathHull::check() const
957 BOOST_ASSERT(nonum_.size() == nrows());
958 BOOST_ASSERT(label_.size() == nrows());
962 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
966 idocstringstream iss(func.argument());
967 iss >> dlang >> extra;
969 extra = from_ascii("noextra");
970 string const lang = to_ascii(dlang);
972 // FIXME: temporarily disabled
973 //if (cur.selection()) {
976 // lyxerr << "use selection: " << ar << endl;
977 // insert(pipeThroughExtern(lang, extra, ar));
982 eq.push_back(MathAtom(new InsetMathChar('=')));
984 // go to first item in line
985 cur.idx() -= cur.idx() % ncols();
988 if (getType() == hullSimple) {
989 size_type pos = cur.cell().find_last(eq);
991 if (cur.inMathed() && cur.selection()) {
992 asArray(grabAndEraseSelection(cur), ar);
993 } else if (pos == cur.cell().size()) {
995 lyxerr << "use whole cell: " << ar << endl;
997 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
998 lyxerr << "use partial cell form pos: " << pos << endl;
1000 cur.cell().append(eq);
1001 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1002 cur.pos() = cur.lastpos();
1006 if (getType() == hullEquation) {
1007 lyxerr << "use equation inset" << endl;
1008 mutate(hullEqnArray);
1009 MathData & ar = cur.cell();
1010 lyxerr << "use cell: " << ar << endl;
1014 cur.cell() = pipeThroughExtern(lang, extra, ar);
1015 // move to end of line
1016 cur.pos() = cur.lastpos();
1021 lyxerr << "use eqnarray" << endl;
1022 cur.idx() += 2 - cur.idx() % ncols();
1024 MathData ar = cur.cell();
1025 lyxerr << "use cell: " << ar << endl;
1026 // FIXME: temporarily disabled
1032 cur.cell() = pipeThroughExtern(lang, extra, ar);
1033 cur.pos() = cur.lastpos();
1038 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1040 //lyxerr << "action: " << cmd.action << endl;
1041 switch (cmd.action) {
1043 case LFUN_FINISHED_BACKWARD:
1044 case LFUN_FINISHED_FORWARD:
1045 case LFUN_FINISHED_RIGHT:
1046 case LFUN_FINISHED_LEFT:
1047 //lyxerr << "action: " << cmd.action << endl;
1048 InsetMathGrid::doDispatch(cur, cmd);
1049 notifyCursorLeaves(cur);
1053 case LFUN_BREAK_PARAGRAPH:
1054 // just swallow this
1058 // some magic for the common case
1059 if (type_ == hullSimple || type_ == hullEquation) {
1060 cur.recordUndoInset();
1062 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1063 mutate(align ? hullAlign : hullEqnArray);
1064 cur.idx() = nrows() * ncols() - 1;
1065 cur.pos() = cur.lastpos();
1067 InsetMathGrid::doDispatch(cur, cmd);
1070 case LFUN_MATH_NUMBER_TOGGLE: {
1071 //lyxerr << "toggling all numbers" << endl;
1072 cur.recordUndoInset();
1073 bool old = numberedType();
1074 if (type_ == hullMultline)
1075 numbered(nrows() - 1, !old);
1077 for (row_type row = 0; row < nrows(); ++row)
1078 numbered(row, !old);
1080 cur.message(old ? _("No number") : _("Number"));
1084 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1085 cur.recordUndoInset();
1086 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1087 bool old = numbered(r);
1088 cur.message(old ? _("No number") : _("Number"));
1093 case LFUN_LABEL_INSERT: {
1094 cur.recordUndoInset();
1095 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1096 docstring old_label = label(r);
1097 docstring const default_label = from_ascii(
1098 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1099 if (old_label.empty())
1100 old_label = default_label;
1102 InsetCommandParams p(LABEL_CODE);
1103 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1104 string const data = InsetCommandMailer::params2string("label", p);
1106 if (cmd.argument().empty())
1107 cur.bv().showDialog("label", data);
1109 FuncRequest fr(LFUN_INSET_INSERT, data);
1115 case LFUN_INSET_INSERT: {
1116 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1117 string const name = cmd.getArg(0);
1118 if (name == "label") {
1119 InsetCommandParams p(LABEL_CODE);
1120 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1121 docstring str = p["name"];
1122 cur.recordUndoInset();
1123 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1127 docstring old = label(r);
1129 cur.bv().buffer().changeRefsIfUnique(old, str,
1135 InsetMathGrid::doDispatch(cur, cmd);
1139 case LFUN_MATH_EXTERN:
1140 cur.recordUndoInset();
1144 case LFUN_MATH_MUTATE: {
1145 cur.recordUndoInset();
1146 row_type row = cur.row();
1147 col_type col = cur.col();
1148 mutate(hullType(cmd.argument()));
1149 cur.idx() = row * ncols() + col;
1150 if (cur.idx() > cur.lastidx()) {
1151 cur.idx() = cur.lastidx();
1152 cur.pos() = cur.lastpos();
1154 if (cur.pos() > cur.lastpos())
1155 cur.pos() = cur.lastpos();
1157 // FIXME: find some more clever handling of the selection,
1158 // i.e. preserve it.
1159 cur.clearSelection();
1160 //cur.dispatched(FINISHED);
1164 case LFUN_MATH_DISPLAY: {
1165 cur.recordUndoInset();
1166 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1168 cur.pos() = cur.lastpos();
1169 //cur.dispatched(FINISHED);
1174 InsetMathGrid::doDispatch(cur, cmd);
1180 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1181 FuncStatus & status) const
1183 switch (cmd.action) {
1184 case LFUN_FINISHED_BACKWARD:
1185 case LFUN_FINISHED_FORWARD:
1186 case LFUN_FINISHED_RIGHT:
1187 case LFUN_FINISHED_LEFT:
1191 case LFUN_MATH_EXTERN:
1192 case LFUN_MATH_MUTATE:
1193 case LFUN_MATH_DISPLAY:
1195 status.enabled(true);
1197 case LFUN_MATH_NUMBER_TOGGLE:
1198 // FIXME: what is the right test, this or the one of
1200 status.enabled(display());
1201 status.setOnOff(numberedType());
1203 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1204 // FIXME: what is the right test, this or the one of
1206 status.enabled(display());
1207 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1208 status.setOnOff(numbered(r));
1211 case LFUN_LABEL_INSERT:
1212 status.enabled(type_ != hullSimple);
1214 case LFUN_INSET_INSERT:
1215 if (cmd.getArg(0) == "label") {
1216 status.enabled(type_ != hullSimple);
1219 return InsetMathGrid::getStatus(cur, cmd, status);
1220 case LFUN_TABULAR_FEATURE: {
1221 istringstream is(to_utf8(cmd.argument()));
1225 && (s == "append-row"
1226 || s == "delete-row"
1227 || s == "copy-row")) {
1228 status.message(bformat(
1229 from_utf8(N_("Can't change number of rows in '%1$s'")),
1231 status.enabled(false);
1235 && (s == "append-column"
1236 || s == "delete-column"
1237 || s == "copy-column")) {
1238 status.message(bformat(
1239 from_utf8(N_("Can't change number of columns in '%1$s'")),
1241 status.enabled(false);
1244 if ((type_ == hullSimple
1245 || type_ == hullEquation
1246 || type_ == hullNone) &&
1247 (s == "add-hline-above" || s == "add-hline-below")) {
1248 status.message(bformat(
1249 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1251 status.enabled(false);
1254 if (s == "add-vline-left" || s == "add-vline-right") {
1255 status.message(bformat(
1256 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1258 status.enabled(false);
1261 if (s == "valign-top" || s == "valign-middle"
1262 || s == "valign-bottom" || s == "align-left"
1263 || s == "align-center" || s == "align-right") {
1264 status.enabled(false);
1267 return InsetMathGrid::getStatus(cur, cmd, status);
1270 return InsetMathGrid::getStatus(cur, cmd, status);
1273 // This cannot really happen, but inserted to shut-up gcc
1274 return InsetMathGrid::getStatus(cur, cmd, status);
1278 /////////////////////////////////////////////////////////////////////
1282 // simply scrap this function if you want
1283 void InsetMathHull::mutateToText()
1286 // translate to latex
1288 latex(NULL, os, false, false);
1289 string str = os.str();
1292 Text * lt = view_->cursor().innerText();
1293 string::const_iterator cit = str.begin();
1294 string::const_iterator end = str.end();
1295 for (; cit != end; ++cit)
1296 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1299 //dispatch(LFUN_ESCAPE);
1304 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1305 docstring const & font)
1307 // this whole function is a hack and won't work for incremental font
1310 if (cur.inset().asInsetMath()->name() == font)
1311 cur.handleFont(to_utf8(font));
1313 cur.handleNest(createInsetMath(font));
1319 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1324 font.fromString(to_utf8(arg), b);
1325 if (font.fontInfo().color() != Color_inherit) {
1326 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1327 cur.handleNest(at, 0);
1332 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1335 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1336 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1337 enter_front ? idxFirst(cur) : idxLast(cur);
1338 // The inset formula dimension is not necessarily the same as the
1339 // one of the instant preview image, so we have to indicate to the
1340 // BufferView that a metrics update is needed.
1341 cur.updateFlags(Update::Force);
1345 docstring const InsetMathHull::editMessage() const
1347 return _("Math editor mode");
1351 void InsetMathHull::revealCodes(Cursor & cur) const
1353 if (!cur.inMathed())
1355 odocstringstream os;
1357 cur.message(os.str());
1359 // write something to the minibuffer
1360 // translate to latex
1364 string str = os.str();
1366 string::size_type pos = 0;
1368 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1371 else if (*it == '\0') {
1373 pos = it - str.begin();
1379 res = res.substr(pos - 30);
1380 if (res.size() > 60)
1381 res = res.substr(0, 60);
1387 InsetCode InsetMathHull::lyxCode() const
1393 /////////////////////////////////////////////////////////////////////
1397 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1400 // FIXME: completely broken
1401 static InsetMathHull * lastformula = 0;
1402 static CursorBase current = DocIterator(ibegin(nucleus()));
1404 static string laststr;
1406 if (lastformula != this || laststr != str) {
1407 //lyxerr << "reset lastformula to " << this << endl;
1410 current = ibegin(nucleus());
1412 mathed_parse_cell(ar, str);
1416 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1418 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1419 CursorSlice & top = it.back();
1420 MathData const & a = top.asInsetMath()->cell(top.idx_);
1421 if (a.matchpart(ar, top.pos_)) {
1422 bv->cursor().setSelection(it, ar.size());
1424 top.pos_ += ar.size();
1430 //lyxerr << "not found!" << endl;
1437 void InsetMathHull::write(Buffer const &, ostream & os) const
1439 odocstringstream oss;
1440 WriteStream wi(oss, false, false);
1443 os << to_utf8(oss.str());
1447 void InsetMathHull::read(Buffer const &, Lexer & lex)
1450 mathed_parse_normal(at, lex);
1451 operator=(*at->asHullInset());
1455 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1456 OutputParams const &) const
1458 if (0 && display()) {
1462 TextPainter tpain(dim.width(), dim.height());
1463 drawT(tpain, 0, dim.ascent());
1465 // reset metrics cache to "real" values
1467 return tpain.textheight();
1469 odocstringstream oss;
1470 WriteStream wi(oss, false, true);
1473 docstring const str = oss.str();
1480 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1481 OutputParams const & runparams) const
1486 if (getType() == hullSimple)
1487 name = from_ascii("inlineequation");
1489 name = from_ascii("informalequation");
1491 docstring bname = name;
1492 if (!label(0).empty())
1493 bname += " id='" + sgml::cleanID(buf, runparams, label(0)) + "'";
1495 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1497 odocstringstream ls;
1498 if (runparams.flavor == OutputParams::XML) {
1499 ms << MTag("alt role='tex' ");
1500 // Workaround for db2latex: db2latex always includes equations with
1501 // \ensuremath{} or \begin{display}\end{display}
1502 // so we strip LyX' math environment
1503 WriteStream wi(ls, false, false);
1504 InsetMathGrid::write(wi);
1505 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1510 InsetMathGrid::mathmlize(ms);
1513 ms << MTag("alt role='tex'");
1514 res = latex(buf, ls, runparams);
1515 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1519 ms << from_ascii("<graphic fileref=\"eqn/");
1520 if (!label(0).empty())
1521 ms << sgml::cleanID(buf, runparams, label(0));
1523 ms << sgml::uniqueID(from_ascii("anon"));
1525 if (runparams.flavor == OutputParams::XML)
1526 ms << from_ascii("\"/>");
1528 ms << from_ascii("\">");
1530 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1532 return ms.line() + res;
1536 void InsetMathHull::textString(Buffer const & buf, odocstream & os) const
1538 plaintext(buf, os, OutputParams(0));