2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CutAndPaste.h"
32 #include "FuncStatus.h"
33 #include "LaTeXFeatures.h"
35 #include "DispatchResult.h"
36 #include "FuncRequest.h"
38 #include "OutputParams.h"
39 #include "ParIterator.h"
42 #include "TextPainter.h"
43 #include "TocBackend.h"
45 #include "insets/RenderPreview.h"
46 #include "insets/InsetLabel.h"
48 #include "graphics/PreviewImage.h"
49 #include "graphics/PreviewLoader.h"
51 #include "frontends/Painter.h"
53 #include "support/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
60 using namespace lyx::support;
64 using cap::grabAndEraseSelection;
68 int getCols(HullType type)
85 // returns position of first relation operator in the array
86 // used for "intelligent splitting"
87 size_t firstRelOp(MathData const & ar)
89 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
91 return it - ar.begin();
96 char const * star(bool numbered)
98 return numbered ? "" : "*";
102 } // end anon namespace
105 HullType hullType(docstring const & s)
107 if (s == "none") return hullNone;
108 if (s == "simple") return hullSimple;
109 if (s == "equation") return hullEquation;
110 if (s == "eqnarray") return hullEqnArray;
111 if (s == "align") return hullAlign;
112 if (s == "alignat") return hullAlignAt;
113 if (s == "xalignat") return hullXAlignAt;
114 if (s == "xxalignat") return hullXXAlignAt;
115 if (s == "multline") return hullMultline;
116 if (s == "gather") return hullGather;
117 if (s == "flalign") return hullFlAlign;
118 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
123 docstring hullName(HullType type)
126 case hullNone: return from_ascii("none");
127 case hullSimple: return from_ascii("simple");
128 case hullEquation: return from_ascii("equation");
129 case hullEqnArray: return from_ascii("eqnarray");
130 case hullAlign: return from_ascii("align");
131 case hullAlignAt: return from_ascii("alignat");
132 case hullXAlignAt: return from_ascii("xalignat");
133 case hullXXAlignAt: return from_ascii("xxalignat");
134 case hullMultline: return from_ascii("multline");
135 case hullGather: return from_ascii("gather");
136 case hullFlAlign: return from_ascii("flalign");
138 lyxerr << "unknown hull type '" << type << "'" << endl;
139 return from_ascii("none");
143 static InsetLabel * dummy_pointer = 0;
145 InsetMathHull::InsetMathHull()
146 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false), label_(1, dummy_pointer),
147 preview_(new RenderPreview(this))
149 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
150 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
151 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
152 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
158 InsetMathHull::InsetMathHull(HullType type)
159 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false), label_(1, dummy_pointer),
160 preview_(new RenderPreview(this))
167 InsetMathHull::InsetMathHull(InsetMathHull const & other)
173 InsetMathHull::~InsetMathHull()
175 for (size_t i = 0; i < label_.size(); ++i) {
182 Inset * InsetMathHull::clone() const
184 return new InsetMathHull(*this);
188 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
192 InsetMathGrid::operator=(other);
194 nonum_ = other.nonum_;
195 for (size_t i = 0; i < label_.size(); ++i) {
199 label_ = other.label_;
200 for (size_t i = 0; i != label_.size(); ++i) {
202 label_[i] = new InsetLabel(*label_[i]);
204 preview_.reset(new RenderPreview(*other.preview_, this));
210 void InsetMathHull::setBuffer(Buffer & buffer)
213 for (size_t i = 0; i != label_.size(); ++i) {
215 label_[i]->setBuffer(buffer);
220 void InsetMathHull::updateLabels(ParIterator const & it)
223 //FIXME: buffer_ should be set at creation for this inset! Problem is
224 // This inset is created at too many places (see Parser::parse1() in
228 for (size_t i = 0; i != label_.size(); ++i) {
230 label_[i]->updateLabels(it);
235 void InsetMathHull::addToToc(ParConstIterator const & pit) const
238 //FIXME: buffer_ should be set at creation for this inset! Problem is
239 // This inset is created at too many places (see Parser::parse1() in
244 // FIXME: it would be way better to directly use InsetLabel instead of this
245 // label list. But it should be possible to copy&paste the code in
246 // InsetLabel::addToToc() anyway.
248 Toc & toc = buffer().tocBackend().toc("equation");
250 for (row_type row = 0; row != nrows(); ++row) {
254 label_[row]->addToToc(pit);
255 toc.push_back(TocItem(pit, 0, nicelabel(row)));
260 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
266 return InsetMathNest::editXY(cur, x, y);
270 InsetMath::mode_type InsetMathHull::currentMode() const
272 if (type_ == hullNone)
273 return UNDECIDED_MODE;
274 // definitely math mode ...
279 bool InsetMathHull::idxFirst(Cursor & cur) const
287 bool InsetMathHull::idxLast(Cursor & cur) const
289 cur.idx() = nargs() - 1;
290 cur.pos() = cur.lastpos();
295 char InsetMathHull::defaultColAlign(col_type col)
297 if (type_ == hullEqnArray)
299 if (type_ == hullGather)
301 if (type_ >= hullAlign)
302 return "rl"[col & 1];
307 int InsetMathHull::defaultColSpace(col_type col)
309 if (type_ == hullAlign || type_ == hullAlignAt)
311 if (type_ == hullXAlignAt)
312 return (col & 1) ? 20 : 0;
313 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
314 return (col & 1) ? 40 : 0;
319 docstring InsetMathHull::standardFont() const
321 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
325 bool InsetMathHull::previewState(BufferView * bv) const
327 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
328 graphics::PreviewImage const * pimage =
329 preview_->getPreviewImage(bv->buffer());
330 return pimage && pimage->image();
336 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
338 if (previewState(mi.base.bv)) {
339 preview_->metrics(mi, dim);
340 // insert a one pixel gap in front of the formula
343 dim.des += displayMargin();
344 // Cache the inset dimension.
345 setDimCache(mi, dim);
349 FontSetChanger dummy1(mi.base, standardFont());
350 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
352 // let the cells adjust themselves
353 InsetMathGrid::metrics(mi, dim);
356 dim.asc += displayMargin();
357 dim.des += displayMargin();
360 if (numberedType()) {
361 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
363 for (row_type row = 0; row < nrows(); ++row)
364 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
370 // make it at least as high as the current font
373 math_font_max_dim(mi.base.font, asc, des);
374 dim.asc = max(dim.asc, asc);
375 dim.des = max(dim.des, des);
376 // Cache the inset dimension.
377 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
378 setDimCache(mi, dim);
382 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
384 use_preview_ = previewState(pi.base.bv);
385 Dimension const dim = dimension(*pi.base.bv);
387 // background of mathed under focus is not painted because
388 // selection at the top level of nested inset is difficult to handle.
389 if (!editing(pi.base.bv))
390 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
391 dim.asc + dim.des - 1, Color_mathbg);
394 // one pixel gap in front
395 preview_->draw(pi, x + 1, y);
396 setPosCache(pi, x, y);
400 FontSetChanger dummy1(pi.base, standardFont());
401 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
402 InsetMathGrid::draw(pi, x + 1, y);
404 if (numberedType()) {
405 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
406 for (row_type row = 0; row < nrows(); ++row) {
407 int const yy = y + rowinfo_[row].offset_;
408 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
409 docstring const nl = nicelabel(row);
413 setPosCache(pi, x, y);
417 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
420 InsetMathGrid::metricsT(mi, dim);
423 WriteStream wi(os, false, true);
425 dim.wid = os.str().size();
432 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
435 InsetMathGrid::drawT(pain, x, y);
438 WriteStream wi(os, false, true);
440 pain.draw(x, y, os.str().c_str());
447 docstring const latex_string(InsetMathHull const & inset)
450 WriteStream wi(ls, false, false);
458 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
460 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
461 docstring const snippet = latex_string(*this);
462 preview_->addPreview(snippet, ploader);
467 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
469 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
470 Buffer const & buffer = cur.buffer();
471 docstring const snippet = latex_string(*this);
472 preview_->addPreview(snippet, buffer);
473 preview_->startLoading(buffer);
474 cur.updateFlags(Update::Force);
480 docstring InsetMathHull::label(row_type row) const
482 BOOST_ASSERT(row < nrows());
483 if (InsetLabel * il = label_[row])
484 return il->screenLabel();
489 void InsetMathHull::label(row_type row, docstring const & label)
491 //lyxerr << "setting label '" << label << "' for row " << row << endl;
493 label_[row]->updateCommand(label);
496 InsetCommandParams p(LABEL_CODE);
498 label_[row] = new InsetLabel(p);
500 label_[row]->setBuffer(buffer());
504 void InsetMathHull::numbered(row_type row, bool num)
507 if (nonum_[row] && label_[row]) {
514 bool InsetMathHull::numbered(row_type row) const
520 bool InsetMathHull::ams() const
523 type_ == hullAlign ||
524 type_ == hullFlAlign ||
525 type_ == hullMultline ||
526 type_ == hullGather ||
527 type_ == hullAlignAt ||
528 type_ == hullXAlignAt ||
529 type_ == hullXXAlignAt;
533 Inset::DisplayType InsetMathHull::display() const
535 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
539 void InsetMathHull::getLabelList(vector<docstring> & labels) const
541 for (row_type row = 0; row < nrows(); ++row)
542 if (label_[row] && !nonum_[row])
543 labels.push_back(label_[row]->screenLabel());
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 doesn't like this:
703 // swap(nonum_[row], nonum_[row + 1]);
704 // so we do it manually:
705 bool const b = nonum_[row];
706 nonum_[row] = nonum_[row + 1]
708 swap(label_[row], label_[row + 1]);
709 InsetMathGrid::swapRow(row);
713 void InsetMathHull::delRow(row_type row)
715 if (nrows() <= 1 || !rowChangeOK())
717 InsetMathGrid::delRow(row);
718 // The last dummy row has no number info nor a label.
719 // Test nrows() + 1 because we have already erased the row.
720 if (row == nrows() + 1)
722 nonum_.erase(nonum_.begin() + row);
725 label_.erase(label_.begin() + row);
729 void InsetMathHull::addCol(col_type col)
733 InsetMathGrid::addCol(col);
737 void InsetMathHull::delCol(col_type col)
739 if (ncols() <= 1 || !colChangeOK())
741 InsetMathGrid::delCol(col);
745 docstring InsetMathHull::nicelabel(row_type row) const
750 return from_ascii("(#)");
751 return '(' + label_[row]->screenLabel() + ')';
755 void InsetMathHull::glueall()
758 for (idx_type i = 0; i < nargs(); ++i)
760 *this = InsetMathHull(hullSimple);
766 void InsetMathHull::splitTo2Cols()
768 BOOST_ASSERT(ncols() == 1);
769 InsetMathGrid::addCol(1);
770 for (row_type row = 0; row < nrows(); ++row) {
771 idx_type const i = 2 * row;
772 pos_type pos = firstRelOp(cell(i));
773 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
774 cell(i).erase(pos, cell(i).size());
779 void InsetMathHull::splitTo3Cols()
781 BOOST_ASSERT(ncols() < 3);
784 InsetMathGrid::addCol(2);
785 for (row_type row = 0; row < nrows(); ++row) {
786 idx_type const i = 3 * row + 1;
787 if (cell(i).size()) {
788 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
789 cell(i).erase(1, cell(i).size());
795 void InsetMathHull::changeCols(col_type cols)
799 else if (ncols() < cols) {
805 while (ncols() < cols)
806 InsetMathGrid::addCol(ncols());
812 for (row_type row = 0; row < nrows(); ++row) {
813 idx_type const i = row * ncols();
814 for (col_type col = cols; col < ncols(); ++col) {
815 cell(i + cols - 1).append(cell(i + col));
819 while (ncols() > cols) {
820 InsetMathGrid::delCol(ncols() - 1);
825 HullType InsetMathHull::getType() const
831 void InsetMathHull::setType(HullType type)
838 void InsetMathHull::mutate(HullType newtype)
840 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
842 // we try to move along the chain
843 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
845 // +-------------------------------------+
846 // we use eqnarray as intermediate type for mutations that are not
847 // directly supported because it handles labels and numbering for
850 if (newtype == type_) {
854 else if (newtype < hullNone) {
859 else if (type_ == hullNone) {
865 else if (type_ == hullSimple) {
866 if (newtype == hullNone) {
870 setType(hullEquation);
876 else if (type_ == hullEquation) {
877 if (newtype < type_) {
881 } else if (newtype == hullEqnArray) {
882 // split it "nicely" on the first relop
884 setType(hullEqnArray);
885 } else if (newtype == hullMultline || newtype == hullGather) {
895 else if (type_ == hullEqnArray) {
896 if (newtype < type_) {
897 // set correct (no)numbering
899 for (row_type row = 0; row < nrows(); ++row) {
906 // set first non-empty label
907 for (row_type row = 0; row < nrows(); ++row) {
909 label_[0] = label_[row];
916 } else { // align & Co.
923 else if (type_ == hullAlign || type_ == hullAlignAt ||
924 type_ == hullXAlignAt || type_ == hullFlAlign) {
925 if (newtype < hullAlign) {
927 setType(hullEqnArray);
929 } else if (newtype == hullGather || newtype == hullMultline) {
932 } else if (newtype == hullXXAlignAt) {
933 for (row_type row = 0; row < nrows(); ++row)
934 numbered(row, false);
941 else if (type_ == hullXXAlignAt) {
942 for (row_type row = 0; row < nrows(); ++row)
943 numbered(row, false);
944 if (newtype < hullAlign) {
946 setType(hullEqnArray);
948 } else if (newtype == hullGather || newtype == hullMultline) {
956 else if (type_ == hullMultline || type_ == hullGather) {
957 if (newtype == hullGather || newtype == hullMultline)
959 else if (newtype == hullAlign || newtype == hullFlAlign ||
960 newtype == hullAlignAt || newtype == hullXAlignAt) {
963 } else if (newtype == hullXXAlignAt) {
965 for (row_type row = 0; row < nrows(); ++row)
966 numbered(row, false);
970 setType(hullEqnArray);
976 lyxerr << "mutation from '" << to_utf8(hullName(type_))
977 << "' to '" << to_utf8(hullName(newtype))
978 << "' not implemented" << endl;
983 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
986 if (numberedType()) {
987 if (label_[row] && !nonum_[row])
988 res += "\\label{" + label_[row]->getParam("name") + '}';
989 if (nonum_[row] && (type_ != hullMultline))
990 res += "\\nonumber ";
992 return res + InsetMathGrid::eolString(row, emptyline, fragile);
996 void InsetMathHull::write(WriteStream & os) const
999 InsetMathGrid::write(os);
1004 void InsetMathHull::normalize(NormalStream & os) const
1006 os << "[formula " << hullName(type_) << ' ';
1007 InsetMathGrid::normalize(os);
1012 void InsetMathHull::mathmlize(MathStream & os) const
1014 InsetMathGrid::mathmlize(os);
1018 void InsetMathHull::infoize(odocstream & os) const
1020 os << "Type: " << hullName(type_);
1024 void InsetMathHull::check() const
1026 BOOST_ASSERT(nonum_.size() == nrows());
1027 BOOST_ASSERT(label_.size() == nrows());
1031 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1035 idocstringstream iss(func.argument());
1036 iss >> dlang >> extra;
1038 extra = from_ascii("noextra");
1039 string const lang = to_ascii(dlang);
1041 // FIXME: temporarily disabled
1042 //if (cur.selection()) {
1045 // lyxerr << "use selection: " << ar << endl;
1046 // insert(pipeThroughExtern(lang, extra, ar));
1051 eq.push_back(MathAtom(new InsetMathChar('=')));
1053 // go to first item in line
1054 cur.idx() -= cur.idx() % ncols();
1057 if (getType() == hullSimple) {
1058 size_type pos = cur.cell().find_last(eq);
1060 if (cur.inMathed() && cur.selection()) {
1061 asArray(grabAndEraseSelection(cur), ar);
1062 } else if (pos == cur.cell().size()) {
1064 lyxerr << "use whole cell: " << ar << endl;
1066 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1067 lyxerr << "use partial cell form pos: " << pos << endl;
1069 cur.cell().append(eq);
1070 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1071 cur.pos() = cur.lastpos();
1075 if (getType() == hullEquation) {
1076 lyxerr << "use equation inset" << endl;
1077 mutate(hullEqnArray);
1078 MathData & ar = cur.cell();
1079 lyxerr << "use cell: " << ar << endl;
1083 cur.cell() = pipeThroughExtern(lang, extra, ar);
1084 // move to end of line
1085 cur.pos() = cur.lastpos();
1090 lyxerr << "use eqnarray" << endl;
1091 cur.idx() += 2 - cur.idx() % ncols();
1093 MathData ar = cur.cell();
1094 lyxerr << "use cell: " << ar << endl;
1095 // FIXME: temporarily disabled
1101 cur.cell() = pipeThroughExtern(lang, extra, ar);
1102 cur.pos() = cur.lastpos();
1107 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1109 //lyxerr << "action: " << cmd.action << endl;
1110 switch (cmd.action) {
1112 case LFUN_FINISHED_BACKWARD:
1113 case LFUN_FINISHED_FORWARD:
1114 case LFUN_FINISHED_RIGHT:
1115 case LFUN_FINISHED_LEFT:
1116 //lyxerr << "action: " << cmd.action << endl;
1117 InsetMathGrid::doDispatch(cur, cmd);
1121 case LFUN_BREAK_PARAGRAPH:
1122 // just swallow this
1126 // some magic for the common case
1127 if (type_ == hullSimple || type_ == hullEquation) {
1128 cur.recordUndoInset();
1130 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1131 mutate(align ? hullAlign : hullEqnArray);
1132 cur.idx() = nrows() * ncols() - 1;
1133 cur.pos() = cur.lastpos();
1135 InsetMathGrid::doDispatch(cur, cmd);
1138 case LFUN_MATH_NUMBER_TOGGLE: {
1139 //lyxerr << "toggling all numbers" << endl;
1140 cur.recordUndoInset();
1141 bool old = numberedType();
1142 if (type_ == hullMultline)
1143 numbered(nrows() - 1, !old);
1145 for (row_type row = 0; row < nrows(); ++row)
1146 numbered(row, !old);
1148 cur.message(old ? _("No number") : _("Number"));
1152 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1153 cur.recordUndoInset();
1154 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1155 bool old = numbered(r);
1156 cur.message(old ? _("No number") : _("Number"));
1161 case LFUN_LABEL_INSERT: {
1162 cur.recordUndoInset();
1163 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1164 docstring old_label = label(r);
1165 docstring const default_label = from_ascii(
1166 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1167 if (old_label.empty())
1168 old_label = default_label;
1170 InsetCommandParams p(LABEL_CODE);
1171 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1172 string const data = InsetCommandMailer::params2string("label", p);
1174 if (cmd.argument().empty())
1175 cur.bv().showDialog("label", data);
1177 FuncRequest fr(LFUN_INSET_INSERT, data);
1183 case LFUN_INSET_INSERT: {
1184 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1185 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1186 string const name = cmd.getArg(0);
1187 if (name == "label") {
1188 InsetCommandParams p(LABEL_CODE);
1189 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1190 docstring str = p["name"];
1191 cur.recordUndoInset();
1192 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1196 docstring old = label(r);
1199 // The label will take care of the reference update.
1203 // Newly created inset so initialize it.
1204 label_[r]->initView();
1209 InsetMathGrid::doDispatch(cur, cmd);
1213 case LFUN_MATH_EXTERN:
1214 cur.recordUndoInset();
1218 case LFUN_MATH_MUTATE: {
1219 cur.recordUndoInset();
1220 row_type row = cur.row();
1221 col_type col = cur.col();
1222 mutate(hullType(cmd.argument()));
1223 cur.idx() = row * ncols() + col;
1224 if (cur.idx() > cur.lastidx()) {
1225 cur.idx() = cur.lastidx();
1226 cur.pos() = cur.lastpos();
1228 if (cur.pos() > cur.lastpos())
1229 cur.pos() = cur.lastpos();
1231 // FIXME: find some more clever handling of the selection,
1232 // i.e. preserve it.
1233 cur.clearSelection();
1234 //cur.dispatched(FINISHED);
1238 case LFUN_MATH_DISPLAY: {
1239 cur.recordUndoInset();
1240 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1242 cur.pos() = cur.lastpos();
1243 //cur.dispatched(FINISHED);
1248 InsetMathGrid::doDispatch(cur, cmd);
1254 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1255 FuncStatus & status) const
1257 switch (cmd.action) {
1258 case LFUN_FINISHED_BACKWARD:
1259 case LFUN_FINISHED_FORWARD:
1260 case LFUN_FINISHED_RIGHT:
1261 case LFUN_FINISHED_LEFT:
1265 case LFUN_MATH_EXTERN:
1266 case LFUN_MATH_MUTATE:
1267 case LFUN_MATH_DISPLAY:
1269 status.enabled(true);
1271 case LFUN_MATH_NUMBER_TOGGLE:
1272 // FIXME: what is the right test, this or the one of
1274 status.enabled(display());
1275 status.setOnOff(numberedType());
1277 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1278 // FIXME: what is the right test, this or the one of
1280 status.enabled(display());
1281 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1282 status.setOnOff(numbered(r));
1285 case LFUN_LABEL_INSERT:
1286 status.enabled(type_ != hullSimple);
1288 case LFUN_INSET_INSERT:
1289 if (cmd.getArg(0) == "label") {
1290 status.enabled(type_ != hullSimple);
1293 return InsetMathGrid::getStatus(cur, cmd, status);
1294 case LFUN_TABULAR_FEATURE: {
1295 istringstream is(to_utf8(cmd.argument()));
1299 && (s == "append-row"
1300 || s == "delete-row"
1301 || s == "copy-row")) {
1302 status.message(bformat(
1303 from_utf8(N_("Can't change number of rows in '%1$s'")),
1305 status.enabled(false);
1309 && (s == "append-column"
1310 || s == "delete-column"
1311 || s == "copy-column")) {
1312 status.message(bformat(
1313 from_utf8(N_("Can't change number of columns in '%1$s'")),
1315 status.enabled(false);
1318 if ((type_ == hullSimple
1319 || type_ == hullEquation
1320 || type_ == hullNone) &&
1321 (s == "add-hline-above" || s == "add-hline-below")) {
1322 status.message(bformat(
1323 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1325 status.enabled(false);
1328 if (s == "add-vline-left" || s == "add-vline-right") {
1329 status.message(bformat(
1330 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1332 status.enabled(false);
1335 if (s == "valign-top" || s == "valign-middle"
1336 || s == "valign-bottom" || s == "align-left"
1337 || s == "align-center" || s == "align-right") {
1338 status.enabled(false);
1341 return InsetMathGrid::getStatus(cur, cmd, status);
1344 return InsetMathGrid::getStatus(cur, cmd, status);
1347 // This cannot really happen, but inserted to shut-up gcc
1348 return InsetMathGrid::getStatus(cur, cmd, status);
1352 /////////////////////////////////////////////////////////////////////
1356 // simply scrap this function if you want
1357 void InsetMathHull::mutateToText()
1360 // translate to latex
1362 latex(NULL, os, false, false);
1363 string str = os.str();
1366 Text * lt = view_->cursor().innerText();
1367 string::const_iterator cit = str.begin();
1368 string::const_iterator end = str.end();
1369 for (; cit != end; ++cit)
1370 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1373 //dispatch(LFUN_ESCAPE);
1378 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1379 docstring const & font)
1381 // this whole function is a hack and won't work for incremental font
1384 if (cur.inset().asInsetMath()->name() == font)
1385 cur.handleFont(to_utf8(font));
1387 cur.handleNest(createInsetMath(font));
1393 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1398 font.fromString(to_utf8(arg), b);
1399 if (font.fontInfo().color() != Color_inherit) {
1400 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1401 cur.handleNest(at, 0);
1406 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1409 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1410 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1411 enter_front ? idxFirst(cur) : idxLast(cur);
1412 // The inset formula dimension is not necessarily the same as the
1413 // one of the instant preview image, so we have to indicate to the
1414 // BufferView that a metrics update is needed.
1415 cur.updateFlags(Update::Force);
1419 docstring InsetMathHull::editMessage() const
1421 return _("Math editor mode");
1425 void InsetMathHull::revealCodes(Cursor & cur) const
1427 if (!cur.inMathed())
1429 odocstringstream os;
1431 cur.message(os.str());
1433 // write something to the minibuffer
1434 // translate to latex
1438 string str = os.str();
1440 string::size_type pos = 0;
1442 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1445 else if (*it == '\0') {
1447 pos = it - str.begin();
1453 res = res.substr(pos - 30);
1454 if (res.size() > 60)
1455 res = res.substr(0, 60);
1461 InsetCode InsetMathHull::lyxCode() const
1467 /////////////////////////////////////////////////////////////////////
1471 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1474 // FIXME: completely broken
1475 static InsetMathHull * lastformula = 0;
1476 static CursorBase current = DocIterator(ibegin(nucleus()));
1478 static string laststr;
1480 if (lastformula != this || laststr != str) {
1481 //lyxerr << "reset lastformula to " << this << endl;
1484 current = ibegin(nucleus());
1486 mathed_parse_cell(ar, str);
1490 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1492 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1493 CursorSlice & top = it.back();
1494 MathData const & a = top.asInsetMath()->cell(top.idx_);
1495 if (a.matchpart(ar, top.pos_)) {
1496 bv->cursor().setSelection(it, ar.size());
1498 top.pos_ += ar.size();
1504 //lyxerr << "not found!" << endl;
1511 void InsetMathHull::write(ostream & os) const
1513 odocstringstream oss;
1514 WriteStream wi(oss, false, false);
1517 os << to_utf8(oss.str());
1521 void InsetMathHull::read(Lexer & lex)
1524 mathed_parse_normal(at, lex);
1525 operator=(*at->asHullInset());
1529 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1531 if (0 && display()) {
1535 TextPainter tpain(dim.width(), dim.height());
1536 drawT(tpain, 0, dim.ascent());
1538 // reset metrics cache to "real" values
1540 return tpain.textheight();
1542 odocstringstream oss;
1543 WriteStream wi(oss, false, true);
1546 docstring const str = oss.str();
1553 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1558 if (getType() == hullSimple)
1559 name = from_ascii("inlineequation");
1561 name = from_ascii("informalequation");
1563 docstring bname = name;
1564 if (!label(0).empty())
1565 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1567 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1569 odocstringstream ls;
1570 if (runparams.flavor == OutputParams::XML) {
1571 ms << MTag("alt role='tex' ");
1572 // Workaround for db2latex: db2latex always includes equations with
1573 // \ensuremath{} or \begin{display}\end{display}
1574 // so we strip LyX' math environment
1575 WriteStream wi(ls, false, false);
1576 InsetMathGrid::write(wi);
1577 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1582 InsetMathGrid::mathmlize(ms);
1585 ms << MTag("alt role='tex'");
1586 res = latex(ls, runparams);
1587 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1591 ms << from_ascii("<graphic fileref=\"eqn/");
1592 if (!label(0).empty())
1593 ms << sgml::cleanID(buffer(), runparams, label(0));
1595 ms << sgml::uniqueID(from_ascii("anon"));
1597 if (runparams.flavor == OutputParams::XML)
1598 ms << from_ascii("\"/>");
1600 ms << from_ascii("\">");
1602 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1604 return ms.line() + res;
1608 void InsetMathHull::textString(odocstream & os) const
1610 plaintext(os, OutputParams(0));