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");
144 InsetMathHull::InsetMathHull()
145 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false), label_(1, 0),
146 preview_(new RenderPreview(this))
148 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
149 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
150 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
151 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
157 InsetMathHull::InsetMathHull(HullType type)
158 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false), label_(1, 0),
159 preview_(new RenderPreview(this))
166 InsetMathHull::InsetMathHull(InsetMathHull const & other)
172 InsetMathHull::~InsetMathHull()
174 for (size_t i = 0; i < label_.size(); ++i) {
181 Inset * InsetMathHull::clone() const
183 return new InsetMathHull(*this);
187 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
191 InsetMathGrid::operator=(other);
193 nonum_ = other.nonum_;
194 for (size_t i = 0; i < label_.size(); ++i) {
198 label_ = other.label_;
199 for (size_t i = 0; i != label_.size(); ++i) {
201 label_[i] = new InsetLabel(*label_[i]);
203 preview_.reset(new RenderPreview(*other.preview_, this));
209 void InsetMathHull::setBuffer(Buffer & buffer)
212 for (size_t i = 0; i != label_.size(); ++i) {
214 label_[i]->setBuffer(buffer);
219 void InsetMathHull::updateLabels(ParIterator const & it)
222 //FIXME: buffer_ should be set at creation for this inset! Problem is
223 // This inset is created at too many places (see Parser::parse1() in
227 for (size_t i = 0; i != label_.size(); ++i) {
229 label_[i]->updateLabels(it);
234 void InsetMathHull::addToToc(ParConstIterator const & pit) const
237 //FIXME: buffer_ should be set at creation for this inset! Problem is
238 // This inset is created at too many places (see Parser::parse1() in
243 // FIXME: it would be way better to directly use InsetLabel instead of this
244 // label list. But it should be possible to copy&paste the code in
245 // InsetLabel::addToToc() anyway.
247 Toc & toc = buffer().tocBackend().toc("equation");
249 for (row_type row = 0; row != nrows(); ++row) {
253 label_[row]->addToToc(pit);
254 toc.push_back(TocItem(pit, 0, nicelabel(row)));
259 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
265 return InsetMathNest::editXY(cur, x, y);
269 InsetMath::mode_type InsetMathHull::currentMode() const
271 if (type_ == hullNone)
272 return UNDECIDED_MODE;
273 // definitely math mode ...
278 bool InsetMathHull::idxFirst(Cursor & cur) const
286 bool InsetMathHull::idxLast(Cursor & cur) const
288 cur.idx() = nargs() - 1;
289 cur.pos() = cur.lastpos();
294 char InsetMathHull::defaultColAlign(col_type col)
296 if (type_ == hullEqnArray)
298 if (type_ == hullGather)
300 if (type_ >= hullAlign)
301 return "rl"[col & 1];
306 int InsetMathHull::defaultColSpace(col_type col)
308 if (type_ == hullAlign || type_ == hullAlignAt)
310 if (type_ == hullXAlignAt)
311 return (col & 1) ? 20 : 0;
312 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
313 return (col & 1) ? 40 : 0;
318 docstring InsetMathHull::standardFont() const
320 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
324 bool InsetMathHull::previewState(BufferView * bv) const
326 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
327 graphics::PreviewImage const * pimage =
328 preview_->getPreviewImage(bv->buffer());
329 return pimage && pimage->image();
335 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
337 if (previewState(mi.base.bv)) {
338 preview_->metrics(mi, dim);
339 // insert a one pixel gap in front of the formula
342 dim.des += displayMargin();
343 // Cache the inset dimension.
344 setDimCache(mi, dim);
348 FontSetChanger dummy1(mi.base, standardFont());
349 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
351 // let the cells adjust themselves
352 InsetMathGrid::metrics(mi, dim);
355 dim.asc += displayMargin();
356 dim.des += displayMargin();
359 if (numberedType()) {
360 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
362 for (row_type row = 0; row < nrows(); ++row)
363 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
369 // make it at least as high as the current font
372 math_font_max_dim(mi.base.font, asc, des);
373 dim.asc = max(dim.asc, asc);
374 dim.des = max(dim.des, des);
375 // Cache the inset dimension.
376 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
377 setDimCache(mi, dim);
381 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
383 use_preview_ = previewState(pi.base.bv);
384 Dimension const dim = dimension(*pi.base.bv);
386 // background of mathed under focus is not painted because
387 // selection at the top level of nested inset is difficult to handle.
388 if (!editing(pi.base.bv))
389 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
390 dim.asc + dim.des - 1, Color_mathbg);
393 // one pixel gap in front
394 preview_->draw(pi, x + 1, y);
395 setPosCache(pi, x, y);
399 FontSetChanger dummy1(pi.base, standardFont());
400 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
401 InsetMathGrid::draw(pi, x + 1, y);
403 if (numberedType()) {
404 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
405 for (row_type row = 0; row < nrows(); ++row) {
406 int const yy = y + rowinfo_[row].offset_;
407 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
408 docstring const nl = nicelabel(row);
412 setPosCache(pi, x, y);
416 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
419 InsetMathGrid::metricsT(mi, dim);
422 WriteStream wi(os, false, true);
424 dim.wid = os.str().size();
431 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
434 InsetMathGrid::drawT(pain, x, y);
437 WriteStream wi(os, false, true);
439 pain.draw(x, y, os.str().c_str());
446 docstring const latex_string(InsetMathHull const & inset)
449 WriteStream wi(ls, false, false);
457 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
459 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
460 docstring const snippet = latex_string(*this);
461 preview_->addPreview(snippet, ploader);
466 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
468 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
469 Buffer const & buffer = cur.buffer();
470 docstring const snippet = latex_string(*this);
471 preview_->addPreview(snippet, buffer);
472 preview_->startLoading(buffer);
473 cur.updateFlags(Update::Force);
479 docstring InsetMathHull::label(row_type row) const
481 BOOST_ASSERT(row < nrows());
482 if (InsetLabel * il = label_[row])
483 return il->screenLabel();
488 void InsetMathHull::label(row_type row, docstring const & label)
490 //lyxerr << "setting label '" << label << "' for row " << row << endl;
492 label_[row]->updateCommand(label);
495 InsetCommandParams p(LABEL_CODE);
497 label_[row] = new InsetLabel(p);
499 label_[row]->setBuffer(buffer());
503 void InsetMathHull::numbered(row_type row, bool num)
506 if (nonum_[row] && label_[row]) {
513 bool InsetMathHull::numbered(row_type row) const
519 bool InsetMathHull::ams() const
522 type_ == hullAlign ||
523 type_ == hullFlAlign ||
524 type_ == hullMultline ||
525 type_ == hullGather ||
526 type_ == hullAlignAt ||
527 type_ == hullXAlignAt ||
528 type_ == hullXXAlignAt;
532 Inset::DisplayType InsetMathHull::display() const
534 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
538 void InsetMathHull::getLabelList(vector<docstring> & labels) const
540 for (row_type row = 0; row < nrows(); ++row)
541 if (label_[row] && !nonum_[row])
542 labels.push_back(label_[row]->screenLabel());
546 bool InsetMathHull::numberedType() const
548 if (type_ == hullNone)
550 if (type_ == hullSimple)
552 if (type_ == hullXXAlignAt)
554 for (row_type row = 0; row < nrows(); ++row)
561 void InsetMathHull::validate(LaTeXFeatures & features) const
564 features.require("amsmath");
567 // Validation is necessary only if not using AMS math.
568 // To be safe, we will always run mathedvalidate.
569 //if (features.amsstyle)
572 features.require("boldsymbol");
573 //features.binom = true;
575 InsetMathGrid::validate(features);
579 void InsetMathHull::header_write(WriteStream & os) const
581 bool n = numberedType();
595 os << "\\begin{equation" << star(n) << "}\n";
605 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
610 os << "\\begin{" << hullName(type_) << star(n) << '}'
611 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
615 os << "\\begin{" << hullName(type_) << '}'
616 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
620 os << "\\begin{unknown" << star(n) << '}';
626 void InsetMathHull::footer_write(WriteStream & os) const
628 bool n = numberedType();
641 os << "\\end{equation" << star(n) << "}\n";
653 os << "\\end{" << hullName(type_) << star(n) << "}\n";
657 os << "\\end{" << hullName(type_) << "}\n";
661 os << "\\end{unknown" << star(n) << '}';
667 bool InsetMathHull::rowChangeOK() const
670 type_ == hullEqnArray || type_ == hullAlign ||
671 type_ == hullFlAlign || type_ == hullAlignAt ||
672 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
673 type_ == hullGather || type_ == hullMultline;
677 bool InsetMathHull::colChangeOK() const
680 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
681 type_ == hullXAlignAt || type_ == hullXXAlignAt;
685 void InsetMathHull::addRow(row_type row)
689 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
690 label_.insert(label_.begin() + row + 1, 0);
691 InsetMathGrid::addRow(row);
695 void InsetMathHull::swapRow(row_type row)
699 if (row + 1 == nrows())
701 swap(nonum_[row], nonum_[row + 1]);
702 swap(label_[row], label_[row + 1]);
703 InsetMathGrid::swapRow(row);
707 void InsetMathHull::delRow(row_type row)
709 if (nrows() <= 1 || !rowChangeOK())
711 InsetMathGrid::delRow(row);
712 // The last dummy row has no number info nor a label.
713 // Test nrows() + 1 because we have already erased the row.
714 if (row == nrows() + 1)
716 nonum_.erase(nonum_.begin() + row);
719 label_.erase(label_.begin() + row);
723 void InsetMathHull::addCol(col_type col)
727 InsetMathGrid::addCol(col);
731 void InsetMathHull::delCol(col_type col)
733 if (ncols() <= 1 || !colChangeOK())
735 InsetMathGrid::delCol(col);
739 docstring InsetMathHull::nicelabel(row_type row) const
744 return from_ascii("(#)");
745 return '(' + label_[row]->screenLabel() + ')';
749 void InsetMathHull::glueall()
752 for (idx_type i = 0; i < nargs(); ++i)
754 *this = InsetMathHull(hullSimple);
760 void InsetMathHull::splitTo2Cols()
762 BOOST_ASSERT(ncols() == 1);
763 InsetMathGrid::addCol(1);
764 for (row_type row = 0; row < nrows(); ++row) {
765 idx_type const i = 2 * row;
766 pos_type pos = firstRelOp(cell(i));
767 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
768 cell(i).erase(pos, cell(i).size());
773 void InsetMathHull::splitTo3Cols()
775 BOOST_ASSERT(ncols() < 3);
778 InsetMathGrid::addCol(2);
779 for (row_type row = 0; row < nrows(); ++row) {
780 idx_type const i = 3 * row + 1;
781 if (cell(i).size()) {
782 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
783 cell(i).erase(1, cell(i).size());
789 void InsetMathHull::changeCols(col_type cols)
793 else if (ncols() < cols) {
799 while (ncols() < cols)
800 InsetMathGrid::addCol(ncols());
806 for (row_type row = 0; row < nrows(); ++row) {
807 idx_type const i = row * ncols();
808 for (col_type col = cols; col < ncols(); ++col) {
809 cell(i + cols - 1).append(cell(i + col));
813 while (ncols() > cols) {
814 InsetMathGrid::delCol(ncols() - 1);
819 HullType InsetMathHull::getType() const
825 void InsetMathHull::setType(HullType type)
832 void InsetMathHull::mutate(HullType newtype)
834 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
836 // we try to move along the chain
837 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
839 // +-------------------------------------+
840 // we use eqnarray as intermediate type for mutations that are not
841 // directly supported because it handles labels and numbering for
844 if (newtype == type_) {
848 else if (newtype < hullNone) {
853 else if (type_ == hullNone) {
859 else if (type_ == hullSimple) {
860 if (newtype == hullNone) {
864 setType(hullEquation);
870 else if (type_ == hullEquation) {
871 if (newtype < type_) {
875 } else if (newtype == hullEqnArray) {
876 // split it "nicely" on the first relop
878 setType(hullEqnArray);
879 } else if (newtype == hullMultline || newtype == hullGather) {
889 else if (type_ == hullEqnArray) {
890 if (newtype < type_) {
891 // set correct (no)numbering
893 for (row_type row = 0; row < nrows(); ++row) {
900 // set first non-empty label
901 for (row_type row = 0; row < nrows(); ++row) {
903 label_[0] = label_[row];
910 } else { // align & Co.
917 else if (type_ == hullAlign || type_ == hullAlignAt ||
918 type_ == hullXAlignAt || type_ == hullFlAlign) {
919 if (newtype < hullAlign) {
921 setType(hullEqnArray);
923 } else if (newtype == hullGather || newtype == hullMultline) {
926 } else if (newtype == hullXXAlignAt) {
927 for (row_type row = 0; row < nrows(); ++row)
928 numbered(row, false);
935 else if (type_ == hullXXAlignAt) {
936 for (row_type row = 0; row < nrows(); ++row)
937 numbered(row, false);
938 if (newtype < hullAlign) {
940 setType(hullEqnArray);
942 } else if (newtype == hullGather || newtype == hullMultline) {
950 else if (type_ == hullMultline || type_ == hullGather) {
951 if (newtype == hullGather || newtype == hullMultline)
953 else if (newtype == hullAlign || newtype == hullFlAlign ||
954 newtype == hullAlignAt || newtype == hullXAlignAt) {
957 } else if (newtype == hullXXAlignAt) {
959 for (row_type row = 0; row < nrows(); ++row)
960 numbered(row, false);
964 setType(hullEqnArray);
970 lyxerr << "mutation from '" << to_utf8(hullName(type_))
971 << "' to '" << to_utf8(hullName(newtype))
972 << "' not implemented" << endl;
977 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
980 if (numberedType()) {
981 if (label_[row] && !nonum_[row])
982 res += "\\label{" + label_[row]->screenLabel() + '}';
983 if (nonum_[row] && (type_ != hullMultline))
984 res += "\\nonumber ";
986 return res + InsetMathGrid::eolString(row, emptyline, fragile);
990 void InsetMathHull::write(WriteStream & os) const
993 InsetMathGrid::write(os);
998 void InsetMathHull::normalize(NormalStream & os) const
1000 os << "[formula " << hullName(type_) << ' ';
1001 InsetMathGrid::normalize(os);
1006 void InsetMathHull::mathmlize(MathStream & os) const
1008 InsetMathGrid::mathmlize(os);
1012 void InsetMathHull::infoize(odocstream & os) const
1014 os << "Type: " << hullName(type_);
1018 void InsetMathHull::check() const
1020 BOOST_ASSERT(nonum_.size() == nrows());
1021 BOOST_ASSERT(label_.size() == nrows());
1025 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1029 idocstringstream iss(func.argument());
1030 iss >> dlang >> extra;
1032 extra = from_ascii("noextra");
1033 string const lang = to_ascii(dlang);
1035 // FIXME: temporarily disabled
1036 //if (cur.selection()) {
1039 // lyxerr << "use selection: " << ar << endl;
1040 // insert(pipeThroughExtern(lang, extra, ar));
1045 eq.push_back(MathAtom(new InsetMathChar('=')));
1047 // go to first item in line
1048 cur.idx() -= cur.idx() % ncols();
1051 if (getType() == hullSimple) {
1052 size_type pos = cur.cell().find_last(eq);
1054 if (cur.inMathed() && cur.selection()) {
1055 asArray(grabAndEraseSelection(cur), ar);
1056 } else if (pos == cur.cell().size()) {
1058 lyxerr << "use whole cell: " << ar << endl;
1060 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1061 lyxerr << "use partial cell form pos: " << pos << endl;
1063 cur.cell().append(eq);
1064 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1065 cur.pos() = cur.lastpos();
1069 if (getType() == hullEquation) {
1070 lyxerr << "use equation inset" << endl;
1071 mutate(hullEqnArray);
1072 MathData & ar = cur.cell();
1073 lyxerr << "use cell: " << ar << endl;
1077 cur.cell() = pipeThroughExtern(lang, extra, ar);
1078 // move to end of line
1079 cur.pos() = cur.lastpos();
1084 lyxerr << "use eqnarray" << endl;
1085 cur.idx() += 2 - cur.idx() % ncols();
1087 MathData ar = cur.cell();
1088 lyxerr << "use cell: " << ar << endl;
1089 // FIXME: temporarily disabled
1095 cur.cell() = pipeThroughExtern(lang, extra, ar);
1096 cur.pos() = cur.lastpos();
1101 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1103 //lyxerr << "action: " << cmd.action << endl;
1104 switch (cmd.action) {
1106 case LFUN_FINISHED_BACKWARD:
1107 case LFUN_FINISHED_FORWARD:
1108 case LFUN_FINISHED_RIGHT:
1109 case LFUN_FINISHED_LEFT:
1110 //lyxerr << "action: " << cmd.action << endl;
1111 InsetMathGrid::doDispatch(cur, cmd);
1115 case LFUN_BREAK_PARAGRAPH:
1116 // just swallow this
1120 // some magic for the common case
1121 if (type_ == hullSimple || type_ == hullEquation) {
1122 cur.recordUndoInset();
1124 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1125 mutate(align ? hullAlign : hullEqnArray);
1126 cur.idx() = nrows() * ncols() - 1;
1127 cur.pos() = cur.lastpos();
1129 InsetMathGrid::doDispatch(cur, cmd);
1132 case LFUN_MATH_NUMBER_TOGGLE: {
1133 //lyxerr << "toggling all numbers" << endl;
1134 cur.recordUndoInset();
1135 bool old = numberedType();
1136 if (type_ == hullMultline)
1137 numbered(nrows() - 1, !old);
1139 for (row_type row = 0; row < nrows(); ++row)
1140 numbered(row, !old);
1142 cur.message(old ? _("No number") : _("Number"));
1146 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1147 cur.recordUndoInset();
1148 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1149 bool old = numbered(r);
1150 cur.message(old ? _("No number") : _("Number"));
1155 case LFUN_LABEL_INSERT: {
1156 cur.recordUndoInset();
1157 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1158 docstring old_label = label(r);
1159 docstring const default_label = from_ascii(
1160 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1161 if (old_label.empty())
1162 old_label = default_label;
1164 InsetCommandParams p(LABEL_CODE);
1165 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1166 string const data = InsetCommandMailer::params2string("label", p);
1168 if (cmd.argument().empty())
1169 cur.bv().showDialog("label", data);
1171 FuncRequest fr(LFUN_INSET_INSERT, data);
1177 case LFUN_INSET_INSERT: {
1178 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1179 string const name = cmd.getArg(0);
1180 if (name == "label") {
1181 InsetCommandParams p(LABEL_CODE);
1182 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1183 docstring str = p["name"];
1184 cur.recordUndoInset();
1185 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1189 docstring old = label(r);
1191 cur.bv().buffer().changeRefsIfUnique(old, str,
1197 InsetMathGrid::doDispatch(cur, cmd);
1201 case LFUN_MATH_EXTERN:
1202 cur.recordUndoInset();
1206 case LFUN_MATH_MUTATE: {
1207 cur.recordUndoInset();
1208 row_type row = cur.row();
1209 col_type col = cur.col();
1210 mutate(hullType(cmd.argument()));
1211 cur.idx() = row * ncols() + col;
1212 if (cur.idx() > cur.lastidx()) {
1213 cur.idx() = cur.lastidx();
1214 cur.pos() = cur.lastpos();
1216 if (cur.pos() > cur.lastpos())
1217 cur.pos() = cur.lastpos();
1219 // FIXME: find some more clever handling of the selection,
1220 // i.e. preserve it.
1221 cur.clearSelection();
1222 //cur.dispatched(FINISHED);
1226 case LFUN_MATH_DISPLAY: {
1227 cur.recordUndoInset();
1228 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1230 cur.pos() = cur.lastpos();
1231 //cur.dispatched(FINISHED);
1236 InsetMathGrid::doDispatch(cur, cmd);
1242 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1243 FuncStatus & status) const
1245 switch (cmd.action) {
1246 case LFUN_FINISHED_BACKWARD:
1247 case LFUN_FINISHED_FORWARD:
1248 case LFUN_FINISHED_RIGHT:
1249 case LFUN_FINISHED_LEFT:
1253 case LFUN_MATH_EXTERN:
1254 case LFUN_MATH_MUTATE:
1255 case LFUN_MATH_DISPLAY:
1257 status.enabled(true);
1259 case LFUN_MATH_NUMBER_TOGGLE:
1260 // FIXME: what is the right test, this or the one of
1262 status.enabled(display());
1263 status.setOnOff(numberedType());
1265 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1266 // FIXME: what is the right test, this or the one of
1268 status.enabled(display());
1269 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1270 status.setOnOff(numbered(r));
1273 case LFUN_LABEL_INSERT:
1274 status.enabled(type_ != hullSimple);
1276 case LFUN_INSET_INSERT:
1277 if (cmd.getArg(0) == "label") {
1278 status.enabled(type_ != hullSimple);
1281 return InsetMathGrid::getStatus(cur, cmd, status);
1282 case LFUN_TABULAR_FEATURE: {
1283 istringstream is(to_utf8(cmd.argument()));
1287 && (s == "append-row"
1288 || s == "delete-row"
1289 || s == "copy-row")) {
1290 status.message(bformat(
1291 from_utf8(N_("Can't change number of rows in '%1$s'")),
1293 status.enabled(false);
1297 && (s == "append-column"
1298 || s == "delete-column"
1299 || s == "copy-column")) {
1300 status.message(bformat(
1301 from_utf8(N_("Can't change number of columns in '%1$s'")),
1303 status.enabled(false);
1306 if ((type_ == hullSimple
1307 || type_ == hullEquation
1308 || type_ == hullNone) &&
1309 (s == "add-hline-above" || s == "add-hline-below")) {
1310 status.message(bformat(
1311 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1313 status.enabled(false);
1316 if (s == "add-vline-left" || s == "add-vline-right") {
1317 status.message(bformat(
1318 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1320 status.enabled(false);
1323 if (s == "valign-top" || s == "valign-middle"
1324 || s == "valign-bottom" || s == "align-left"
1325 || s == "align-center" || s == "align-right") {
1326 status.enabled(false);
1329 return InsetMathGrid::getStatus(cur, cmd, status);
1332 return InsetMathGrid::getStatus(cur, cmd, status);
1335 // This cannot really happen, but inserted to shut-up gcc
1336 return InsetMathGrid::getStatus(cur, cmd, status);
1340 /////////////////////////////////////////////////////////////////////
1344 // simply scrap this function if you want
1345 void InsetMathHull::mutateToText()
1348 // translate to latex
1350 latex(NULL, os, false, false);
1351 string str = os.str();
1354 Text * lt = view_->cursor().innerText();
1355 string::const_iterator cit = str.begin();
1356 string::const_iterator end = str.end();
1357 for (; cit != end; ++cit)
1358 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1361 //dispatch(LFUN_ESCAPE);
1366 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1367 docstring const & font)
1369 // this whole function is a hack and won't work for incremental font
1372 if (cur.inset().asInsetMath()->name() == font)
1373 cur.handleFont(to_utf8(font));
1375 cur.handleNest(createInsetMath(font));
1381 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1386 font.fromString(to_utf8(arg), b);
1387 if (font.fontInfo().color() != Color_inherit) {
1388 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1389 cur.handleNest(at, 0);
1394 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1397 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1398 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1399 enter_front ? idxFirst(cur) : idxLast(cur);
1400 // The inset formula dimension is not necessarily the same as the
1401 // one of the instant preview image, so we have to indicate to the
1402 // BufferView that a metrics update is needed.
1403 cur.updateFlags(Update::Force);
1407 docstring InsetMathHull::editMessage() const
1409 return _("Math editor mode");
1413 void InsetMathHull::revealCodes(Cursor & cur) const
1415 if (!cur.inMathed())
1417 odocstringstream os;
1419 cur.message(os.str());
1421 // write something to the minibuffer
1422 // translate to latex
1426 string str = os.str();
1428 string::size_type pos = 0;
1430 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1433 else if (*it == '\0') {
1435 pos = it - str.begin();
1441 res = res.substr(pos - 30);
1442 if (res.size() > 60)
1443 res = res.substr(0, 60);
1449 InsetCode InsetMathHull::lyxCode() const
1455 /////////////////////////////////////////////////////////////////////
1459 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1462 // FIXME: completely broken
1463 static InsetMathHull * lastformula = 0;
1464 static CursorBase current = DocIterator(ibegin(nucleus()));
1466 static string laststr;
1468 if (lastformula != this || laststr != str) {
1469 //lyxerr << "reset lastformula to " << this << endl;
1472 current = ibegin(nucleus());
1474 mathed_parse_cell(ar, str);
1478 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1480 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1481 CursorSlice & top = it.back();
1482 MathData const & a = top.asInsetMath()->cell(top.idx_);
1483 if (a.matchpart(ar, top.pos_)) {
1484 bv->cursor().setSelection(it, ar.size());
1486 top.pos_ += ar.size();
1492 //lyxerr << "not found!" << endl;
1499 void InsetMathHull::write(ostream & os) const
1501 odocstringstream oss;
1502 WriteStream wi(oss, false, false);
1505 os << to_utf8(oss.str());
1509 void InsetMathHull::read(Lexer & lex)
1512 mathed_parse_normal(at, lex);
1513 operator=(*at->asHullInset());
1517 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1519 if (0 && display()) {
1523 TextPainter tpain(dim.width(), dim.height());
1524 drawT(tpain, 0, dim.ascent());
1526 // reset metrics cache to "real" values
1528 return tpain.textheight();
1530 odocstringstream oss;
1531 WriteStream wi(oss, false, true);
1534 docstring const str = oss.str();
1541 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1546 if (getType() == hullSimple)
1547 name = from_ascii("inlineequation");
1549 name = from_ascii("informalequation");
1551 docstring bname = name;
1552 if (!label(0).empty())
1553 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1555 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1557 odocstringstream ls;
1558 if (runparams.flavor == OutputParams::XML) {
1559 ms << MTag("alt role='tex' ");
1560 // Workaround for db2latex: db2latex always includes equations with
1561 // \ensuremath{} or \begin{display}\end{display}
1562 // so we strip LyX' math environment
1563 WriteStream wi(ls, false, false);
1564 InsetMathGrid::write(wi);
1565 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1570 InsetMathGrid::mathmlize(ms);
1573 ms << MTag("alt role='tex'");
1574 res = latex(ls, runparams);
1575 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1579 ms << from_ascii("<graphic fileref=\"eqn/");
1580 if (!label(0).empty())
1581 ms << sgml::cleanID(buffer(), runparams, label(0));
1583 ms << sgml::uniqueID(from_ascii("anon"));
1585 if (runparams.flavor == OutputParams::XML)
1586 ms << from_ascii("\"/>");
1588 ms << from_ascii("\">");
1590 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1592 return ms.line() + res;
1596 void InsetMathHull::textString(odocstream & os) const
1598 plaintext(os, OutputParams(0));