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"
39 #include "OutputParams.h"
40 #include "ParIterator.h"
43 #include "TextPainter.h"
44 #include "TocBackend.h"
46 #include "insets/RenderPreview.h"
47 #include "insets/InsetLabel.h"
49 #include "graphics/PreviewImage.h"
50 #include "graphics/PreviewLoader.h"
52 #include "frontends/Painter.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/gettext.h"
57 #include "support/lstrings.h"
62 using namespace lyx::support;
66 using cap::grabAndEraseSelection;
70 int getCols(HullType type)
87 // returns position of first relation operator in the array
88 // used for "intelligent splitting"
89 size_t firstRelOp(MathData const & ar)
91 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
93 return it - ar.begin();
98 char const * star(bool numbered)
100 return numbered ? "" : "*";
104 } // end anon namespace
107 HullType hullType(docstring const & s)
109 if (s == "none") return hullNone;
110 if (s == "simple") return hullSimple;
111 if (s == "equation") return hullEquation;
112 if (s == "eqnarray") return hullEqnArray;
113 if (s == "align") return hullAlign;
114 if (s == "alignat") return hullAlignAt;
115 if (s == "xalignat") return hullXAlignAt;
116 if (s == "xxalignat") return hullXXAlignAt;
117 if (s == "multline") return hullMultline;
118 if (s == "gather") return hullGather;
119 if (s == "flalign") return hullFlAlign;
120 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
125 docstring hullName(HullType type)
128 case hullNone: return from_ascii("none");
129 case hullSimple: return from_ascii("simple");
130 case hullEquation: return from_ascii("equation");
131 case hullEqnArray: return from_ascii("eqnarray");
132 case hullAlign: return from_ascii("align");
133 case hullAlignAt: return from_ascii("alignat");
134 case hullXAlignAt: return from_ascii("xalignat");
135 case hullXXAlignAt: return from_ascii("xxalignat");
136 case hullMultline: return from_ascii("multline");
137 case hullGather: return from_ascii("gather");
138 case hullFlAlign: return from_ascii("flalign");
140 lyxerr << "unknown hull type '" << type << "'" << endl;
141 return from_ascii("none");
145 static InsetLabel * dummy_pointer = 0;
147 InsetMathHull::InsetMathHull()
148 : InsetMathGrid(1, 1), type_(hullNone), nonum_(1, false),
149 label_(1, dummy_pointer), preview_(new RenderPreview(this))
151 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
152 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
153 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
154 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
160 InsetMathHull::InsetMathHull(HullType type)
161 : InsetMathGrid(getCols(type), 1), type_(type), nonum_(1, false),
162 label_(1, dummy_pointer), preview_(new RenderPreview(this))
169 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid()
175 InsetMathHull::~InsetMathHull()
177 for (size_t i = 0; i < label_.size(); ++i)
182 Inset * InsetMathHull::clone() const
184 return new InsetMathHull(*this);
188 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
192 InsetMathGrid::operator=(other);
194 nonum_ = other.nonum_;
195 for (size_t i = 0; i < label_.size(); ++i)
197 label_ = other.label_;
198 for (size_t i = 0; i != label_.size(); ++i) {
200 label_[i] = new InsetLabel(*label_[i]);
202 preview_.reset(new RenderPreview(*other.preview_, this));
208 void InsetMathHull::setBuffer(Buffer & buffer)
211 for (idx_type i = 0, n = nargs(); i != n; ++i) {
212 MathData & data = cell(i);
213 for (size_t j = 0; j != data.size(); ++j)
214 data[j].nucleus()->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::draw(PainterInfo & pi, int x, int y) const
384 use_preview_ = previewState(pi.base.bv);
385 Dimension const dim = dimension(*pi.base.bv);
387 // background of mathed under focus is not painted because
388 // selection at the top level of nested inset is difficult to handle.
389 if (!editing(pi.base.bv))
390 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
391 dim.asc + dim.des - 1, Color_mathbg);
394 // one pixel gap in front
395 preview_->draw(pi, x + 1, y);
396 setPosCache(pi, x, y);
400 FontSetChanger dummy1(pi.base, standardFont());
401 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
402 InsetMathGrid::draw(pi, x + 1, y);
404 if (numberedType()) {
405 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
406 for (row_type row = 0; row < nrows(); ++row) {
407 int const yy = y + rowinfo_[row].offset_;
408 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
409 docstring const nl = nicelabel(row);
413 setPosCache(pi, x, y);
417 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
420 InsetMathGrid::metricsT(mi, dim);
423 WriteStream wi(os, false, true, false);
425 dim.wid = os.str().size();
432 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
435 InsetMathGrid::drawT(pain, x, y);
438 WriteStream wi(os, false, true, false);
440 pain.draw(x, y, os.str().c_str());
445 static docstring latexString(InsetMathHull const & inset)
448 WriteStream wi(ls, false, false, false);
454 void InsetMathHull::addPreview(graphics::PreviewLoader & ploader) const
456 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
457 docstring const snippet = latexString(*this);
458 preview_->addPreview(snippet, ploader);
463 bool InsetMathHull::notifyCursorLeaves(Cursor const & /*old*/, Cursor & cur)
465 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
466 Buffer const & buffer = cur.buffer();
467 docstring const snippet = latexString(*this);
468 preview_->addPreview(snippet, buffer);
469 preview_->startLoading(buffer);
470 cur.updateFlags(Update::Force);
476 docstring InsetMathHull::label(row_type row) const
478 LASSERT(row < nrows(), /**/);
479 if (InsetLabel * il = label_[row])
480 return il->screenLabel();
485 void InsetMathHull::label(row_type row, docstring const & label)
487 //lyxerr << "setting label '" << label << "' for row " << row << endl;
491 label_[row] = dummy_pointer;
492 // We need an update of the Buffer reference cache.
493 // This is achieved by updateLabels().
494 lyx::updateLabels(buffer());
496 label_[row]->updateCommand(label);
499 InsetCommandParams p(LABEL_CODE);
501 label_[row] = new InsetLabel(p);
503 label_[row]->setBuffer(buffer());
507 void InsetMathHull::numbered(row_type row, bool num)
510 if (nonum_[row] && label_[row]) {
513 // We need an update of the Buffer reference cache.
514 // This is achieved by updateLabels().
515 lyx::updateLabels(buffer());
520 bool InsetMathHull::numbered(row_type row) const
526 bool InsetMathHull::ams() const
529 type_ == hullAlign ||
530 type_ == hullFlAlign ||
531 type_ == hullMultline ||
532 type_ == hullGather ||
533 type_ == hullAlignAt ||
534 type_ == hullXAlignAt ||
535 type_ == hullXXAlignAt;
539 Inset::DisplayType InsetMathHull::display() const
541 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
545 bool InsetMathHull::numberedType() const
547 if (type_ == hullNone)
549 if (type_ == hullSimple)
551 if (type_ == hullXXAlignAt)
553 for (row_type row = 0; row < nrows(); ++row)
560 void InsetMathHull::validate(LaTeXFeatures & features) const
563 features.require("amsmath");
565 // Validation is necessary only if not using AMS math.
566 // To be safe, we will always run mathedvalidate.
567 //if (features.amsstyle)
570 //features.binom = true;
572 InsetMathGrid::validate(features);
576 void InsetMathHull::header_write(WriteStream & os) const
578 bool n = numberedType();
592 os << "\\begin{equation" << star(n) << "}\n";
602 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
607 os << "\\begin{" << hullName(type_) << star(n) << '}'
608 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
612 os << "\\begin{" << hullName(type_) << '}'
613 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
617 os << "\\begin{unknown" << star(n) << '}';
623 void InsetMathHull::footer_write(WriteStream & os) const
625 bool n = numberedType();
638 os << "\\end{equation" << star(n) << "}\n";
650 os << "\\end{" << hullName(type_) << star(n) << "}\n";
654 os << "\\end{" << hullName(type_) << "}\n";
658 os << "\\end{unknown" << star(n) << '}';
664 bool InsetMathHull::rowChangeOK() const
667 type_ == hullEqnArray || type_ == hullAlign ||
668 type_ == hullFlAlign || type_ == hullAlignAt ||
669 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
670 type_ == hullGather || type_ == hullMultline;
674 bool InsetMathHull::colChangeOK() const
677 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
678 type_ == hullXAlignAt || type_ == hullXXAlignAt;
682 void InsetMathHull::addRow(row_type row)
687 bool numbered = numberedType();
689 if (type_ == hullMultline) {
690 if (row + 1 == nrows()) {
697 nonum_.insert(nonum_.begin() + row + 1, !numbered);
698 label_.insert(label_.begin() + row + 1, dummy_pointer);
701 InsetMathGrid::addRow(row);
705 void InsetMathHull::swapRow(row_type row)
709 if (row + 1 == nrows())
711 // gcc implements the standard std::vector<bool> which is *not* a container:
712 // http://www.gotw.ca/publications/N1185.pdf
713 // As a results, it doesn't like this:
714 // swap(nonum_[row], nonum_[row + 1]);
715 // so we do it manually:
716 bool const b = nonum_[row];
717 nonum_[row] = nonum_[row + 1];
719 swap(label_[row], label_[row + 1]);
720 InsetMathGrid::swapRow(row);
724 void InsetMathHull::delRow(row_type row)
726 if (nrows() <= 1 || !rowChangeOK())
728 if (row + 1 == nrows() && type_ == hullMultline) {
729 bool const b = nonum_[row - 1];
730 nonum_[row - 1] = nonum_[row];
732 swap(label_[row - 1], label_[row]);
733 InsetMathGrid::delRow(row);
736 InsetMathGrid::delRow(row);
737 // The last dummy row has no number info nor a label.
738 // Test nrows() + 1 because we have already erased the row.
739 if (row == nrows() + 1)
741 nonum_.erase(nonum_.begin() + row);
743 label_.erase(label_.begin() + row);
747 void InsetMathHull::addCol(col_type col)
751 InsetMathGrid::addCol(col);
755 void InsetMathHull::delCol(col_type col)
757 if (ncols() <= 1 || !colChangeOK())
759 InsetMathGrid::delCol(col);
763 docstring InsetMathHull::nicelabel(row_type row) const
768 return from_ascii("(#)");
769 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
773 void InsetMathHull::glueall()
776 for (idx_type i = 0; i < nargs(); ++i)
778 *this = InsetMathHull(hullSimple);
784 void InsetMathHull::splitTo2Cols()
786 LASSERT(ncols() == 1, /**/);
787 InsetMathGrid::addCol(1);
788 for (row_type row = 0; row < nrows(); ++row) {
789 idx_type const i = 2 * row;
790 pos_type pos = firstRelOp(cell(i));
791 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
792 cell(i).erase(pos, cell(i).size());
797 void InsetMathHull::splitTo3Cols()
799 LASSERT(ncols() < 3, /**/);
802 InsetMathGrid::addCol(2);
803 for (row_type row = 0; row < nrows(); ++row) {
804 idx_type const i = 3 * row + 1;
805 if (cell(i).size()) {
806 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
807 cell(i).erase(1, cell(i).size());
813 void InsetMathHull::changeCols(col_type cols)
817 else if (ncols() < cols) {
823 while (ncols() < cols)
824 InsetMathGrid::addCol(ncols());
830 for (row_type row = 0; row < nrows(); ++row) {
831 idx_type const i = row * ncols();
832 for (col_type col = cols; col < ncols(); ++col) {
833 cell(i + cols - 1).append(cell(i + col));
837 while (ncols() > cols) {
838 InsetMathGrid::delCol(ncols() - 1);
843 HullType InsetMathHull::getType() const
849 void InsetMathHull::setType(HullType type)
856 void InsetMathHull::mutate(HullType newtype)
858 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
860 // we try to move along the chain
861 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
863 // +-------------------------------------+
864 // we use eqnarray as intermediate type for mutations that are not
865 // directly supported because it handles labels and numbering for
868 if (newtype == type_) {
872 else if (newtype < hullNone) {
877 else if (type_ == hullNone) {
883 else if (type_ == hullSimple) {
884 if (newtype == hullNone) {
888 setType(hullEquation);
894 else if (type_ == hullEquation) {
895 if (newtype < type_) {
899 } else if (newtype == hullEqnArray) {
900 // split it "nicely" on the first relop
902 setType(hullEqnArray);
903 } else if (newtype == hullMultline || newtype == hullGather) {
913 else if (type_ == hullEqnArray) {
914 if (newtype < type_) {
915 // set correct (no)numbering
917 for (row_type row = 0; row < nrows(); ++row) {
924 // set first non-empty label
925 for (row_type row = 0; row < nrows(); ++row) {
927 label_[0] = label_[row];
934 } else { // align & Co.
941 else if (type_ == hullAlign || type_ == hullAlignAt ||
942 type_ == hullXAlignAt || type_ == hullFlAlign) {
943 if (newtype < hullAlign) {
945 setType(hullEqnArray);
947 } else if (newtype == hullGather || newtype == hullMultline) {
950 } else if (newtype == hullXXAlignAt) {
951 for (row_type row = 0; row < nrows(); ++row)
952 numbered(row, false);
959 else if (type_ == hullXXAlignAt) {
960 for (row_type row = 0; row < nrows(); ++row)
961 numbered(row, false);
962 if (newtype < hullAlign) {
964 setType(hullEqnArray);
966 } else if (newtype == hullGather || newtype == hullMultline) {
974 else if (type_ == hullMultline || type_ == hullGather) {
975 if (newtype == hullGather || newtype == hullMultline)
977 else if (newtype == hullAlign || newtype == hullFlAlign ||
978 newtype == hullAlignAt || newtype == hullXAlignAt) {
981 } else if (newtype == hullXXAlignAt) {
983 for (row_type row = 0; row < nrows(); ++row)
984 numbered(row, false);
988 setType(hullEqnArray);
994 lyxerr << "mutation from '" << to_utf8(hullName(type_))
995 << "' to '" << to_utf8(hullName(newtype))
996 << "' not implemented" << endl;
1001 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1004 if (numberedType()) {
1005 if (label_[row] && !nonum_[row])
1006 res += "\\label{" + label_[row]->getParam("name") + '}';
1007 if (nonum_[row] && (type_ != hullMultline))
1008 res += "\\nonumber ";
1010 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1014 void InsetMathHull::write(WriteStream & os) const
1017 InsetMathGrid::write(os);
1022 void InsetMathHull::normalize(NormalStream & os) const
1024 os << "[formula " << hullName(type_) << ' ';
1025 InsetMathGrid::normalize(os);
1030 void InsetMathHull::mathmlize(MathStream & os) const
1032 InsetMathGrid::mathmlize(os);
1036 void InsetMathHull::infoize(odocstream & os) const
1038 os << "Type: " << hullName(type_);
1042 void InsetMathHull::check() const
1044 LASSERT(nonum_.size() == nrows(), /**/);
1045 LASSERT(label_.size() == nrows(), /**/);
1049 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1053 idocstringstream iss(func.argument());
1054 iss >> dlang >> extra;
1056 extra = from_ascii("noextra");
1057 string const lang = to_ascii(dlang);
1059 // FIXME: temporarily disabled
1060 //if (cur.selection()) {
1063 // lyxerr << "use selection: " << ar << endl;
1064 // insert(pipeThroughExtern(lang, extra, ar));
1069 eq.push_back(MathAtom(new InsetMathChar('=')));
1071 // go to first item in line
1072 cur.idx() -= cur.idx() % ncols();
1075 if (getType() == hullSimple) {
1076 size_type pos = cur.cell().find_last(eq);
1078 if (cur.inMathed() && cur.selection()) {
1079 asArray(grabAndEraseSelection(cur), ar);
1080 } else if (pos == cur.cell().size()) {
1082 lyxerr << "use whole cell: " << ar << endl;
1084 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1085 lyxerr << "use partial cell form pos: " << pos << endl;
1087 cur.cell().append(eq);
1088 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1089 cur.pos() = cur.lastpos();
1093 if (getType() == hullEquation) {
1094 lyxerr << "use equation inset" << endl;
1095 mutate(hullEqnArray);
1096 MathData & ar = cur.cell();
1097 lyxerr << "use cell: " << ar << endl;
1101 cur.cell() = pipeThroughExtern(lang, extra, ar);
1102 // move to end of line
1103 cur.pos() = cur.lastpos();
1108 lyxerr << "use eqnarray" << endl;
1109 cur.idx() += 2 - cur.idx() % ncols();
1111 MathData ar = cur.cell();
1112 lyxerr << "use cell: " << ar << endl;
1113 // FIXME: temporarily disabled
1119 cur.cell() = pipeThroughExtern(lang, extra, ar);
1120 cur.pos() = cur.lastpos();
1125 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1127 //lyxerr << "action: " << cmd.action << endl;
1128 switch (cmd.action) {
1130 case LFUN_FINISHED_BACKWARD:
1131 case LFUN_FINISHED_FORWARD:
1132 case LFUN_FINISHED_RIGHT:
1133 case LFUN_FINISHED_LEFT:
1134 //lyxerr << "action: " << cmd.action << endl;
1135 InsetMathGrid::doDispatch(cur, cmd);
1139 case LFUN_BREAK_PARAGRAPH:
1140 // just swallow this
1143 case LFUN_NEWLINE_INSERT:
1144 // some magic for the common case
1145 if (type_ == hullSimple || type_ == hullEquation) {
1146 cur.recordUndoInset();
1148 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1149 mutate(align ? hullAlign : hullEqnArray);
1150 cur.idx() = nrows() * ncols() - 1;
1151 cur.pos() = cur.lastpos();
1153 InsetMathGrid::doDispatch(cur, cmd);
1156 case LFUN_MATH_NUMBER_TOGGLE: {
1157 //lyxerr << "toggling all numbers" << endl;
1158 cur.recordUndoInset();
1159 bool old = numberedType();
1160 if (type_ == hullMultline)
1161 numbered(nrows() - 1, !old);
1163 for (row_type row = 0; row < nrows(); ++row)
1164 numbered(row, !old);
1166 cur.message(old ? _("No number") : _("Number"));
1170 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1171 cur.recordUndoInset();
1172 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1173 bool old = numbered(r);
1174 cur.message(old ? _("No number") : _("Number"));
1179 case LFUN_LABEL_INSERT: {
1180 cur.recordUndoInset();
1181 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1182 docstring old_label = label(r);
1183 docstring const default_label = from_ascii(
1184 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1185 if (old_label.empty())
1186 old_label = default_label;
1188 InsetCommandParams p(LABEL_CODE);
1189 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1190 string const data = InsetCommand::params2string("label", p);
1192 if (cmd.argument().empty())
1193 cur.bv().showDialog("label", data);
1195 FuncRequest fr(LFUN_INSET_INSERT, data);
1201 case LFUN_WORD_DELETE_FORWARD:
1202 case LFUN_CHAR_DELETE_FORWARD:
1203 if (col(cur.idx()) + 1 == ncols()
1204 && cur.pos() == cur.lastpos()) {
1205 if (!label(row(cur.idx())).empty()) {
1206 cur.recordUndoInset();
1207 label(row(cur.idx()), docstring());
1208 } else if (numbered(row(cur.idx()))) {
1209 cur.recordUndoInset();
1210 numbered(row(cur.idx()), false);
1212 InsetMathGrid::doDispatch(cur, cmd);
1216 InsetMathGrid::doDispatch(cur, cmd);
1221 case LFUN_INSET_INSERT: {
1222 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1223 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1224 string const name = cmd.getArg(0);
1225 if (name == "label") {
1226 InsetCommandParams p(LABEL_CODE);
1227 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1228 docstring str = p["name"];
1229 cur.recordUndoInset();
1230 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1234 docstring old = label(r);
1237 // The label will take care of the reference update.
1241 // Newly created inset so initialize it.
1242 label_[r]->initView();
1247 InsetMathGrid::doDispatch(cur, cmd);
1251 case LFUN_MATH_EXTERN:
1252 cur.recordUndoInset();
1256 case LFUN_MATH_MUTATE: {
1257 cur.recordUndoInset();
1258 row_type row = cur.row();
1259 col_type col = cur.col();
1260 mutate(hullType(cmd.argument()));
1261 cur.idx() = row * ncols() + col;
1262 if (cur.idx() > cur.lastidx()) {
1263 cur.idx() = cur.lastidx();
1264 cur.pos() = cur.lastpos();
1266 if (cur.pos() > cur.lastpos())
1267 cur.pos() = cur.lastpos();
1269 // FIXME: find some more clever handling of the selection,
1270 // i.e. preserve it.
1271 cur.clearSelection();
1272 //cur.dispatched(FINISHED);
1276 case LFUN_MATH_DISPLAY: {
1277 cur.recordUndoInset();
1278 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1280 cur.pos() = cur.lastpos();
1281 //cur.dispatched(FINISHED);
1286 InsetMathGrid::doDispatch(cur, cmd);
1292 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1293 FuncStatus & status) const
1295 switch (cmd.action) {
1296 case LFUN_FINISHED_BACKWARD:
1297 case LFUN_FINISHED_FORWARD:
1298 case LFUN_FINISHED_RIGHT:
1299 case LFUN_FINISHED_LEFT:
1302 case LFUN_NEWLINE_INSERT:
1303 case LFUN_MATH_EXTERN:
1304 case LFUN_MATH_MUTATE:
1305 case LFUN_MATH_DISPLAY:
1307 status.setEnabled(true);
1309 case LFUN_MATH_NUMBER_TOGGLE:
1310 // FIXME: what is the right test, this or the one of
1312 status.setEnabled(display());
1313 status.setOnOff(numberedType());
1315 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1316 // FIXME: what is the right test, this or the one of
1318 bool const enable = (type_ == hullMultline) ?
1319 (nrows() - 1 == cur.row()) : display();
1320 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1321 status.setEnabled(enable);
1322 status.setOnOff(numbered(r));
1325 case LFUN_LABEL_INSERT:
1326 status.setEnabled(type_ != hullSimple);
1328 case LFUN_INSET_INSERT:
1329 if (cmd.getArg(0) == "label") {
1330 status.setEnabled(type_ != hullSimple);
1333 return InsetMathGrid::getStatus(cur, cmd, status);
1334 case LFUN_TABULAR_FEATURE: {
1335 istringstream is(to_utf8(cmd.argument()));
1339 && (s == "append-row"
1340 || s == "delete-row"
1341 || s == "copy-row")) {
1342 status.message(bformat(
1343 from_utf8(N_("Can't change number of rows in '%1$s'")),
1345 status.setEnabled(false);
1349 && (s == "append-column"
1350 || s == "delete-column"
1351 || s == "copy-column")) {
1352 status.message(bformat(
1353 from_utf8(N_("Can't change number of columns in '%1$s'")),
1355 status.setEnabled(false);
1358 if ((type_ == hullSimple
1359 || type_ == hullEquation
1360 || type_ == hullNone) &&
1361 (s == "add-hline-above" || s == "add-hline-below")) {
1362 status.message(bformat(
1363 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1365 status.setEnabled(false);
1368 if (s == "add-vline-left" || s == "add-vline-right") {
1369 status.message(bformat(
1370 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1372 status.setEnabled(false);
1375 if (s == "valign-top" || s == "valign-middle"
1376 || s == "valign-bottom" || s == "align-left"
1377 || s == "align-center" || s == "align-right") {
1378 status.setEnabled(false);
1381 return InsetMathGrid::getStatus(cur, cmd, status);
1384 return InsetMathGrid::getStatus(cur, cmd, status);
1387 // This cannot really happen, but inserted to shut-up gcc
1388 return InsetMathGrid::getStatus(cur, cmd, status);
1392 /////////////////////////////////////////////////////////////////////
1396 // simply scrap this function if you want
1397 void InsetMathHull::mutateToText()
1400 // translate to latex
1402 latex(os, false, false);
1403 string str = os.str();
1406 Text * lt = view_->cursor().innerText();
1407 string::const_iterator cit = str.begin();
1408 string::const_iterator end = str.end();
1409 for (; cit != end; ++cit)
1410 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1413 //dispatch(LFUN_ESCAPE);
1418 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1419 docstring const & font)
1421 // this whole function is a hack and won't work for incremental font
1424 if (cur.inset().asInsetMath()->name() == font)
1425 cur.handleFont(to_utf8(font));
1427 cur.handleNest(createInsetMath(font));
1433 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1438 font.fromString(to_utf8(arg), b);
1439 if (font.fontInfo().color() != Color_inherit) {
1440 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1441 cur.handleNest(at, 0);
1446 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1449 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1450 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1451 enter_front ? idxFirst(cur) : idxLast(cur);
1452 // The inset formula dimension is not necessarily the same as the
1453 // one of the instant preview image, so we have to indicate to the
1454 // BufferView that a metrics update is needed.
1455 cur.updateFlags(Update::Force);
1459 docstring InsetMathHull::editMessage() const
1461 return _("Math editor mode");
1465 void InsetMathHull::revealCodes(Cursor & cur) const
1467 if (!cur.inMathed())
1469 odocstringstream os;
1471 cur.message(os.str());
1473 // write something to the minibuffer
1474 // translate to latex
1478 string str = os.str();
1480 string::size_type pos = 0;
1482 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1485 else if (*it == '\0') {
1487 pos = it - str.begin();
1493 res = res.substr(pos - 30);
1494 if (res.size() > 60)
1495 res = res.substr(0, 60);
1501 InsetCode InsetMathHull::lyxCode() const
1507 /////////////////////////////////////////////////////////////////////
1511 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1514 // FIXME: completely broken
1515 static InsetMathHull * lastformula = 0;
1516 static CursorBase current = DocIterator(ibegin(nucleus()));
1518 static string laststr;
1520 if (lastformula != this || laststr != str) {
1521 //lyxerr << "reset lastformula to " << this << endl;
1524 current = ibegin(nucleus());
1526 mathed_parse_cell(ar, str);
1530 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1532 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1533 CursorSlice & top = it.back();
1534 MathData const & a = top.asInsetMath()->cell(top.idx_);
1535 if (a.matchpart(ar, top.pos_)) {
1536 bv->cursor().setSelection(it, ar.size());
1538 top.pos_ += ar.size();
1544 //lyxerr << "not found!" << endl;
1551 void InsetMathHull::write(ostream & os) const
1553 odocstringstream oss;
1554 WriteStream wi(oss, false, false, false);
1557 os << to_utf8(oss.str());
1561 void InsetMathHull::read(Lexer & lex)
1564 mathed_parse_normal(at, lex);
1565 operator=(*at->asHullInset());
1569 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1571 if (0 && display()) {
1575 TextPainter tpain(dim.width(), dim.height());
1576 drawT(tpain, 0, dim.ascent());
1578 // reset metrics cache to "real" values
1580 return tpain.textheight();
1582 odocstringstream oss;
1583 WriteStream wi(oss, false, true, false, runparams.encoding);
1586 docstring const str = oss.str();
1593 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1598 if (getType() == hullSimple)
1599 name = from_ascii("inlineequation");
1601 name = from_ascii("informalequation");
1603 docstring bname = name;
1604 if (!label(0).empty())
1605 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1607 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1609 odocstringstream ls;
1610 if (runparams.flavor == OutputParams::XML) {
1611 ms << MTag("alt role='tex' ");
1612 // Workaround for db2latex: db2latex always includes equations with
1613 // \ensuremath{} or \begin{display}\end{display}
1614 // so we strip LyX' math environment
1615 WriteStream wi(ls, false, false, false, runparams.encoding);
1616 InsetMathGrid::write(wi);
1617 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1622 InsetMathGrid::mathmlize(ms);
1625 ms << MTag("alt role='tex'");
1626 res = latex(ls, runparams);
1627 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1631 ms << from_ascii("<graphic fileref=\"eqn/");
1632 if (!label(0).empty())
1633 ms << sgml::cleanID(buffer(), runparams, label(0));
1635 ms << sgml::uniqueID(from_ascii("anon"));
1637 if (runparams.flavor == OutputParams::XML)
1638 ms << from_ascii("\"/>");
1640 ms << from_ascii("\">");
1642 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1644 return ms.line() + res;
1648 void InsetMathHull::textString(odocstream & os) const
1650 plaintext(os, OutputParams(0));
1654 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1656 return from_ascii("context-math");