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
1023 InsetMathGrid::write(os);
1028 void InsetMathHull::normalize(NormalStream & os) const
1030 os << "[formula " << hullName(type_) << ' ';
1031 InsetMathGrid::normalize(os);
1036 void InsetMathHull::mathmlize(MathStream & os) const
1038 InsetMathGrid::mathmlize(os);
1042 void InsetMathHull::infoize(odocstream & os) const
1044 os << "Type: " << hullName(type_);
1048 void InsetMathHull::check() const
1050 LASSERT(nonum_.size() == nrows(), /**/);
1051 LASSERT(label_.size() == nrows(), /**/);
1055 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1059 idocstringstream iss(func.argument());
1060 iss >> dlang >> extra;
1062 extra = from_ascii("noextra");
1063 string const lang = to_ascii(dlang);
1065 // FIXME: temporarily disabled
1066 //if (cur.selection()) {
1069 // lyxerr << "use selection: " << ar << endl;
1070 // insert(pipeThroughExtern(lang, extra, ar));
1075 eq.push_back(MathAtom(new InsetMathChar('=')));
1077 // go to first item in line
1078 cur.idx() -= cur.idx() % ncols();
1081 if (getType() == hullSimple) {
1082 size_type pos = cur.cell().find_last(eq);
1084 if (cur.inMathed() && cur.selection()) {
1085 asArray(grabAndEraseSelection(cur), ar);
1086 } else if (pos == cur.cell().size()) {
1088 lyxerr << "use whole cell: " << ar << endl;
1090 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1091 lyxerr << "use partial cell form pos: " << pos << endl;
1093 cur.cell().append(eq);
1094 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1095 cur.pos() = cur.lastpos();
1099 if (getType() == hullEquation) {
1100 lyxerr << "use equation inset" << endl;
1101 mutate(hullEqnArray);
1102 MathData & ar = cur.cell();
1103 lyxerr << "use cell: " << ar << endl;
1107 cur.cell() = pipeThroughExtern(lang, extra, ar);
1108 // move to end of line
1109 cur.pos() = cur.lastpos();
1114 lyxerr << "use eqnarray" << endl;
1115 cur.idx() += 2 - cur.idx() % ncols();
1117 MathData ar = cur.cell();
1118 lyxerr << "use cell: " << ar << endl;
1119 // FIXME: temporarily disabled
1125 cur.cell() = pipeThroughExtern(lang, extra, ar);
1126 cur.pos() = cur.lastpos();
1131 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1133 //lyxerr << "action: " << cmd.action << endl;
1134 switch (cmd.action) {
1136 case LFUN_FINISHED_BACKWARD:
1137 case LFUN_FINISHED_FORWARD:
1138 case LFUN_FINISHED_RIGHT:
1139 case LFUN_FINISHED_LEFT:
1140 //lyxerr << "action: " << cmd.action << endl;
1141 InsetMathGrid::doDispatch(cur, cmd);
1145 case LFUN_BREAK_PARAGRAPH:
1146 // just swallow this
1149 case LFUN_NEWLINE_INSERT:
1150 // some magic for the common case
1151 if (type_ == hullSimple || type_ == hullEquation) {
1152 cur.recordUndoInset();
1154 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1155 mutate(align ? hullAlign : hullEqnArray);
1156 cur.idx() = nrows() * ncols() - 1;
1157 cur.pos() = cur.lastpos();
1159 InsetMathGrid::doDispatch(cur, cmd);
1162 case LFUN_MATH_NUMBER_TOGGLE: {
1163 //lyxerr << "toggling all numbers" << endl;
1164 cur.recordUndoInset();
1165 bool old = numberedType();
1166 if (type_ == hullMultline)
1167 numbered(nrows() - 1, !old);
1169 for (row_type row = 0; row < nrows(); ++row)
1170 numbered(row, !old);
1172 cur.message(old ? _("No number") : _("Number"));
1176 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1177 cur.recordUndoInset();
1178 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1179 bool old = numbered(r);
1180 cur.message(old ? _("No number") : _("Number"));
1185 case LFUN_LABEL_INSERT: {
1186 cur.recordUndoInset();
1187 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1188 docstring old_label = label(r);
1189 docstring const default_label = from_ascii(
1190 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1191 if (old_label.empty())
1192 old_label = default_label;
1194 InsetCommandParams p(LABEL_CODE);
1195 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1196 string const data = InsetCommand::params2string("label", p);
1198 if (cmd.argument().empty())
1199 cur.bv().showDialog("label", data);
1201 FuncRequest fr(LFUN_INSET_INSERT, data);
1207 case LFUN_WORD_DELETE_FORWARD:
1208 case LFUN_CHAR_DELETE_FORWARD:
1209 if (col(cur.idx()) + 1 == ncols()
1210 && cur.pos() == cur.lastpos()) {
1211 if (!label(row(cur.idx())).empty()) {
1212 cur.recordUndoInset();
1213 label(row(cur.idx()), docstring());
1214 } else if (numbered(row(cur.idx()))) {
1215 cur.recordUndoInset();
1216 numbered(row(cur.idx()), false);
1218 InsetMathGrid::doDispatch(cur, cmd);
1222 InsetMathGrid::doDispatch(cur, cmd);
1227 case LFUN_INSET_INSERT: {
1228 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1229 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1230 string const name = cmd.getArg(0);
1231 if (name == "label") {
1232 InsetCommandParams p(LABEL_CODE);
1233 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1234 docstring str = p["name"];
1235 cur.recordUndoInset();
1236 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1240 docstring old = label(r);
1243 // The label will take care of the reference update.
1247 // Newly created inset so initialize it.
1248 label_[r]->initView();
1253 InsetMathGrid::doDispatch(cur, cmd);
1257 case LFUN_MATH_EXTERN:
1258 cur.recordUndoInset();
1262 case LFUN_MATH_MUTATE: {
1263 cur.recordUndoInset();
1264 row_type row = cur.row();
1265 col_type col = cur.col();
1266 mutate(hullType(cmd.argument()));
1267 cur.idx() = row * ncols() + col;
1268 if (cur.idx() > cur.lastidx()) {
1269 cur.idx() = cur.lastidx();
1270 cur.pos() = cur.lastpos();
1272 if (cur.pos() > cur.lastpos())
1273 cur.pos() = cur.lastpos();
1275 // FIXME: find some more clever handling of the selection,
1276 // i.e. preserve it.
1277 cur.clearSelection();
1278 //cur.dispatched(FINISHED);
1282 case LFUN_MATH_DISPLAY: {
1283 cur.recordUndoInset();
1284 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1286 cur.pos() = cur.lastpos();
1287 //cur.dispatched(FINISHED);
1292 InsetMathGrid::doDispatch(cur, cmd);
1298 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1299 FuncStatus & status) const
1301 switch (cmd.action) {
1302 case LFUN_FINISHED_BACKWARD:
1303 case LFUN_FINISHED_FORWARD:
1304 case LFUN_FINISHED_RIGHT:
1305 case LFUN_FINISHED_LEFT:
1308 case LFUN_NEWLINE_INSERT:
1309 case LFUN_MATH_EXTERN:
1310 case LFUN_MATH_MUTATE:
1311 case LFUN_MATH_DISPLAY:
1313 status.setEnabled(true);
1315 case LFUN_MATH_NUMBER_TOGGLE:
1316 // FIXME: what is the right test, this or the one of
1318 status.setEnabled(display());
1319 status.setOnOff(numberedType());
1321 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1322 // FIXME: what is the right test, this or the one of
1324 bool const enable = (type_ == hullMultline) ?
1325 (nrows() - 1 == cur.row()) : display();
1326 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1327 status.setEnabled(enable);
1328 status.setOnOff(numbered(r));
1331 case LFUN_LABEL_INSERT:
1332 status.setEnabled(type_ != hullSimple);
1334 case LFUN_INSET_INSERT:
1335 if (cmd.getArg(0) == "label") {
1336 status.setEnabled(type_ != hullSimple);
1339 return InsetMathGrid::getStatus(cur, cmd, status);
1340 case LFUN_TABULAR_FEATURE: {
1341 istringstream is(to_utf8(cmd.argument()));
1345 && (s == "append-row"
1346 || s == "delete-row"
1347 || s == "copy-row")) {
1348 status.message(bformat(
1349 from_utf8(N_("Can't change number of rows in '%1$s'")),
1351 status.setEnabled(false);
1355 && (s == "append-column"
1356 || s == "delete-column"
1357 || s == "copy-column")) {
1358 status.message(bformat(
1359 from_utf8(N_("Can't change number of columns in '%1$s'")),
1361 status.setEnabled(false);
1364 if ((type_ == hullSimple
1365 || type_ == hullEquation
1366 || type_ == hullNone) &&
1367 (s == "add-hline-above" || s == "add-hline-below")) {
1368 status.message(bformat(
1369 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1371 status.setEnabled(false);
1374 if (s == "add-vline-left" || s == "add-vline-right") {
1375 status.message(bformat(
1376 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1378 status.setEnabled(false);
1381 if (s == "valign-top" || s == "valign-middle"
1382 || s == "valign-bottom" || s == "align-left"
1383 || s == "align-center" || s == "align-right") {
1384 status.setEnabled(false);
1387 return InsetMathGrid::getStatus(cur, cmd, status);
1390 return InsetMathGrid::getStatus(cur, cmd, status);
1393 // This cannot really happen, but inserted to shut-up gcc
1394 return InsetMathGrid::getStatus(cur, cmd, status);
1398 /////////////////////////////////////////////////////////////////////
1402 // simply scrap this function if you want
1403 void InsetMathHull::mutateToText()
1406 // translate to latex
1408 latex(os, false, false);
1409 string str = os.str();
1412 Text * lt = view_->cursor().innerText();
1413 string::const_iterator cit = str.begin();
1414 string::const_iterator end = str.end();
1415 for (; cit != end; ++cit)
1416 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1419 //dispatch(LFUN_ESCAPE);
1424 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1425 docstring const & font)
1427 // this whole function is a hack and won't work for incremental font
1430 if (cur.inset().asInsetMath()->name() == font)
1431 cur.handleFont(to_utf8(font));
1433 cur.handleNest(createInsetMath(font));
1439 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1444 font.fromString(to_utf8(arg), b);
1445 if (font.fontInfo().color() != Color_inherit) {
1446 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1447 cur.handleNest(at, 0);
1452 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1455 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1456 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1457 enter_front ? idxFirst(cur) : idxLast(cur);
1458 // The inset formula dimension is not necessarily the same as the
1459 // one of the instant preview image, so we have to indicate to the
1460 // BufferView that a metrics update is needed.
1461 cur.updateFlags(Update::Force);
1465 docstring InsetMathHull::editMessage() const
1467 return _("Math editor mode");
1471 void InsetMathHull::revealCodes(Cursor & cur) const
1473 if (!cur.inMathed())
1475 odocstringstream os;
1477 cur.message(os.str());
1479 // write something to the minibuffer
1480 // translate to latex
1484 string str = os.str();
1486 string::size_type pos = 0;
1488 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1491 else if (*it == '\0') {
1493 pos = it - str.begin();
1499 res = res.substr(pos - 30);
1500 if (res.size() > 60)
1501 res = res.substr(0, 60);
1507 InsetCode InsetMathHull::lyxCode() const
1513 /////////////////////////////////////////////////////////////////////
1517 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1520 // FIXME: completely broken
1521 static InsetMathHull * lastformula = 0;
1522 static CursorBase current = DocIterator(ibegin(nucleus()));
1524 static string laststr;
1526 if (lastformula != this || laststr != str) {
1527 //lyxerr << "reset lastformula to " << this << endl;
1530 current = ibegin(nucleus());
1532 mathed_parse_cell(ar, str);
1536 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1538 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1539 CursorSlice & top = it.back();
1540 MathData const & a = top.asInsetMath()->cell(top.idx_);
1541 if (a.matchpart(ar, top.pos_)) {
1542 bv->cursor().setSelection(it, ar.size());
1544 top.pos_ += ar.size();
1550 //lyxerr << "not found!" << endl;
1557 void InsetMathHull::write(ostream & os) const
1559 odocstringstream oss;
1560 WriteStream wi(oss, false, false, false);
1563 os << to_utf8(oss.str());
1567 void InsetMathHull::read(Lexer & lex)
1570 mathed_parse_normal(at, lex);
1571 operator=(*at->asHullInset());
1575 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1577 if (0 && display()) {
1581 TextPainter tpain(dim.width(), dim.height());
1582 drawT(tpain, 0, dim.ascent());
1584 // reset metrics cache to "real" values
1586 return tpain.textheight();
1588 odocstringstream oss;
1589 WriteStream wi(oss, false, true, false, runparams.encoding);
1592 docstring const str = oss.str();
1599 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1604 if (getType() == hullSimple)
1605 name = from_ascii("inlineequation");
1607 name = from_ascii("informalequation");
1609 docstring bname = name;
1610 if (!label(0).empty())
1611 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1613 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1615 odocstringstream ls;
1616 if (runparams.flavor == OutputParams::XML) {
1617 ms << MTag("alt role='tex' ");
1618 // Workaround for db2latex: db2latex always includes equations with
1619 // \ensuremath{} or \begin{display}\end{display}
1620 // so we strip LyX' math environment
1621 WriteStream wi(ls, false, false, false, runparams.encoding);
1622 InsetMathGrid::write(wi);
1623 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1628 InsetMathGrid::mathmlize(ms);
1631 ms << MTag("alt role='tex'");
1632 res = latex(ls, runparams);
1633 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1637 ms << from_ascii("<graphic fileref=\"eqn/");
1638 if (!label(0).empty())
1639 ms << sgml::cleanID(buffer(), runparams, label(0));
1641 ms << sgml::uniqueID(from_ascii("anon"));
1643 if (runparams.flavor == OutputParams::XML)
1644 ms << from_ascii("\"/>");
1646 ms << from_ascii("\">");
1648 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1650 return ms.line() + res;
1654 void InsetMathHull::textString(odocstream & os) const
1656 plaintext(os, OutputParams(0));
1660 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1662 return from_ascii("context-math");