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 "support/debug.h"
36 #include "DispatchResult.h"
37 #include "FuncRequest.h"
38 #include "support/gettext.h"
40 #include "OutputParams.h"
43 #include "TextPainter.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/lstrings.h"
58 using namespace lyx::support;
62 using cap::grabAndEraseSelection;
66 int getCols(HullType type)
83 // returns position of first relation operator in the array
84 // used for "intelligent splitting"
85 size_t firstRelOp(MathData const & ar)
87 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
89 return it - ar.begin();
94 char const * star(bool numbered)
96 return numbered ? "" : "*";
100 } // end anon namespace
103 HullType hullType(docstring const & s)
105 if (s == "none") return hullNone;
106 if (s == "simple") return hullSimple;
107 if (s == "equation") return hullEquation;
108 if (s == "eqnarray") return hullEqnArray;
109 if (s == "align") return hullAlign;
110 if (s == "alignat") return hullAlignAt;
111 if (s == "xalignat") return hullXAlignAt;
112 if (s == "xxalignat") return hullXXAlignAt;
113 if (s == "multline") return hullMultline;
114 if (s == "gather") return hullGather;
115 if (s == "flalign") return hullFlAlign;
116 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
121 docstring hullName(HullType type)
124 case hullNone: return from_ascii("none");
125 case hullSimple: return from_ascii("simple");
126 case hullEquation: return from_ascii("equation");
127 case hullEqnArray: return from_ascii("eqnarray");
128 case hullAlign: return from_ascii("align");
129 case hullAlignAt: return from_ascii("alignat");
130 case hullXAlignAt: return from_ascii("xalignat");
131 case hullXXAlignAt: return from_ascii("xxalignat");
132 case hullMultline: return from_ascii("multline");
133 case hullGather: return from_ascii("gather");
134 case hullFlAlign: return from_ascii("flalign");
136 lyxerr << "unknown hull type '" << type << "'" << endl;
137 return from_ascii("none");
142 InsetMathHull::InsetMathHull()
143 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1), label_(1),
144 preview_(new RenderPreview(this))
146 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
147 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
148 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
149 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
155 InsetMathHull::InsetMathHull(HullType type)
156 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1), label_(1),
157 preview_(new RenderPreview(this))
164 InsetMathHull::InsetMathHull(InsetMathHull const & other)
165 : InsetMathGrid(other),
166 type_(other.type_), nonum_(other.nonum_), label_(other.label_),
167 preview_(new RenderPreview(*other.preview_, this))
171 InsetMathHull::~InsetMathHull()
175 Inset * InsetMathHull::clone() const
177 return new InsetMathHull(*this);
181 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
185 *static_cast<InsetMathGrid*>(this) = InsetMathGrid(other);
187 nonum_ = other.nonum_;
188 label_ = other.label_;
189 preview_.reset(new RenderPreview(*other.preview_, this));
195 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
201 return InsetMathNest::editXY(cur, x, y);
205 InsetMath::mode_type InsetMathHull::currentMode() const
207 if (type_ == hullNone)
208 return UNDECIDED_MODE;
209 // definitely math mode ...
214 bool InsetMathHull::idxFirst(Cursor & cur) const
222 bool InsetMathHull::idxLast(Cursor & cur) const
224 cur.idx() = nargs() - 1;
225 cur.pos() = cur.lastpos();
230 char InsetMathHull::defaultColAlign(col_type col)
232 if (type_ == hullEqnArray)
234 if (type_ == hullGather)
236 if (type_ >= hullAlign)
237 return "rl"[col & 1];
242 int InsetMathHull::defaultColSpace(col_type col)
244 if (type_ == hullAlign || type_ == hullAlignAt)
246 if (type_ == hullXAlignAt)
247 return (col & 1) ? 20 : 0;
248 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
249 return (col & 1) ? 40 : 0;
254 docstring InsetMathHull::standardFont() const
256 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
260 bool InsetMathHull::previewState(BufferView * bv) const
262 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
263 graphics::PreviewImage const * pimage =
264 preview_->getPreviewImage(bv->buffer());
265 return pimage && pimage->image();
271 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
273 if (previewState(mi.base.bv)) {
274 preview_->metrics(mi, dim);
275 // insert a one pixel gap in front of the formula
278 dim.des += displayMargin();
279 // Cache the inset dimension.
280 setDimCache(mi, dim);
284 FontSetChanger dummy1(mi.base, standardFont());
285 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
287 // let the cells adjust themselves
288 InsetMathGrid::metrics(mi, dim);
291 dim.asc += displayMargin();
292 dim.des += displayMargin();
295 if (numberedType()) {
296 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
298 for (row_type row = 0; row < nrows(); ++row)
299 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
305 // make it at least as high as the current font
308 math_font_max_dim(mi.base.font, asc, des);
309 dim.asc = max(dim.asc, asc);
310 dim.des = max(dim.des, des);
311 // Cache the inset dimension.
312 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
313 setDimCache(mi, dim);
317 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
319 use_preview_ = previewState(pi.base.bv);
320 Dimension const dim = dimension(*pi.base.bv);
322 // background of mathed under focus is not painted because
323 // selection at the top level of nested inset is difficult to handle.
324 if (!editing(pi.base.bv))
325 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
326 dim.asc + dim.des - 1, Color_mathbg);
329 // one pixel gap in front
330 preview_->draw(pi, x + 1, y);
331 setPosCache(pi, x, y);
335 FontSetChanger dummy1(pi.base, standardFont());
336 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
337 InsetMathGrid::draw(pi, x + 1, y);
339 if (numberedType()) {
340 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
341 for (row_type row = 0; row < nrows(); ++row) {
342 int const yy = y + rowinfo_[row].offset_;
343 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
344 docstring const nl = nicelabel(row);
348 setPosCache(pi, x, y);
352 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
355 InsetMathGrid::metricsT(mi, dim);
358 WriteStream wi(os, false, true);
360 dim.wid = os.str().size();
367 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
370 InsetMathGrid::drawT(pain, x, y);
373 WriteStream wi(os, false, true);
375 pain.draw(x, y, os.str().c_str());
382 docstring const latex_string(InsetMathHull const & inset)
385 WriteStream wi(ls, false, false);
393 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
395 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
396 docstring const snippet = latex_string(*this);
397 preview_->addPreview(snippet, ploader);
402 bool InsetMathHull::notifyCursorLeaves(Cursor & cur)
404 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
405 Buffer const & buffer = cur.buffer();
406 docstring const snippet = latex_string(*this);
407 preview_->addPreview(snippet, buffer);
408 preview_->startLoading(buffer);
409 cur.updateFlags(Update::Force);
415 docstring InsetMathHull::label(row_type row) const
417 BOOST_ASSERT(row < nrows());
422 void InsetMathHull::label(row_type row, docstring const & label)
424 //lyxerr << "setting label '" << label << "' for row " << row << endl;
429 void InsetMathHull::numbered(row_type row, bool num)
437 bool InsetMathHull::numbered(row_type row) const
443 bool InsetMathHull::ams() const
446 type_ == hullAlign ||
447 type_ == hullFlAlign ||
448 type_ == hullMultline ||
449 type_ == hullGather ||
450 type_ == hullAlignAt ||
451 type_ == hullXAlignAt ||
452 type_ == hullXXAlignAt;
456 Inset::DisplayType InsetMathHull::display() const
458 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
462 void InsetMathHull::getLabelList(Buffer const &, vector<docstring> & labels) const
464 for (row_type row = 0; row < nrows(); ++row)
465 if (!label_[row].empty() && nonum_[row] != 1)
466 labels.push_back(label_[row]);
470 bool InsetMathHull::numberedType() const
472 if (type_ == hullNone)
474 if (type_ == hullSimple)
476 if (type_ == hullXXAlignAt)
478 for (row_type row = 0; row < nrows(); ++row)
485 void InsetMathHull::validate(LaTeXFeatures & features) const
488 features.require("amsmath");
491 // Validation is necessary only if not using AMS math.
492 // To be safe, we will always run mathedvalidate.
493 //if (features.amsstyle)
496 features.require("boldsymbol");
497 //features.binom = true;
499 InsetMathGrid::validate(features);
503 void InsetMathHull::header_write(WriteStream & os) const
505 bool n = numberedType();
519 os << "\\begin{equation" << star(n) << "}\n";
529 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
534 os << "\\begin{" << hullName(type_) << star(n) << '}'
535 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
539 os << "\\begin{" << hullName(type_) << '}'
540 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
544 os << "\\begin{unknown" << star(n) << '}';
550 void InsetMathHull::footer_write(WriteStream & os) const
552 bool n = numberedType();
565 os << "\\end{equation" << star(n) << "}\n";
577 os << "\\end{" << hullName(type_) << star(n) << "}\n";
581 os << "\\end{" << hullName(type_) << "}\n";
585 os << "\\end{unknown" << star(n) << '}';
591 bool InsetMathHull::rowChangeOK() const
594 type_ == hullEqnArray || type_ == hullAlign ||
595 type_ == hullFlAlign || type_ == hullAlignAt ||
596 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
597 type_ == hullGather || type_ == hullMultline;
601 bool InsetMathHull::colChangeOK() const
604 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
605 type_ == hullXAlignAt || type_ == hullXXAlignAt;
609 void InsetMathHull::addRow(row_type row)
613 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
614 label_.insert(label_.begin() + row + 1, docstring());
615 InsetMathGrid::addRow(row);
619 void InsetMathHull::swapRow(row_type row)
623 if (row + 1 == nrows())
625 swap(nonum_[row], nonum_[row + 1]);
626 swap(label_[row], label_[row + 1]);
627 InsetMathGrid::swapRow(row);
631 void InsetMathHull::delRow(row_type row)
633 if (nrows() <= 1 || !rowChangeOK())
635 InsetMathGrid::delRow(row);
636 // The last dummy row has no number info nor a label.
637 // Test nrows() + 1 because we have already erased the row.
638 if (row == nrows() + 1)
640 nonum_.erase(nonum_.begin() + row);
641 label_.erase(label_.begin() + row);
645 void InsetMathHull::addCol(col_type col)
649 InsetMathGrid::addCol(col);
653 void InsetMathHull::delCol(col_type col)
655 if (ncols() <= 1 || !colChangeOK())
657 InsetMathGrid::delCol(col);
661 docstring InsetMathHull::nicelabel(row_type row) const
665 if (label_[row].empty())
666 return from_ascii("(#)");
667 return '(' + label_[row] + ')';
671 void InsetMathHull::glueall()
674 for (idx_type i = 0; i < nargs(); ++i)
676 *this = InsetMathHull(hullSimple);
682 void InsetMathHull::splitTo2Cols()
684 BOOST_ASSERT(ncols() == 1);
685 InsetMathGrid::addCol(1);
686 for (row_type row = 0; row < nrows(); ++row) {
687 idx_type const i = 2 * row;
688 pos_type pos = firstRelOp(cell(i));
689 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
690 cell(i).erase(pos, cell(i).size());
695 void InsetMathHull::splitTo3Cols()
697 BOOST_ASSERT(ncols() < 3);
700 InsetMathGrid::addCol(2);
701 for (row_type row = 0; row < nrows(); ++row) {
702 idx_type const i = 3 * row + 1;
703 if (cell(i).size()) {
704 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
705 cell(i).erase(1, cell(i).size());
711 void InsetMathHull::changeCols(col_type cols)
715 else if (ncols() < cols) {
721 while (ncols() < cols)
722 InsetMathGrid::addCol(ncols());
728 for (row_type row = 0; row < nrows(); ++row) {
729 idx_type const i = row * ncols();
730 for (col_type col = cols; col < ncols(); ++col) {
731 cell(i + cols - 1).append(cell(i + col));
735 while (ncols() > cols) {
736 InsetMathGrid::delCol(ncols() - 1);
741 HullType InsetMathHull::getType() const
747 void InsetMathHull::setType(HullType type)
754 void InsetMathHull::mutate(HullType newtype)
756 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
758 // we try to move along the chain
759 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
761 // +-------------------------------------+
762 // we use eqnarray as intermediate type for mutations that are not
763 // directly supported because it handles labels and numbering for
766 if (newtype == type_) {
770 else if (newtype < hullNone) {
775 else if (type_ == hullNone) {
781 else if (type_ == hullSimple) {
782 if (newtype == hullNone) {
786 setType(hullEquation);
792 else if (type_ == hullEquation) {
793 if (newtype < type_) {
797 } else if (newtype == hullEqnArray) {
798 // split it "nicely" on the first relop
800 setType(hullEqnArray);
801 } else if (newtype == hullMultline || newtype == hullGather) {
811 else if (type_ == hullEqnArray) {
812 if (newtype < type_) {
813 // set correct (no)numbering
814 bool allnonum = true;
815 for (row_type row = 0; row < nrows(); ++row)
819 // set first non-empty label
821 for (row_type row = 0; row < nrows(); ++row) {
822 if (!label_[row].empty()) {
829 nonum_[0] = allnonum;
832 } else { // align & Co.
839 else if (type_ == hullAlign || type_ == hullAlignAt ||
840 type_ == hullXAlignAt || type_ == hullFlAlign) {
841 if (newtype < hullAlign) {
843 setType(hullEqnArray);
845 } else if (newtype == hullGather || newtype == hullMultline) {
848 } else if (newtype == hullXXAlignAt) {
849 for (row_type row = 0; row < nrows(); ++row)
850 numbered(row, false);
857 else if (type_ == hullXXAlignAt) {
858 for (row_type row = 0; row < nrows(); ++row)
859 numbered(row, false);
860 if (newtype < hullAlign) {
862 setType(hullEqnArray);
864 } else if (newtype == hullGather || newtype == hullMultline) {
872 else if (type_ == hullMultline || type_ == hullGather) {
873 if (newtype == hullGather || newtype == hullMultline)
875 else if (newtype == hullAlign || newtype == hullFlAlign ||
876 newtype == hullAlignAt || newtype == hullXAlignAt) {
879 } else if (newtype == hullXXAlignAt) {
881 for (row_type row = 0; row < nrows(); ++row)
882 numbered(row, false);
886 setType(hullEqnArray);
892 lyxerr << "mutation from '" << to_utf8(hullName(type_))
893 << "' to '" << to_utf8(hullName(newtype))
894 << "' not implemented" << endl;
899 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
902 if (numberedType()) {
903 if (!label_[row].empty() && !nonum_[row])
904 res += "\\label{" + label_[row] + '}';
905 if (nonum_[row] && (type_ != hullMultline))
906 res += "\\nonumber ";
908 return res + InsetMathGrid::eolString(row, emptyline, fragile);
912 void InsetMathHull::write(WriteStream & os) const
915 InsetMathGrid::write(os);
920 void InsetMathHull::normalize(NormalStream & os) const
922 os << "[formula " << hullName(type_) << ' ';
923 InsetMathGrid::normalize(os);
928 void InsetMathHull::mathmlize(MathStream & os) const
930 InsetMathGrid::mathmlize(os);
934 void InsetMathHull::infoize(odocstream & os) const
936 os << "Type: " << hullName(type_);
940 void InsetMathHull::check() const
942 BOOST_ASSERT(nonum_.size() == nrows());
943 BOOST_ASSERT(label_.size() == nrows());
947 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
951 idocstringstream iss(func.argument());
952 iss >> dlang >> extra;
954 extra = from_ascii("noextra");
955 string const lang = to_ascii(dlang);
957 // FIXME: temporarily disabled
958 //if (cur.selection()) {
961 // lyxerr << "use selection: " << ar << endl;
962 // insert(pipeThroughExtern(lang, extra, ar));
967 eq.push_back(MathAtom(new InsetMathChar('=')));
969 // go to first item in line
970 cur.idx() -= cur.idx() % ncols();
973 if (getType() == hullSimple) {
974 size_type pos = cur.cell().find_last(eq);
976 if (cur.inMathed() && cur.selection()) {
977 asArray(grabAndEraseSelection(cur), ar);
978 } else if (pos == cur.cell().size()) {
980 lyxerr << "use whole cell: " << ar << endl;
982 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
983 lyxerr << "use partial cell form pos: " << pos << endl;
985 cur.cell().append(eq);
986 cur.cell().append(pipeThroughExtern(lang, extra, ar));
987 cur.pos() = cur.lastpos();
991 if (getType() == hullEquation) {
992 lyxerr << "use equation inset" << endl;
993 mutate(hullEqnArray);
994 MathData & ar = cur.cell();
995 lyxerr << "use cell: " << ar << endl;
999 cur.cell() = pipeThroughExtern(lang, extra, ar);
1000 // move to end of line
1001 cur.pos() = cur.lastpos();
1006 lyxerr << "use eqnarray" << endl;
1007 cur.idx() += 2 - cur.idx() % ncols();
1009 MathData ar = cur.cell();
1010 lyxerr << "use cell: " << ar << endl;
1011 // FIXME: temporarily disabled
1017 cur.cell() = pipeThroughExtern(lang, extra, ar);
1018 cur.pos() = cur.lastpos();
1023 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1025 //lyxerr << "action: " << cmd.action << endl;
1026 switch (cmd.action) {
1028 case LFUN_FINISHED_BACKWARD:
1029 case LFUN_FINISHED_FORWARD:
1030 case LFUN_FINISHED_RIGHT:
1031 case LFUN_FINISHED_LEFT:
1032 //lyxerr << "action: " << cmd.action << endl;
1033 InsetMathGrid::doDispatch(cur, cmd);
1034 notifyCursorLeaves(cur);
1038 case LFUN_BREAK_PARAGRAPH:
1039 // just swallow this
1043 // some magic for the common case
1044 if (type_ == hullSimple || type_ == hullEquation) {
1045 cur.recordUndoInset();
1047 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1048 mutate(align ? hullAlign : hullEqnArray);
1049 cur.idx() = nrows() * ncols() - 1;
1050 cur.pos() = cur.lastpos();
1052 InsetMathGrid::doDispatch(cur, cmd);
1055 case LFUN_MATH_NUMBER_TOGGLE: {
1056 //lyxerr << "toggling all numbers" << endl;
1057 cur.recordUndoInset();
1058 bool old = numberedType();
1059 if (type_ == hullMultline)
1060 numbered(nrows() - 1, !old);
1062 for (row_type row = 0; row < nrows(); ++row)
1063 numbered(row, !old);
1065 cur.message(old ? _("No number") : _("Number"));
1069 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1070 cur.recordUndoInset();
1071 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1072 bool old = numbered(r);
1073 cur.message(old ? _("No number") : _("Number"));
1078 case LFUN_LABEL_INSERT: {
1079 cur.recordUndoInset();
1080 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1081 docstring old_label = label(r);
1082 docstring const default_label = from_ascii(
1083 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1084 if (old_label.empty())
1085 old_label = default_label;
1087 InsetCommandParams p(LABEL_CODE);
1088 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1089 string const data = InsetCommandMailer::params2string("label", p);
1091 if (cmd.argument().empty())
1092 cur.bv().showDialog("label", data);
1094 FuncRequest fr(LFUN_INSET_INSERT, data);
1100 case LFUN_INSET_INSERT: {
1101 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1102 string const name = cmd.getArg(0);
1103 if (name == "label") {
1104 InsetCommandParams p(LABEL_CODE);
1105 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1106 docstring str = p["name"];
1107 cur.recordUndoInset();
1108 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1112 docstring old = label(r);
1114 cur.bv().buffer().changeRefsIfUnique(old, str,
1120 InsetMathGrid::doDispatch(cur, cmd);
1124 case LFUN_MATH_EXTERN:
1125 cur.recordUndoInset();
1129 case LFUN_MATH_MUTATE: {
1130 cur.recordUndoInset();
1131 row_type row = cur.row();
1132 col_type col = cur.col();
1133 mutate(hullType(cmd.argument()));
1134 cur.idx() = row * ncols() + col;
1135 if (cur.idx() > cur.lastidx()) {
1136 cur.idx() = cur.lastidx();
1137 cur.pos() = cur.lastpos();
1139 if (cur.pos() > cur.lastpos())
1140 cur.pos() = cur.lastpos();
1142 // FIXME: find some more clever handling of the selection,
1143 // i.e. preserve it.
1144 cur.clearSelection();
1145 //cur.dispatched(FINISHED);
1149 case LFUN_MATH_DISPLAY: {
1150 cur.recordUndoInset();
1151 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1153 cur.pos() = cur.lastpos();
1154 //cur.dispatched(FINISHED);
1159 InsetMathGrid::doDispatch(cur, cmd);
1165 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1166 FuncStatus & status) const
1168 switch (cmd.action) {
1169 case LFUN_FINISHED_BACKWARD:
1170 case LFUN_FINISHED_FORWARD:
1171 case LFUN_FINISHED_RIGHT:
1172 case LFUN_FINISHED_LEFT:
1176 case LFUN_MATH_EXTERN:
1177 case LFUN_MATH_MUTATE:
1178 case LFUN_MATH_DISPLAY:
1180 status.enabled(true);
1182 case LFUN_MATH_NUMBER_TOGGLE:
1183 // FIXME: what is the right test, this or the one of
1185 status.enabled(display());
1186 status.setOnOff(numberedType());
1188 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1189 // FIXME: what is the right test, this or the one of
1191 status.enabled(display());
1192 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1193 status.setOnOff(numbered(r));
1196 case LFUN_LABEL_INSERT:
1197 status.enabled(type_ != hullSimple);
1199 case LFUN_INSET_INSERT:
1200 if (cmd.getArg(0) == "label") {
1201 status.enabled(type_ != hullSimple);
1204 return InsetMathGrid::getStatus(cur, cmd, status);
1205 case LFUN_TABULAR_FEATURE: {
1206 istringstream is(to_utf8(cmd.argument()));
1210 && (s == "append-row"
1211 || s == "delete-row"
1212 || s == "copy-row")) {
1213 status.message(bformat(
1214 from_utf8(N_("Can't change number of rows in '%1$s'")),
1216 status.enabled(false);
1220 && (s == "append-column"
1221 || s == "delete-column"
1222 || s == "copy-column")) {
1223 status.message(bformat(
1224 from_utf8(N_("Can't change number of columns in '%1$s'")),
1226 status.enabled(false);
1229 if ((type_ == hullSimple
1230 || type_ == hullEquation
1231 || type_ == hullNone) &&
1232 (s == "add-hline-above" || s == "add-hline-below")) {
1233 status.message(bformat(
1234 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1236 status.enabled(false);
1239 if (s == "add-vline-left" || s == "add-vline-right") {
1240 status.message(bformat(
1241 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1243 status.enabled(false);
1246 if (s == "valign-top" || s == "valign-middle"
1247 || s == "valign-bottom" || s == "align-left"
1248 || s == "align-center" || s == "align-right") {
1249 status.enabled(false);
1252 return InsetMathGrid::getStatus(cur, cmd, status);
1255 return InsetMathGrid::getStatus(cur, cmd, status);
1258 // This cannot really happen, but inserted to shut-up gcc
1259 return InsetMathGrid::getStatus(cur, cmd, status);
1263 /////////////////////////////////////////////////////////////////////
1267 // simply scrap this function if you want
1268 void InsetMathHull::mutateToText()
1271 // translate to latex
1273 latex(NULL, os, false, false);
1274 string str = os.str();
1277 Text * lt = view_->cursor().innerText();
1278 string::const_iterator cit = str.begin();
1279 string::const_iterator end = str.end();
1280 for (; cit != end; ++cit)
1281 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1284 //dispatch(LFUN_ESCAPE);
1289 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1290 docstring const & font)
1292 // this whole function is a hack and won't work for incremental font
1295 if (cur.inset().asInsetMath()->name() == font)
1296 cur.handleFont(to_utf8(font));
1298 cur.handleNest(createInsetMath(font));
1304 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1309 font.fromString(to_utf8(arg), b);
1310 if (font.fontInfo().color() != Color_inherit) {
1311 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1312 cur.handleNest(at, 0);
1317 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1320 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1321 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1322 enter_front ? idxFirst(cur) : idxLast(cur);
1323 // The inset formula dimension is not necessarily the same as the
1324 // one of the instant preview image, so we have to indicate to the
1325 // BufferView that a metrics update is needed.
1326 cur.updateFlags(Update::Force);
1330 docstring const InsetMathHull::editMessage() const
1332 return _("Math editor mode");
1336 void InsetMathHull::revealCodes(Cursor & cur) const
1338 if (!cur.inMathed())
1340 odocstringstream os;
1342 cur.message(os.str());
1344 // write something to the minibuffer
1345 // translate to latex
1349 string str = os.str();
1351 string::size_type pos = 0;
1353 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1356 else if (*it == '\0') {
1358 pos = it - str.begin();
1364 res = res.substr(pos - 30);
1365 if (res.size() > 60)
1366 res = res.substr(0, 60);
1372 InsetCode InsetMathHull::lyxCode() const
1378 /////////////////////////////////////////////////////////////////////
1382 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1385 // FIXME: completely broken
1386 static InsetMathHull * lastformula = 0;
1387 static CursorBase current = DocIterator(ibegin(nucleus()));
1389 static string laststr;
1391 if (lastformula != this || laststr != str) {
1392 //lyxerr << "reset lastformula to " << this << endl;
1395 current = ibegin(nucleus());
1397 mathed_parse_cell(ar, str);
1401 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1403 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1404 CursorSlice & top = it.back();
1405 MathData const & a = top.asInsetMath()->cell(top.idx_);
1406 if (a.matchpart(ar, top.pos_)) {
1407 bv->cursor().setSelection(it, ar.size());
1409 top.pos_ += ar.size();
1415 //lyxerr << "not found!" << endl;
1422 void InsetMathHull::write(Buffer const &, ostream & os) const
1424 odocstringstream oss;
1425 WriteStream wi(oss, false, false);
1428 os << to_utf8(oss.str());
1432 void InsetMathHull::read(Buffer const &, Lexer & lex)
1435 mathed_parse_normal(at, lex);
1436 operator=(*at->asHullInset());
1440 int InsetMathHull::plaintext(Buffer const &, odocstream & os,
1441 OutputParams const &) const
1443 if (0 && display()) {
1447 TextPainter tpain(dim.width(), dim.height());
1448 drawT(tpain, 0, dim.ascent());
1450 // reset metrics cache to "real" values
1452 return tpain.textheight();
1454 odocstringstream oss;
1455 WriteStream wi(oss, false, true);
1458 docstring const str = oss.str();
1465 int InsetMathHull::docbook(Buffer const & buf, odocstream & os,
1466 OutputParams const & runparams) const
1471 if (getType() == hullSimple)
1472 name = from_ascii("inlineequation");
1474 name = from_ascii("informalequation");
1476 docstring bname = name;
1477 if (!label(0).empty())
1478 bname += " id='" + sgml::cleanID(buf, runparams, label(0)) + "'";
1480 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1482 odocstringstream ls;
1483 if (runparams.flavor == OutputParams::XML) {
1484 ms << MTag("alt role='tex' ");
1485 // Workaround for db2latex: db2latex always includes equations with
1486 // \ensuremath{} or \begin{display}\end{display}
1487 // so we strip LyX' math environment
1488 WriteStream wi(ls, false, false);
1489 InsetMathGrid::write(wi);
1490 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1495 InsetMathGrid::mathmlize(ms);
1498 ms << MTag("alt role='tex'");
1499 res = latex(buf, ls, runparams);
1500 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1504 ms << from_ascii("<graphic fileref=\"eqn/");
1505 if (!label(0).empty())
1506 ms << sgml::cleanID(buf, runparams, label(0));
1508 ms << sgml::uniqueID(from_ascii("anon"));
1510 if (runparams.flavor == OutputParams::XML)
1511 ms << from_ascii("\"/>");
1513 ms << from_ascii("\">");
1515 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1517 return ms.line() + res;
1521 void InsetMathHull::textString(Buffer const & buf, odocstream & os) const
1523 plaintext(buf, os, OutputParams(0));