2 * \file InsetMathHull.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathArray.h"
14 #include "InsetMathChar.h"
15 #include "InsetMathColor.h"
17 #include "InsetMathDelim.h"
18 #include "MathExtern.h"
19 #include "MathFactory.h"
20 #include "InsetMathHull.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "InsetMathSpace.h"
24 #include "MathStream.h"
25 #include "MathSupport.h"
26 #include "InsetMathRef.h"
29 #include "buffer_funcs.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "CutAndPaste.h"
33 #include "FuncStatus.h"
34 #include "LaTeXFeatures.h"
36 #include "DispatchResult.h"
37 #include "FuncRequest.h"
40 #include "OutputParams.h"
41 #include "ParIterator.h"
44 #include "TextPainter.h"
45 #include "TocBackend.h"
47 #include "insets/RenderPreview.h"
48 #include "insets/InsetLabel.h"
50 #include "graphics/PreviewImage.h"
51 #include "graphics/PreviewLoader.h"
53 #include "frontends/Painter.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
63 using namespace lyx::support;
67 using cap::grabAndEraseSelection;
71 int getCols(HullType type)
88 // returns position of first relation operator in the array
89 // used for "intelligent splitting"
90 size_t firstRelOp(MathData const & ar)
92 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
94 return it - ar.begin();
99 char const * star(bool numbered)
101 return numbered ? "" : "*";
105 } // end anon namespace
108 HullType hullType(docstring const & s)
110 if (s == "none") return hullNone;
111 if (s == "simple") return hullSimple;
112 if (s == "equation") return hullEquation;
113 if (s == "eqnarray") return hullEqnArray;
114 if (s == "align") return hullAlign;
115 if (s == "alignat") return hullAlignAt;
116 if (s == "xalignat") return hullXAlignAt;
117 if (s == "xxalignat") return hullXXAlignAt;
118 if (s == "multline") return hullMultline;
119 if (s == "gather") return hullGather;
120 if (s == "flalign") return hullFlAlign;
121 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
126 docstring hullName(HullType type)
129 case hullNone: return from_ascii("none");
130 case hullSimple: return from_ascii("simple");
131 case hullEquation: return from_ascii("equation");
132 case hullEqnArray: return from_ascii("eqnarray");
133 case hullAlign: return from_ascii("align");
134 case hullAlignAt: return from_ascii("alignat");
135 case hullXAlignAt: return from_ascii("xalignat");
136 case hullXXAlignAt: return from_ascii("xxalignat");
137 case hullMultline: return from_ascii("multline");
138 case hullGather: return from_ascii("gather");
139 case hullFlAlign: return from_ascii("flalign");
141 lyxerr << "unknown hull type '" << type << "'" << endl;
142 return from_ascii("none");
146 static InsetLabel * dummy_pointer = 0;
148 InsetMathHull::InsetMathHull()
149 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
150 label_(1, dummy_pointer), preview_(new RenderPreview(this))
152 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
153 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
154 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
155 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
161 InsetMathHull::InsetMathHull(HullType type)
162 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
163 label_(1, dummy_pointer), preview_(new RenderPreview(this))
170 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
176 InsetMathHull::~InsetMathHull()
178 for (size_t i = 0; i < label_.size(); ++i)
183 Inset * InsetMathHull::clone() const
185 return new InsetMathHull(*this);
189 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
193 InsetMathGrid::operator=(other);
195 nonum_ = other.nonum_;
196 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 (idx_type i = 0, n = nargs(); i != n; ++i) {
213 MathData & data = cell(i);
214 for (size_t j = 0; j != data.size(); ++j)
215 data[j].nucleus()->setBuffer(buffer);
218 for (size_t i = 0; i != label_.size(); ++i) {
220 label_[i]->setBuffer(buffer);
225 void InsetMathHull::updateLabels(ParIterator const & it)
228 //FIXME: buffer_ should be set at creation for this inset! Problem is
229 // This inset is created at too many places (see Parser::parse1() in
233 for (size_t i = 0; i != label_.size(); ++i) {
235 label_[i]->updateLabels(it);
240 void InsetMathHull::addToToc(DocIterator const & pit)
243 //FIXME: buffer_ should be set at creation for this inset! Problem is
244 // This inset is created at too many places (see Parser::parse1() in
249 Toc & toc = buffer().tocBackend().toc("equation");
251 for (row_type row = 0; row != nrows(); ++row) {
255 label_[row]->addToToc(pit);
256 toc.push_back(TocItem(pit, 0, nicelabel(row)));
261 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
267 return InsetMathNest::editXY(cur, x, y);
271 InsetMath::mode_type InsetMathHull::currentMode() const
273 if (type_ == hullNone)
274 return UNDECIDED_MODE;
275 // definitely math mode ...
280 bool InsetMathHull::idxFirst(Cursor & cur) const
288 bool InsetMathHull::idxLast(Cursor & cur) const
290 cur.idx() = nargs() - 1;
291 cur.pos() = cur.lastpos();
296 char InsetMathHull::defaultColAlign(col_type col)
298 if (type_ == hullEqnArray)
300 if (type_ == hullGather)
302 if (type_ >= hullAlign)
303 return "rl"[col & 1];
308 int InsetMathHull::defaultColSpace(col_type col)
310 if (type_ == hullAlign || type_ == hullAlignAt)
312 if (type_ == hullXAlignAt)
313 return (col & 1) ? 20 : 0;
314 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
315 return (col & 1) ? 40 : 0;
320 docstring InsetMathHull::standardFont() const
322 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
326 bool InsetMathHull::previewState(BufferView * bv) const
328 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
329 graphics::PreviewImage const * pimage =
330 preview_->getPreviewImage(bv->buffer());
331 return pimage && pimage->image();
337 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
339 if (previewState(mi.base.bv)) {
340 preview_->metrics(mi, dim);
341 // insert a one pixel gap in front of the formula
344 dim.des += displayMargin();
345 // Cache the inset dimension.
346 setDimCache(mi, dim);
350 FontSetChanger dummy1(mi.base, standardFont());
351 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
353 // let the cells adjust themselves
354 InsetMathGrid::metrics(mi, dim);
357 dim.asc += displayMargin();
358 dim.des += displayMargin();
361 if (numberedType()) {
362 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
364 for (row_type row = 0; row < nrows(); ++row)
365 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
371 // make it at least as high as the current font
374 math_font_max_dim(mi.base.font, asc, des);
375 dim.asc = max(dim.asc, asc);
376 dim.des = max(dim.des, des);
377 // Cache the inset dimension.
378 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
379 setDimCache(mi, dim);
383 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
385 use_preview_ = previewState(pi.base.bv);
386 Dimension const dim = dimension(*pi.base.bv);
388 // background of mathed under focus is not painted because
389 // selection at the top level of nested inset is difficult to handle.
390 if (!editing(pi.base.bv))
391 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
392 dim.asc + dim.des - 1, Color_mathbg);
395 // one pixel gap in front
396 preview_->draw(pi, x + 1, y);
397 setPosCache(pi, x, y);
401 FontSetChanger dummy1(pi.base, standardFont());
402 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
403 InsetMathGrid::draw(pi, x + 1, y);
405 if (numberedType()) {
406 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
407 for (row_type row = 0; row < nrows(); ++row) {
408 int const yy = y + rowinfo_[row].offset_;
409 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
410 docstring const nl = nicelabel(row);
414 setPosCache(pi, x, y);
418 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
421 InsetMathGrid::metricsT(mi, dim);
424 WriteStream wi(os, false, true, false);
426 dim.wid = os.str().size();
433 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
436 InsetMathGrid::drawT(pain, x, y);
439 WriteStream wi(os, false, true, false);
441 pain.draw(x, y, os.str().c_str());
446 static docstring latexString(InsetMathHull const & inset)
449 // This has to be static, because a preview snippet containing math
450 // in text mode (such as $\text{$\phi$}$) gets processed twice. The
451 // first time as a whole, and the second time only the inner math.
452 // In this last case inset.buffer() would be invalid.
453 // FIXME: preview snippets should only be processed once, such that
454 // both static qualifier and isBufferValid() check can be dropped.
455 static Encoding const * encoding = 0;
456 if (inset.isBufferValid())
457 encoding = &(inset.buffer().params().encoding());
458 WriteStream wi(ls, false, true, false, encoding);
464 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
466 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
467 docstring const snippet = latexString(*this);
468 preview_->addPreview(snippet, ploader);
473 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
475 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
476 Buffer const & buffer = cur.buffer();
477 docstring const snippet = latexString(*this);
478 preview_->addPreview(snippet, buffer);
479 preview_->startLoading(buffer);
480 cur.updateFlags(Update::Force);
486 docstring InsetMathHull::label(row_type row) const
488 LASSERT(row < nrows(), /**/);
489 if (InsetLabel * il = label_[row])
490 return il->screenLabel();
495 void InsetMathHull::label(row_type row, docstring const & label)
497 //lyxerr << "setting label '" << label << "' for row " << row << endl;
501 label_[row] = dummy_pointer;
502 // We need an update of the Buffer reference cache.
503 // This is achieved by updateLabels().
504 lyx::updateLabels(buffer());
506 label_[row]->updateCommand(label);
509 InsetCommandParams p(LABEL_CODE);
511 label_[row] = new InsetLabel(p);
513 label_[row]->setBuffer(buffer());
517 void InsetMathHull::numbered(row_type row, bool num)
520 if (nonum_[row] && label_[row]) {
523 // We need an update of the Buffer reference cache.
524 // This is achieved by updateLabels().
525 lyx::updateLabels(buffer());
530 bool InsetMathHull::numbered(row_type row) const
536 bool InsetMathHull::ams() const
539 type_ == hullAlign ||
540 type_ == hullFlAlign ||
541 type_ == hullMultline ||
542 type_ == hullGather ||
543 type_ == hullAlignAt ||
544 type_ == hullXAlignAt ||
545 type_ == hullXXAlignAt;
549 Inset::DisplayType InsetMathHull::display() const
551 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
555 bool InsetMathHull::numberedType() const
557 if (type_ == hullNone)
559 if (type_ == hullSimple)
561 if (type_ == hullXXAlignAt)
563 for (row_type row = 0; row < nrows(); ++row)
570 void InsetMathHull::validate(LaTeXFeatures & features) const
573 features.require("amsmath");
575 // Validation is necessary only if not using AMS math.
576 // To be safe, we will always run mathedvalidate.
577 //if (features.amsstyle)
580 //features.binom = true;
582 InsetMathGrid::validate(features);
586 void InsetMathHull::header_write(WriteStream & os) const
588 bool n = numberedType();
602 os << "\\begin{equation" << star(n) << "}\n";
612 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
617 os << "\\begin{" << hullName(type_) << star(n) << '}'
618 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
622 os << "\\begin{" << hullName(type_) << '}'
623 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
627 os << "\\begin{unknown" << star(n) << '}';
633 void InsetMathHull::footer_write(WriteStream & os) const
635 bool n = numberedType();
648 os << "\\end{equation" << star(n) << "}\n";
660 os << "\\end{" << hullName(type_) << star(n) << "}\n";
664 os << "\\end{" << hullName(type_) << "}\n";
668 os << "\\end{unknown" << star(n) << '}';
674 bool InsetMathHull::rowChangeOK() const
677 type_ == hullEqnArray || type_ == hullAlign ||
678 type_ == hullFlAlign || type_ == hullAlignAt ||
679 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
680 type_ == hullGather || type_ == hullMultline;
684 bool InsetMathHull::colChangeOK() const
687 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
688 type_ == hullXAlignAt || type_ == hullXXAlignAt;
692 void InsetMathHull::addRow(row_type row)
697 bool numbered = numberedType();
699 if (type_ == hullMultline) {
700 if (row + 1 == nrows()) {
707 nonum_.insert(nonum_.begin() + row + 1, !numbered);
708 label_.insert(label_.begin() + row + 1, dummy_pointer);
711 InsetMathGrid::addRow(row);
715 void InsetMathHull::swapRow(row_type row)
719 if (row + 1 == nrows())
721 // gcc implements the standard std::vector<bool> which is *not* a container:
722 // http://www.gotw.ca/publications/N1185.pdf
723 // As a results, it doesn't like this:
724 // swap(nonum_[row], nonum_[row + 1]);
725 // so we do it manually:
726 bool const b = nonum_[row];
727 nonum_[row] = nonum_[row + 1];
729 swap(label_[row], label_[row + 1]);
730 InsetMathGrid::swapRow(row);
734 void InsetMathHull::delRow(row_type row)
736 if (nrows() <= 1 || !rowChangeOK())
738 if (row + 1 == nrows() && type_ == hullMultline) {
739 bool const b = nonum_[row - 1];
740 nonum_[row - 1] = nonum_[row];
742 swap(label_[row - 1], label_[row]);
743 InsetMathGrid::delRow(row);
746 InsetMathGrid::delRow(row);
747 // The last dummy row has no number info nor a label.
748 // Test nrows() + 1 because we have already erased the row.
749 if (row == nrows() + 1)
751 nonum_.erase(nonum_.begin() + row);
753 label_.erase(label_.begin() + row);
757 void InsetMathHull::addCol(col_type col)
761 InsetMathGrid::addCol(col);
765 void InsetMathHull::delCol(col_type col)
767 if (ncols() <= 1 || !colChangeOK())
769 InsetMathGrid::delCol(col);
773 docstring InsetMathHull::nicelabel(row_type row) const
778 return from_ascii("(#)");
779 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
783 void InsetMathHull::glueall()
786 for (idx_type i = 0; i < nargs(); ++i)
788 *this = InsetMathHull(hullSimple);
794 void InsetMathHull::splitTo2Cols()
796 LASSERT(ncols() == 1, /**/);
797 InsetMathGrid::addCol(1);
798 for (row_type row = 0; row < nrows(); ++row) {
799 idx_type const i = 2 * row;
800 pos_type pos = firstRelOp(cell(i));
801 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
802 cell(i).erase(pos, cell(i).size());
807 void InsetMathHull::splitTo3Cols()
809 LASSERT(ncols() < 3, /**/);
812 InsetMathGrid::addCol(2);
813 for (row_type row = 0; row < nrows(); ++row) {
814 idx_type const i = 3 * row + 1;
815 if (cell(i).size()) {
816 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
817 cell(i).erase(1, cell(i).size());
823 void InsetMathHull::changeCols(col_type cols)
827 else if (ncols() < cols) {
833 while (ncols() < cols)
834 InsetMathGrid::addCol(ncols());
840 for (row_type row = 0; row < nrows(); ++row) {
841 idx_type const i = row * ncols();
842 for (col_type col = cols; col < ncols(); ++col) {
843 cell(i + cols - 1).append(cell(i + col));
847 while (ncols() > cols) {
848 InsetMathGrid::delCol(ncols() - 1);
853 HullType InsetMathHull::getType() const
859 void InsetMathHull::setType(HullType type)
866 void InsetMathHull::mutate(HullType newtype)
868 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
870 // we try to move along the chain
871 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
873 // +-------------------------------------+
874 // we use eqnarray as intermediate type for mutations that are not
875 // directly supported because it handles labels and numbering for
878 if (newtype == type_) {
882 else if (newtype < hullNone) {
887 else if (type_ == hullNone) {
893 else if (type_ == hullSimple) {
894 if (newtype == hullNone) {
898 setType(hullEquation);
904 else if (type_ == hullEquation) {
905 if (newtype < type_) {
909 } else if (newtype == hullEqnArray) {
910 // split it "nicely" on the first relop
912 setType(hullEqnArray);
913 } else if (newtype == hullMultline || newtype == hullGather) {
923 else if (type_ == hullEqnArray) {
924 if (newtype < type_) {
925 // set correct (no)numbering
927 for (row_type row = 0; row < nrows(); ++row) {
934 // set first non-empty label
935 for (row_type row = 0; row < nrows(); ++row) {
937 label_[0] = label_[row];
944 } else { // align & Co.
951 else if (type_ == hullAlign || type_ == hullAlignAt ||
952 type_ == hullXAlignAt || type_ == hullFlAlign) {
953 if (newtype < hullAlign) {
955 setType(hullEqnArray);
957 } else if (newtype == hullGather || newtype == hullMultline) {
960 } else if (newtype == hullXXAlignAt) {
961 for (row_type row = 0; row < nrows(); ++row)
962 numbered(row, false);
969 else if (type_ == hullXXAlignAt) {
970 for (row_type row = 0; row < nrows(); ++row)
971 numbered(row, false);
972 if (newtype < hullAlign) {
974 setType(hullEqnArray);
976 } else if (newtype == hullGather || newtype == hullMultline) {
984 else if (type_ == hullMultline || type_ == hullGather) {
985 if (newtype == hullGather || newtype == hullMultline)
987 else if (newtype == hullAlign || newtype == hullFlAlign ||
988 newtype == hullAlignAt || newtype == hullXAlignAt) {
991 } else if (newtype == hullXXAlignAt) {
993 for (row_type row = 0; row < nrows(); ++row)
994 numbered(row, false);
998 setType(hullEqnArray);
1004 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1005 << "' to '" << to_utf8(hullName(newtype))
1006 << "' not implemented" << endl;
1011 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1014 if (numberedType()) {
1015 if (label_[row] && !nonum_[row])
1016 res += "\\label{" + label_[row]->getParam("name") + '}';
1017 if (nonum_[row] && (type_ != hullMultline))
1018 res += "\\nonumber ";
1020 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1024 void InsetMathHull::write(WriteStream & os) const
1026 ModeSpecifier specifier(os, MATH_MODE);
1028 InsetMathGrid::write(os);
1033 void InsetMathHull::normalize(NormalStream & os) const
1035 os << "[formula " << hullName(type_) << ' ';
1036 InsetMathGrid::normalize(os);
1041 void InsetMathHull::mathmlize(MathStream & os) const
1043 InsetMathGrid::mathmlize(os);
1047 void InsetMathHull::infoize(odocstream & os) const
1049 os << "Type: " << hullName(type_);
1053 void InsetMathHull::check() const
1055 LASSERT(nonum_.size() == nrows(), /**/);
1056 LASSERT(label_.size() == nrows(), /**/);
1060 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1064 idocstringstream iss(func.argument());
1065 iss >> dlang >> extra;
1067 extra = from_ascii("noextra");
1068 string const lang = to_ascii(dlang);
1070 // FIXME: temporarily disabled
1071 //if (cur.selection()) {
1074 // lyxerr << "use selection: " << ar << endl;
1075 // insert(pipeThroughExtern(lang, extra, ar));
1080 eq.push_back(MathAtom(new InsetMathChar('=')));
1082 // go to first item in line
1083 cur.idx() -= cur.idx() % ncols();
1086 if (getType() == hullSimple) {
1087 size_type pos = cur.cell().find_last(eq);
1089 if (cur.inMathed() && cur.selection()) {
1090 asArray(grabAndEraseSelection(cur), ar);
1091 } else if (pos == cur.cell().size()) {
1093 lyxerr << "use whole cell: " << ar << endl;
1095 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1096 lyxerr << "use partial cell form pos: " << pos << endl;
1098 cur.cell().append(eq);
1099 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1100 cur.pos() = cur.lastpos();
1104 if (getType() == hullEquation) {
1105 lyxerr << "use equation inset" << endl;
1106 mutate(hullEqnArray);
1107 MathData & ar = cur.cell();
1108 lyxerr << "use cell: " << ar << endl;
1112 cur.cell() = pipeThroughExtern(lang, extra, ar);
1113 // move to end of line
1114 cur.pos() = cur.lastpos();
1119 lyxerr << "use eqnarray" << endl;
1120 cur.idx() += 2 - cur.idx() % ncols();
1122 MathData ar = cur.cell();
1123 lyxerr << "use cell: " << ar << endl;
1124 // FIXME: temporarily disabled
1130 cur.cell() = pipeThroughExtern(lang, extra, ar);
1131 cur.pos() = cur.lastpos();
1136 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1138 //lyxerr << "action: " << cmd.action << endl;
1139 switch (cmd.action) {
1141 case LFUN_FINISHED_BACKWARD:
1142 case LFUN_FINISHED_FORWARD:
1143 case LFUN_FINISHED_RIGHT:
1144 case LFUN_FINISHED_LEFT:
1145 //lyxerr << "action: " << cmd.action << endl;
1146 InsetMathGrid::doDispatch(cur, cmd);
1150 case LFUN_BREAK_PARAGRAPH:
1151 // just swallow this
1154 case LFUN_NEWLINE_INSERT:
1155 // some magic for the common case
1156 if (type_ == hullSimple || type_ == hullEquation) {
1157 cur.recordUndoInset();
1159 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1160 mutate(align ? hullAlign : hullEqnArray);
1161 cur.idx() = nrows() * ncols() - 1;
1162 cur.pos() = cur.lastpos();
1164 InsetMathGrid::doDispatch(cur, cmd);
1167 case LFUN_MATH_NUMBER_TOGGLE: {
1168 //lyxerr << "toggling all numbers" << endl;
1169 cur.recordUndoInset();
1170 bool old = numberedType();
1171 if (type_ == hullMultline)
1172 numbered(nrows() - 1, !old);
1174 for (row_type row = 0; row < nrows(); ++row)
1175 numbered(row, !old);
1177 cur.message(old ? _("No number") : _("Number"));
1181 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1182 cur.recordUndoInset();
1183 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1184 bool old = numbered(r);
1185 cur.message(old ? _("No number") : _("Number"));
1190 case LFUN_LABEL_INSERT: {
1191 cur.recordUndoInset();
1192 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1193 docstring old_label = label(r);
1194 docstring const default_label = from_ascii(
1195 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1196 if (old_label.empty())
1197 old_label = default_label;
1199 InsetCommandParams p(LABEL_CODE);
1200 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1201 string const data = InsetCommand::params2string("label", p);
1203 if (cmd.argument().empty())
1204 cur.bv().showDialog("label", data);
1206 FuncRequest fr(LFUN_INSET_INSERT, data);
1212 case LFUN_WORD_DELETE_FORWARD:
1213 case LFUN_CHAR_DELETE_FORWARD:
1214 if (col(cur.idx()) + 1 == ncols()
1215 && cur.pos() == cur.lastpos()) {
1216 if (!label(row(cur.idx())).empty()) {
1217 cur.recordUndoInset();
1218 label(row(cur.idx()), docstring());
1219 } else if (numbered(row(cur.idx()))) {
1220 cur.recordUndoInset();
1221 numbered(row(cur.idx()), false);
1223 InsetMathGrid::doDispatch(cur, cmd);
1227 InsetMathGrid::doDispatch(cur, cmd);
1232 case LFUN_INSET_INSERT: {
1233 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1234 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1235 string const name = cmd.getArg(0);
1236 if (name == "label") {
1237 InsetCommandParams p(LABEL_CODE);
1238 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1239 docstring str = p["name"];
1240 cur.recordUndoInset();
1241 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1245 docstring old = label(r);
1248 // The label will take care of the reference update.
1252 // Newly created inset so initialize it.
1253 label_[r]->initView();
1258 InsetMathGrid::doDispatch(cur, cmd);
1262 case LFUN_MATH_EXTERN:
1263 cur.recordUndoInset();
1267 case LFUN_MATH_MUTATE: {
1268 cur.recordUndoInset();
1269 row_type row = cur.row();
1270 col_type col = cur.col();
1271 mutate(hullType(cmd.argument()));
1272 cur.idx() = row * ncols() + col;
1273 if (cur.idx() > cur.lastidx()) {
1274 cur.idx() = cur.lastidx();
1275 cur.pos() = cur.lastpos();
1277 if (cur.pos() > cur.lastpos())
1278 cur.pos() = cur.lastpos();
1280 // FIXME: find some more clever handling of the selection,
1281 // i.e. preserve it.
1282 cur.clearSelection();
1283 //cur.dispatched(FINISHED);
1287 case LFUN_MATH_DISPLAY: {
1288 cur.recordUndoInset();
1289 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1291 cur.pos() = cur.lastpos();
1292 //cur.dispatched(FINISHED);
1297 InsetMathGrid::doDispatch(cur, cmd);
1303 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1304 FuncStatus & status) const
1306 switch (cmd.action) {
1307 case LFUN_FINISHED_BACKWARD:
1308 case LFUN_FINISHED_FORWARD:
1309 case LFUN_FINISHED_RIGHT:
1310 case LFUN_FINISHED_LEFT:
1313 case LFUN_NEWLINE_INSERT:
1314 case LFUN_MATH_EXTERN:
1315 case LFUN_MATH_MUTATE:
1316 case LFUN_MATH_DISPLAY:
1318 status.setEnabled(true);
1320 case LFUN_MATH_NUMBER_TOGGLE:
1321 // FIXME: what is the right test, this or the one of
1323 status.setEnabled(display());
1324 status.setOnOff(numberedType());
1326 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1327 // FIXME: what is the right test, this or the one of
1329 bool const enable = (type_ == hullMultline) ?
1330 (nrows() - 1 == cur.row()) : display();
1331 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1332 status.setEnabled(enable);
1333 status.setOnOff(numbered(r));
1336 case LFUN_LABEL_INSERT:
1337 status.setEnabled(type_ != hullSimple);
1339 case LFUN_INSET_INSERT:
1340 if (cmd.getArg(0) == "label") {
1341 status.setEnabled(type_ != hullSimple);
1344 return InsetMathGrid::getStatus(cur, cmd, status);
1345 case LFUN_TABULAR_FEATURE: {
1346 istringstream is(to_utf8(cmd.argument()));
1350 && (s == "append-row"
1351 || s == "delete-row"
1352 || s == "copy-row")) {
1353 status.message(bformat(
1354 from_utf8(N_("Can't change number of rows in '%1$s'")),
1356 status.setEnabled(false);
1360 && (s == "append-column"
1361 || s == "delete-column"
1362 || s == "copy-column")) {
1363 status.message(bformat(
1364 from_utf8(N_("Can't change number of columns in '%1$s'")),
1366 status.setEnabled(false);
1369 if ((type_ == hullSimple
1370 || type_ == hullEquation
1371 || type_ == hullNone) &&
1372 (s == "add-hline-above" || s == "add-hline-below")) {
1373 status.message(bformat(
1374 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1376 status.setEnabled(false);
1379 if (s == "add-vline-left" || s == "add-vline-right") {
1380 status.message(bformat(
1381 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1383 status.setEnabled(false);
1386 if (s == "valign-top" || s == "valign-middle"
1387 || s == "valign-bottom" || s == "align-left"
1388 || s == "align-center" || s == "align-right") {
1389 status.setEnabled(false);
1392 return InsetMathGrid::getStatus(cur, cmd, status);
1395 return InsetMathGrid::getStatus(cur, cmd, status);
1398 // This cannot really happen, but inserted to shut-up gcc
1399 return InsetMathGrid::getStatus(cur, cmd, status);
1403 /////////////////////////////////////////////////////////////////////
1407 // simply scrap this function if you want
1408 void InsetMathHull::mutateToText()
1411 // translate to latex
1413 latex(os, false, false);
1414 string str = os.str();
1417 Text * lt = view_->cursor().innerText();
1418 string::const_iterator cit = str.begin();
1419 string::const_iterator end = str.end();
1420 for (; cit != end; ++cit)
1421 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1424 //dispatch(LFUN_ESCAPE);
1429 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1430 docstring const & font)
1432 // this whole function is a hack and won't work for incremental font
1435 if (cur.inset().asInsetMath()->name() == font)
1436 cur.handleFont(to_utf8(font));
1438 cur.handleNest(createInsetMath(font));
1444 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1449 font.fromString(to_utf8(arg), b);
1450 if (font.fontInfo().color() != Color_inherit) {
1451 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1452 cur.handleNest(at, 0);
1457 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1460 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1461 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1462 enter_front ? idxFirst(cur) : idxLast(cur);
1463 // The inset formula dimension is not necessarily the same as the
1464 // one of the instant preview image, so we have to indicate to the
1465 // BufferView that a metrics update is needed.
1466 cur.updateFlags(Update::Force);
1470 docstring InsetMathHull::editMessage() const
1472 return _("Math editor mode");
1476 void InsetMathHull::revealCodes(Cursor & cur) const
1478 if (!cur.inMathed())
1480 odocstringstream os;
1482 cur.message(os.str());
1484 // write something to the minibuffer
1485 // translate to latex
1489 string str = os.str();
1491 string::size_type pos = 0;
1493 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1496 else if (*it == '\0') {
1498 pos = it - str.begin();
1504 res = res.substr(pos - 30);
1505 if (res.size() > 60)
1506 res = res.substr(0, 60);
1512 InsetCode InsetMathHull::lyxCode() const
1518 /////////////////////////////////////////////////////////////////////
1522 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1525 // FIXME: completely broken
1526 static InsetMathHull * lastformula = 0;
1527 static CursorBase current = DocIterator(ibegin(nucleus()));
1529 static string laststr;
1531 if (lastformula != this || laststr != str) {
1532 //lyxerr << "reset lastformula to " << this << endl;
1535 current = ibegin(nucleus());
1537 mathed_parse_cell(ar, str);
1541 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1543 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1544 CursorSlice & top = it.back();
1545 MathData const & a = top.asInsetMath()->cell(top.idx_);
1546 if (a.matchpart(ar, top.pos_)) {
1547 bv->cursor().setSelection(it, ar.size());
1549 top.pos_ += ar.size();
1555 //lyxerr << "not found!" << endl;
1562 void InsetMathHull::write(ostream & os) const
1564 odocstringstream oss;
1565 WriteStream wi(oss, false, false, false);
1568 os << to_utf8(oss.str());
1572 void InsetMathHull::read(Lexer & lex)
1575 mathed_parse_normal(at, lex);
1576 operator=(*at->asHullInset());
1580 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1582 if (0 && display()) {
1586 TextPainter tpain(dim.width(), dim.height());
1587 drawT(tpain, 0, dim.ascent());
1589 // reset metrics cache to "real" values
1591 return tpain.textheight();
1593 odocstringstream oss;
1594 WriteStream wi(oss, false, true, false, runparams.encoding);
1597 docstring const str = oss.str();
1604 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1609 if (getType() == hullSimple)
1610 name = from_ascii("inlineequation");
1612 name = from_ascii("informalequation");
1614 docstring bname = name;
1615 if (!label(0).empty())
1616 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1618 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1620 odocstringstream ls;
1621 if (runparams.flavor == OutputParams::XML) {
1622 ms << MTag("alt role='tex' ");
1623 // Workaround for db2latex: db2latex always includes equations with
1624 // \ensuremath{} or \begin{display}\end{display}
1625 // so we strip LyX' math environment
1626 WriteStream wi(ls, false, false, false, runparams.encoding);
1627 InsetMathGrid::write(wi);
1628 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1633 InsetMathGrid::mathmlize(ms);
1636 ms << MTag("alt role='tex'");
1637 res = latex(ls, runparams);
1638 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1642 ms << from_ascii("<graphic fileref=\"eqn/");
1643 if (!label(0).empty())
1644 ms << sgml::cleanID(buffer(), runparams, label(0));
1646 ms << sgml::uniqueID(from_ascii("anon"));
1648 if (runparams.flavor == OutputParams::XML)
1649 ms << from_ascii("\"/>");
1651 ms << from_ascii("\">");
1653 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1655 return ms.line() + res;
1659 void InsetMathHull::textString(odocstream & os) const
1661 plaintext(os, OutputParams(0));
1665 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1667 return from_ascii("context-math");