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 void InsetMathHull::getLabelList(vector<docstring> & labels) const
543 for (row_type row = 0; row < nrows(); ++row)
544 if (label_[row] && !nonum_[row])
545 labels.push_back(label_[row]->screenLabel());
549 bool InsetMathHull::numberedType() const
551 if (type_ == hullNone)
553 if (type_ == hullSimple)
555 if (type_ == hullXXAlignAt)
557 for (row_type row = 0; row < nrows(); ++row)
564 void InsetMathHull::validate(LaTeXFeatures & features) const
567 features.require("amsmath");
570 // Validation is necessary only if not using AMS math.
571 // To be safe, we will always run mathedvalidate.
572 //if (features.amsstyle)
575 features.require("boldsymbol");
576 //features.binom = true;
578 InsetMathGrid::validate(features);
582 void InsetMathHull::header_write(WriteStream & os) const
584 bool n = numberedType();
598 os << "\\begin{equation" << star(n) << "}\n";
608 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
613 os << "\\begin{" << hullName(type_) << star(n) << '}'
614 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
618 os << "\\begin{" << hullName(type_) << '}'
619 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
623 os << "\\begin{unknown" << star(n) << '}';
629 void InsetMathHull::footer_write(WriteStream & os) const
631 bool n = numberedType();
644 os << "\\end{equation" << star(n) << "}\n";
656 os << "\\end{" << hullName(type_) << star(n) << "}\n";
660 os << "\\end{" << hullName(type_) << "}\n";
664 os << "\\end{unknown" << star(n) << '}';
670 bool InsetMathHull::rowChangeOK() const
673 type_ == hullEqnArray || type_ == hullAlign ||
674 type_ == hullFlAlign || type_ == hullAlignAt ||
675 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
676 type_ == hullGather || type_ == hullMultline;
680 bool InsetMathHull::colChangeOK() const
683 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
684 type_ == hullXAlignAt || type_ == hullXXAlignAt;
688 void InsetMathHull::addRow(row_type row)
692 nonum_.insert(nonum_.begin() + row + 1, !numberedType());
693 label_.insert(label_.begin() + row + 1, dummy_pointer);
694 InsetMathGrid::addRow(row);
698 void InsetMathHull::swapRow(row_type row)
702 if (row + 1 == nrows())
704 // gcc doesn't like this:
705 // swap(nonum_[row], nonum_[row + 1]);
706 // so we do it manually:
707 bool const b = nonum_[row];
708 nonum_[row] = nonum_[row + 1];
710 swap(label_[row], label_[row + 1]);
711 InsetMathGrid::swapRow(row);
715 void InsetMathHull::delRow(row_type row)
717 if (nrows() <= 1 || !rowChangeOK())
719 InsetMathGrid::delRow(row);
720 // The last dummy row has no number info nor a label.
721 // Test nrows() + 1 because we have already erased the row.
722 if (row == nrows() + 1)
724 nonum_.erase(nonum_.begin() + row);
726 label_.erase(label_.begin() + row);
730 void InsetMathHull::addCol(col_type col)
734 InsetMathGrid::addCol(col);
738 void InsetMathHull::delCol(col_type col)
740 if (ncols() <= 1 || !colChangeOK())
742 InsetMathGrid::delCol(col);
746 docstring InsetMathHull::nicelabel(row_type row) const
751 return from_ascii("(#)");
752 return '(' + label_[row]->screenLabel() + ')';
756 void InsetMathHull::glueall()
759 for (idx_type i = 0; i < nargs(); ++i)
761 *this = InsetMathHull(hullSimple);
767 void InsetMathHull::splitTo2Cols()
769 BOOST_ASSERT(ncols() == 1);
770 InsetMathGrid::addCol(1);
771 for (row_type row = 0; row < nrows(); ++row) {
772 idx_type const i = 2 * row;
773 pos_type pos = firstRelOp(cell(i));
774 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
775 cell(i).erase(pos, cell(i).size());
780 void InsetMathHull::splitTo3Cols()
782 BOOST_ASSERT(ncols() < 3);
785 InsetMathGrid::addCol(2);
786 for (row_type row = 0; row < nrows(); ++row) {
787 idx_type const i = 3 * row + 1;
788 if (cell(i).size()) {
789 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
790 cell(i).erase(1, cell(i).size());
796 void InsetMathHull::changeCols(col_type cols)
800 else if (ncols() < cols) {
806 while (ncols() < cols)
807 InsetMathGrid::addCol(ncols());
813 for (row_type row = 0; row < nrows(); ++row) {
814 idx_type const i = row * ncols();
815 for (col_type col = cols; col < ncols(); ++col) {
816 cell(i + cols - 1).append(cell(i + col));
820 while (ncols() > cols) {
821 InsetMathGrid::delCol(ncols() - 1);
826 HullType InsetMathHull::getType() const
832 void InsetMathHull::setType(HullType type)
839 void InsetMathHull::mutate(HullType newtype)
841 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
843 // we try to move along the chain
844 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
846 // +-------------------------------------+
847 // we use eqnarray as intermediate type for mutations that are not
848 // directly supported because it handles labels and numbering for
851 if (newtype == type_) {
855 else if (newtype < hullNone) {
860 else if (type_ == hullNone) {
866 else if (type_ == hullSimple) {
867 if (newtype == hullNone) {
871 setType(hullEquation);
877 else if (type_ == hullEquation) {
878 if (newtype < type_) {
882 } else if (newtype == hullEqnArray) {
883 // split it "nicely" on the first relop
885 setType(hullEqnArray);
886 } else if (newtype == hullMultline || newtype == hullGather) {
896 else if (type_ == hullEqnArray) {
897 if (newtype < type_) {
898 // set correct (no)numbering
900 for (row_type row = 0; row < nrows(); ++row) {
907 // set first non-empty label
908 for (row_type row = 0; row < nrows(); ++row) {
910 label_[0] = label_[row];
917 } else { // align & Co.
924 else if (type_ == hullAlign || type_ == hullAlignAt ||
925 type_ == hullXAlignAt || type_ == hullFlAlign) {
926 if (newtype < hullAlign) {
928 setType(hullEqnArray);
930 } else if (newtype == hullGather || newtype == hullMultline) {
933 } else if (newtype == hullXXAlignAt) {
934 for (row_type row = 0; row < nrows(); ++row)
935 numbered(row, false);
942 else if (type_ == hullXXAlignAt) {
943 for (row_type row = 0; row < nrows(); ++row)
944 numbered(row, false);
945 if (newtype < hullAlign) {
947 setType(hullEqnArray);
949 } else if (newtype == hullGather || newtype == hullMultline) {
957 else if (type_ == hullMultline || type_ == hullGather) {
958 if (newtype == hullGather || newtype == hullMultline)
960 else if (newtype == hullAlign || newtype == hullFlAlign ||
961 newtype == hullAlignAt || newtype == hullXAlignAt) {
964 } else if (newtype == hullXXAlignAt) {
966 for (row_type row = 0; row < nrows(); ++row)
967 numbered(row, false);
971 setType(hullEqnArray);
977 lyxerr << "mutation from '" << to_utf8(hullName(type_))
978 << "' to '" << to_utf8(hullName(newtype))
979 << "' not implemented" << endl;
984 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
987 if (numberedType()) {
988 if (label_[row] && !nonum_[row])
989 res += "\\label{" + label_[row]->getParam("name") + '}';
990 if (nonum_[row] && (type_ != hullMultline))
991 res += "\\nonumber ";
993 return res + InsetMathGrid::eolString(row, emptyline, fragile);
997 void InsetMathHull::write(WriteStream & os) const
1000 InsetMathGrid::write(os);
1005 void InsetMathHull::normalize(NormalStream & os) const
1007 os << "[formula " << hullName(type_) << ' ';
1008 InsetMathGrid::normalize(os);
1013 void InsetMathHull::mathmlize(MathStream & os) const
1015 InsetMathGrid::mathmlize(os);
1019 void InsetMathHull::infoize(odocstream & os) const
1021 os << "Type: " << hullName(type_);
1025 void InsetMathHull::check() const
1027 BOOST_ASSERT(nonum_.size() == nrows());
1028 BOOST_ASSERT(label_.size() == nrows());
1032 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1036 idocstringstream iss(func.argument());
1037 iss >> dlang >> extra;
1039 extra = from_ascii("noextra");
1040 string const lang = to_ascii(dlang);
1042 // FIXME: temporarily disabled
1043 //if (cur.selection()) {
1046 // lyxerr << "use selection: " << ar << endl;
1047 // insert(pipeThroughExtern(lang, extra, ar));
1052 eq.push_back(MathAtom(new InsetMathChar('=')));
1054 // go to first item in line
1055 cur.idx() -= cur.idx() % ncols();
1058 if (getType() == hullSimple) {
1059 size_type pos = cur.cell().find_last(eq);
1061 if (cur.inMathed() && cur.selection()) {
1062 asArray(grabAndEraseSelection(cur), ar);
1063 } else if (pos == cur.cell().size()) {
1065 lyxerr << "use whole cell: " << ar << endl;
1067 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1068 lyxerr << "use partial cell form pos: " << pos << endl;
1070 cur.cell().append(eq);
1071 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1072 cur.pos() = cur.lastpos();
1076 if (getType() == hullEquation) {
1077 lyxerr << "use equation inset" << endl;
1078 mutate(hullEqnArray);
1079 MathData & ar = cur.cell();
1080 lyxerr << "use cell: " << ar << endl;
1084 cur.cell() = pipeThroughExtern(lang, extra, ar);
1085 // move to end of line
1086 cur.pos() = cur.lastpos();
1091 lyxerr << "use eqnarray" << endl;
1092 cur.idx() += 2 - cur.idx() % ncols();
1094 MathData ar = cur.cell();
1095 lyxerr << "use cell: " << ar << endl;
1096 // FIXME: temporarily disabled
1102 cur.cell() = pipeThroughExtern(lang, extra, ar);
1103 cur.pos() = cur.lastpos();
1108 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1110 //lyxerr << "action: " << cmd.action << endl;
1111 switch (cmd.action) {
1113 case LFUN_FINISHED_BACKWARD:
1114 case LFUN_FINISHED_FORWARD:
1115 case LFUN_FINISHED_RIGHT:
1116 case LFUN_FINISHED_LEFT:
1117 //lyxerr << "action: " << cmd.action << endl;
1118 InsetMathGrid::doDispatch(cur, cmd);
1122 case LFUN_BREAK_PARAGRAPH:
1123 // just swallow this
1127 // some magic for the common case
1128 if (type_ == hullSimple || type_ == hullEquation) {
1129 cur.recordUndoInset();
1131 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1132 mutate(align ? hullAlign : hullEqnArray);
1133 cur.idx() = nrows() * ncols() - 1;
1134 cur.pos() = cur.lastpos();
1136 InsetMathGrid::doDispatch(cur, cmd);
1139 case LFUN_MATH_NUMBER_TOGGLE: {
1140 //lyxerr << "toggling all numbers" << endl;
1141 cur.recordUndoInset();
1142 bool old = numberedType();
1143 if (type_ == hullMultline)
1144 numbered(nrows() - 1, !old);
1146 for (row_type row = 0; row < nrows(); ++row)
1147 numbered(row, !old);
1149 cur.message(old ? _("No number") : _("Number"));
1153 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1154 cur.recordUndoInset();
1155 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1156 bool old = numbered(r);
1157 cur.message(old ? _("No number") : _("Number"));
1162 case LFUN_LABEL_INSERT: {
1163 cur.recordUndoInset();
1164 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1165 docstring old_label = label(r);
1166 docstring const default_label = from_ascii(
1167 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1168 if (old_label.empty())
1169 old_label = default_label;
1171 InsetCommandParams p(LABEL_CODE);
1172 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1173 string const data = InsetCommandMailer::params2string("label", p);
1175 if (cmd.argument().empty())
1176 cur.bv().showDialog("label", data);
1178 FuncRequest fr(LFUN_INSET_INSERT, data);
1184 case LFUN_INSET_INSERT: {
1185 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1186 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1187 string const name = cmd.getArg(0);
1188 if (name == "label") {
1189 InsetCommandParams p(LABEL_CODE);
1190 InsetCommandMailer::string2params(name, to_utf8(cmd.argument()), p);
1191 docstring str = p["name"];
1192 cur.recordUndoInset();
1193 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1197 docstring old = label(r);
1200 // The label will take care of the reference update.
1204 // Newly created inset so initialize it.
1205 label_[r]->initView();
1210 InsetMathGrid::doDispatch(cur, cmd);
1214 case LFUN_MATH_EXTERN:
1215 cur.recordUndoInset();
1219 case LFUN_MATH_MUTATE: {
1220 cur.recordUndoInset();
1221 row_type row = cur.row();
1222 col_type col = cur.col();
1223 mutate(hullType(cmd.argument()));
1224 cur.idx() = row * ncols() + col;
1225 if (cur.idx() > cur.lastidx()) {
1226 cur.idx() = cur.lastidx();
1227 cur.pos() = cur.lastpos();
1229 if (cur.pos() > cur.lastpos())
1230 cur.pos() = cur.lastpos();
1232 // FIXME: find some more clever handling of the selection,
1233 // i.e. preserve it.
1234 cur.clearSelection();
1235 //cur.dispatched(FINISHED);
1239 case LFUN_MATH_DISPLAY: {
1240 cur.recordUndoInset();
1241 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1243 cur.pos() = cur.lastpos();
1244 //cur.dispatched(FINISHED);
1249 InsetMathGrid::doDispatch(cur, cmd);
1255 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1256 FuncStatus & status) const
1258 switch (cmd.action) {
1259 case LFUN_FINISHED_BACKWARD:
1260 case LFUN_FINISHED_FORWARD:
1261 case LFUN_FINISHED_RIGHT:
1262 case LFUN_FINISHED_LEFT:
1266 case LFUN_MATH_EXTERN:
1267 case LFUN_MATH_MUTATE:
1268 case LFUN_MATH_DISPLAY:
1270 status.enabled(true);
1272 case LFUN_MATH_NUMBER_TOGGLE:
1273 // FIXME: what is the right test, this or the one of
1275 status.enabled(display());
1276 status.setOnOff(numberedType());
1278 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1279 // FIXME: what is the right test, this or the one of
1281 status.enabled(display());
1282 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1283 status.setOnOff(numbered(r));
1286 case LFUN_LABEL_INSERT:
1287 status.enabled(type_ != hullSimple);
1289 case LFUN_INSET_INSERT:
1290 if (cmd.getArg(0) == "label") {
1291 status.enabled(type_ != hullSimple);
1294 return InsetMathGrid::getStatus(cur, cmd, status);
1295 case LFUN_TABULAR_FEATURE: {
1296 istringstream is(to_utf8(cmd.argument()));
1300 && (s == "append-row"
1301 || s == "delete-row"
1302 || s == "copy-row")) {
1303 status.message(bformat(
1304 from_utf8(N_("Can't change number of rows in '%1$s'")),
1306 status.enabled(false);
1310 && (s == "append-column"
1311 || s == "delete-column"
1312 || s == "copy-column")) {
1313 status.message(bformat(
1314 from_utf8(N_("Can't change number of columns in '%1$s'")),
1316 status.enabled(false);
1319 if ((type_ == hullSimple
1320 || type_ == hullEquation
1321 || type_ == hullNone) &&
1322 (s == "add-hline-above" || s == "add-hline-below")) {
1323 status.message(bformat(
1324 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1326 status.enabled(false);
1329 if (s == "add-vline-left" || s == "add-vline-right") {
1330 status.message(bformat(
1331 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1333 status.enabled(false);
1336 if (s == "valign-top" || s == "valign-middle"
1337 || s == "valign-bottom" || s == "align-left"
1338 || s == "align-center" || s == "align-right") {
1339 status.enabled(false);
1342 return InsetMathGrid::getStatus(cur, cmd, status);
1345 return InsetMathGrid::getStatus(cur, cmd, status);
1348 // This cannot really happen, but inserted to shut-up gcc
1349 return InsetMathGrid::getStatus(cur, cmd, status);
1353 /////////////////////////////////////////////////////////////////////
1357 // simply scrap this function if you want
1358 void InsetMathHull::mutateToText()
1361 // translate to latex
1363 latex(NULL, os, false, false);
1364 string str = os.str();
1367 Text * lt = view_->cursor().innerText();
1368 string::const_iterator cit = str.begin();
1369 string::const_iterator end = str.end();
1370 for (; cit != end; ++cit)
1371 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1374 //dispatch(LFUN_ESCAPE);
1379 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1380 docstring const & font)
1382 // this whole function is a hack and won't work for incremental font
1385 if (cur.inset().asInsetMath()->name() == font)
1386 cur.handleFont(to_utf8(font));
1388 cur.handleNest(createInsetMath(font));
1394 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1399 font.fromString(to_utf8(arg), b);
1400 if (font.fontInfo().color() != Color_inherit) {
1401 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1402 cur.handleNest(at, 0);
1407 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1410 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1411 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1412 enter_front ? idxFirst(cur) : idxLast(cur);
1413 // The inset formula dimension is not necessarily the same as the
1414 // one of the instant preview image, so we have to indicate to the
1415 // BufferView that a metrics update is needed.
1416 cur.updateFlags(Update::Force);
1420 docstring InsetMathHull::editMessage() const
1422 return _("Math editor mode");
1426 void InsetMathHull::revealCodes(Cursor & cur) const
1428 if (!cur.inMathed())
1430 odocstringstream os;
1432 cur.message(os.str());
1434 // write something to the minibuffer
1435 // translate to latex
1439 string str = os.str();
1441 string::size_type pos = 0;
1443 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1446 else if (*it == '\0') {
1448 pos = it - str.begin();
1454 res = res.substr(pos - 30);
1455 if (res.size() > 60)
1456 res = res.substr(0, 60);
1462 InsetCode InsetMathHull::lyxCode() const
1468 /////////////////////////////////////////////////////////////////////
1472 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1475 // FIXME: completely broken
1476 static InsetMathHull * lastformula = 0;
1477 static CursorBase current = DocIterator(ibegin(nucleus()));
1479 static string laststr;
1481 if (lastformula != this || laststr != str) {
1482 //lyxerr << "reset lastformula to " << this << endl;
1485 current = ibegin(nucleus());
1487 mathed_parse_cell(ar, str);
1491 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1493 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1494 CursorSlice & top = it.back();
1495 MathData const & a = top.asInsetMath()->cell(top.idx_);
1496 if (a.matchpart(ar, top.pos_)) {
1497 bv->cursor().setSelection(it, ar.size());
1499 top.pos_ += ar.size();
1505 //lyxerr << "not found!" << endl;
1512 void InsetMathHull::write(ostream & os) const
1514 odocstringstream oss;
1515 WriteStream wi(oss, false, false);
1518 os << to_utf8(oss.str());
1522 void InsetMathHull::read(Lexer & lex)
1525 mathed_parse_normal(at, lex);
1526 operator=(*at->asHullInset());
1530 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1532 if (0 && display()) {
1536 TextPainter tpain(dim.width(), dim.height());
1537 drawT(tpain, 0, dim.ascent());
1539 // reset metrics cache to "real" values
1541 return tpain.textheight();
1543 odocstringstream oss;
1544 WriteStream wi(oss, false, true);
1547 docstring const str = oss.str();
1554 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1559 if (getType() == hullSimple)
1560 name = from_ascii("inlineequation");
1562 name = from_ascii("informalequation");
1564 docstring bname = name;
1565 if (!label(0).empty())
1566 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1568 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1570 odocstringstream ls;
1571 if (runparams.flavor == OutputParams::XML) {
1572 ms << MTag("alt role='tex' ");
1573 // Workaround for db2latex: db2latex always includes equations with
1574 // \ensuremath{} or \begin{display}\end{display}
1575 // so we strip LyX' math environment
1576 WriteStream wi(ls, false, false);
1577 InsetMathGrid::write(wi);
1578 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1583 InsetMathGrid::mathmlize(ms);
1586 ms << MTag("alt role='tex'");
1587 res = latex(ls, runparams);
1588 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1592 ms << from_ascii("<graphic fileref=\"eqn/");
1593 if (!label(0).empty())
1594 ms << sgml::cleanID(buffer(), runparams, label(0));
1596 ms << sgml::uniqueID(from_ascii("anon"));
1598 if (runparams.flavor == OutputParams::XML)
1599 ms << from_ascii("\"/>");
1601 ms << from_ascii("\">");
1603 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1605 return ms.line() + res;
1609 void InsetMathHull::textString(odocstream & os) const
1611 plaintext(os, OutputParams(0));