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 static Encoding const * encoding = inset.buffer().language()->encoding();
454 WriteStream wi(ls, false, true, false, encoding);
460 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
462 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
463 docstring const snippet = latexString(*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 = latexString(*this);
474 preview_->addPreview(snippet, buffer);
475 preview_->startLoading(buffer);
476 cur.updateFlags(Update::Force);
482 docstring InsetMathHull::label(row_type row) const
484 LASSERT(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;
497 label_[row] = dummy_pointer;
498 // We need an update of the Buffer reference cache.
499 // This is achieved by updateLabels().
500 lyx::updateLabels(buffer());
502 label_[row]->updateCommand(label);
505 InsetCommandParams p(LABEL_CODE);
507 label_[row] = new InsetLabel(p);
509 label_[row]->setBuffer(buffer());
513 void InsetMathHull::numbered(row_type row, bool num)
516 if (nonum_[row] && label_[row]) {
519 // We need an update of the Buffer reference cache.
520 // This is achieved by updateLabels().
521 lyx::updateLabels(buffer());
526 bool InsetMathHull::numbered(row_type row) const
532 bool InsetMathHull::ams() const
535 type_ == hullAlign ||
536 type_ == hullFlAlign ||
537 type_ == hullMultline ||
538 type_ == hullGather ||
539 type_ == hullAlignAt ||
540 type_ == hullXAlignAt ||
541 type_ == hullXXAlignAt;
545 Inset::DisplayType InsetMathHull::display() const
547 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
551 bool InsetMathHull::numberedType() const
553 if (type_ == hullNone)
555 if (type_ == hullSimple)
557 if (type_ == hullXXAlignAt)
559 for (row_type row = 0; row < nrows(); ++row)
566 void InsetMathHull::validate(LaTeXFeatures & features) const
569 features.require("amsmath");
571 // Validation is necessary only if not using AMS math.
572 // To be safe, we will always run mathedvalidate.
573 //if (features.amsstyle)
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)
693 bool numbered = numberedType();
695 if (type_ == hullMultline) {
696 if (row + 1 == nrows()) {
703 nonum_.insert(nonum_.begin() + row + 1, !numbered);
704 label_.insert(label_.begin() + row + 1, dummy_pointer);
707 InsetMathGrid::addRow(row);
711 void InsetMathHull::swapRow(row_type row)
715 if (row + 1 == nrows())
717 // gcc implements the standard std::vector<bool> which is *not* a container:
718 // http://www.gotw.ca/publications/N1185.pdf
719 // As a results, it doesn't like this:
720 // swap(nonum_[row], nonum_[row + 1]);
721 // so we do it manually:
722 bool const b = nonum_[row];
723 nonum_[row] = nonum_[row + 1];
725 swap(label_[row], label_[row + 1]);
726 InsetMathGrid::swapRow(row);
730 void InsetMathHull::delRow(row_type row)
732 if (nrows() <= 1 || !rowChangeOK())
734 if (row + 1 == nrows() && type_ == hullMultline) {
735 bool const b = nonum_[row - 1];
736 nonum_[row - 1] = nonum_[row];
738 swap(label_[row - 1], label_[row]);
739 InsetMathGrid::delRow(row);
742 InsetMathGrid::delRow(row);
743 // The last dummy row has no number info nor a label.
744 // Test nrows() + 1 because we have already erased the row.
745 if (row == nrows() + 1)
747 nonum_.erase(nonum_.begin() + row);
749 label_.erase(label_.begin() + row);
753 void InsetMathHull::addCol(col_type col)
757 InsetMathGrid::addCol(col);
761 void InsetMathHull::delCol(col_type col)
763 if (ncols() <= 1 || !colChangeOK())
765 InsetMathGrid::delCol(col);
769 docstring InsetMathHull::nicelabel(row_type row) const
774 return from_ascii("(#)");
775 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
779 void InsetMathHull::glueall()
782 for (idx_type i = 0; i < nargs(); ++i)
784 *this = InsetMathHull(hullSimple);
790 void InsetMathHull::splitTo2Cols()
792 LASSERT(ncols() == 1, /**/);
793 InsetMathGrid::addCol(1);
794 for (row_type row = 0; row < nrows(); ++row) {
795 idx_type const i = 2 * row;
796 pos_type pos = firstRelOp(cell(i));
797 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
798 cell(i).erase(pos, cell(i).size());
803 void InsetMathHull::splitTo3Cols()
805 LASSERT(ncols() < 3, /**/);
808 InsetMathGrid::addCol(2);
809 for (row_type row = 0; row < nrows(); ++row) {
810 idx_type const i = 3 * row + 1;
811 if (cell(i).size()) {
812 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
813 cell(i).erase(1, cell(i).size());
819 void InsetMathHull::changeCols(col_type cols)
823 else if (ncols() < cols) {
829 while (ncols() < cols)
830 InsetMathGrid::addCol(ncols());
836 for (row_type row = 0; row < nrows(); ++row) {
837 idx_type const i = row * ncols();
838 for (col_type col = cols; col < ncols(); ++col) {
839 cell(i + cols - 1).append(cell(i + col));
843 while (ncols() > cols) {
844 InsetMathGrid::delCol(ncols() - 1);
849 HullType InsetMathHull::getType() const
855 void InsetMathHull::setType(HullType type)
862 void InsetMathHull::mutate(HullType newtype)
864 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
866 // we try to move along the chain
867 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
869 // +-------------------------------------+
870 // we use eqnarray as intermediate type for mutations that are not
871 // directly supported because it handles labels and numbering for
874 if (newtype == type_) {
878 else if (newtype < hullNone) {
883 else if (type_ == hullNone) {
889 else if (type_ == hullSimple) {
890 if (newtype == hullNone) {
894 setType(hullEquation);
900 else if (type_ == hullEquation) {
901 if (newtype < type_) {
905 } else if (newtype == hullEqnArray) {
906 // split it "nicely" on the first relop
908 setType(hullEqnArray);
909 } else if (newtype == hullMultline || newtype == hullGather) {
919 else if (type_ == hullEqnArray) {
920 if (newtype < type_) {
921 // set correct (no)numbering
923 for (row_type row = 0; row < nrows(); ++row) {
930 // set first non-empty label
931 for (row_type row = 0; row < nrows(); ++row) {
933 label_[0] = label_[row];
940 } else { // align & Co.
947 else if (type_ == hullAlign || type_ == hullAlignAt ||
948 type_ == hullXAlignAt || type_ == hullFlAlign) {
949 if (newtype < hullAlign) {
951 setType(hullEqnArray);
953 } else if (newtype == hullGather || newtype == hullMultline) {
956 } else if (newtype == hullXXAlignAt) {
957 for (row_type row = 0; row < nrows(); ++row)
958 numbered(row, false);
965 else if (type_ == hullXXAlignAt) {
966 for (row_type row = 0; row < nrows(); ++row)
967 numbered(row, false);
968 if (newtype < hullAlign) {
970 setType(hullEqnArray);
972 } else if (newtype == hullGather || newtype == hullMultline) {
980 else if (type_ == hullMultline || type_ == hullGather) {
981 if (newtype == hullGather || newtype == hullMultline)
983 else if (newtype == hullAlign || newtype == hullFlAlign ||
984 newtype == hullAlignAt || newtype == hullXAlignAt) {
987 } else if (newtype == hullXXAlignAt) {
989 for (row_type row = 0; row < nrows(); ++row)
990 numbered(row, false);
994 setType(hullEqnArray);
1000 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1001 << "' to '" << to_utf8(hullName(newtype))
1002 << "' not implemented" << endl;
1007 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1010 if (numberedType()) {
1011 if (label_[row] && !nonum_[row])
1012 res += "\\label{" + label_[row]->getParam("name") + '}';
1013 if (nonum_[row] && (type_ != hullMultline))
1014 res += "\\nonumber ";
1016 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1020 void InsetMathHull::write(WriteStream & os) const
1022 ModeSpecifier specifier(os, MATH_MODE);
1024 InsetMathGrid::write(os);
1029 void InsetMathHull::normalize(NormalStream & os) const
1031 os << "[formula " << hullName(type_) << ' ';
1032 InsetMathGrid::normalize(os);
1037 void InsetMathHull::mathmlize(MathStream & os) const
1039 InsetMathGrid::mathmlize(os);
1043 void InsetMathHull::infoize(odocstream & os) const
1045 os << "Type: " << hullName(type_);
1049 void InsetMathHull::check() const
1051 LASSERT(nonum_.size() == nrows(), /**/);
1052 LASSERT(label_.size() == nrows(), /**/);
1056 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1060 idocstringstream iss(func.argument());
1061 iss >> dlang >> extra;
1063 extra = from_ascii("noextra");
1064 string const lang = to_ascii(dlang);
1066 // FIXME: temporarily disabled
1067 //if (cur.selection()) {
1070 // lyxerr << "use selection: " << ar << endl;
1071 // insert(pipeThroughExtern(lang, extra, ar));
1076 eq.push_back(MathAtom(new InsetMathChar('=')));
1078 // go to first item in line
1079 cur.idx() -= cur.idx() % ncols();
1082 if (getType() == hullSimple) {
1083 size_type pos = cur.cell().find_last(eq);
1085 if (cur.inMathed() && cur.selection()) {
1086 asArray(grabAndEraseSelection(cur), ar);
1087 } else if (pos == cur.cell().size()) {
1089 lyxerr << "use whole cell: " << ar << endl;
1091 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1092 lyxerr << "use partial cell form pos: " << pos << endl;
1094 cur.cell().append(eq);
1095 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1096 cur.pos() = cur.lastpos();
1100 if (getType() == hullEquation) {
1101 lyxerr << "use equation inset" << endl;
1102 mutate(hullEqnArray);
1103 MathData & ar = cur.cell();
1104 lyxerr << "use cell: " << ar << endl;
1108 cur.cell() = pipeThroughExtern(lang, extra, ar);
1109 // move to end of line
1110 cur.pos() = cur.lastpos();
1115 lyxerr << "use eqnarray" << endl;
1116 cur.idx() += 2 - cur.idx() % ncols();
1118 MathData ar = cur.cell();
1119 lyxerr << "use cell: " << ar << endl;
1120 // FIXME: temporarily disabled
1126 cur.cell() = pipeThroughExtern(lang, extra, ar);
1127 cur.pos() = cur.lastpos();
1132 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1134 //lyxerr << "action: " << cmd.action << endl;
1135 switch (cmd.action) {
1137 case LFUN_FINISHED_BACKWARD:
1138 case LFUN_FINISHED_FORWARD:
1139 case LFUN_FINISHED_RIGHT:
1140 case LFUN_FINISHED_LEFT:
1141 //lyxerr << "action: " << cmd.action << endl;
1142 InsetMathGrid::doDispatch(cur, cmd);
1146 case LFUN_BREAK_PARAGRAPH:
1147 // just swallow this
1150 case LFUN_NEWLINE_INSERT:
1151 // some magic for the common case
1152 if (type_ == hullSimple || type_ == hullEquation) {
1153 cur.recordUndoInset();
1155 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1156 mutate(align ? hullAlign : hullEqnArray);
1157 cur.idx() = nrows() * ncols() - 1;
1158 cur.pos() = cur.lastpos();
1160 InsetMathGrid::doDispatch(cur, cmd);
1163 case LFUN_MATH_NUMBER_TOGGLE: {
1164 //lyxerr << "toggling all numbers" << endl;
1165 cur.recordUndoInset();
1166 bool old = numberedType();
1167 if (type_ == hullMultline)
1168 numbered(nrows() - 1, !old);
1170 for (row_type row = 0; row < nrows(); ++row)
1171 numbered(row, !old);
1173 cur.message(old ? _("No number") : _("Number"));
1177 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1178 cur.recordUndoInset();
1179 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1180 bool old = numbered(r);
1181 cur.message(old ? _("No number") : _("Number"));
1186 case LFUN_LABEL_INSERT: {
1187 cur.recordUndoInset();
1188 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1189 docstring old_label = label(r);
1190 docstring const default_label = from_ascii(
1191 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1192 if (old_label.empty())
1193 old_label = default_label;
1195 InsetCommandParams p(LABEL_CODE);
1196 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1197 string const data = InsetCommand::params2string("label", p);
1199 if (cmd.argument().empty())
1200 cur.bv().showDialog("label", data);
1202 FuncRequest fr(LFUN_INSET_INSERT, data);
1208 case LFUN_WORD_DELETE_FORWARD:
1209 case LFUN_CHAR_DELETE_FORWARD:
1210 if (col(cur.idx()) + 1 == ncols()
1211 && cur.pos() == cur.lastpos()) {
1212 if (!label(row(cur.idx())).empty()) {
1213 cur.recordUndoInset();
1214 label(row(cur.idx()), docstring());
1215 } else if (numbered(row(cur.idx()))) {
1216 cur.recordUndoInset();
1217 numbered(row(cur.idx()), false);
1219 InsetMathGrid::doDispatch(cur, cmd);
1223 InsetMathGrid::doDispatch(cur, cmd);
1228 case LFUN_INSET_INSERT: {
1229 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1230 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1231 string const name = cmd.getArg(0);
1232 if (name == "label") {
1233 InsetCommandParams p(LABEL_CODE);
1234 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1235 docstring str = p["name"];
1236 cur.recordUndoInset();
1237 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1241 docstring old = label(r);
1244 // The label will take care of the reference update.
1248 // Newly created inset so initialize it.
1249 label_[r]->initView();
1254 InsetMathGrid::doDispatch(cur, cmd);
1258 case LFUN_MATH_EXTERN:
1259 cur.recordUndoInset();
1263 case LFUN_MATH_MUTATE: {
1264 cur.recordUndoInset();
1265 row_type row = cur.row();
1266 col_type col = cur.col();
1267 mutate(hullType(cmd.argument()));
1268 cur.idx() = row * ncols() + col;
1269 if (cur.idx() > cur.lastidx()) {
1270 cur.idx() = cur.lastidx();
1271 cur.pos() = cur.lastpos();
1273 if (cur.pos() > cur.lastpos())
1274 cur.pos() = cur.lastpos();
1276 // FIXME: find some more clever handling of the selection,
1277 // i.e. preserve it.
1278 cur.clearSelection();
1279 //cur.dispatched(FINISHED);
1283 case LFUN_MATH_DISPLAY: {
1284 cur.recordUndoInset();
1285 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1287 cur.pos() = cur.lastpos();
1288 //cur.dispatched(FINISHED);
1293 InsetMathGrid::doDispatch(cur, cmd);
1299 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1300 FuncStatus & status) const
1302 switch (cmd.action) {
1303 case LFUN_FINISHED_BACKWARD:
1304 case LFUN_FINISHED_FORWARD:
1305 case LFUN_FINISHED_RIGHT:
1306 case LFUN_FINISHED_LEFT:
1309 case LFUN_NEWLINE_INSERT:
1310 case LFUN_MATH_EXTERN:
1311 case LFUN_MATH_MUTATE:
1312 case LFUN_MATH_DISPLAY:
1314 status.setEnabled(true);
1316 case LFUN_MATH_NUMBER_TOGGLE:
1317 // FIXME: what is the right test, this or the one of
1319 status.setEnabled(display());
1320 status.setOnOff(numberedType());
1322 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1323 // FIXME: what is the right test, this or the one of
1325 bool const enable = (type_ == hullMultline) ?
1326 (nrows() - 1 == cur.row()) : display();
1327 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1328 status.setEnabled(enable);
1329 status.setOnOff(numbered(r));
1332 case LFUN_LABEL_INSERT:
1333 status.setEnabled(type_ != hullSimple);
1335 case LFUN_INSET_INSERT:
1336 if (cmd.getArg(0) == "label") {
1337 status.setEnabled(type_ != hullSimple);
1340 return InsetMathGrid::getStatus(cur, cmd, status);
1341 case LFUN_TABULAR_FEATURE: {
1342 istringstream is(to_utf8(cmd.argument()));
1346 && (s == "append-row"
1347 || s == "delete-row"
1348 || s == "copy-row")) {
1349 status.message(bformat(
1350 from_utf8(N_("Can't change number of rows in '%1$s'")),
1352 status.setEnabled(false);
1356 && (s == "append-column"
1357 || s == "delete-column"
1358 || s == "copy-column")) {
1359 status.message(bformat(
1360 from_utf8(N_("Can't change number of columns in '%1$s'")),
1362 status.setEnabled(false);
1365 if ((type_ == hullSimple
1366 || type_ == hullEquation
1367 || type_ == hullNone) &&
1368 (s == "add-hline-above" || s == "add-hline-below")) {
1369 status.message(bformat(
1370 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1372 status.setEnabled(false);
1375 if (s == "add-vline-left" || s == "add-vline-right") {
1376 status.message(bformat(
1377 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1379 status.setEnabled(false);
1382 if (s == "valign-top" || s == "valign-middle"
1383 || s == "valign-bottom" || s == "align-left"
1384 || s == "align-center" || s == "align-right") {
1385 status.setEnabled(false);
1388 return InsetMathGrid::getStatus(cur, cmd, status);
1391 return InsetMathGrid::getStatus(cur, cmd, status);
1394 // This cannot really happen, but inserted to shut-up gcc
1395 return InsetMathGrid::getStatus(cur, cmd, status);
1399 /////////////////////////////////////////////////////////////////////
1403 // simply scrap this function if you want
1404 void InsetMathHull::mutateToText()
1407 // translate to latex
1409 latex(os, false, false);
1410 string str = os.str();
1413 Text * lt = view_->cursor().innerText();
1414 string::const_iterator cit = str.begin();
1415 string::const_iterator end = str.end();
1416 for (; cit != end; ++cit)
1417 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1420 //dispatch(LFUN_ESCAPE);
1425 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1426 docstring const & font)
1428 // this whole function is a hack and won't work for incremental font
1431 if (cur.inset().asInsetMath()->name() == font)
1432 cur.handleFont(to_utf8(font));
1434 cur.handleNest(createInsetMath(font));
1440 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1445 font.fromString(to_utf8(arg), b);
1446 if (font.fontInfo().color() != Color_inherit) {
1447 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1448 cur.handleNest(at, 0);
1453 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1456 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1457 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1458 enter_front ? idxFirst(cur) : idxLast(cur);
1459 // The inset formula dimension is not necessarily the same as the
1460 // one of the instant preview image, so we have to indicate to the
1461 // BufferView that a metrics update is needed.
1462 cur.updateFlags(Update::Force);
1466 docstring InsetMathHull::editMessage() const
1468 return _("Math editor mode");
1472 void InsetMathHull::revealCodes(Cursor & cur) const
1474 if (!cur.inMathed())
1476 odocstringstream os;
1478 cur.message(os.str());
1480 // write something to the minibuffer
1481 // translate to latex
1485 string str = os.str();
1487 string::size_type pos = 0;
1489 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1492 else if (*it == '\0') {
1494 pos = it - str.begin();
1500 res = res.substr(pos - 30);
1501 if (res.size() > 60)
1502 res = res.substr(0, 60);
1508 InsetCode InsetMathHull::lyxCode() const
1514 /////////////////////////////////////////////////////////////////////
1518 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1521 // FIXME: completely broken
1522 static InsetMathHull * lastformula = 0;
1523 static CursorBase current = DocIterator(ibegin(nucleus()));
1525 static string laststr;
1527 if (lastformula != this || laststr != str) {
1528 //lyxerr << "reset lastformula to " << this << endl;
1531 current = ibegin(nucleus());
1533 mathed_parse_cell(ar, str);
1537 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1539 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1540 CursorSlice & top = it.back();
1541 MathData const & a = top.asInsetMath()->cell(top.idx_);
1542 if (a.matchpart(ar, top.pos_)) {
1543 bv->cursor().setSelection(it, ar.size());
1545 top.pos_ += ar.size();
1551 //lyxerr << "not found!" << endl;
1558 void InsetMathHull::write(ostream & os) const
1560 odocstringstream oss;
1561 WriteStream wi(oss, false, false, false);
1564 os << to_utf8(oss.str());
1568 void InsetMathHull::read(Lexer & lex)
1571 mathed_parse_normal(at, lex);
1572 operator=(*at->asHullInset());
1576 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1578 if (0 && display()) {
1582 TextPainter tpain(dim.width(), dim.height());
1583 drawT(tpain, 0, dim.ascent());
1585 // reset metrics cache to "real" values
1587 return tpain.textheight();
1589 odocstringstream oss;
1590 WriteStream wi(oss, false, true, false, runparams.encoding);
1593 docstring const str = oss.str();
1600 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1605 if (getType() == hullSimple)
1606 name = from_ascii("inlineequation");
1608 name = from_ascii("informalequation");
1610 docstring bname = name;
1611 if (!label(0).empty())
1612 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1614 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1616 odocstringstream ls;
1617 if (runparams.flavor == OutputParams::XML) {
1618 ms << MTag("alt role='tex' ");
1619 // Workaround for db2latex: db2latex always includes equations with
1620 // \ensuremath{} or \begin{display}\end{display}
1621 // so we strip LyX' math environment
1622 WriteStream wi(ls, false, false, false, runparams.encoding);
1623 InsetMathGrid::write(wi);
1624 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1629 InsetMathGrid::mathmlize(ms);
1632 ms << MTag("alt role='tex'");
1633 res = latex(ls, runparams);
1634 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1638 ms << from_ascii("<graphic fileref=\"eqn/");
1639 if (!label(0).empty())
1640 ms << sgml::cleanID(buffer(), runparams, label(0));
1642 ms << sgml::uniqueID(from_ascii("anon"));
1644 if (runparams.flavor == OutputParams::XML)
1645 ms << from_ascii("\"/>");
1647 ms << from_ascii("\">");
1649 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1651 return ms.line() + res;
1655 void InsetMathHull::textString(odocstream & os) const
1657 plaintext(os, OutputParams(0));
1661 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1663 return from_ascii("context-math");