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 "buffer_funcs.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "CutAndPaste.h"
33 #include "FuncStatus.h"
34 #include "LaTeXFeatures.h"
36 #include "DispatchResult.h"
37 #include "FuncRequest.h"
39 #include "OutputParams.h"
40 #include "ParIterator.h"
43 #include "TextPainter.h"
44 #include "TocBackend.h"
46 #include "insets/RenderPreview.h"
47 #include "insets/InsetLabel.h"
49 #include "graphics/PreviewImage.h"
50 #include "graphics/PreviewLoader.h"
52 #include "frontends/Painter.h"
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
61 using namespace lyx::support;
65 using cap::grabAndEraseSelection;
69 int getCols(HullType type)
86 // returns position of first relation operator in the array
87 // used for "intelligent splitting"
88 size_t firstRelOp(MathData const & ar)
90 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
92 return it - ar.begin();
97 char const * star(bool numbered)
99 return numbered ? "" : "*";
103 } // end anon namespace
106 HullType hullType(docstring const & s)
108 if (s == "none") return hullNone;
109 if (s == "simple") return hullSimple;
110 if (s == "equation") return hullEquation;
111 if (s == "eqnarray") return hullEqnArray;
112 if (s == "align") return hullAlign;
113 if (s == "alignat") return hullAlignAt;
114 if (s == "xalignat") return hullXAlignAt;
115 if (s == "xxalignat") return hullXXAlignAt;
116 if (s == "multline") return hullMultline;
117 if (s == "gather") return hullGather;
118 if (s == "flalign") return hullFlAlign;
119 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
124 docstring hullName(HullType type)
127 case hullNone: return from_ascii("none");
128 case hullSimple: return from_ascii("simple");
129 case hullEquation: return from_ascii("equation");
130 case hullEqnArray: return from_ascii("eqnarray");
131 case hullAlign: return from_ascii("align");
132 case hullAlignAt: return from_ascii("alignat");
133 case hullXAlignAt: return from_ascii("xalignat");
134 case hullXXAlignAt: return from_ascii("xxalignat");
135 case hullMultline: return from_ascii("multline");
136 case hullGather: return from_ascii("gather");
137 case hullFlAlign: return from_ascii("flalign");
139 lyxerr << "unknown hull type '" << type << "'" << endl;
140 return from_ascii("none");
144 static InsetLabel * dummy_pointer = 0;
146 InsetMathHull::InsetMathHull()
147 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false), label_(1, dummy_pointer),
148 preview_(new RenderPreview(this))
150 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
151 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
152 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
153 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
159 InsetMathHull::InsetMathHull(HullType type)
160 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false), label_(1, dummy_pointer),
161 preview_(new RenderPreview(this))
168 InsetMathHull::InsetMathHull(InsetMathHull const & other)
174 InsetMathHull::~InsetMathHull()
176 for (size_t i = 0; i < label_.size(); ++i)
181 Inset * InsetMathHull::clone() const
183 return new InsetMathHull(*this);
187 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
191 InsetMathGrid::operator=(other);
193 nonum_ = other.nonum_;
194 for (size_t i = 0; i < label_.size(); ++i)
196 label_ = other.label_;
197 for (size_t i = 0; i != label_.size(); ++i) {
199 label_[i] = new InsetLabel(*label_[i]);
201 preview_.reset(new RenderPreview(*other.preview_, this));
207 void InsetMathHull::setBuffer(Buffer & buffer)
210 for (idx_type i = 0, n = nargs(); i != n; ++i) {
211 MathData & data = cell(i);
212 for (size_t j = 0; j != data.size(); ++j)
213 data[j].nucleus()->setBuffer(buffer);
216 for (size_t i = 0; i != label_.size(); ++i) {
218 label_[i]->setBuffer(buffer);
223 void InsetMathHull::updateLabels(ParIterator const & it)
226 //FIXME: buffer_ should be set at creation for this inset! Problem is
227 // This inset is created at too many places (see Parser::parse1() in
231 for (size_t i = 0; i != label_.size(); ++i) {
233 label_[i]->updateLabels(it);
238 void InsetMathHull::addToToc(ParConstIterator const & pit) const
241 //FIXME: buffer_ should be set at creation for this inset! Problem is
242 // This inset is created at too many places (see Parser::parse1() in
247 // FIXME: it would be way better to directly use InsetLabel instead of this
248 // label list. But it should be possible to copy&paste the code in
249 // InsetLabel::addToToc() anyway.
251 Toc & toc = buffer().tocBackend().toc("equation");
253 for (row_type row = 0; row != nrows(); ++row) {
257 label_[row]->addToToc(pit);
258 toc.push_back(TocItem(pit, 0, nicelabel(row)));
263 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
269 return InsetMathNest::editXY(cur, x, y);
273 InsetMath::mode_type InsetMathHull::currentMode() const
275 if (type_ == hullNone)
276 return UNDECIDED_MODE;
277 // definitely math mode ...
282 bool InsetMathHull::idxFirst(Cursor & cur) const
290 bool InsetMathHull::idxLast(Cursor & cur) const
292 cur.idx() = nargs() - 1;
293 cur.pos() = cur.lastpos();
298 char InsetMathHull::defaultColAlign(col_type col)
300 if (type_ == hullEqnArray)
302 if (type_ == hullGather)
304 if (type_ >= hullAlign)
305 return "rl"[col & 1];
310 int InsetMathHull::defaultColSpace(col_type col)
312 if (type_ == hullAlign || type_ == hullAlignAt)
314 if (type_ == hullXAlignAt)
315 return (col & 1) ? 20 : 0;
316 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
317 return (col & 1) ? 40 : 0;
322 docstring InsetMathHull::standardFont() const
324 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
328 bool InsetMathHull::previewState(BufferView * bv) const
330 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
331 graphics::PreviewImage const * pimage =
332 preview_->getPreviewImage(bv->buffer());
333 return pimage && pimage->image();
339 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
341 if (previewState(mi.base.bv)) {
342 preview_->metrics(mi, dim);
343 // insert a one pixel gap in front of the formula
346 dim.des += displayMargin();
347 // Cache the inset dimension.
348 setDimCache(mi, dim);
352 FontSetChanger dummy1(mi.base, standardFont());
353 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
355 // let the cells adjust themselves
356 InsetMathGrid::metrics(mi, dim);
359 dim.asc += displayMargin();
360 dim.des += displayMargin();
363 if (numberedType()) {
364 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
366 for (row_type row = 0; row < nrows(); ++row)
367 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
373 // make it at least as high as the current font
376 math_font_max_dim(mi.base.font, asc, des);
377 dim.asc = max(dim.asc, asc);
378 dim.des = max(dim.des, des);
379 // Cache the inset dimension.
380 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
381 setDimCache(mi, dim);
385 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
387 use_preview_ = previewState(pi.base.bv);
388 Dimension const dim = dimension(*pi.base.bv);
390 // background of mathed under focus is not painted because
391 // selection at the top level of nested inset is difficult to handle.
392 if (!editing(pi.base.bv))
393 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
394 dim.asc + dim.des - 1, Color_mathbg);
397 // one pixel gap in front
398 preview_->draw(pi, x + 1, y);
399 setPosCache(pi, x, y);
403 FontSetChanger dummy1(pi.base, standardFont());
404 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
405 InsetMathGrid::draw(pi, x + 1, y);
407 if (numberedType()) {
408 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
409 for (row_type row = 0; row < nrows(); ++row) {
410 int const yy = y + rowinfo_[row].offset_;
411 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
412 docstring const nl = nicelabel(row);
416 setPosCache(pi, x, y);
420 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
423 InsetMathGrid::metricsT(mi, dim);
426 WriteStream wi(os, false, true);
428 dim.wid = os.str().size();
435 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
438 InsetMathGrid::drawT(pain, x, y);
441 WriteStream wi(os, false, true);
443 pain.draw(x, y, os.str().c_str());
450 docstring const latex_string(InsetMathHull const & inset)
453 WriteStream wi(ls, false, false);
461 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
463 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
464 docstring const snippet = latex_string(*this);
465 preview_->addPreview(snippet, ploader);
470 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
472 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
473 Buffer const & buffer = cur.buffer();
474 docstring const snippet = latex_string(*this);
475 preview_->addPreview(snippet, buffer);
476 preview_->startLoading(buffer);
477 cur.updateFlags(Update::Force);
483 docstring InsetMathHull::label(row_type row) const
485 BOOST_ASSERT(row < nrows());
486 if (InsetLabel * il = label_[row])
487 return il->screenLabel();
492 void InsetMathHull::label(row_type row, docstring const & label)
494 //lyxerr << "setting label '" << label << "' for row " << row << endl;
499 label_[row] = dummy_pointer;
501 label_[row]->updateCommand(label);
504 InsetCommandParams p(LABEL_CODE);
506 label_[row] = new InsetLabel(p);
508 label_[row]->setBuffer(buffer());
512 void InsetMathHull::numbered(row_type row, bool num)
515 if (nonum_[row] && label_[row]) {
522 bool InsetMathHull::numbered(row_type row) const
528 bool InsetMathHull::ams() const
531 type_ == hullAlign ||
532 type_ == hullFlAlign ||
533 type_ == hullMultline ||
534 type_ == hullGather ||
535 type_ == hullAlignAt ||
536 type_ == hullXAlignAt ||
537 type_ == hullXXAlignAt;
541 Inset::DisplayType InsetMathHull::display() const
543 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
547 bool InsetMathHull::numberedType() const
549 if (type_ == hullNone)
551 if (type_ == hullSimple)
553 if (type_ == hullXXAlignAt)
555 for (row_type row = 0; row < nrows(); ++row)
562 void InsetMathHull::validate(LaTeXFeatures & features) const
565 features.require("amsmath");
568 // Validation is necessary only if not using AMS math.
569 // To be safe, we will always run mathedvalidate.
570 //if (features.amsstyle)
573 features.require("boldsymbol");
574 //features.binom = true;
576 InsetMathGrid::validate(features);
580 void InsetMathHull::header_write(WriteStream & os) const
582 bool n = numberedType();
596 os << "\\begin{equation" << star(n) << "}\n";
606 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
611 os << "\\begin{" << hullName(type_) << star(n) << '}'
612 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
616 os << "\\begin{" << hullName(type_) << '}'
617 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
621 os << "\\begin{unknown" << star(n) << '}';
627 void InsetMathHull::footer_write(WriteStream & os) const
629 bool n = numberedType();
642 os << "\\end{equation" << star(n) << "}\n";
654 os << "\\end{" << hullName(type_) << star(n) << "}\n";
658 os << "\\end{" << hullName(type_) << "}\n";
662 os << "\\end{unknown" << star(n) << '}';
668 bool InsetMathHull::rowChangeOK() const
671 type_ == hullEqnArray || type_ == hullAlign ||
672 type_ == hullFlAlign || type_ == hullAlignAt ||
673 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
674 type_ == hullGather || type_ == hullMultline;
678 bool InsetMathHull::colChangeOK() const
681 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
682 type_ == hullXAlignAt || type_ == hullXXAlignAt;
686 void InsetMathHull::addRow(row_type row)
690 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
691 label_.insert(label_.begin() + row + 1, dummy_pointer);
692 InsetMathGrid::addRow(row);
696 void InsetMathHull::swapRow(row_type row)
700 if (row + 1 == nrows())
702 // gcc implements the standard std::vector<bool> which is *not* a container:
703 // http://www.gotw.ca/publications/N1185.pdf
704 // As a results, it doesn't like this:
705 // swap(nonum_[row], nonum_[row + 1]);
706 // so we do it manually:
707 bool const b = nonum_[row];
708 nonum_[row] = nonum_[row + 1];
710 swap(label_[row], label_[row + 1]);
711 InsetMathGrid::swapRow(row);
715 void InsetMathHull::delRow(row_type row)
717 if (nrows() <= 1 || !rowChangeOK())
719 InsetMathGrid::delRow(row);
720 // The last dummy row has no number info nor a label.
721 // Test nrows() + 1 because we have already erased the row.
722 if (row == nrows() + 1)
724 nonum_.erase(nonum_.begin() + row);
726 label_.erase(label_.begin() + row);
730 void InsetMathHull::addCol(col_type col)
734 InsetMathGrid::addCol(col);
738 void InsetMathHull::delCol(col_type col)
740 if (ncols() <= 1 || !colChangeOK())
742 InsetMathGrid::delCol(col);
746 docstring InsetMathHull::nicelabel(row_type row) const
751 return from_ascii("(#)");
752 return '(' + label_[row]->screenLabel() + ')';
756 void InsetMathHull::glueall()
759 for (idx_type i = 0; i < nargs(); ++i)
761 *this = InsetMathHull(hullSimple);
767 void InsetMathHull::splitTo2Cols()
769 BOOST_ASSERT(ncols() == 1);
770 InsetMathGrid::addCol(1);
771 for (row_type row = 0; row < nrows(); ++row) {
772 idx_type const i = 2 * row;
773 pos_type pos = firstRelOp(cell(i));
774 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
775 cell(i).erase(pos, cell(i).size());
780 void InsetMathHull::splitTo3Cols()
782 BOOST_ASSERT(ncols() < 3);
785 InsetMathGrid::addCol(2);
786 for (row_type row = 0; row < nrows(); ++row) {
787 idx_type const i = 3 * row + 1;
788 if (cell(i).size()) {
789 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
790 cell(i).erase(1, cell(i).size());
796 void InsetMathHull::changeCols(col_type cols)
800 else if (ncols() < cols) {
806 while (ncols() < cols)
807 InsetMathGrid::addCol(ncols());
813 for (row_type row = 0; row < nrows(); ++row) {
814 idx_type const i = row * ncols();
815 for (col_type col = cols; col < ncols(); ++col) {
816 cell(i + cols - 1).append(cell(i + col));
820 while (ncols() > cols) {
821 InsetMathGrid::delCol(ncols() - 1);
826 HullType InsetMathHull::getType() const
832 void InsetMathHull::setType(HullType type)
839 void InsetMathHull::mutate(HullType newtype)
841 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
843 // we try to move along the chain
844 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
846 // +-------------------------------------+
847 // we use eqnarray as intermediate type for mutations that are not
848 // directly supported because it handles labels and numbering for
851 if (newtype == type_) {
855 else if (newtype < hullNone) {
860 else if (type_ == hullNone) {
866 else if (type_ == hullSimple) {
867 if (newtype == hullNone) {
871 setType(hullEquation);
877 else if (type_ == hullEquation) {
878 if (newtype < type_) {
882 } else if (newtype == hullEqnArray) {
883 // split it "nicely" on the first relop
885 setType(hullEqnArray);
886 } else if (newtype == hullMultline || newtype == hullGather) {
896 else if (type_ == hullEqnArray) {
897 if (newtype < type_) {
898 // set correct (no)numbering
900 for (row_type row = 0; row < nrows(); ++row) {
907 // set first non-empty label
908 for (row_type row = 0; row < nrows(); ++row) {
910 label_[0] = label_[row];
917 } else { // align & Co.
924 else if (type_ == hullAlign || type_ == hullAlignAt ||
925 type_ == hullXAlignAt || type_ == hullFlAlign) {
926 if (newtype < hullAlign) {
928 setType(hullEqnArray);
930 } else if (newtype == hullGather || newtype == hullMultline) {
933 } else if (newtype == hullXXAlignAt) {
934 for (row_type row = 0; row < nrows(); ++row)
935 numbered(row, false);
942 else if (type_ == hullXXAlignAt) {
943 for (row_type row = 0; row < nrows(); ++row)
944 numbered(row, false);
945 if (newtype < hullAlign) {
947 setType(hullEqnArray);
949 } else if (newtype == hullGather || newtype == hullMultline) {
957 else if (type_ == hullMultline || type_ == hullGather) {
958 if (newtype == hullGather || newtype == hullMultline)
960 else if (newtype == hullAlign || newtype == hullFlAlign ||
961 newtype == hullAlignAt || newtype == hullXAlignAt) {
964 } else if (newtype == hullXXAlignAt) {
966 for (row_type row = 0; row < nrows(); ++row)
967 numbered(row, false);
971 setType(hullEqnArray);
977 lyxerr << "mutation from '" << to_utf8(hullName(type_))
978 << "' to '" << to_utf8(hullName(newtype))
979 << "' not implemented" << endl;
984 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
987 if (numberedType()) {
988 if (label_[row] && !nonum_[row])
989 res += "\\label{" + label_[row]->getParam("name") + '}';
990 if (nonum_[row] && (type_ != hullMultline))
991 res += "\\nonumber ";
993 return res + InsetMathGrid::eolString(row, emptyline, fragile);
997 void InsetMathHull::write(WriteStream & os) const
1000 InsetMathGrid::write(os);
1005 void InsetMathHull::normalize(NormalStream & os) const
1007 os << "[formula " << hullName(type_) << ' ';
1008 InsetMathGrid::normalize(os);
1013 void InsetMathHull::mathmlize(MathStream & os) const
1015 InsetMathGrid::mathmlize(os);
1019 void InsetMathHull::infoize(odocstream & os) const
1021 os << "Type: " << hullName(type_);
1025 void InsetMathHull::check() const
1027 BOOST_ASSERT(nonum_.size() == nrows());
1028 BOOST_ASSERT(label_.size() == nrows());
1032 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1036 idocstringstream iss(func.argument());
1037 iss >> dlang >> extra;
1039 extra = from_ascii("noextra");
1040 string const lang = to_ascii(dlang);
1042 // FIXME: temporarily disabled
1043 //if (cur.selection()) {
1046 // lyxerr << "use selection: " << ar << endl;
1047 // insert(pipeThroughExtern(lang, extra, ar));
1052 eq.push_back(MathAtom(new InsetMathChar('=')));
1054 // go to first item in line
1055 cur.idx() -= cur.idx() % ncols();
1058 if (getType() == hullSimple) {
1059 size_type pos = cur.cell().find_last(eq);
1061 if (cur.inMathed() && cur.selection()) {
1062 asArray(grabAndEraseSelection(cur), ar);
1063 } else if (pos == cur.cell().size()) {
1065 lyxerr << "use whole cell: " << ar << endl;
1067 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1068 lyxerr << "use partial cell form pos: " << pos << endl;
1070 cur.cell().append(eq);
1071 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1072 cur.pos() = cur.lastpos();
1076 if (getType() == hullEquation) {
1077 lyxerr << "use equation inset" << endl;
1078 mutate(hullEqnArray);
1079 MathData & ar = cur.cell();
1080 lyxerr << "use cell: " << ar << endl;
1084 cur.cell() = pipeThroughExtern(lang, extra, ar);
1085 // move to end of line
1086 cur.pos() = cur.lastpos();
1091 lyxerr << "use eqnarray" << endl;
1092 cur.idx() += 2 - cur.idx() % ncols();
1094 MathData ar = cur.cell();
1095 lyxerr << "use cell: " << ar << endl;
1096 // FIXME: temporarily disabled
1102 cur.cell() = pipeThroughExtern(lang, extra, ar);
1103 cur.pos() = cur.lastpos();
1108 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1110 //lyxerr << "action: " << cmd.action << endl;
1111 switch (cmd.action) {
1113 case LFUN_FINISHED_BACKWARD:
1114 case LFUN_FINISHED_FORWARD:
1115 case LFUN_FINISHED_RIGHT:
1116 case LFUN_FINISHED_LEFT:
1117 //lyxerr << "action: " << cmd.action << endl;
1118 InsetMathGrid::doDispatch(cur, cmd);
1122 case LFUN_BREAK_PARAGRAPH:
1123 // just swallow this
1127 // some magic for the common case
1128 if (type_ == hullSimple || type_ == hullEquation) {
1129 cur.recordUndoInset();
1131 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1132 mutate(align ? hullAlign : hullEqnArray);
1133 cur.idx() = nrows() * ncols() - 1;
1134 cur.pos() = cur.lastpos();
1136 InsetMathGrid::doDispatch(cur, cmd);
1139 case LFUN_MATH_NUMBER_TOGGLE: {
1140 //lyxerr << "toggling all numbers" << endl;
1141 cur.recordUndoInset();
1142 bool old = numberedType();
1143 if (type_ == hullMultline)
1144 numbered(nrows() - 1, !old);
1146 for (row_type row = 0; row < nrows(); ++row)
1147 numbered(row, !old);
1149 cur.message(old ? _("No number") : _("Number"));
1153 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1154 cur.recordUndoInset();
1155 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1156 bool old = numbered(r);
1157 cur.message(old ? _("No number") : _("Number"));
1162 case LFUN_LABEL_INSERT: {
1163 cur.recordUndoInset();
1164 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1165 docstring old_label = label(r);
1166 docstring const default_label = from_ascii(
1167 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1168 if (old_label.empty())
1169 old_label = default_label;
1171 InsetCommandParams p(LABEL_CODE);
1172 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1173 string const data = InsetCommandMailer::params2string("label", p);
1175 if (cmd.argument().empty())
1176 cur.bv().showDialog("label", data);
1178 FuncRequest fr(LFUN_INSET_INSERT, data);
1184 case LFUN_WORD_DELETE_FORWARD:
1185 case LFUN_CHAR_DELETE_FORWARD:
1186 if (col(cur.idx()) + 1 == ncols()
1187 && cur.pos() == cur.lastpos()) {
1188 if (!label(row(cur.idx())).empty()) {
1189 cur.recordUndoInset();
1190 label(row(cur.idx()), docstring());
1191 } else if (numbered(row(cur.idx()))) {
1192 cur.recordUndoInset();
1193 numbered(row(cur.idx()), false);
1195 InsetMathGrid::doDispatch(cur, cmd);
1199 InsetMathGrid::doDispatch(cur, cmd);
1204 case LFUN_INSET_INSERT: {
1205 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1206 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1207 string const name = cmd.getArg(0);
1208 if (name == "label") {
1209 InsetCommandParams p(LABEL_CODE);
1210 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1211 docstring str = p["name"];
1212 cur.recordUndoInset();
1213 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1217 docstring old = label(r);
1220 // The label will take care of the reference update.
1224 // Newly created inset so initialize it.
1225 label_[r]->initView();
1230 InsetMathGrid::doDispatch(cur, cmd);
1234 case LFUN_MATH_EXTERN:
1235 cur.recordUndoInset();
1239 case LFUN_MATH_MUTATE: {
1240 cur.recordUndoInset();
1241 row_type row = cur.row();
1242 col_type col = cur.col();
1243 mutate(hullType(cmd.argument()));
1244 cur.idx() = row * ncols() + col;
1245 if (cur.idx() > cur.lastidx()) {
1246 cur.idx() = cur.lastidx();
1247 cur.pos() = cur.lastpos();
1249 if (cur.pos() > cur.lastpos())
1250 cur.pos() = cur.lastpos();
1252 // FIXME: find some more clever handling of the selection,
1253 // i.e. preserve it.
1254 cur.clearSelection();
1255 //cur.dispatched(FINISHED);
1259 case LFUN_MATH_DISPLAY: {
1260 cur.recordUndoInset();
1261 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1263 cur.pos() = cur.lastpos();
1264 //cur.dispatched(FINISHED);
1269 InsetMathGrid::doDispatch(cur, cmd);
1275 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1276 FuncStatus & status) const
1278 switch (cmd.action) {
1279 case LFUN_FINISHED_BACKWARD:
1280 case LFUN_FINISHED_FORWARD:
1281 case LFUN_FINISHED_RIGHT:
1282 case LFUN_FINISHED_LEFT:
1286 case LFUN_MATH_EXTERN:
1287 case LFUN_MATH_MUTATE:
1288 case LFUN_MATH_DISPLAY:
1290 status.enabled(true);
1292 case LFUN_MATH_NUMBER_TOGGLE:
1293 // FIXME: what is the right test, this or the one of
1295 status.enabled(display());
1296 status.setOnOff(numberedType());
1298 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1299 // FIXME: what is the right test, this or the one of
1301 status.enabled(display());
1302 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1303 status.setOnOff(numbered(r));
1306 case LFUN_LABEL_INSERT:
1307 status.enabled(type_ != hullSimple);
1309 case LFUN_INSET_INSERT:
1310 if (cmd.getArg(0) == "label") {
1311 status.enabled(type_ != hullSimple);
1314 return InsetMathGrid::getStatus(cur, cmd, status);
1315 case LFUN_TABULAR_FEATURE: {
1316 istringstream is(to_utf8(cmd.argument()));
1320 && (s == "append-row"
1321 || s == "delete-row"
1322 || s == "copy-row")) {
1323 status.message(bformat(
1324 from_utf8(N_("Can't change number of rows in '%1$s'")),
1326 status.enabled(false);
1330 && (s == "append-column"
1331 || s == "delete-column"
1332 || s == "copy-column")) {
1333 status.message(bformat(
1334 from_utf8(N_("Can't change number of columns in '%1$s'")),
1336 status.enabled(false);
1339 if ((type_ == hullSimple
1340 || type_ == hullEquation
1341 || type_ == hullNone) &&
1342 (s == "add-hline-above" || s == "add-hline-below")) {
1343 status.message(bformat(
1344 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1346 status.enabled(false);
1349 if (s == "add-vline-left" || s == "add-vline-right") {
1350 status.message(bformat(
1351 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1353 status.enabled(false);
1356 if (s == "valign-top" || s == "valign-middle"
1357 || s == "valign-bottom" || s == "align-left"
1358 || s == "align-center" || s == "align-right") {
1359 status.enabled(false);
1362 return InsetMathGrid::getStatus(cur, cmd, status);
1365 return InsetMathGrid::getStatus(cur, cmd, status);
1368 // This cannot really happen, but inserted to shut-up gcc
1369 return InsetMathGrid::getStatus(cur, cmd, status);
1373 /////////////////////////////////////////////////////////////////////
1377 // simply scrap this function if you want
1378 void InsetMathHull::mutateToText()
1381 // translate to latex
1383 latex(NULL, os, false, false);
1384 string str = os.str();
1387 Text * lt = view_->cursor().innerText();
1388 string::const_iterator cit = str.begin();
1389 string::const_iterator end = str.end();
1390 for (; cit != end; ++cit)
1391 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1394 //dispatch(LFUN_ESCAPE);
1399 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1400 docstring const & font)
1402 // this whole function is a hack and won't work for incremental font
1405 if (cur.inset().asInsetMath()->name() == font)
1406 cur.handleFont(to_utf8(font));
1408 cur.handleNest(createInsetMath(font));
1414 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1419 font.fromString(to_utf8(arg), b);
1420 if (font.fontInfo().color() != Color_inherit) {
1421 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1422 cur.handleNest(at, 0);
1427 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1430 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1431 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1432 enter_front ? idxFirst(cur) : idxLast(cur);
1433 // The inset formula dimension is not necessarily the same as the
1434 // one of the instant preview image, so we have to indicate to the
1435 // BufferView that a metrics update is needed.
1436 cur.updateFlags(Update::Force);
1440 docstring InsetMathHull::editMessage() const
1442 return _("Math editor mode");
1446 void InsetMathHull::revealCodes(Cursor & cur) const
1448 if (!cur.inMathed())
1450 odocstringstream os;
1452 cur.message(os.str());
1454 // write something to the minibuffer
1455 // translate to latex
1459 string str = os.str();
1461 string::size_type pos = 0;
1463 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1466 else if (*it == '\0') {
1468 pos = it - str.begin();
1474 res = res.substr(pos - 30);
1475 if (res.size() > 60)
1476 res = res.substr(0, 60);
1482 InsetCode InsetMathHull::lyxCode() const
1488 /////////////////////////////////////////////////////////////////////
1492 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1495 // FIXME: completely broken
1496 static InsetMathHull * lastformula = 0;
1497 static CursorBase current = DocIterator(ibegin(nucleus()));
1499 static string laststr;
1501 if (lastformula != this || laststr != str) {
1502 //lyxerr << "reset lastformula to " << this << endl;
1505 current = ibegin(nucleus());
1507 mathed_parse_cell(ar, str);
1511 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1513 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1514 CursorSlice & top = it.back();
1515 MathData const & a = top.asInsetMath()->cell(top.idx_);
1516 if (a.matchpart(ar, top.pos_)) {
1517 bv->cursor().setSelection(it, ar.size());
1519 top.pos_ += ar.size();
1525 //lyxerr << "not found!" << endl;
1532 void InsetMathHull::write(ostream & os) const
1534 odocstringstream oss;
1535 WriteStream wi(oss, false, false);
1538 os << to_utf8(oss.str());
1542 void InsetMathHull::read(Lexer & lex)
1545 mathed_parse_normal(at, lex);
1546 operator=(*at->asHullInset());
1550 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1552 if (0 && display()) {
1556 TextPainter tpain(dim.width(), dim.height());
1557 drawT(tpain, 0, dim.ascent());
1559 // reset metrics cache to "real" values
1561 return tpain.textheight();
1563 odocstringstream oss;
1564 WriteStream wi(oss, false, true);
1567 docstring const str = oss.str();
1574 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1579 if (getType() == hullSimple)
1580 name = from_ascii("inlineequation");
1582 name = from_ascii("informalequation");
1584 docstring bname = name;
1585 if (!label(0).empty())
1586 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1588 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1590 odocstringstream ls;
1591 if (runparams.flavor == OutputParams::XML) {
1592 ms << MTag("alt role='tex' ");
1593 // Workaround for db2latex: db2latex always includes equations with
1594 // \ensuremath{} or \begin{display}\end{display}
1595 // so we strip LyX' math environment
1596 WriteStream wi(ls, false, false);
1597 InsetMathGrid::write(wi);
1598 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1603 InsetMathGrid::mathmlize(ms);
1606 ms << MTag("alt role='tex'");
1607 res = latex(ls, runparams);
1608 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1612 ms << from_ascii("<graphic fileref=\"eqn/");
1613 if (!label(0).empty())
1614 ms << sgml::cleanID(buffer(), runparams, label(0));
1616 ms << sgml::uniqueID(from_ascii("anon"));
1618 if (runparams.flavor == OutputParams::XML)
1619 ms << from_ascii("\"/>");
1621 ms << from_ascii("\">");
1623 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1625 return ms.line() + res;
1629 void InsetMathHull::textString(odocstream & os) const
1631 plaintext(os, OutputParams(0));
1635 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1637 return from_ascii("context-math");