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"
40 #include "OutputParams.h"
41 #include "ParIterator.h"
44 #include "TextPainter.h"
45 #include "TocBackend.h"
47 #include "insets/RenderPreview.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetRef.h"
51 #include "graphics/PreviewImage.h"
52 #include "graphics/PreviewLoader.h"
54 #include "frontends/Painter.h"
56 #include "support/lassert.h"
57 #include "support/debug.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
64 using namespace lyx::support;
68 using cap::grabAndEraseSelection;
72 int getCols(HullType type)
89 // returns position of first relation operator in the array
90 // used for "intelligent splitting"
91 size_t firstRelOp(MathData const & ar)
93 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
95 return it - ar.begin();
100 char const * star(bool numbered)
102 return numbered ? "" : "*";
106 } // end anon namespace
109 HullType hullType(docstring const & s)
111 if (s == "none") return hullNone;
112 if (s == "simple") return hullSimple;
113 if (s == "equation") return hullEquation;
114 if (s == "eqnarray") return hullEqnArray;
115 if (s == "align") return hullAlign;
116 if (s == "alignat") return hullAlignAt;
117 if (s == "xalignat") return hullXAlignAt;
118 if (s == "xxalignat") return hullXXAlignAt;
119 if (s == "multline") return hullMultline;
120 if (s == "gather") return hullGather;
121 if (s == "flalign") return hullFlAlign;
122 if (s == "regexp") return hullRegexp;
123 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
128 docstring hullName(HullType type)
131 case hullNone: return from_ascii("none");
132 case hullSimple: return from_ascii("simple");
133 case hullEquation: return from_ascii("equation");
134 case hullEqnArray: return from_ascii("eqnarray");
135 case hullAlign: return from_ascii("align");
136 case hullAlignAt: return from_ascii("alignat");
137 case hullXAlignAt: return from_ascii("xalignat");
138 case hullXXAlignAt: return from_ascii("xxalignat");
139 case hullMultline: return from_ascii("multline");
140 case hullGather: return from_ascii("gather");
141 case hullFlAlign: return from_ascii("flalign");
142 case hullRegexp: return from_ascii("regexp");
144 lyxerr << "unknown hull type '" << type << "'" << endl;
145 return from_ascii("none");
149 static InsetLabel * dummy_pointer = 0;
151 InsetMathHull::InsetMathHull()
152 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
153 label_(1, dummy_pointer), preview_(new RenderPreview(this))
155 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
156 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
157 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
158 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
164 InsetMathHull::InsetMathHull(HullType type)
165 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
166 label_(1, dummy_pointer), preview_(new RenderPreview(this))
173 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
179 InsetMathHull::~InsetMathHull()
181 for (size_t i = 0; i < label_.size(); ++i)
186 Inset * InsetMathHull::clone() const
188 return new InsetMathHull(*this);
192 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
196 InsetMathGrid::operator=(other);
198 nonum_ = other.nonum_;
199 for (size_t i = 0; i < label_.size(); ++i)
201 label_ = other.label_;
202 for (size_t i = 0; i != label_.size(); ++i) {
204 label_[i] = new InsetLabel(*label_[i]);
206 preview_.reset(new RenderPreview(*other.preview_, this));
212 void InsetMathHull::setBuffer(Buffer & buffer)
215 for (idx_type i = 0, n = nargs(); i != n; ++i) {
216 MathData & data = cell(i);
217 for (size_t j = 0; j != data.size(); ++j)
218 data[j].nucleus()->setBuffer(buffer);
221 for (size_t i = 0; i != label_.size(); ++i) {
223 label_[i]->setBuffer(buffer);
228 void InsetMathHull::updateLabels(ParIterator const & it)
231 //FIXME: buffer_ should be set at creation for this inset! Problem is
232 // This inset is created at too many places (see Parser::parse1() in
236 for (size_t i = 0; i != label_.size(); ++i) {
238 label_[i]->updateLabels(it);
243 void InsetMathHull::addToToc(DocIterator const & pit)
246 //FIXME: buffer_ should be set at creation for this inset! Problem is
247 // This inset is created at too many places (see Parser::parse1() in
252 Toc & toc = buffer().tocBackend().toc("equation");
254 for (row_type row = 0; row != nrows(); ++row) {
258 label_[row]->addToToc(pit);
259 toc.push_back(TocItem(pit, 0, nicelabel(row)));
264 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
270 return InsetMathNest::editXY(cur, x, y);
274 InsetMath::mode_type InsetMathHull::currentMode() const
276 if (type_ == hullNone)
277 return UNDECIDED_MODE;
278 // definitely math mode ...
283 bool InsetMathHull::idxFirst(Cursor & cur) const
291 bool InsetMathHull::idxLast(Cursor & cur) const
293 cur.idx() = nargs() - 1;
294 cur.pos() = cur.lastpos();
299 char InsetMathHull::defaultColAlign(col_type col)
301 if (type_ == hullEqnArray)
303 if (type_ == hullGather)
305 if (type_ >= hullAlign)
306 return "rl"[col & 1];
311 int InsetMathHull::defaultColSpace(col_type col)
313 if (type_ == hullAlign || type_ == hullAlignAt)
315 if (type_ == hullXAlignAt)
316 return (col & 1) ? 20 : 0;
317 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
318 return (col & 1) ? 40 : 0;
323 docstring InsetMathHull::standardFont() const
325 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
329 bool InsetMathHull::previewState(BufferView * bv) const
331 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
332 graphics::PreviewImage const * pimage =
333 preview_->getPreviewImage(bv->buffer());
334 return pimage && pimage->image();
340 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
342 if (previewState(mi.base.bv)) {
343 preview_->metrics(mi, dim);
344 // insert a one pixel gap in front of the formula
347 dim.des += displayMargin();
348 // Cache the inset dimension.
349 setDimCache(mi, dim);
353 FontSetChanger dummy1(mi.base, standardFont());
354 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
356 // let the cells adjust themselves
357 InsetMathGrid::metrics(mi, dim);
360 dim.asc += displayMargin();
361 dim.des += displayMargin();
364 if (numberedType()) {
365 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
367 for (row_type row = 0; row < nrows(); ++row)
368 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
374 // make it at least as high as the current font
377 math_font_max_dim(mi.base.font, asc, des);
378 dim.asc = max(dim.asc, asc);
379 dim.des = max(dim.des, des);
380 // Cache the inset dimension.
381 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
382 setDimCache(mi, dim);
386 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
388 Dimension const dim = dimension(*pi.base.bv);
389 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
390 dim.asc + dim.des - 1, pi.backgroundColor(this));
394 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
396 use_preview_ = previewState(pi.base.bv);
399 // one pixel gap in front
400 preview_->draw(pi, x + 1, y);
401 setPosCache(pi, x, y);
405 FontSetChanger dummy1(pi.base, standardFont());
406 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
407 InsetMathGrid::draw(pi, x + 1, y);
409 if (numberedType()) {
410 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
411 for (row_type row = 0; row < nrows(); ++row) {
412 int const yy = y + rowinfo_[row].offset_;
413 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
414 docstring const nl = nicelabel(row);
418 setPosCache(pi, x, y);
422 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
425 InsetMathGrid::metricsT(mi, dim);
428 WriteStream wi(os, false, true, false);
430 dim.wid = os.str().size();
437 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
440 InsetMathGrid::drawT(pain, x, y);
443 WriteStream wi(os, false, true, false);
445 pain.draw(x, y, os.str().c_str());
450 static docstring latexString(InsetMathHull const & inset)
453 Encoding const * encoding = &(inset.buffer().params().encoding());
454 WriteStream wi(ls, false, true, false, encoding);
460 void InsetMathHull::initUnicodeMath() const
462 // Trigger classification of the unicode symbols in this inset
463 docstring const dummy = latexString(*this);
467 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
469 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
470 docstring const snippet = latexString(*this);
471 preview_->addPreview(snippet, ploader);
476 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
478 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
479 Buffer const * buffer = cur.buffer();
480 docstring const snippet = latexString(*this);
481 preview_->addPreview(snippet, *buffer);
482 preview_->startLoading(*buffer);
483 cur.updateFlags(Update::Force);
489 docstring InsetMathHull::label(row_type row) const
491 LASSERT(row < nrows(), /**/);
492 if (InsetLabel * il = label_[row])
493 return il->screenLabel();
498 void InsetMathHull::label(row_type row, docstring const & label)
500 //lyxerr << "setting label '" << label << "' for row " << row << endl;
504 label_[row] = dummy_pointer;
505 // We need an update of the Buffer reference cache.
506 // This is achieved by updateLabels().
507 buffer().updateLabels();
509 label_[row]->updateCommand(label);
513 InsetCommandParams p(LABEL_CODE);
515 label_[row] = new InsetLabel(p);
517 label_[row]->setBuffer(buffer());
521 void InsetMathHull::numbered(row_type row, bool num)
524 if (nonum_[row] && label_[row]) {
528 // The buffer is set at the end of readInset.
529 // When parsing the inset, buffer_ is 0.
532 // We need an update of the Buffer reference cache.
533 // This is achieved by updateLabels().
534 buffer().updateLabels();
539 bool InsetMathHull::numbered(row_type row) const
545 bool InsetMathHull::ams() const
547 return type_ == hullAlign
548 || type_ == hullFlAlign
549 || type_ == hullMultline
550 || type_ == hullGather
551 || type_ == hullAlignAt
552 || type_ == hullXAlignAt
553 || type_ == hullXXAlignAt;
557 Inset::DisplayType InsetMathHull::display() const
559 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
564 bool InsetMathHull::numberedType() const
566 if (type_ == hullNone)
568 if (type_ == hullSimple)
570 if (type_ == hullXXAlignAt)
572 if (type_ == hullRegexp)
574 for (row_type row = 0; row < nrows(); ++row)
581 void InsetMathHull::validate(LaTeXFeatures & features) const
584 features.require("amsmath");
586 // Validation is necessary only if not using AMS math.
587 // To be safe, we will always run mathedvalidate.
588 //if (features.amsstyle)
591 //features.binom = true;
593 InsetMathGrid::validate(features);
597 void InsetMathHull::header_write(WriteStream & os) const
599 bool n = numberedType();
613 os << "\\begin{equation" << star(n) << "}\n";
623 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
628 os << "\\begin{" << hullName(type_) << star(n) << '}'
629 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
633 os << "\\begin{" << hullName(type_) << '}'
634 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
642 os << "\\begin{unknown" << star(n) << '}';
648 void InsetMathHull::footer_write(WriteStream & os) const
650 bool n = numberedType();
663 os << "\\end{equation" << star(n) << "}\n";
675 os << "\\end{" << hullName(type_) << star(n) << "}\n";
679 os << "\\end{" << hullName(type_) << "}\n";
687 os << "\\end{unknown" << star(n) << '}';
693 bool InsetMathHull::rowChangeOK() const
696 type_ == hullEqnArray || type_ == hullAlign ||
697 type_ == hullFlAlign || type_ == hullAlignAt ||
698 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
699 type_ == hullGather || type_ == hullMultline;
703 bool InsetMathHull::colChangeOK() const
706 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
707 type_ == hullXAlignAt || type_ == hullXXAlignAt;
711 void InsetMathHull::addRow(row_type row)
716 bool numbered = numberedType();
718 if (type_ == hullMultline) {
719 if (row + 1 == nrows()) {
726 nonum_.insert(nonum_.begin() + row + 1, !numbered);
727 label_.insert(label_.begin() + row + 1, dummy_pointer);
730 InsetMathGrid::addRow(row);
734 void InsetMathHull::swapRow(row_type row)
738 if (row + 1 == nrows())
740 // gcc implements the standard std::vector<bool> which is *not* a container:
741 // http://www.gotw.ca/publications/N1185.pdf
742 // As a results, it doesn't like this:
743 // swap(nonum_[row], nonum_[row + 1]);
744 // so we do it manually:
745 bool const b = nonum_[row];
746 nonum_[row] = nonum_[row + 1];
748 swap(label_[row], label_[row + 1]);
749 InsetMathGrid::swapRow(row);
753 void InsetMathHull::delRow(row_type row)
755 if (nrows() <= 1 || !rowChangeOK())
757 if (row + 1 == nrows() && type_ == hullMultline) {
758 bool const b = nonum_[row - 1];
759 nonum_[row - 1] = nonum_[row];
761 swap(label_[row - 1], label_[row]);
762 InsetMathGrid::delRow(row);
765 InsetMathGrid::delRow(row);
766 // The last dummy row has no number info nor a label.
767 // Test nrows() + 1 because we have already erased the row.
768 if (row == nrows() + 1)
770 nonum_.erase(nonum_.begin() + row);
772 label_.erase(label_.begin() + row);
776 void InsetMathHull::addCol(col_type col)
780 InsetMathGrid::addCol(col);
784 void InsetMathHull::delCol(col_type col)
786 if (ncols() <= 1 || !colChangeOK())
788 InsetMathGrid::delCol(col);
792 docstring InsetMathHull::nicelabel(row_type row) const
797 return from_ascii("(#)");
798 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
802 void InsetMathHull::glueall()
805 for (idx_type i = 0; i < nargs(); ++i)
807 *this = InsetMathHull(hullSimple);
813 void InsetMathHull::splitTo2Cols()
815 LASSERT(ncols() == 1, /**/);
816 InsetMathGrid::addCol(1);
817 for (row_type row = 0; row < nrows(); ++row) {
818 idx_type const i = 2 * row;
819 pos_type pos = firstRelOp(cell(i));
820 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
821 cell(i).erase(pos, cell(i).size());
826 void InsetMathHull::splitTo3Cols()
828 LASSERT(ncols() < 3, /**/);
831 InsetMathGrid::addCol(2);
832 for (row_type row = 0; row < nrows(); ++row) {
833 idx_type const i = 3 * row + 1;
834 if (cell(i).size()) {
835 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
836 cell(i).erase(1, cell(i).size());
842 void InsetMathHull::changeCols(col_type cols)
846 else if (ncols() < cols) {
852 while (ncols() < cols)
853 InsetMathGrid::addCol(ncols());
859 for (row_type row = 0; row < nrows(); ++row) {
860 idx_type const i = row * ncols();
861 for (col_type col = cols; col < ncols(); ++col) {
862 cell(i + cols - 1).append(cell(i + col));
866 while (ncols() > cols) {
867 InsetMathGrid::delCol(ncols() - 1);
872 HullType InsetMathHull::getType() const
878 void InsetMathHull::setType(HullType type)
885 void InsetMathHull::mutate(HullType newtype)
887 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
889 // we try to move along the chain
890 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
892 // +-------------------------------------+
893 // we use eqnarray as intermediate type for mutations that are not
894 // directly supported because it handles labels and numbering for
897 if (newtype == type_) {
901 else if (newtype < hullNone) {
906 else if (type_ == hullNone) {
912 else if (type_ == hullSimple) {
913 if (newtype == hullNone) {
917 setType(hullEquation);
923 else if (type_ == hullEquation) {
924 if (newtype < type_) {
928 } else if (newtype == hullEqnArray) {
929 // split it "nicely" on the first relop
931 setType(hullEqnArray);
932 } else if (newtype == hullMultline || newtype == hullGather) {
942 else if (type_ == hullEqnArray) {
943 if (newtype < type_) {
944 // set correct (no)numbering
946 for (row_type row = 0; row < nrows(); ++row) {
953 // set first non-empty label
954 for (row_type row = 0; row < nrows(); ++row) {
956 label_[0] = label_[row];
963 } else { // align & Co.
970 else if (type_ == hullAlign || type_ == hullAlignAt ||
971 type_ == hullXAlignAt || type_ == hullFlAlign) {
972 if (newtype < hullAlign) {
974 setType(hullEqnArray);
976 } else if (newtype == hullGather || newtype == hullMultline) {
979 } else if (newtype == hullXXAlignAt) {
980 for (row_type row = 0; row < nrows(); ++row)
981 numbered(row, false);
988 else if (type_ == hullXXAlignAt) {
989 for (row_type row = 0; row < nrows(); ++row)
990 numbered(row, false);
991 if (newtype < hullAlign) {
993 setType(hullEqnArray);
995 } else if (newtype == hullGather || newtype == hullMultline) {
1003 else if (type_ == hullMultline || type_ == hullGather) {
1004 if (newtype == hullGather || newtype == hullMultline)
1006 else if (newtype == hullAlign || newtype == hullFlAlign ||
1007 newtype == hullAlignAt || newtype == hullXAlignAt) {
1010 } else if (newtype == hullXXAlignAt) {
1012 for (row_type row = 0; row < nrows(); ++row)
1013 numbered(row, false);
1017 setType(hullEqnArray);
1023 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1024 << "' to '" << to_utf8(hullName(newtype))
1025 << "' not implemented" << endl;
1030 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1033 if (numberedType()) {
1034 if (label_[row] && !nonum_[row])
1035 res += "\\label{" + label_[row]->getParam("name") + '}';
1036 if (nonum_[row] && (type_ != hullMultline))
1037 res += "\\nonumber ";
1039 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1043 void InsetMathHull::write(WriteStream & os) const
1045 ModeSpecifier specifier(os, MATH_MODE);
1047 InsetMathGrid::write(os);
1052 void InsetMathHull::normalize(NormalStream & os) const
1054 os << "[formula " << hullName(type_) << ' ';
1055 InsetMathGrid::normalize(os);
1060 void InsetMathHull::mathmlize(MathStream & os) const
1062 InsetMathGrid::mathmlize(os);
1066 void InsetMathHull::infoize(odocstream & os) const
1068 os << "Type: " << hullName(type_);
1072 void InsetMathHull::check() const
1074 LASSERT(nonum_.size() == nrows(), /**/);
1075 LASSERT(label_.size() == nrows(), /**/);
1079 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1083 idocstringstream iss(func.argument());
1084 iss >> dlang >> extra;
1086 extra = from_ascii("noextra");
1087 string const lang = to_ascii(dlang);
1089 // FIXME: temporarily disabled
1090 //if (cur.selection()) {
1093 // lyxerr << "use selection: " << ar << endl;
1094 // insert(pipeThroughExtern(lang, extra, ar));
1099 eq.push_back(MathAtom(new InsetMathChar('=')));
1101 // go to first item in line
1102 cur.idx() -= cur.idx() % ncols();
1105 if (getType() == hullSimple) {
1106 size_type pos = cur.cell().find_last(eq);
1108 if (cur.inMathed() && cur.selection()) {
1109 asArray(grabAndEraseSelection(cur), ar);
1110 } else if (pos == cur.cell().size()) {
1112 lyxerr << "use whole cell: " << ar << endl;
1114 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1115 lyxerr << "use partial cell form pos: " << pos << endl;
1117 cur.cell().append(eq);
1118 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1119 cur.pos() = cur.lastpos();
1123 if (getType() == hullEquation) {
1124 lyxerr << "use equation inset" << endl;
1125 mutate(hullEqnArray);
1126 MathData & ar = cur.cell();
1127 lyxerr << "use cell: " << ar << endl;
1131 cur.cell() = pipeThroughExtern(lang, extra, ar);
1132 // move to end of line
1133 cur.pos() = cur.lastpos();
1138 lyxerr << "use eqnarray" << endl;
1139 cur.idx() += 2 - cur.idx() % ncols();
1141 MathData ar = cur.cell();
1142 lyxerr << "use cell: " << ar << endl;
1143 // FIXME: temporarily disabled
1149 cur.cell() = pipeThroughExtern(lang, extra, ar);
1150 cur.pos() = cur.lastpos();
1155 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1157 //lyxerr << "action: " << cmd.action << endl;
1158 switch (cmd.action) {
1160 case LFUN_FINISHED_BACKWARD:
1161 case LFUN_FINISHED_FORWARD:
1162 case LFUN_FINISHED_RIGHT:
1163 case LFUN_FINISHED_LEFT:
1164 //lyxerr << "action: " << cmd.action << endl;
1165 InsetMathGrid::doDispatch(cur, cmd);
1169 case LFUN_BREAK_PARAGRAPH:
1170 // just swallow this
1173 case LFUN_NEWLINE_INSERT:
1174 // some magic for the common case
1175 if (type_ == hullSimple || type_ == hullEquation) {
1176 cur.recordUndoInset();
1178 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1179 mutate(align ? hullAlign : hullEqnArray);
1180 cur.idx() = nrows() * ncols() - 1;
1181 cur.pos() = cur.lastpos();
1183 InsetMathGrid::doDispatch(cur, cmd);
1186 case LFUN_MATH_NUMBER_TOGGLE: {
1187 //lyxerr << "toggling all numbers" << endl;
1188 cur.recordUndoInset();
1189 bool old = numberedType();
1190 if (type_ == hullMultline)
1191 numbered(nrows() - 1, !old);
1193 for (row_type row = 0; row < nrows(); ++row)
1194 numbered(row, !old);
1196 cur.message(old ? _("No number") : _("Number"));
1200 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1201 cur.recordUndoInset();
1202 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1203 bool old = numbered(r);
1204 cur.message(old ? _("No number") : _("Number"));
1209 case LFUN_LABEL_INSERT: {
1210 cur.recordUndoInset();
1211 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1212 docstring old_label = label(r);
1213 docstring const default_label = from_ascii(
1214 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1215 if (old_label.empty())
1216 old_label = default_label;
1218 InsetCommandParams p(LABEL_CODE);
1219 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1220 string const data = InsetCommand::params2string("label", p);
1222 if (cmd.argument().empty())
1223 cur.bv().showDialog("label", data);
1225 FuncRequest fr(LFUN_INSET_INSERT, data);
1231 case LFUN_LABEL_COPY_AS_REF: {
1233 if (cmd.argument().empty() && &cur.inset() == this)
1234 // if there is no argument and we're inside math, we retrieve
1235 // the row number from the cursor position.
1236 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1238 // if there is an argument, find the corresponding label, else
1239 // check whether there is at least one label.
1240 for (row = 0; row != nrows(); ++row)
1241 if (!nonum_[row] && label_[row]
1242 && (cmd.argument().empty() || label(row) == cmd.argument()))
1249 InsetCommandParams p(REF_CODE, "ref");
1250 p["reference"] = label(row);
1251 cap::clearSelection();
1252 cap::copyInset(cur, new InsetRef(*cur.buffer(), p), label(row));
1256 case LFUN_WORD_DELETE_FORWARD:
1257 case LFUN_CHAR_DELETE_FORWARD:
1258 if (col(cur.idx()) + 1 == ncols()
1259 && cur.pos() == cur.lastpos()) {
1260 if (!label(row(cur.idx())).empty()) {
1261 cur.recordUndoInset();
1262 label(row(cur.idx()), docstring());
1263 } else if (numbered(row(cur.idx()))) {
1264 cur.recordUndoInset();
1265 numbered(row(cur.idx()), false);
1267 InsetMathGrid::doDispatch(cur, cmd);
1271 InsetMathGrid::doDispatch(cur, cmd);
1276 case LFUN_INSET_INSERT: {
1277 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1278 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1279 string const name = cmd.getArg(0);
1280 if (name == "label") {
1281 InsetCommandParams p(LABEL_CODE);
1282 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1283 docstring str = p["name"];
1284 cur.recordUndoInset();
1285 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1289 docstring old = label(r);
1292 // The label will take care of the reference update.
1296 // Newly created inset so initialize it.
1297 label_[r]->initView();
1302 InsetMathGrid::doDispatch(cur, cmd);
1306 case LFUN_MATH_EXTERN:
1307 cur.recordUndoInset();
1311 case LFUN_MATH_MUTATE: {
1312 cur.recordUndoInset();
1313 row_type row = cur.row();
1314 col_type col = cur.col();
1315 mutate(hullType(cmd.argument()));
1316 cur.idx() = row * ncols() + col;
1317 if (cur.idx() > cur.lastidx()) {
1318 cur.idx() = cur.lastidx();
1319 cur.pos() = cur.lastpos();
1321 if (cur.pos() > cur.lastpos())
1322 cur.pos() = cur.lastpos();
1324 // FIXME: find some more clever handling of the selection,
1325 // i.e. preserve it.
1326 cur.clearSelection();
1327 //cur.dispatched(FINISHED);
1331 case LFUN_MATH_DISPLAY: {
1332 cur.recordUndoInset();
1333 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1335 cur.pos() = cur.lastpos();
1336 //cur.dispatched(FINISHED);
1341 InsetMathGrid::doDispatch(cur, cmd);
1347 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1348 FuncStatus & status) const
1350 switch (cmd.action) {
1351 case LFUN_FINISHED_BACKWARD:
1352 case LFUN_FINISHED_FORWARD:
1353 case LFUN_FINISHED_RIGHT:
1354 case LFUN_FINISHED_LEFT:
1357 case LFUN_NEWLINE_INSERT:
1358 case LFUN_MATH_EXTERN:
1359 case LFUN_MATH_DISPLAY:
1361 status.setEnabled(true);
1364 case LFUN_MATH_MUTATE: {
1365 HullType ht = hullType(cmd.argument());
1366 status.setOnOff(type_ == ht);
1367 status.setEnabled(true);
1371 case LFUN_MATH_NUMBER_TOGGLE:
1372 // FIXME: what is the right test, this or the one of
1374 status.setEnabled(display());
1375 status.setOnOff(numberedType());
1378 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1379 // FIXME: what is the right test, this or the one of
1381 bool const enable = (type_ == hullMultline)
1382 ? (nrows() - 1 == cur.row())
1383 : display() != Inline && nrows() > 1;
1384 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1385 status.setEnabled(enable);
1386 status.setOnOff(enable && numbered(r));
1390 case LFUN_LABEL_INSERT:
1391 status.setEnabled(type_ != hullSimple);
1394 case LFUN_LABEL_COPY_AS_REF: {
1395 bool enabled = false;
1397 if (cmd.argument().empty() && &cur.inset() == this) {
1398 // if there is no argument and we're inside math, we retrieve
1399 // the row number from the cursor position.
1400 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1401 enabled = numberedType() && label_[row] && !nonum_[row];
1403 // if there is an argument, find the corresponding label, else
1404 // check whether there is at least one label.
1405 for (row_type row = 0; row != nrows(); ++row) {
1406 if (!nonum_[row] && label_[row] &&
1407 (cmd.argument().empty() || label(row) == cmd.argument())) {
1413 status.setEnabled(enabled);
1417 case LFUN_INSET_INSERT:
1418 if (cmd.getArg(0) == "label") {
1419 status.setEnabled(type_ != hullSimple);
1422 return InsetMathGrid::getStatus(cur, cmd, status);
1424 case LFUN_TABULAR_FEATURE: {
1425 istringstream is(to_utf8(cmd.argument()));
1429 && (s == "append-row"
1430 || s == "delete-row"
1431 || s == "copy-row")) {
1432 status.message(bformat(
1433 from_utf8(N_("Can't change number of rows in '%1$s'")),
1435 status.setEnabled(false);
1439 && (s == "append-column"
1440 || s == "delete-column"
1441 || s == "copy-column")) {
1442 status.message(bformat(
1443 from_utf8(N_("Can't change number of columns in '%1$s'")),
1445 status.setEnabled(false);
1448 if ((type_ == hullSimple
1449 || type_ == hullEquation
1450 || type_ == hullNone) &&
1451 (s == "add-hline-above" || s == "add-hline-below")) {
1452 status.message(bformat(
1453 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1455 status.setEnabled(false);
1458 if (s == "add-vline-left" || s == "add-vline-right") {
1459 status.message(bformat(
1460 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1462 status.setEnabled(false);
1465 if (s == "valign-top" || s == "valign-middle"
1466 || s == "valign-bottom" || s == "align-left"
1467 || s == "align-center" || s == "align-right") {
1468 status.setEnabled(false);
1471 return InsetMathGrid::getStatus(cur, cmd, status);
1475 return InsetMathGrid::getStatus(cur, cmd, status);
1478 // This cannot really happen, but inserted to shut-up gcc
1479 return InsetMathGrid::getStatus(cur, cmd, status);
1483 /////////////////////////////////////////////////////////////////////
1487 // simply scrap this function if you want
1488 void InsetMathHull::mutateToText()
1491 // translate to latex
1493 latex(os, false, false);
1494 string str = os.str();
1497 Text * lt = view_->cursor().innerText();
1498 string::const_iterator cit = str.begin();
1499 string::const_iterator end = str.end();
1500 for (; cit != end; ++cit)
1501 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1504 //dispatch(LFUN_ESCAPE);
1509 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1510 docstring const & font)
1512 // this whole function is a hack and won't work for incremental font
1515 if (cur.inset().asInsetMath()->name() == font)
1516 cur.handleFont(to_utf8(font));
1518 cur.handleNest(createInsetMath(font));
1524 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1529 font.fromString(to_utf8(arg), b);
1530 if (font.fontInfo().color() != Color_inherit) {
1531 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1532 cur.handleNest(at, 0);
1537 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1540 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1541 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1542 enter_front ? idxFirst(cur) : idxLast(cur);
1543 // The inset formula dimension is not necessarily the same as the
1544 // one of the instant preview image, so we have to indicate to the
1545 // BufferView that a metrics update is needed.
1546 cur.updateFlags(Update::Force);
1550 docstring InsetMathHull::editMessage() const
1552 return _("Math editor mode");
1556 void InsetMathHull::revealCodes(Cursor & cur) const
1558 if (!cur.inMathed())
1560 odocstringstream os;
1562 cur.message(os.str());
1564 // write something to the minibuffer
1565 // translate to latex
1569 string str = os.str();
1571 string::size_type pos = 0;
1573 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1576 else if (*it == '\0') {
1578 pos = it - str.begin();
1584 res = res.substr(pos - 30);
1585 if (res.size() > 60)
1586 res = res.substr(0, 60);
1592 InsetCode InsetMathHull::lyxCode() const
1598 /////////////////////////////////////////////////////////////////////
1602 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1605 // FIXME: completely broken
1606 static InsetMathHull * lastformula = 0;
1607 static CursorBase current = DocIterator(ibegin(nucleus()));
1609 static string laststr;
1611 if (lastformula != this || laststr != str) {
1612 //lyxerr << "reset lastformula to " << this << endl;
1615 current = ibegin(nucleus());
1617 mathed_parse_cell(ar, str);
1621 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1623 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1624 CursorSlice & top = it.back();
1625 MathData const & a = top.asInsetMath()->cell(top.idx_);
1626 if (a.matchpart(ar, top.pos_)) {
1627 bv->cursor().setSelection(it, ar.size());
1629 top.pos_ += ar.size();
1635 //lyxerr << "not found!" << endl;
1642 void InsetMathHull::write(ostream & os) const
1644 odocstringstream oss;
1645 WriteStream wi(oss, false, false, false);
1648 os << to_utf8(oss.str());
1652 void InsetMathHull::read(Lexer & lex)
1655 mathed_parse_normal(at, lex);
1656 operator=(*at->asHullInset());
1660 bool InsetMathHull::readQuiet(Lexer & lex)
1663 bool result = mathed_parse_normal(at, lex, Parse::QUIET);
1664 operator=(*at->asHullInset());
1669 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1671 if (0 && display()) {
1675 TextPainter tpain(dim.width(), dim.height());
1676 drawT(tpain, 0, dim.ascent());
1678 // reset metrics cache to "real" values
1680 return tpain.textheight();
1682 odocstringstream oss;
1683 WriteStream wi(oss, false, true, false, runparams.encoding);
1686 docstring const str = oss.str();
1693 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1698 if (getType() == hullSimple)
1699 name = from_ascii("inlineequation");
1701 name = from_ascii("informalequation");
1703 docstring bname = name;
1704 if (!label(0).empty())
1705 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1707 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1709 odocstringstream ls;
1710 if (runparams.flavor == OutputParams::XML) {
1711 ms << MTag("alt role='tex' ");
1712 // Workaround for db2latex: db2latex always includes equations with
1713 // \ensuremath{} or \begin{display}\end{display}
1714 // so we strip LyX' math environment
1715 WriteStream wi(ls, false, false, false, runparams.encoding);
1716 InsetMathGrid::write(wi);
1717 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1722 InsetMathGrid::mathmlize(ms);
1725 ms << MTag("alt role='tex'");
1726 res = latex(ls, runparams);
1727 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1731 ms << from_ascii("<graphic fileref=\"eqn/");
1732 if (!label(0).empty())
1733 ms << sgml::cleanID(buffer(), runparams, label(0));
1735 ms << sgml::uniqueID(from_ascii("anon"));
1737 if (runparams.flavor == OutputParams::XML)
1738 ms << from_ascii("\"/>");
1740 ms << from_ascii("\">");
1742 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1744 return ms.line() + res;
1748 void InsetMathHull::textString(odocstream & os) const
1750 plaintext(os, OutputParams(0));
1754 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1756 return from_ascii("context-math");