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");
566 // Validation is necessary only if not using AMS math.
567 // To be safe, we will always run mathedvalidate.
568 //if (features.amsstyle)
571 //features.binom = true;
573 InsetMathGrid::validate(features);
577 void InsetMathHull::header_write(WriteStream & os) const
579 bool n = numberedType();
593 os << "\\begin{equation" << star(n) << "}\n";
603 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
608 os << "\\begin{" << hullName(type_) << star(n) << '}'
609 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
613 os << "\\begin{" << hullName(type_) << '}'
614 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
618 os << "\\begin{unknown" << star(n) << '}';
624 void InsetMathHull::footer_write(WriteStream & os) const
626 bool n = numberedType();
639 os << "\\end{equation" << star(n) << "}\n";
651 os << "\\end{" << hullName(type_) << star(n) << "}\n";
655 os << "\\end{" << hullName(type_) << "}\n";
659 os << "\\end{unknown" << star(n) << '}';
665 bool InsetMathHull::rowChangeOK() const
668 type_ == hullEqnArray || type_ == hullAlign ||
669 type_ == hullFlAlign || type_ == hullAlignAt ||
670 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
671 type_ == hullGather || type_ == hullMultline;
675 bool InsetMathHull::colChangeOK() const
678 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
679 type_ == hullXAlignAt || type_ == hullXXAlignAt;
683 void InsetMathHull::addRow(row_type row)
688 bool numbered = numberedType();
690 if (type_ == hullMultline) {
691 if (row + 1 == nrows()) {
698 nonum_.insert(nonum_.begin() + row + 1, !numbered);
699 label_.insert(label_.begin() + row + 1, dummy_pointer);
702 InsetMathGrid::addRow(row);
706 void InsetMathHull::swapRow(row_type row)
710 if (row + 1 == nrows())
712 // gcc implements the standard std::vector<bool> which is *not* a container:
713 // http://www.gotw.ca/publications/N1185.pdf
714 // As a results, it doesn't like this:
715 // swap(nonum_[row], nonum_[row + 1]);
716 // so we do it manually:
717 bool const b = nonum_[row];
718 nonum_[row] = nonum_[row + 1];
720 swap(label_[row], label_[row + 1]);
721 InsetMathGrid::swapRow(row);
725 void InsetMathHull::delRow(row_type row)
727 if (nrows() <= 1 || !rowChangeOK())
729 if (row + 1 == nrows() && type_ == hullMultline) {
730 bool const b = nonum_[row - 1];
731 nonum_[row - 1] = nonum_[row];
733 swap(label_[row - 1], label_[row]);
734 InsetMathGrid::delRow(row);
737 InsetMathGrid::delRow(row);
738 // The last dummy row has no number info nor a label.
739 // Test nrows() + 1 because we have already erased the row.
740 if (row == nrows() + 1)
742 nonum_.erase(nonum_.begin() + row);
744 label_.erase(label_.begin() + row);
748 void InsetMathHull::addCol(col_type col)
752 InsetMathGrid::addCol(col);
756 void InsetMathHull::delCol(col_type col)
758 if (ncols() <= 1 || !colChangeOK())
760 InsetMathGrid::delCol(col);
764 docstring InsetMathHull::nicelabel(row_type row) const
769 return from_ascii("(#)");
770 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
774 void InsetMathHull::glueall()
777 for (idx_type i = 0; i < nargs(); ++i)
779 *this = InsetMathHull(hullSimple);
785 void InsetMathHull::splitTo2Cols()
787 LASSERT(ncols() == 1, /**/);
788 InsetMathGrid::addCol(1);
789 for (row_type row = 0; row < nrows(); ++row) {
790 idx_type const i = 2 * row;
791 pos_type pos = firstRelOp(cell(i));
792 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
793 cell(i).erase(pos, cell(i).size());
798 void InsetMathHull::splitTo3Cols()
800 LASSERT(ncols() < 3, /**/);
803 InsetMathGrid::addCol(2);
804 for (row_type row = 0; row < nrows(); ++row) {
805 idx_type const i = 3 * row + 1;
806 if (cell(i).size()) {
807 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
808 cell(i).erase(1, cell(i).size());
814 void InsetMathHull::changeCols(col_type cols)
818 else if (ncols() < cols) {
824 while (ncols() < cols)
825 InsetMathGrid::addCol(ncols());
831 for (row_type row = 0; row < nrows(); ++row) {
832 idx_type const i = row * ncols();
833 for (col_type col = cols; col < ncols(); ++col) {
834 cell(i + cols - 1).append(cell(i + col));
838 while (ncols() > cols) {
839 InsetMathGrid::delCol(ncols() - 1);
844 HullType InsetMathHull::getType() const
850 void InsetMathHull::setType(HullType type)
857 void InsetMathHull::mutate(HullType newtype)
859 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
861 // we try to move along the chain
862 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
864 // +-------------------------------------+
865 // we use eqnarray as intermediate type for mutations that are not
866 // directly supported because it handles labels and numbering for
869 if (newtype == type_) {
873 else if (newtype < hullNone) {
878 else if (type_ == hullNone) {
884 else if (type_ == hullSimple) {
885 if (newtype == hullNone) {
889 setType(hullEquation);
895 else if (type_ == hullEquation) {
896 if (newtype < type_) {
900 } else if (newtype == hullEqnArray) {
901 // split it "nicely" on the first relop
903 setType(hullEqnArray);
904 } else if (newtype == hullMultline || newtype == hullGather) {
914 else if (type_ == hullEqnArray) {
915 if (newtype < type_) {
916 // set correct (no)numbering
918 for (row_type row = 0; row < nrows(); ++row) {
925 // set first non-empty label
926 for (row_type row = 0; row < nrows(); ++row) {
928 label_[0] = label_[row];
935 } else { // align & Co.
942 else if (type_ == hullAlign || type_ == hullAlignAt ||
943 type_ == hullXAlignAt || type_ == hullFlAlign) {
944 if (newtype < hullAlign) {
946 setType(hullEqnArray);
948 } else if (newtype == hullGather || newtype == hullMultline) {
951 } else if (newtype == hullXXAlignAt) {
952 for (row_type row = 0; row < nrows(); ++row)
953 numbered(row, false);
960 else if (type_ == hullXXAlignAt) {
961 for (row_type row = 0; row < nrows(); ++row)
962 numbered(row, false);
963 if (newtype < hullAlign) {
965 setType(hullEqnArray);
967 } else if (newtype == hullGather || newtype == hullMultline) {
975 else if (type_ == hullMultline || type_ == hullGather) {
976 if (newtype == hullGather || newtype == hullMultline)
978 else if (newtype == hullAlign || newtype == hullFlAlign ||
979 newtype == hullAlignAt || newtype == hullXAlignAt) {
982 } else if (newtype == hullXXAlignAt) {
984 for (row_type row = 0; row < nrows(); ++row)
985 numbered(row, false);
989 setType(hullEqnArray);
995 lyxerr << "mutation from '" << to_utf8(hullName(type_))
996 << "' to '" << to_utf8(hullName(newtype))
997 << "' not implemented" << endl;
1002 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
1005 if (numberedType()) {
1006 if (label_[row] && !nonum_[row])
1007 res += "\\label{" + label_[row]->getParam("name") + '}';
1008 if (nonum_[row] && (type_ != hullMultline))
1009 res += "\\nonumber ";
1011 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1015 void InsetMathHull::write(WriteStream & os) const
1018 InsetMathGrid::write(os);
1023 void InsetMathHull::normalize(NormalStream & os) const
1025 os << "[formula " << hullName(type_) << ' ';
1026 InsetMathGrid::normalize(os);
1031 void InsetMathHull::mathmlize(MathStream & os) const
1033 InsetMathGrid::mathmlize(os);
1037 void InsetMathHull::infoize(odocstream & os) const
1039 os << "Type: " << hullName(type_);
1043 void InsetMathHull::check() const
1045 LASSERT(nonum_.size() == nrows(), /**/);
1046 LASSERT(label_.size() == nrows(), /**/);
1050 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1054 idocstringstream iss(func.argument());
1055 iss >> dlang >> extra;
1057 extra = from_ascii("noextra");
1058 string const lang = to_ascii(dlang);
1060 // FIXME: temporarily disabled
1061 //if (cur.selection()) {
1064 // lyxerr << "use selection: " << ar << endl;
1065 // insert(pipeThroughExtern(lang, extra, ar));
1070 eq.push_back(MathAtom(new InsetMathChar('=')));
1072 // go to first item in line
1073 cur.idx() -= cur.idx() % ncols();
1076 if (getType() == hullSimple) {
1077 size_type pos = cur.cell().find_last(eq);
1079 if (cur.inMathed() && cur.selection()) {
1080 asArray(grabAndEraseSelection(cur), ar);
1081 } else if (pos == cur.cell().size()) {
1083 lyxerr << "use whole cell: " << ar << endl;
1085 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1086 lyxerr << "use partial cell form pos: " << pos << endl;
1088 cur.cell().append(eq);
1089 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1090 cur.pos() = cur.lastpos();
1094 if (getType() == hullEquation) {
1095 lyxerr << "use equation inset" << endl;
1096 mutate(hullEqnArray);
1097 MathData & ar = cur.cell();
1098 lyxerr << "use cell: " << ar << endl;
1102 cur.cell() = pipeThroughExtern(lang, extra, ar);
1103 // move to end of line
1104 cur.pos() = cur.lastpos();
1109 lyxerr << "use eqnarray" << endl;
1110 cur.idx() += 2 - cur.idx() % ncols();
1112 MathData ar = cur.cell();
1113 lyxerr << "use cell: " << ar << endl;
1114 // FIXME: temporarily disabled
1120 cur.cell() = pipeThroughExtern(lang, extra, ar);
1121 cur.pos() = cur.lastpos();
1126 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1128 //lyxerr << "action: " << cmd.action << endl;
1129 switch (cmd.action) {
1131 case LFUN_FINISHED_BACKWARD:
1132 case LFUN_FINISHED_FORWARD:
1133 case LFUN_FINISHED_RIGHT:
1134 case LFUN_FINISHED_LEFT:
1135 //lyxerr << "action: " << cmd.action << endl;
1136 InsetMathGrid::doDispatch(cur, cmd);
1140 case LFUN_BREAK_PARAGRAPH:
1141 // just swallow this
1144 case LFUN_NEWLINE_INSERT:
1145 // some magic for the common case
1146 if (type_ == hullSimple || type_ == hullEquation) {
1147 cur.recordUndoInset();
1149 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1150 mutate(align ? hullAlign : hullEqnArray);
1151 cur.idx() = nrows() * ncols() - 1;
1152 cur.pos() = cur.lastpos();
1154 InsetMathGrid::doDispatch(cur, cmd);
1157 case LFUN_MATH_NUMBER_TOGGLE: {
1158 //lyxerr << "toggling all numbers" << endl;
1159 cur.recordUndoInset();
1160 bool old = numberedType();
1161 if (type_ == hullMultline)
1162 numbered(nrows() - 1, !old);
1164 for (row_type row = 0; row < nrows(); ++row)
1165 numbered(row, !old);
1167 cur.message(old ? _("No number") : _("Number"));
1171 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1172 cur.recordUndoInset();
1173 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1174 bool old = numbered(r);
1175 cur.message(old ? _("No number") : _("Number"));
1180 case LFUN_LABEL_INSERT: {
1181 cur.recordUndoInset();
1182 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1183 docstring old_label = label(r);
1184 docstring const default_label = from_ascii(
1185 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1186 if (old_label.empty())
1187 old_label = default_label;
1189 InsetCommandParams p(LABEL_CODE);
1190 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1191 string const data = InsetCommand::params2string("label", p);
1193 if (cmd.argument().empty())
1194 cur.bv().showDialog("label", data);
1196 FuncRequest fr(LFUN_INSET_INSERT, data);
1202 case LFUN_WORD_DELETE_FORWARD:
1203 case LFUN_CHAR_DELETE_FORWARD:
1204 if (col(cur.idx()) + 1 == ncols()
1205 && cur.pos() == cur.lastpos()) {
1206 if (!label(row(cur.idx())).empty()) {
1207 cur.recordUndoInset();
1208 label(row(cur.idx()), docstring());
1209 } else if (numbered(row(cur.idx()))) {
1210 cur.recordUndoInset();
1211 numbered(row(cur.idx()), false);
1213 InsetMathGrid::doDispatch(cur, cmd);
1217 InsetMathGrid::doDispatch(cur, cmd);
1222 case LFUN_INSET_INSERT: {
1223 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1224 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1225 string const name = cmd.getArg(0);
1226 if (name == "label") {
1227 InsetCommandParams p(LABEL_CODE);
1228 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1229 docstring str = p["name"];
1230 cur.recordUndoInset();
1231 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1235 docstring old = label(r);
1238 // The label will take care of the reference update.
1242 // Newly created inset so initialize it.
1243 label_[r]->initView();
1248 InsetMathGrid::doDispatch(cur, cmd);
1252 case LFUN_MATH_EXTERN:
1253 cur.recordUndoInset();
1257 case LFUN_MATH_MUTATE: {
1258 cur.recordUndoInset();
1259 row_type row = cur.row();
1260 col_type col = cur.col();
1261 mutate(hullType(cmd.argument()));
1262 cur.idx() = row * ncols() + col;
1263 if (cur.idx() > cur.lastidx()) {
1264 cur.idx() = cur.lastidx();
1265 cur.pos() = cur.lastpos();
1267 if (cur.pos() > cur.lastpos())
1268 cur.pos() = cur.lastpos();
1270 // FIXME: find some more clever handling of the selection,
1271 // i.e. preserve it.
1272 cur.clearSelection();
1273 //cur.dispatched(FINISHED);
1277 case LFUN_MATH_DISPLAY: {
1278 cur.recordUndoInset();
1279 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1281 cur.pos() = cur.lastpos();
1282 //cur.dispatched(FINISHED);
1287 InsetMathGrid::doDispatch(cur, cmd);
1293 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1294 FuncStatus & status) const
1296 switch (cmd.action) {
1297 case LFUN_FINISHED_BACKWARD:
1298 case LFUN_FINISHED_FORWARD:
1299 case LFUN_FINISHED_RIGHT:
1300 case LFUN_FINISHED_LEFT:
1303 case LFUN_NEWLINE_INSERT:
1304 case LFUN_MATH_EXTERN:
1305 case LFUN_MATH_MUTATE:
1306 case LFUN_MATH_DISPLAY:
1308 status.setEnabled(true);
1310 case LFUN_MATH_NUMBER_TOGGLE:
1311 // FIXME: what is the right test, this or the one of
1313 status.setEnabled(display());
1314 status.setOnOff(numberedType());
1316 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1317 // FIXME: what is the right test, this or the one of
1319 bool const enable = (type_ == hullMultline) ?
1320 (nrows() - 1 == cur.row()) : display();
1321 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1322 status.setEnabled(enable);
1323 status.setOnOff(numbered(r));
1326 case LFUN_LABEL_INSERT:
1327 status.setEnabled(type_ != hullSimple);
1329 case LFUN_INSET_INSERT:
1330 if (cmd.getArg(0) == "label") {
1331 status.setEnabled(type_ != hullSimple);
1334 return InsetMathGrid::getStatus(cur, cmd, status);
1335 case LFUN_TABULAR_FEATURE: {
1336 istringstream is(to_utf8(cmd.argument()));
1340 && (s == "append-row"
1341 || s == "delete-row"
1342 || s == "copy-row")) {
1343 status.message(bformat(
1344 from_utf8(N_("Can't change number of rows in '%1$s'")),
1346 status.setEnabled(false);
1350 && (s == "append-column"
1351 || s == "delete-column"
1352 || s == "copy-column")) {
1353 status.message(bformat(
1354 from_utf8(N_("Can't change number of columns in '%1$s'")),
1356 status.setEnabled(false);
1359 if ((type_ == hullSimple
1360 || type_ == hullEquation
1361 || type_ == hullNone) &&
1362 (s == "add-hline-above" || s == "add-hline-below")) {
1363 status.message(bformat(
1364 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1366 status.setEnabled(false);
1369 if (s == "add-vline-left" || s == "add-vline-right") {
1370 status.message(bformat(
1371 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1373 status.setEnabled(false);
1376 if (s == "valign-top" || s == "valign-middle"
1377 || s == "valign-bottom" || s == "align-left"
1378 || s == "align-center" || s == "align-right") {
1379 status.setEnabled(false);
1382 return InsetMathGrid::getStatus(cur, cmd, status);
1385 return InsetMathGrid::getStatus(cur, cmd, status);
1388 // This cannot really happen, but inserted to shut-up gcc
1389 return InsetMathGrid::getStatus(cur, cmd, status);
1393 /////////////////////////////////////////////////////////////////////
1397 // simply scrap this function if you want
1398 void InsetMathHull::mutateToText()
1401 // translate to latex
1403 latex(os, false, false);
1404 string str = os.str();
1407 Text * lt = view_->cursor().innerText();
1408 string::const_iterator cit = str.begin();
1409 string::const_iterator end = str.end();
1410 for (; cit != end; ++cit)
1411 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1414 //dispatch(LFUN_ESCAPE);
1419 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1420 docstring const & font)
1422 // this whole function is a hack and won't work for incremental font
1425 if (cur.inset().asInsetMath()->name() == font)
1426 cur.handleFont(to_utf8(font));
1428 cur.handleNest(createInsetMath(font));
1434 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1439 font.fromString(to_utf8(arg), b);
1440 if (font.fontInfo().color() != Color_inherit) {
1441 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1442 cur.handleNest(at, 0);
1447 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1450 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1451 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1452 enter_front ? idxFirst(cur) : idxLast(cur);
1453 // The inset formula dimension is not necessarily the same as the
1454 // one of the instant preview image, so we have to indicate to the
1455 // BufferView that a metrics update is needed.
1456 cur.updateFlags(Update::Force);
1460 docstring InsetMathHull::editMessage() const
1462 return _("Math editor mode");
1466 void InsetMathHull::revealCodes(Cursor & cur) const
1468 if (!cur.inMathed())
1470 odocstringstream os;
1472 cur.message(os.str());
1474 // write something to the minibuffer
1475 // translate to latex
1479 string str = os.str();
1481 string::size_type pos = 0;
1483 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1486 else if (*it == '\0') {
1488 pos = it - str.begin();
1494 res = res.substr(pos - 30);
1495 if (res.size() > 60)
1496 res = res.substr(0, 60);
1502 InsetCode InsetMathHull::lyxCode() const
1508 /////////////////////////////////////////////////////////////////////
1512 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1515 // FIXME: completely broken
1516 static InsetMathHull * lastformula = 0;
1517 static CursorBase current = DocIterator(ibegin(nucleus()));
1519 static string laststr;
1521 if (lastformula != this || laststr != str) {
1522 //lyxerr << "reset lastformula to " << this << endl;
1525 current = ibegin(nucleus());
1527 mathed_parse_cell(ar, str);
1531 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1533 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1534 CursorSlice & top = it.back();
1535 MathData const & a = top.asInsetMath()->cell(top.idx_);
1536 if (a.matchpart(ar, top.pos_)) {
1537 bv->cursor().setSelection(it, ar.size());
1539 top.pos_ += ar.size();
1545 //lyxerr << "not found!" << endl;
1552 void InsetMathHull::write(ostream & os) const
1554 odocstringstream oss;
1555 WriteStream wi(oss, false, false, false);
1558 os << to_utf8(oss.str());
1562 void InsetMathHull::read(Lexer & lex)
1565 mathed_parse_normal(at, lex);
1566 operator=(*at->asHullInset());
1570 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1572 if (0 && display()) {
1576 TextPainter tpain(dim.width(), dim.height());
1577 drawT(tpain, 0, dim.ascent());
1579 // reset metrics cache to "real" values
1581 return tpain.textheight();
1583 odocstringstream oss;
1584 WriteStream wi(oss, false, true, false, runparams.encoding);
1587 docstring const str = oss.str();
1594 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1599 if (getType() == hullSimple)
1600 name = from_ascii("inlineequation");
1602 name = from_ascii("informalequation");
1604 docstring bname = name;
1605 if (!label(0).empty())
1606 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1608 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1610 odocstringstream ls;
1611 if (runparams.flavor == OutputParams::XML) {
1612 ms << MTag("alt role='tex' ");
1613 // Workaround for db2latex: db2latex always includes equations with
1614 // \ensuremath{} or \begin{display}\end{display}
1615 // so we strip LyX' math environment
1616 WriteStream wi(ls, false, false, false, runparams.encoding);
1617 InsetMathGrid::write(wi);
1618 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1623 InsetMathGrid::mathmlize(ms);
1626 ms << MTag("alt role='tex'");
1627 res = latex(ls, runparams);
1628 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1632 ms << from_ascii("<graphic fileref=\"eqn/");
1633 if (!label(0).empty())
1634 ms << sgml::cleanID(buffer(), runparams, label(0));
1636 ms << sgml::uniqueID(from_ascii("anon"));
1638 if (runparams.flavor == OutputParams::XML)
1639 ms << from_ascii("\"/>");
1641 ms << from_ascii("\">");
1643 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1645 return ms.line() + res;
1649 void InsetMathHull::textString(odocstream & os) const
1651 plaintext(os, OutputParams(0));
1655 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1657 return from_ascii("context-math");