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"
34 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "DispatchResult.h"
38 #include "FuncRequest.h"
41 #include "OutputParams.h"
42 #include "ParIterator.h"
45 #include "TextPainter.h"
46 #include "TocBackend.h"
48 #include "insets/RenderPreview.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetRef.h"
52 #include "graphics/PreviewImage.h"
53 #include "graphics/PreviewLoader.h"
55 #include "frontends/Painter.h"
57 #include "support/lassert.h"
58 #include "support/debug.h"
59 #include "support/gettext.h"
60 #include "support/lstrings.h"
65 using namespace lyx::support;
69 using cap::grabAndEraseSelection;
73 int getCols(HullType type)
90 // returns position of first relation operator in the array
91 // used for "intelligent splitting"
92 size_t firstRelOp(MathData const & ar)
94 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
96 return it - ar.begin();
101 char const * star(bool numbered)
103 return numbered ? "" : "*";
107 } // end anon namespace
110 HullType hullType(docstring const & s)
112 if (s == "none") return hullNone;
113 if (s == "simple") return hullSimple;
114 if (s == "equation") return hullEquation;
115 if (s == "eqnarray") return hullEqnArray;
116 if (s == "align") return hullAlign;
117 if (s == "alignat") return hullAlignAt;
118 if (s == "xalignat") return hullXAlignAt;
119 if (s == "xxalignat") return hullXXAlignAt;
120 if (s == "multline") return hullMultline;
121 if (s == "gather") return hullGather;
122 if (s == "flalign") return hullFlAlign;
123 if (s == "regexp") return hullRegexp;
124 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
129 docstring hullName(HullType type)
132 case hullNone: return from_ascii("none");
133 case hullSimple: return from_ascii("simple");
134 case hullEquation: return from_ascii("equation");
135 case hullEqnArray: return from_ascii("eqnarray");
136 case hullAlign: return from_ascii("align");
137 case hullAlignAt: return from_ascii("alignat");
138 case hullXAlignAt: return from_ascii("xalignat");
139 case hullXXAlignAt: return from_ascii("xxalignat");
140 case hullMultline: return from_ascii("multline");
141 case hullGather: return from_ascii("gather");
142 case hullFlAlign: return from_ascii("flalign");
143 case hullRegexp: return from_ascii("regexp");
145 lyxerr << "unknown hull type '" << type << "'" << endl;
146 return from_ascii("none");
150 static InsetLabel * dummy_pointer = 0;
152 InsetMathHull::InsetMathHull()
153 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
154 label_(1, dummy_pointer), preview_(new RenderPreview(this))
156 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
157 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
158 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
159 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
165 InsetMathHull::InsetMathHull(HullType type)
166 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
167 label_(1, dummy_pointer), preview_(new RenderPreview(this))
174 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
180 InsetMathHull::~InsetMathHull()
182 for (size_t i = 0; i < label_.size(); ++i)
187 Inset * InsetMathHull::clone() const
189 return new InsetMathHull(*this);
193 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
197 InsetMathGrid::operator=(other);
199 nonum_ = other.nonum_;
200 for (size_t i = 0; i < label_.size(); ++i)
202 label_ = other.label_;
203 for (size_t i = 0; i != label_.size(); ++i) {
205 label_[i] = new InsetLabel(*label_[i]);
207 preview_.reset(new RenderPreview(*other.preview_, this));
213 void InsetMathHull::setBuffer(Buffer & buffer)
215 InsetMathGrid::setBuffer(buffer);
217 for (size_t i = 0; i != label_.size(); ++i) {
219 label_[i]->setBuffer(buffer);
224 void InsetMathHull::updateLabels(ParIterator const & it)
227 //FIXME: buffer_ should be set at creation for this inset! Problem is
228 // This inset is created at too many places (see Parser::parse1() in
232 for (size_t i = 0; i != label_.size(); ++i) {
234 label_[i]->updateLabels(it);
239 void InsetMathHull::addToToc(DocIterator const & pit)
242 //FIXME: buffer_ should be set at creation for this inset! Problem is
243 // This inset is created at too many places (see Parser::parse1() in
248 Toc & toc = buffer().tocBackend().toc("equation");
250 for (row_type row = 0; row != nrows(); ++row) {
254 label_[row]->addToToc(pit);
255 toc.push_back(TocItem(pit, 0, nicelabel(row)));
260 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
266 return InsetMathNest::editXY(cur, x, y);
270 InsetMath::mode_type InsetMathHull::currentMode() const
272 if (type_ == hullNone)
273 return UNDECIDED_MODE;
274 // definitely math mode ...
279 bool InsetMathHull::idxFirst(Cursor & cur) const
287 bool InsetMathHull::idxLast(Cursor & cur) const
289 cur.idx() = nargs() - 1;
290 cur.pos() = cur.lastpos();
295 char InsetMathHull::defaultColAlign(col_type col)
297 if (type_ == hullEqnArray)
299 if (type_ == hullGather)
301 if (type_ >= hullAlign)
302 return "rl"[col & 1];
307 int InsetMathHull::defaultColSpace(col_type col)
309 if (type_ == hullAlign || type_ == hullAlignAt)
311 if (type_ == hullXAlignAt)
312 return (col & 1) ? 20 : 0;
313 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
314 return (col & 1) ? 40 : 0;
319 docstring InsetMathHull::standardFont() const
321 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
325 bool InsetMathHull::previewState(BufferView * bv) const
327 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
328 graphics::PreviewImage const * pimage =
329 preview_->getPreviewImage(bv->buffer());
330 return pimage && pimage->image();
336 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
338 if (previewState(mi.base.bv)) {
339 preview_->metrics(mi, dim);
340 // insert a one pixel gap in front of the formula
343 dim.des += displayMargin();
344 // Cache the inset dimension.
345 setDimCache(mi, dim);
349 FontSetChanger dummy1(mi.base, standardFont());
350 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
352 // let the cells adjust themselves
353 InsetMathGrid::metrics(mi, dim);
356 dim.asc += displayMargin();
357 dim.des += displayMargin();
360 if (numberedType()) {
361 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
363 for (row_type row = 0; row < nrows(); ++row)
364 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
370 // make it at least as high as the current font
373 math_font_max_dim(mi.base.font, asc, des);
374 dim.asc = max(dim.asc, asc);
375 dim.des = max(dim.des, des);
376 // Cache the inset dimension.
377 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
378 setDimCache(mi, dim);
382 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
384 Dimension const dim = dimension(*pi.base.bv);
385 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
386 dim.asc + dim.des - 1, pi.backgroundColor(this));
390 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
392 use_preview_ = previewState(pi.base.bv);
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, WriteStream::wsDefault);
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, WriteStream::wsDefault);
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 or a math
450 // macro containing math in text mode (such as $\text{$\phi$}$ or
451 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
452 // first time as a whole, and the second time only the inner math.
453 // In this last case inset.buffer() would be invalid.
454 static Encoding const * encoding = 0;
455 if (inset.isBufferValid())
456 encoding = &(inset.buffer().params().encoding());
457 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
463 void InsetMathHull::initUnicodeMath() const
465 // Trigger classification of the unicode symbols in this inset
466 docstring const dummy = latexString(*this);
470 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
472 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
473 docstring const snippet = latexString(*this);
474 preview_->addPreview(snippet, ploader);
479 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
481 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
482 Buffer const * buffer = cur.buffer();
483 docstring const snippet = latexString(*this);
484 preview_->addPreview(snippet, *buffer);
485 preview_->startLoading(*buffer);
486 cur.updateFlags(Update::Force);
492 docstring InsetMathHull::label(row_type row) const
494 LASSERT(row < nrows(), /**/);
495 if (InsetLabel * il = label_[row])
496 return il->screenLabel();
501 void InsetMathHull::label(row_type row, docstring const & label)
503 //lyxerr << "setting label '" << label << "' for row " << row << endl;
507 label_[row] = dummy_pointer;
508 // We need an update of the Buffer reference cache.
509 // This is achieved by updateLabels().
511 buffer().updateLabels();
514 label_[row]->updateCommand(label);
516 label_[row]->setParam("name", label);
520 InsetCommandParams p(LABEL_CODE);
522 label_[row] = new InsetLabel(p);
524 label_[row]->setBuffer(buffer());
528 void InsetMathHull::numbered(row_type row, bool num)
531 if (nonum_[row] && label_[row]) {
535 // The buffer is set at the end of readInset.
536 // When parsing the inset, buffer_ is 0.
539 // We need an update of the Buffer reference cache.
540 // This is achieved by updateLabels().
541 buffer().updateLabels();
546 bool InsetMathHull::numbered(row_type row) const
552 bool InsetMathHull::ams() const
554 return type_ == hullAlign
555 || type_ == hullFlAlign
556 || type_ == hullMultline
557 || type_ == hullGather
558 || type_ == hullAlignAt
559 || type_ == hullXAlignAt
560 || type_ == hullXXAlignAt;
564 Inset::DisplayType InsetMathHull::display() const
566 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
571 bool InsetMathHull::numberedType() const
573 if (type_ == hullNone)
575 if (type_ == hullSimple)
577 if (type_ == hullXXAlignAt)
579 if (type_ == hullRegexp)
581 for (row_type row = 0; row < nrows(); ++row)
588 void InsetMathHull::validate(LaTeXFeatures & features) const
591 features.require("amsmath");
593 // Validation is necessary only if not using AMS math.
594 // To be safe, we will always run mathedvalidate.
595 //if (features.amsstyle)
598 //features.binom = true;
600 InsetMathGrid::validate(features);
604 void InsetMathHull::header_write(WriteStream & os) const
606 bool n = numberedType();
620 os << "\\begin{equation" << star(n) << "}\n";
630 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
635 os << "\\begin{" << hullName(type_) << star(n) << '}'
636 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
640 os << "\\begin{" << hullName(type_) << '}'
641 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
649 os << "\\begin{unknown" << star(n) << '}';
655 void InsetMathHull::footer_write(WriteStream & os) const
657 bool n = numberedType();
670 os << "\\end{equation" << star(n) << "}\n";
682 os << "\\end{" << hullName(type_) << star(n) << "}\n";
686 os << "\\end{" << hullName(type_) << "}\n";
694 os << "\\end{unknown" << star(n) << '}';
700 bool InsetMathHull::rowChangeOK() const
703 type_ == hullEqnArray || type_ == hullAlign ||
704 type_ == hullFlAlign || type_ == hullAlignAt ||
705 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
706 type_ == hullGather || type_ == hullMultline;
710 bool InsetMathHull::colChangeOK() const
713 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
714 type_ == hullXAlignAt || type_ == hullXXAlignAt;
718 void InsetMathHull::addRow(row_type row)
723 bool numbered = numberedType();
725 if (type_ == hullMultline) {
726 if (row + 1 == nrows()) {
733 nonum_.insert(nonum_.begin() + row + 1, !numbered);
734 label_.insert(label_.begin() + row + 1, dummy_pointer);
737 InsetMathGrid::addRow(row);
741 void InsetMathHull::swapRow(row_type row)
745 if (row + 1 == nrows())
747 // gcc implements the standard std::vector<bool> which is *not* a container:
748 // http://www.gotw.ca/publications/N1185.pdf
749 // As a results, it doesn't like this:
750 // swap(nonum_[row], nonum_[row + 1]);
751 // so we do it manually:
752 bool const b = nonum_[row];
753 nonum_[row] = nonum_[row + 1];
755 swap(label_[row], label_[row + 1]);
756 InsetMathGrid::swapRow(row);
760 void InsetMathHull::delRow(row_type row)
762 if (nrows() <= 1 || !rowChangeOK())
764 if (row + 1 == nrows() && type_ == hullMultline) {
765 bool const b = nonum_[row - 1];
766 nonum_[row - 1] = nonum_[row];
768 swap(label_[row - 1], label_[row]);
769 InsetMathGrid::delRow(row);
772 InsetMathGrid::delRow(row);
773 // The last dummy row has no number info nor a label.
774 // Test nrows() + 1 because we have already erased the row.
775 if (row == nrows() + 1)
777 nonum_.erase(nonum_.begin() + row);
779 label_.erase(label_.begin() + row);
783 void InsetMathHull::addCol(col_type col)
787 InsetMathGrid::addCol(col);
791 void InsetMathHull::delCol(col_type col)
793 if (ncols() <= 1 || !colChangeOK())
795 InsetMathGrid::delCol(col);
799 docstring InsetMathHull::nicelabel(row_type row) const
804 return from_ascii("(#)");
805 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
809 void InsetMathHull::glueall()
812 for (idx_type i = 0; i < nargs(); ++i)
814 *this = InsetMathHull(hullSimple);
820 void InsetMathHull::splitTo2Cols()
822 LASSERT(ncols() == 1, /**/);
823 InsetMathGrid::addCol(1);
824 for (row_type row = 0; row < nrows(); ++row) {
825 idx_type const i = 2 * row;
826 pos_type pos = firstRelOp(cell(i));
827 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
828 cell(i).erase(pos, cell(i).size());
833 void InsetMathHull::splitTo3Cols()
835 LASSERT(ncols() < 3, /**/);
838 InsetMathGrid::addCol(2);
839 for (row_type row = 0; row < nrows(); ++row) {
840 idx_type const i = 3 * row + 1;
841 if (cell(i).size()) {
842 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
843 cell(i).erase(1, cell(i).size());
849 void InsetMathHull::changeCols(col_type cols)
853 else if (ncols() < cols) {
859 while (ncols() < cols)
860 InsetMathGrid::addCol(ncols());
866 for (row_type row = 0; row < nrows(); ++row) {
867 idx_type const i = row * ncols();
868 for (col_type col = cols; col < ncols(); ++col) {
869 cell(i + cols - 1).append(cell(i + col));
873 while (ncols() > cols) {
874 InsetMathGrid::delCol(ncols() - 1);
879 HullType InsetMathHull::getType() const
885 void InsetMathHull::setType(HullType type)
892 void InsetMathHull::mutate(HullType newtype)
894 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
896 // we try to move along the chain
897 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
899 // +-------------------------------------+
900 // we use eqnarray as intermediate type for mutations that are not
901 // directly supported because it handles labels and numbering for
904 if (newtype == type_) {
908 else if (newtype < hullNone) {
913 else if (type_ == hullNone) {
919 else if (type_ == hullSimple) {
920 if (newtype == hullNone) {
924 setType(hullEquation);
930 else if (type_ == hullEquation) {
931 if (newtype < type_) {
935 } else if (newtype == hullEqnArray) {
936 // split it "nicely" on the first relop
938 setType(hullEqnArray);
939 } else if (newtype == hullMultline || newtype == hullGather) {
949 else if (type_ == hullEqnArray) {
950 if (newtype < type_) {
951 // set correct (no)numbering
953 for (row_type row = 0; row < nrows(); ++row) {
960 // set first non-empty label
961 for (row_type row = 0; row < nrows(); ++row) {
963 label_[0] = label_[row];
970 } else { // align & Co.
977 else if (type_ == hullAlign || type_ == hullAlignAt ||
978 type_ == hullXAlignAt || type_ == hullFlAlign) {
979 if (newtype < hullAlign) {
981 setType(hullEqnArray);
983 } else if (newtype == hullGather || newtype == hullMultline) {
986 } else if (newtype == hullXXAlignAt) {
987 for (row_type row = 0; row < nrows(); ++row)
988 numbered(row, false);
995 else if (type_ == hullXXAlignAt) {
996 for (row_type row = 0; row < nrows(); ++row)
997 numbered(row, false);
998 if (newtype < hullAlign) {
1000 setType(hullEqnArray);
1002 } else if (newtype == hullGather || newtype == hullMultline) {
1010 else if (type_ == hullMultline || type_ == hullGather) {
1011 if (newtype == hullGather || newtype == hullMultline)
1013 else if (newtype == hullAlign || newtype == hullFlAlign ||
1014 newtype == hullAlignAt || newtype == hullXAlignAt) {
1017 } else if (newtype == hullXXAlignAt) {
1019 for (row_type row = 0; row < nrows(); ++row)
1020 numbered(row, false);
1024 setType(hullEqnArray);
1030 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1031 << "' to '" << to_utf8(hullName(newtype))
1032 << "' not implemented" << endl;
1037 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1040 if (numberedType()) {
1041 if (label_[row] && !nonum_[row])
1042 res += "\\label{" + label_[row]->getParam("name") + '}';
1043 if (nonum_[row] && (type_ != hullMultline))
1044 res += "\\nonumber ";
1046 return res + InsetMathGrid::eolString(row, fragile);
1050 void InsetMathHull::write(WriteStream & os) const
1052 ModeSpecifier specifier(os, MATH_MODE);
1054 InsetMathGrid::write(os);
1059 void InsetMathHull::normalize(NormalStream & os) const
1061 os << "[formula " << hullName(type_) << ' ';
1062 InsetMathGrid::normalize(os);
1067 void InsetMathHull::mathmlize(MathStream & os) const
1069 InsetMathGrid::mathmlize(os);
1073 void InsetMathHull::infoize(odocstream & os) const
1075 os << "Type: " << hullName(type_);
1079 void InsetMathHull::check() const
1081 LASSERT(nonum_.size() == nrows(), /**/);
1082 LASSERT(label_.size() == nrows(), /**/);
1086 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1090 idocstringstream iss(func.argument());
1091 iss >> dlang >> extra;
1093 extra = from_ascii("noextra");
1094 string const lang = to_ascii(dlang);
1096 // FIXME: temporarily disabled
1097 //if (cur.selection()) {
1100 // lyxerr << "use selection: " << ar << endl;
1101 // insert(pipeThroughExtern(lang, extra, ar));
1106 eq.push_back(MathAtom(new InsetMathChar('=')));
1108 // go to first item in line
1109 cur.idx() -= cur.idx() % ncols();
1112 if (getType() == hullSimple) {
1113 size_type pos = cur.cell().find_last(eq);
1115 if (cur.inMathed() && cur.selection()) {
1116 asArray(grabAndEraseSelection(cur), ar);
1117 } else if (pos == cur.cell().size()) {
1119 lyxerr << "use whole cell: " << ar << endl;
1121 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1122 lyxerr << "use partial cell form pos: " << pos << endl;
1124 cur.cell().append(eq);
1125 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1126 cur.pos() = cur.lastpos();
1130 if (getType() == hullEquation) {
1131 lyxerr << "use equation inset" << endl;
1132 mutate(hullEqnArray);
1133 MathData & ar = cur.cell();
1134 lyxerr << "use cell: " << ar << endl;
1138 cur.cell() = pipeThroughExtern(lang, extra, ar);
1139 // move to end of line
1140 cur.pos() = cur.lastpos();
1145 lyxerr << "use eqnarray" << endl;
1146 cur.idx() += 2 - cur.idx() % ncols();
1148 MathData ar = cur.cell();
1149 lyxerr << "use cell: " << ar << endl;
1150 // FIXME: temporarily disabled
1156 cur.cell() = pipeThroughExtern(lang, extra, ar);
1157 cur.pos() = cur.lastpos();
1162 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1164 //lyxerr << "action: " << cmd.action << endl;
1165 switch (cmd.action) {
1167 case LFUN_FINISHED_BACKWARD:
1168 case LFUN_FINISHED_FORWARD:
1169 case LFUN_FINISHED_RIGHT:
1170 case LFUN_FINISHED_LEFT:
1171 //lyxerr << "action: " << cmd.action << endl;
1172 InsetMathGrid::doDispatch(cur, cmd);
1176 case LFUN_BREAK_PARAGRAPH:
1177 // just swallow this
1180 case LFUN_NEWLINE_INSERT:
1181 // some magic for the common case
1182 if (type_ == hullSimple || type_ == hullEquation) {
1183 cur.recordUndoInset();
1185 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1186 mutate(align ? hullAlign : hullEqnArray);
1187 cur.idx() = nrows() * ncols() - 1;
1188 cur.pos() = cur.lastpos();
1190 InsetMathGrid::doDispatch(cur, cmd);
1193 case LFUN_MATH_NUMBER_TOGGLE: {
1194 //lyxerr << "toggling all numbers" << endl;
1195 cur.recordUndoInset();
1196 bool old = numberedType();
1197 if (type_ == hullMultline)
1198 numbered(nrows() - 1, !old);
1200 for (row_type row = 0; row < nrows(); ++row)
1201 numbered(row, !old);
1203 cur.message(old ? _("No number") : _("Number"));
1207 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1208 cur.recordUndoInset();
1209 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1210 bool old = numbered(r);
1211 cur.message(old ? _("No number") : _("Number"));
1216 case LFUN_LABEL_INSERT: {
1217 cur.recordUndoInset();
1218 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1219 docstring old_label = label(r);
1220 docstring const default_label = from_ascii(
1221 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1222 if (old_label.empty())
1223 old_label = default_label;
1225 InsetCommandParams p(LABEL_CODE);
1226 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1227 string const data = InsetCommand::params2string("label", p);
1229 if (cmd.argument().empty())
1230 cur.bv().showDialog("label", data);
1232 FuncRequest fr(LFUN_INSET_INSERT, data);
1238 case LFUN_LABEL_COPY_AS_REF: {
1240 if (cmd.argument().empty() && &cur.inset() == this)
1241 // if there is no argument and we're inside math, we retrieve
1242 // the row number from the cursor position.
1243 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1245 // if there is an argument, find the corresponding label, else
1246 // check whether there is at least one label.
1247 for (row = 0; row != nrows(); ++row)
1248 if (!nonum_[row] && label_[row]
1249 && (cmd.argument().empty() || label(row) == cmd.argument()))
1256 InsetCommandParams p(REF_CODE, "ref");
1257 p["reference"] = label(row);
1258 cap::clearSelection();
1259 cap::copyInset(cur, new InsetRef(*cur.buffer(), p), label(row));
1263 case LFUN_WORD_DELETE_FORWARD:
1264 case LFUN_CHAR_DELETE_FORWARD:
1265 if (col(cur.idx()) + 1 == ncols()
1266 && cur.pos() == cur.lastpos()
1267 && !cur.selection()) {
1268 if (!label(row(cur.idx())).empty()) {
1269 cur.recordUndoInset();
1270 label(row(cur.idx()), docstring());
1271 } else if (numbered(row(cur.idx()))) {
1272 cur.recordUndoInset();
1273 numbered(row(cur.idx()), false);
1275 InsetMathGrid::doDispatch(cur, cmd);
1279 InsetMathGrid::doDispatch(cur, cmd);
1284 case LFUN_INSET_INSERT: {
1285 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1286 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1287 string const name = cmd.getArg(0);
1288 if (name == "label") {
1289 InsetCommandParams p(LABEL_CODE);
1290 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1291 docstring str = p["name"];
1292 cur.recordUndoInset();
1293 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1297 docstring old = label(r);
1300 // The label will take care of the reference update.
1304 // Newly created inset so initialize it.
1305 label_[r]->initView();
1310 InsetMathGrid::doDispatch(cur, cmd);
1314 case LFUN_MATH_EXTERN:
1315 cur.recordUndoInset();
1319 case LFUN_MATH_MUTATE: {
1320 cur.recordUndoInset();
1321 row_type row = cur.row();
1322 col_type col = cur.col();
1323 mutate(hullType(cmd.argument()));
1324 cur.idx() = row * ncols() + col;
1325 if (cur.idx() > cur.lastidx()) {
1326 cur.idx() = cur.lastidx();
1327 cur.pos() = cur.lastpos();
1329 if (cur.pos() > cur.lastpos())
1330 cur.pos() = cur.lastpos();
1332 // FIXME: find some more clever handling of the selection,
1333 // i.e. preserve it.
1334 cur.clearSelection();
1335 //cur.dispatched(FINISHED);
1339 case LFUN_MATH_DISPLAY: {
1340 cur.recordUndoInset();
1341 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1343 cur.pos() = cur.lastpos();
1344 //cur.dispatched(FINISHED);
1349 InsetMathGrid::doDispatch(cur, cmd);
1355 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1356 FuncStatus & status) const
1358 switch (cmd.action) {
1359 case LFUN_FINISHED_BACKWARD:
1360 case LFUN_FINISHED_FORWARD:
1361 case LFUN_FINISHED_RIGHT:
1362 case LFUN_FINISHED_LEFT:
1365 case LFUN_NEWLINE_INSERT:
1366 case LFUN_MATH_EXTERN:
1367 case LFUN_MATH_DISPLAY:
1369 status.setEnabled(true);
1372 case LFUN_MATH_MUTATE: {
1373 HullType ht = hullType(cmd.argument());
1374 status.setOnOff(type_ == ht);
1375 status.setEnabled(true);
1379 case LFUN_MATH_NUMBER_TOGGLE:
1380 // FIXME: what is the right test, this or the one of
1382 status.setEnabled(display());
1383 status.setOnOff(numberedType());
1386 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1387 // FIXME: what is the right test, this or the one of
1389 bool const enable = (type_ == hullMultline)
1390 ? (nrows() - 1 == cur.row())
1391 : display() != Inline && nrows() > 1;
1392 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1393 status.setEnabled(enable);
1394 status.setOnOff(enable && numbered(r));
1398 case LFUN_LABEL_INSERT:
1399 status.setEnabled(type_ != hullSimple);
1402 case LFUN_LABEL_COPY_AS_REF: {
1403 bool enabled = false;
1405 if (cmd.argument().empty() && &cur.inset() == this) {
1406 // if there is no argument and we're inside math, we retrieve
1407 // the row number from the cursor position.
1408 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1409 enabled = numberedType() && label_[row] && !nonum_[row];
1411 // if there is an argument, find the corresponding label, else
1412 // check whether there is at least one label.
1413 for (row_type row = 0; row != nrows(); ++row) {
1414 if (!nonum_[row] && label_[row] &&
1415 (cmd.argument().empty() || label(row) == cmd.argument())) {
1421 status.setEnabled(enabled);
1425 case LFUN_INSET_INSERT:
1426 if (cmd.getArg(0) == "label") {
1427 status.setEnabled(type_ != hullSimple);
1430 return InsetMathGrid::getStatus(cur, cmd, status);
1432 case LFUN_TABULAR_FEATURE: {
1433 istringstream is(to_utf8(cmd.argument()));
1437 && (s == "append-row"
1438 || s == "delete-row"
1439 || s == "copy-row")) {
1440 status.message(bformat(
1441 from_utf8(N_("Can't change number of rows in '%1$s'")),
1443 status.setEnabled(false);
1447 && (s == "append-column"
1448 || s == "delete-column"
1449 || s == "copy-column")) {
1450 status.message(bformat(
1451 from_utf8(N_("Can't change number of columns in '%1$s'")),
1453 status.setEnabled(false);
1456 if ((type_ == hullSimple
1457 || type_ == hullEquation
1458 || type_ == hullNone) &&
1459 (s == "add-hline-above" || s == "add-hline-below")) {
1460 status.message(bformat(
1461 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1463 status.setEnabled(false);
1466 if (s == "add-vline-left" || s == "add-vline-right") {
1467 status.message(bformat(
1468 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1470 status.setEnabled(false);
1473 if (s == "valign-top" || s == "valign-middle"
1474 || s == "valign-bottom" || s == "align-left"
1475 || s == "align-center" || s == "align-right") {
1476 status.setEnabled(false);
1479 return InsetMathGrid::getStatus(cur, cmd, status);
1483 return InsetMathGrid::getStatus(cur, cmd, status);
1486 // This cannot really happen, but inserted to shut-up gcc
1487 return InsetMathGrid::getStatus(cur, cmd, status);
1491 /////////////////////////////////////////////////////////////////////
1495 // simply scrap this function if you want
1496 void InsetMathHull::mutateToText()
1499 // translate to latex
1501 latex(os, false, false);
1502 string str = os.str();
1505 Text * lt = view_->cursor().innerText();
1506 string::const_iterator cit = str.begin();
1507 string::const_iterator end = str.end();
1508 for (; cit != end; ++cit)
1509 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1512 //dispatch(LFUN_ESCAPE);
1517 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1518 docstring const & font)
1520 // this whole function is a hack and won't work for incremental font
1523 if (cur.inset().asInsetMath()->name() == font)
1524 cur.handleFont(to_utf8(font));
1526 cur.handleNest(createInsetMath(font));
1532 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1537 font.fromString(to_utf8(arg), b);
1538 if (font.fontInfo().color() != Color_inherit) {
1539 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1540 cur.handleNest(at, 0);
1545 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1548 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1549 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1550 enter_front ? idxFirst(cur) : idxLast(cur);
1551 // The inset formula dimension is not necessarily the same as the
1552 // one of the instant preview image, so we have to indicate to the
1553 // BufferView that a metrics update is needed.
1554 cur.updateFlags(Update::Force);
1558 void InsetMathHull::revealCodes(Cursor & cur) const
1560 if (!cur.inMathed())
1562 odocstringstream os;
1564 cur.message(os.str());
1566 // write something to the minibuffer
1567 // translate to latex
1571 string str = os.str();
1573 string::size_type pos = 0;
1575 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1578 else if (*it == '\0') {
1580 pos = it - str.begin();
1586 res = res.substr(pos - 30);
1587 if (res.size() > 60)
1588 res = res.substr(0, 60);
1594 /////////////////////////////////////////////////////////////////////
1598 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1601 // FIXME: completely broken
1602 static InsetMathHull * lastformula = 0;
1603 static CursorBase current = DocIterator(ibegin(nucleus()));
1605 static string laststr;
1607 if (lastformula != this || laststr != str) {
1608 //lyxerr << "reset lastformula to " << this << endl;
1611 current = ibegin(nucleus());
1613 mathed_parse_cell(ar, str);
1617 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1619 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1620 CursorSlice & top = it.back();
1621 MathData const & a = top.asInsetMath()->cell(top.idx_);
1622 if (a.matchpart(ar, top.pos_)) {
1623 bv->cursor().setSelection(it, ar.size());
1625 top.pos_ += ar.size();
1631 //lyxerr << "not found!" << endl;
1638 void InsetMathHull::write(ostream & os) const
1640 odocstringstream oss;
1641 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1644 os << to_utf8(oss.str());
1648 void InsetMathHull::read(Lexer & lex)
1651 mathed_parse_normal(at, lex);
1652 operator=(*at->asHullInset());
1656 bool InsetMathHull::readQuiet(Lexer & lex)
1659 bool result = mathed_parse_normal(at, lex, Parse::QUIET);
1660 operator=(*at->asHullInset());
1665 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1667 if (0 && display()) {
1671 TextPainter tpain(dim.width(), dim.height());
1672 drawT(tpain, 0, dim.ascent());
1674 // reset metrics cache to "real" values
1676 return tpain.textheight();
1678 odocstringstream oss;
1679 Encoding const * const enc = encodings.fromLyXName("utf8");
1680 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1682 if (type_ == hullRegexp)
1686 docstring const str = oss.str();
1693 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1698 if (getType() == hullSimple)
1699 name = from_ascii("inlineequation");
1701 name = from_ascii("informalequation");
1703 docstring bname = name;
1704 if (!label(0).empty())
1705 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1707 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1709 odocstringstream ls;
1710 if (runparams.flavor == OutputParams::XML) {
1711 ms << MTag("alt role='tex' ");
1712 // Workaround for db2latex: db2latex always includes equations with
1713 // \ensuremath{} or \begin{display}\end{display}
1714 // so we strip LyX' math environment
1715 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1716 InsetMathGrid::write(wi);
1717 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1722 InsetMathGrid::mathmlize(ms);
1725 ms << MTag("alt role='tex'");
1726 res = latex(ls, runparams);
1727 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1731 ms << from_ascii("<graphic fileref=\"eqn/");
1732 if (!label(0).empty())
1733 ms << sgml::cleanID(buffer(), runparams, label(0));
1735 ms << sgml::uniqueID(from_ascii("anon"));
1737 if (runparams.flavor == OutputParams::XML)
1738 ms << from_ascii("\"/>");
1740 ms << from_ascii("\">");
1742 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1744 return ms.line() + res;
1748 void InsetMathHull::tocString(odocstream & os) const
1750 plaintext(os, OutputParams(0));
1754 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1756 return from_ascii("context-math");