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)
180 Inset * InsetMathHull::clone() const
182 return new InsetMathHull(*this);
186 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
190 InsetMathGrid::operator=(other);
192 nonum_ = other.nonum_;
193 for (size_t i = 0; i < label_.size(); ++i)
195 label_ = other.label_;
196 for (size_t i = 0; i != label_.size(); ++i) {
198 label_[i] = new InsetLabel(*label_[i]);
200 preview_.reset(new RenderPreview(*other.preview_, this));
206 void InsetMathHull::setBuffer(Buffer & buffer)
209 for (idx_type i = 0, n = nargs(); i != n; ++i) {
210 MathData & data = cell(i);
211 for (size_t j = 0; j != data.size(); ++j)
212 data[j].nucleus()->setBuffer(buffer);
215 for (size_t i = 0; i != label_.size(); ++i) {
217 label_[i]->setBuffer(buffer);
222 void InsetMathHull::updateLabels(ParIterator const & it)
225 //FIXME: buffer_ should be set at creation for this inset! Problem is
226 // This inset is created at too many places (see Parser::parse1() in
230 for (size_t i = 0; i != label_.size(); ++i) {
232 label_[i]->updateLabels(it);
237 void InsetMathHull::addToToc(ParConstIterator const & pit) const
240 //FIXME: buffer_ should be set at creation for this inset! Problem is
241 // This inset is created at too many places (see Parser::parse1() in
246 // FIXME: it would be way better to directly use InsetLabel instead of this
247 // label list. But it should be possible to copy&paste the code in
248 // InsetLabel::addToToc() anyway.
250 Toc & toc = buffer().tocBackend().toc("equation");
252 for (row_type row = 0; row != nrows(); ++row) {
256 label_[row]->addToToc(pit);
257 toc.push_back(TocItem(pit, 0, nicelabel(row)));
262 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
268 return InsetMathNest::editXY(cur, x, y);
272 InsetMath::mode_type InsetMathHull::currentMode() const
274 if (type_ == hullNone)
275 return UNDECIDED_MODE;
276 // definitely math mode ...
281 bool InsetMathHull::idxFirst(Cursor & cur) const
289 bool InsetMathHull::idxLast(Cursor & cur) const
291 cur.idx() = nargs() - 1;
292 cur.pos() = cur.lastpos();
297 char InsetMathHull::defaultColAlign(col_type col)
299 if (type_ == hullEqnArray)
301 if (type_ == hullGather)
303 if (type_ >= hullAlign)
304 return "rl"[col & 1];
309 int InsetMathHull::defaultColSpace(col_type col)
311 if (type_ == hullAlign || type_ == hullAlignAt)
313 if (type_ == hullXAlignAt)
314 return (col & 1) ? 20 : 0;
315 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
316 return (col & 1) ? 40 : 0;
321 docstring InsetMathHull::standardFont() const
323 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
327 bool InsetMathHull::previewState(BufferView * bv) const
329 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
330 graphics::PreviewImage const * pimage =
331 preview_->getPreviewImage(bv->buffer());
332 return pimage && pimage->image();
338 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
340 if (previewState(mi.base.bv)) {
341 preview_->metrics(mi, dim);
342 // insert a one pixel gap in front of the formula
345 dim.des += displayMargin();
346 // Cache the inset dimension.
347 setDimCache(mi, dim);
351 FontSetChanger dummy1(mi.base, standardFont());
352 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
354 // let the cells adjust themselves
355 InsetMathGrid::metrics(mi, dim);
358 dim.asc += displayMargin();
359 dim.des += displayMargin();
362 if (numberedType()) {
363 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
365 for (row_type row = 0; row < nrows(); ++row)
366 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
372 // make it at least as high as the current font
375 math_font_max_dim(mi.base.font, asc, des);
376 dim.asc = max(dim.asc, asc);
377 dim.des = max(dim.des, des);
378 // Cache the inset dimension.
379 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
380 setDimCache(mi, dim);
384 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
386 use_preview_ = previewState(pi.base.bv);
387 Dimension const dim = dimension(*pi.base.bv);
389 // background of mathed under focus is not painted because
390 // selection at the top level of nested inset is difficult to handle.
391 if (!editing(pi.base.bv))
392 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
393 dim.asc + dim.des - 1, Color_mathbg);
396 // one pixel gap in front
397 preview_->draw(pi, x + 1, y);
398 setPosCache(pi, x, y);
402 FontSetChanger dummy1(pi.base, standardFont());
403 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
404 InsetMathGrid::draw(pi, x + 1, y);
406 if (numberedType()) {
407 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
408 for (row_type row = 0; row < nrows(); ++row) {
409 int const yy = y + rowinfo_[row].offset_;
410 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
411 docstring const nl = nicelabel(row);
415 setPosCache(pi, x, y);
419 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
422 InsetMathGrid::metricsT(mi, dim);
425 WriteStream wi(os, false, true);
427 dim.wid = os.str().size();
434 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
437 InsetMathGrid::drawT(pain, x, y);
440 WriteStream wi(os, false, true);
442 pain.draw(x, y, os.str().c_str());
449 docstring const latex_string(InsetMathHull const & inset)
452 WriteStream wi(ls, false, false);
460 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
462 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
463 docstring const snippet = latex_string(*this);
464 preview_->addPreview(snippet, ploader);
469 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
471 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
472 Buffer const & buffer = cur.buffer();
473 docstring const snippet = latex_string(*this);
474 preview_->addPreview(snippet, buffer);
475 preview_->startLoading(buffer);
476 cur.updateFlags(Update::Force);
482 docstring InsetMathHull::label(row_type row) const
484 BOOST_ASSERT(row < nrows());
485 if (InsetLabel * il = label_[row])
486 return il->screenLabel();
491 void InsetMathHull::label(row_type row, docstring const & label)
493 //lyxerr << "setting label '" << label << "' for row " << row << endl;
495 label_[row]->updateCommand(label);
498 InsetCommandParams p(LABEL_CODE);
500 label_[row] = new InsetLabel(p);
502 label_[row]->setBuffer(buffer());
506 void InsetMathHull::numbered(row_type row, bool num)
509 if (nonum_[row] && label_[row]) {
516 bool InsetMathHull::numbered(row_type row) const
522 bool InsetMathHull::ams() const
525 type_ == hullAlign ||
526 type_ == hullFlAlign ||
527 type_ == hullMultline ||
528 type_ == hullGather ||
529 type_ == hullAlignAt ||
530 type_ == hullXAlignAt ||
531 type_ == hullXXAlignAt;
535 Inset::DisplayType InsetMathHull::display() const
537 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
541 bool InsetMathHull::numberedType() const
543 if (type_ == hullNone)
545 if (type_ == hullSimple)
547 if (type_ == hullXXAlignAt)
549 for (row_type row = 0; row < nrows(); ++row)
556 void InsetMathHull::validate(LaTeXFeatures & features) const
559 features.require("amsmath");
562 // Validation is necessary only if not using AMS math.
563 // To be safe, we will always run mathedvalidate.
564 //if (features.amsstyle)
567 features.require("boldsymbol");
568 //features.binom = true;
570 InsetMathGrid::validate(features);
574 void InsetMathHull::header_write(WriteStream & os) const
576 bool n = numberedType();
590 os << "\\begin{equation" << star(n) << "}\n";
600 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
605 os << "\\begin{" << hullName(type_) << star(n) << '}'
606 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
610 os << "\\begin{" << hullName(type_) << '}'
611 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
615 os << "\\begin{unknown" << star(n) << '}';
621 void InsetMathHull::footer_write(WriteStream & os) const
623 bool n = numberedType();
636 os << "\\end{equation" << star(n) << "}\n";
648 os << "\\end{" << hullName(type_) << star(n) << "}\n";
652 os << "\\end{" << hullName(type_) << "}\n";
656 os << "\\end{unknown" << star(n) << '}';
662 bool InsetMathHull::rowChangeOK() const
665 type_ == hullEqnArray || type_ == hullAlign ||
666 type_ == hullFlAlign || type_ == hullAlignAt ||
667 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
668 type_ == hullGather || type_ == hullMultline;
672 bool InsetMathHull::colChangeOK() const
675 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
676 type_ == hullXAlignAt || type_ == hullXXAlignAt;
680 void InsetMathHull::addRow(row_type row)
684 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
685 label_.insert(label_.begin() + row + 1, dummy_pointer);
686 InsetMathGrid::addRow(row);
690 void InsetMathHull::swapRow(row_type row)
694 if (row + 1 == nrows())
696 // gcc implements the standard std::vector<bool> which is *not* a container:
697 // http://www.gotw.ca/publications/N1185.pdf
698 // As a results, it doesn't like this:
699 // swap(nonum_[row], nonum_[row + 1]);
700 // so we do it manually:
701 bool const b = nonum_[row];
702 nonum_[row] = nonum_[row + 1];
704 swap(label_[row], label_[row + 1]);
705 InsetMathGrid::swapRow(row);
709 void InsetMathHull::delRow(row_type row)
711 if (nrows() <= 1 || !rowChangeOK())
713 InsetMathGrid::delRow(row);
714 // The last dummy row has no number info nor a label.
715 // Test nrows() + 1 because we have already erased the row.
716 if (row == nrows() + 1)
718 nonum_.erase(nonum_.begin() + row);
720 label_.erase(label_.begin() + row);
724 void InsetMathHull::addCol(col_type col)
728 InsetMathGrid::addCol(col);
732 void InsetMathHull::delCol(col_type col)
734 if (ncols() <= 1 || !colChangeOK())
736 InsetMathGrid::delCol(col);
740 docstring InsetMathHull::nicelabel(row_type row) const
745 return from_ascii("(#)");
746 return '(' + label_[row]->screenLabel() + ')';
750 void InsetMathHull::glueall()
753 for (idx_type i = 0; i < nargs(); ++i)
755 *this = InsetMathHull(hullSimple);
761 void InsetMathHull::splitTo2Cols()
763 BOOST_ASSERT(ncols() == 1);
764 InsetMathGrid::addCol(1);
765 for (row_type row = 0; row < nrows(); ++row) {
766 idx_type const i = 2 * row;
767 pos_type pos = firstRelOp(cell(i));
768 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
769 cell(i).erase(pos, cell(i).size());
774 void InsetMathHull::splitTo3Cols()
776 BOOST_ASSERT(ncols() < 3);
779 InsetMathGrid::addCol(2);
780 for (row_type row = 0; row < nrows(); ++row) {
781 idx_type const i = 3 * row + 1;
782 if (cell(i).size()) {
783 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
784 cell(i).erase(1, cell(i).size());
790 void InsetMathHull::changeCols(col_type cols)
794 else if (ncols() < cols) {
800 while (ncols() < cols)
801 InsetMathGrid::addCol(ncols());
807 for (row_type row = 0; row < nrows(); ++row) {
808 idx_type const i = row * ncols();
809 for (col_type col = cols; col < ncols(); ++col) {
810 cell(i + cols - 1).append(cell(i + col));
814 while (ncols() > cols) {
815 InsetMathGrid::delCol(ncols() - 1);
820 HullType InsetMathHull::getType() const
826 void InsetMathHull::setType(HullType type)
833 void InsetMathHull::mutate(HullType newtype)
835 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
837 // we try to move along the chain
838 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
840 // +-------------------------------------+
841 // we use eqnarray as intermediate type for mutations that are not
842 // directly supported because it handles labels and numbering for
845 if (newtype == type_) {
849 else if (newtype < hullNone) {
854 else if (type_ == hullNone) {
860 else if (type_ == hullSimple) {
861 if (newtype == hullNone) {
865 setType(hullEquation);
871 else if (type_ == hullEquation) {
872 if (newtype < type_) {
876 } else if (newtype == hullEqnArray) {
877 // split it "nicely" on the first relop
879 setType(hullEqnArray);
880 } else if (newtype == hullMultline || newtype == hullGather) {
890 else if (type_ == hullEqnArray) {
891 if (newtype < type_) {
892 // set correct (no)numbering
894 for (row_type row = 0; row < nrows(); ++row) {
901 // set first non-empty label
902 for (row_type row = 0; row < nrows(); ++row) {
904 label_[0] = label_[row];
911 } else { // align & Co.
918 else if (type_ == hullAlign || type_ == hullAlignAt ||
919 type_ == hullXAlignAt || type_ == hullFlAlign) {
920 if (newtype < hullAlign) {
922 setType(hullEqnArray);
924 } else if (newtype == hullGather || newtype == hullMultline) {
927 } else if (newtype == hullXXAlignAt) {
928 for (row_type row = 0; row < nrows(); ++row)
929 numbered(row, false);
936 else if (type_ == hullXXAlignAt) {
937 for (row_type row = 0; row < nrows(); ++row)
938 numbered(row, false);
939 if (newtype < hullAlign) {
941 setType(hullEqnArray);
943 } else if (newtype == hullGather || newtype == hullMultline) {
951 else if (type_ == hullMultline || type_ == hullGather) {
952 if (newtype == hullGather || newtype == hullMultline)
954 else if (newtype == hullAlign || newtype == hullFlAlign ||
955 newtype == hullAlignAt || newtype == hullXAlignAt) {
958 } else if (newtype == hullXXAlignAt) {
960 for (row_type row = 0; row < nrows(); ++row)
961 numbered(row, false);
965 setType(hullEqnArray);
971 lyxerr << "mutation from '" << to_utf8(hullName(type_))
972 << "' to '" << to_utf8(hullName(newtype))
973 << "' not implemented" << endl;
978 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
981 if (numberedType()) {
982 if (label_[row] && !nonum_[row])
983 res += "\\label{" + label_[row]->getParam("name") + '}';
984 if (nonum_[row] && (type_ != hullMultline))
985 res += "\\nonumber ";
987 return res + InsetMathGrid::eolString(row, emptyline, fragile);
991 void InsetMathHull::write(WriteStream & os) const
994 InsetMathGrid::write(os);
999 void InsetMathHull::normalize(NormalStream & os) const
1001 os << "[formula " << hullName(type_) << ' ';
1002 InsetMathGrid::normalize(os);
1007 void InsetMathHull::mathmlize(MathStream & os) const
1009 InsetMathGrid::mathmlize(os);
1013 void InsetMathHull::infoize(odocstream & os) const
1015 os << "Type: " << hullName(type_);
1019 void InsetMathHull::check() const
1021 BOOST_ASSERT(nonum_.size() == nrows());
1022 BOOST_ASSERT(label_.size() == nrows());
1026 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1030 idocstringstream iss(func.argument());
1031 iss >> dlang >> extra;
1033 extra = from_ascii("noextra");
1034 string const lang = to_ascii(dlang);
1036 // FIXME: temporarily disabled
1037 //if (cur.selection()) {
1040 // lyxerr << "use selection: " << ar << endl;
1041 // insert(pipeThroughExtern(lang, extra, ar));
1046 eq.push_back(MathAtom(new InsetMathChar('=')));
1048 // go to first item in line
1049 cur.idx() -= cur.idx() % ncols();
1052 if (getType() == hullSimple) {
1053 size_type pos = cur.cell().find_last(eq);
1055 if (cur.inMathed() && cur.selection()) {
1056 asArray(grabAndEraseSelection(cur), ar);
1057 } else if (pos == cur.cell().size()) {
1059 lyxerr << "use whole cell: " << ar << endl;
1061 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1062 lyxerr << "use partial cell form pos: " << pos << endl;
1064 cur.cell().append(eq);
1065 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1066 cur.pos() = cur.lastpos();
1070 if (getType() == hullEquation) {
1071 lyxerr << "use equation inset" << endl;
1072 mutate(hullEqnArray);
1073 MathData & ar = cur.cell();
1074 lyxerr << "use cell: " << ar << endl;
1078 cur.cell() = pipeThroughExtern(lang, extra, ar);
1079 // move to end of line
1080 cur.pos() = cur.lastpos();
1085 lyxerr << "use eqnarray" << endl;
1086 cur.idx() += 2 - cur.idx() % ncols();
1088 MathData ar = cur.cell();
1089 lyxerr << "use cell: " << ar << endl;
1090 // FIXME: temporarily disabled
1096 cur.cell() = pipeThroughExtern(lang, extra, ar);
1097 cur.pos() = cur.lastpos();
1102 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1104 //lyxerr << "action: " << cmd.action << endl;
1105 switch (cmd.action) {
1107 case LFUN_FINISHED_BACKWARD:
1108 case LFUN_FINISHED_FORWARD:
1109 case LFUN_FINISHED_RIGHT:
1110 case LFUN_FINISHED_LEFT:
1111 //lyxerr << "action: " << cmd.action << endl;
1112 InsetMathGrid::doDispatch(cur, cmd);
1116 case LFUN_BREAK_PARAGRAPH:
1117 // just swallow this
1121 // some magic for the common case
1122 if (type_ == hullSimple || type_ == hullEquation) {
1123 cur.recordUndoInset();
1125 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1126 mutate(align ? hullAlign : hullEqnArray);
1127 cur.idx() = nrows() * ncols() - 1;
1128 cur.pos() = cur.lastpos();
1130 InsetMathGrid::doDispatch(cur, cmd);
1133 case LFUN_MATH_NUMBER_TOGGLE: {
1134 //lyxerr << "toggling all numbers" << endl;
1135 cur.recordUndoInset();
1136 bool old = numberedType();
1137 if (type_ == hullMultline)
1138 numbered(nrows() - 1, !old);
1140 for (row_type row = 0; row < nrows(); ++row)
1141 numbered(row, !old);
1143 cur.message(old ? _("No number") : _("Number"));
1147 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1148 cur.recordUndoInset();
1149 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1150 bool old = numbered(r);
1151 cur.message(old ? _("No number") : _("Number"));
1156 case LFUN_LABEL_INSERT: {
1157 cur.recordUndoInset();
1158 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1159 docstring old_label = label(r);
1160 docstring const default_label = from_ascii(
1161 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1162 if (old_label.empty())
1163 old_label = default_label;
1165 InsetCommandParams p(LABEL_CODE);
1166 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1167 string const data = InsetCommandMailer::params2string("label", p);
1169 if (cmd.argument().empty())
1170 cur.bv().showDialog("label", data);
1172 FuncRequest fr(LFUN_INSET_INSERT, data);
1178 case LFUN_INSET_INSERT: {
1179 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1180 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1181 string const name = cmd.getArg(0);
1182 if (name == "label") {
1183 InsetCommandParams p(LABEL_CODE);
1184 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1185 docstring str = p["name"];
1186 cur.recordUndoInset();
1187 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1191 docstring old = label(r);
1194 // The label will take care of the reference update.
1198 // Newly created inset so initialize it.
1199 label_[r]->initView();
1204 InsetMathGrid::doDispatch(cur, cmd);
1208 case LFUN_MATH_EXTERN:
1209 cur.recordUndoInset();
1213 case LFUN_MATH_MUTATE: {
1214 cur.recordUndoInset();
1215 row_type row = cur.row();
1216 col_type col = cur.col();
1217 mutate(hullType(cmd.argument()));
1218 cur.idx() = row * ncols() + col;
1219 if (cur.idx() > cur.lastidx()) {
1220 cur.idx() = cur.lastidx();
1221 cur.pos() = cur.lastpos();
1223 if (cur.pos() > cur.lastpos())
1224 cur.pos() = cur.lastpos();
1226 // FIXME: find some more clever handling of the selection,
1227 // i.e. preserve it.
1228 cur.clearSelection();
1229 //cur.dispatched(FINISHED);
1233 case LFUN_MATH_DISPLAY: {
1234 cur.recordUndoInset();
1235 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1237 cur.pos() = cur.lastpos();
1238 //cur.dispatched(FINISHED);
1243 InsetMathGrid::doDispatch(cur, cmd);
1249 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1250 FuncStatus & status) const
1252 switch (cmd.action) {
1253 case LFUN_FINISHED_BACKWARD:
1254 case LFUN_FINISHED_FORWARD:
1255 case LFUN_FINISHED_RIGHT:
1256 case LFUN_FINISHED_LEFT:
1260 case LFUN_MATH_EXTERN:
1261 case LFUN_MATH_MUTATE:
1262 case LFUN_MATH_DISPLAY:
1264 status.enabled(true);
1266 case LFUN_MATH_NUMBER_TOGGLE:
1267 // FIXME: what is the right test, this or the one of
1269 status.enabled(display());
1270 status.setOnOff(numberedType());
1272 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1273 // FIXME: what is the right test, this or the one of
1275 status.enabled(display());
1276 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1277 status.setOnOff(numbered(r));
1280 case LFUN_LABEL_INSERT:
1281 status.enabled(type_ != hullSimple);
1283 case LFUN_INSET_INSERT:
1284 if (cmd.getArg(0) == "label") {
1285 status.enabled(type_ != hullSimple);
1288 return InsetMathGrid::getStatus(cur, cmd, status);
1289 case LFUN_TABULAR_FEATURE: {
1290 istringstream is(to_utf8(cmd.argument()));
1294 && (s == "append-row"
1295 || s == "delete-row"
1296 || s == "copy-row")) {
1297 status.message(bformat(
1298 from_utf8(N_("Can't change number of rows in '%1$s'")),
1300 status.enabled(false);
1304 && (s == "append-column"
1305 || s == "delete-column"
1306 || s == "copy-column")) {
1307 status.message(bformat(
1308 from_utf8(N_("Can't change number of columns in '%1$s'")),
1310 status.enabled(false);
1313 if ((type_ == hullSimple
1314 || type_ == hullEquation
1315 || type_ == hullNone) &&
1316 (s == "add-hline-above" || s == "add-hline-below")) {
1317 status.message(bformat(
1318 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1320 status.enabled(false);
1323 if (s == "add-vline-left" || s == "add-vline-right") {
1324 status.message(bformat(
1325 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1327 status.enabled(false);
1330 if (s == "valign-top" || s == "valign-middle"
1331 || s == "valign-bottom" || s == "align-left"
1332 || s == "align-center" || s == "align-right") {
1333 status.enabled(false);
1336 return InsetMathGrid::getStatus(cur, cmd, status);
1339 return InsetMathGrid::getStatus(cur, cmd, status);
1342 // This cannot really happen, but inserted to shut-up gcc
1343 return InsetMathGrid::getStatus(cur, cmd, status);
1347 /////////////////////////////////////////////////////////////////////
1351 // simply scrap this function if you want
1352 void InsetMathHull::mutateToText()
1355 // translate to latex
1357 latex(NULL, os, false, false);
1358 string str = os.str();
1361 Text * lt = view_->cursor().innerText();
1362 string::const_iterator cit = str.begin();
1363 string::const_iterator end = str.end();
1364 for (; cit != end; ++cit)
1365 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1368 //dispatch(LFUN_ESCAPE);
1373 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1374 docstring const & font)
1376 // this whole function is a hack and won't work for incremental font
1379 if (cur.inset().asInsetMath()->name() == font)
1380 cur.handleFont(to_utf8(font));
1382 cur.handleNest(createInsetMath(font));
1388 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1393 font.fromString(to_utf8(arg), b);
1394 if (font.fontInfo().color() != Color_inherit) {
1395 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1396 cur.handleNest(at, 0);
1401 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1404 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1405 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1406 enter_front ? idxFirst(cur) : idxLast(cur);
1407 // The inset formula dimension is not necessarily the same as the
1408 // one of the instant preview image, so we have to indicate to the
1409 // BufferView that a metrics update is needed.
1410 cur.updateFlags(Update::Force);
1414 docstring InsetMathHull::editMessage() const
1416 return _("Math editor mode");
1420 void InsetMathHull::revealCodes(Cursor & cur) const
1422 if (!cur.inMathed())
1424 odocstringstream os;
1426 cur.message(os.str());
1428 // write something to the minibuffer
1429 // translate to latex
1433 string str = os.str();
1435 string::size_type pos = 0;
1437 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1440 else if (*it == '\0') {
1442 pos = it - str.begin();
1448 res = res.substr(pos - 30);
1449 if (res.size() > 60)
1450 res = res.substr(0, 60);
1456 InsetCode InsetMathHull::lyxCode() const
1462 /////////////////////////////////////////////////////////////////////
1466 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1469 // FIXME: completely broken
1470 static InsetMathHull * lastformula = 0;
1471 static CursorBase current = DocIterator(ibegin(nucleus()));
1473 static string laststr;
1475 if (lastformula != this || laststr != str) {
1476 //lyxerr << "reset lastformula to " << this << endl;
1479 current = ibegin(nucleus());
1481 mathed_parse_cell(ar, str);
1485 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1487 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1488 CursorSlice & top = it.back();
1489 MathData const & a = top.asInsetMath()->cell(top.idx_);
1490 if (a.matchpart(ar, top.pos_)) {
1491 bv->cursor().setSelection(it, ar.size());
1493 top.pos_ += ar.size();
1499 //lyxerr << "not found!" << endl;
1506 void InsetMathHull::write(ostream & os) const
1508 odocstringstream oss;
1509 WriteStream wi(oss, false, false);
1512 os << to_utf8(oss.str());
1516 void InsetMathHull::read(Lexer & lex)
1519 mathed_parse_normal(at, lex);
1520 operator=(*at->asHullInset());
1524 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1526 if (0 && display()) {
1530 TextPainter tpain(dim.width(), dim.height());
1531 drawT(tpain, 0, dim.ascent());
1533 // reset metrics cache to "real" values
1535 return tpain.textheight();
1537 odocstringstream oss;
1538 WriteStream wi(oss, false, true);
1541 docstring const str = oss.str();
1548 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1553 if (getType() == hullSimple)
1554 name = from_ascii("inlineequation");
1556 name = from_ascii("informalequation");
1558 docstring bname = name;
1559 if (!label(0).empty())
1560 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1562 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1564 odocstringstream ls;
1565 if (runparams.flavor == OutputParams::XML) {
1566 ms << MTag("alt role='tex' ");
1567 // Workaround for db2latex: db2latex always includes equations with
1568 // \ensuremath{} or \begin{display}\end{display}
1569 // so we strip LyX' math environment
1570 WriteStream wi(ls, false, false);
1571 InsetMathGrid::write(wi);
1572 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1577 InsetMathGrid::mathmlize(ms);
1580 ms << MTag("alt role='tex'");
1581 res = latex(ls, runparams);
1582 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1586 ms << from_ascii("<graphic fileref=\"eqn/");
1587 if (!label(0).empty())
1588 ms << sgml::cleanID(buffer(), runparams, label(0));
1590 ms << sgml::uniqueID(from_ascii("anon"));
1592 if (runparams.flavor == OutputParams::XML)
1593 ms << from_ascii("\"/>");
1595 ms << from_ascii("\">");
1597 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1599 return ms.line() + res;
1603 void InsetMathHull::textString(odocstream & os) const
1605 plaintext(os, OutputParams(0));
1609 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1611 return from_ascii("context-math");