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;
493 label_[row]->updateCommand(label);
496 InsetCommandParams p(LABEL_CODE);
498 label_[row] = new InsetLabel(p);
500 label_[row]->setBuffer(buffer());
504 void InsetMathHull::numbered(row_type row, bool num)
507 if (nonum_[row] && label_[row]) {
514 bool InsetMathHull::numbered(row_type row) const
520 bool InsetMathHull::ams() const
523 type_ == hullAlign ||
524 type_ == hullFlAlign ||
525 type_ == hullMultline ||
526 type_ == hullGather ||
527 type_ == hullAlignAt ||
528 type_ == hullXAlignAt ||
529 type_ == hullXXAlignAt;
533 Inset::DisplayType InsetMathHull::display() const
535 return (type_ != hullSimple && type_ != hullNone) ? AlignCenter : Inline;
539 bool InsetMathHull::numberedType() const
541 if (type_ == hullNone)
543 if (type_ == hullSimple)
545 if (type_ == hullXXAlignAt)
547 for (row_type row = 0; row < nrows(); ++row)
554 void InsetMathHull::validate(LaTeXFeatures & features) const
557 features.require("amsmath");
560 // Validation is necessary only if not using AMS math.
561 // To be safe, we will always run mathedvalidate.
562 //if (features.amsstyle)
565 //features.binom = true;
567 InsetMathGrid::validate(features);
571 void InsetMathHull::header_write(WriteStream & os) const
573 bool n = numberedType();
587 os << "\\begin{equation" << star(n) << "}\n";
597 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
602 os << "\\begin{" << hullName(type_) << star(n) << '}'
603 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
607 os << "\\begin{" << hullName(type_) << '}'
608 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
612 os << "\\begin{unknown" << star(n) << '}';
618 void InsetMathHull::footer_write(WriteStream & os) const
620 bool n = numberedType();
633 os << "\\end{equation" << star(n) << "}\n";
645 os << "\\end{" << hullName(type_) << star(n) << "}\n";
649 os << "\\end{" << hullName(type_) << "}\n";
653 os << "\\end{unknown" << star(n) << '}';
659 bool InsetMathHull::rowChangeOK() const
662 type_ == hullEqnArray || type_ == hullAlign ||
663 type_ == hullFlAlign || type_ == hullAlignAt ||
664 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
665 type_ == hullGather || type_ == hullMultline;
669 bool InsetMathHull::colChangeOK() const
672 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
673 type_ == hullXAlignAt || type_ == hullXXAlignAt;
677 void InsetMathHull::addRow(row_type row)
682 bool numbered = numberedType();
684 if (type_ == hullMultline) {
685 if (row + 1 == nrows()) {
692 nonum_.insert(nonum_.begin() + row + 1, !numbered);
693 label_.insert(label_.begin() + row + 1, dummy_pointer);
696 InsetMathGrid::addRow(row);
700 void InsetMathHull::swapRow(row_type row)
704 if (row + 1 == nrows())
706 // gcc implements the standard std::vector<bool> which is *not* a container:
707 // http://www.gotw.ca/publications/N1185.pdf
708 // As a results, it doesn't like this:
709 // swap(nonum_[row], nonum_[row + 1]);
710 // so we do it manually:
711 bool const b = nonum_[row];
712 nonum_[row] = nonum_[row + 1];
714 swap(label_[row], label_[row + 1]);
715 InsetMathGrid::swapRow(row);
719 void InsetMathHull::delRow(row_type row)
721 if (nrows() <= 1 || !rowChangeOK())
723 if (row + 1 == nrows() && type_ == hullMultline) {
724 bool const b = nonum_[row - 1];
725 nonum_[row - 1] = nonum_[row];
727 swap(label_[row - 1], label_[row]);
728 InsetMathGrid::delRow(row);
731 InsetMathGrid::delRow(row);
732 // The last dummy row has no number info nor a label.
733 // Test nrows() + 1 because we have already erased the row.
734 if (row == nrows() + 1)
736 nonum_.erase(nonum_.begin() + row);
738 label_.erase(label_.begin() + row);
742 void InsetMathHull::addCol(col_type col)
746 InsetMathGrid::addCol(col);
750 void InsetMathHull::delCol(col_type col)
752 if (ncols() <= 1 || !colChangeOK())
754 InsetMathGrid::delCol(col);
758 docstring InsetMathHull::nicelabel(row_type row) const
763 return from_ascii("(#)");
764 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
768 void InsetMathHull::glueall()
771 for (idx_type i = 0; i < nargs(); ++i)
773 *this = InsetMathHull(hullSimple);
779 void InsetMathHull::splitTo2Cols()
781 LASSERT(ncols() == 1, /**/);
782 InsetMathGrid::addCol(1);
783 for (row_type row = 0; row < nrows(); ++row) {
784 idx_type const i = 2 * row;
785 pos_type pos = firstRelOp(cell(i));
786 cell(i + 1) = MathData(cell(i).begin() + pos, cell(i).end());
787 cell(i).erase(pos, cell(i).size());
792 void InsetMathHull::splitTo3Cols()
794 LASSERT(ncols() < 3, /**/);
797 InsetMathGrid::addCol(2);
798 for (row_type row = 0; row < nrows(); ++row) {
799 idx_type const i = 3 * row + 1;
800 if (cell(i).size()) {
801 cell(i + 1) = MathData(cell(i).begin() + 1, cell(i).end());
802 cell(i).erase(1, cell(i).size());
808 void InsetMathHull::changeCols(col_type cols)
812 else if (ncols() < cols) {
818 while (ncols() < cols)
819 InsetMathGrid::addCol(ncols());
825 for (row_type row = 0; row < nrows(); ++row) {
826 idx_type const i = row * ncols();
827 for (col_type col = cols; col < ncols(); ++col) {
828 cell(i + cols - 1).append(cell(i + col));
832 while (ncols() > cols) {
833 InsetMathGrid::delCol(ncols() - 1);
838 HullType InsetMathHull::getType() const
844 void InsetMathHull::setType(HullType type)
851 void InsetMathHull::mutate(HullType newtype)
853 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
855 // we try to move along the chain
856 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
858 // +-------------------------------------+
859 // we use eqnarray as intermediate type for mutations that are not
860 // directly supported because it handles labels and numbering for
863 if (newtype == type_) {
867 else if (newtype < hullNone) {
872 else if (type_ == hullNone) {
878 else if (type_ == hullSimple) {
879 if (newtype == hullNone) {
883 setType(hullEquation);
889 else if (type_ == hullEquation) {
890 if (newtype < type_) {
894 } else if (newtype == hullEqnArray) {
895 // split it "nicely" on the first relop
897 setType(hullEqnArray);
898 } else if (newtype == hullMultline || newtype == hullGather) {
908 else if (type_ == hullEqnArray) {
909 if (newtype < type_) {
910 // set correct (no)numbering
912 for (row_type row = 0; row < nrows(); ++row) {
919 // set first non-empty label
920 for (row_type row = 0; row < nrows(); ++row) {
922 label_[0] = label_[row];
929 } else { // align & Co.
936 else if (type_ == hullAlign || type_ == hullAlignAt ||
937 type_ == hullXAlignAt || type_ == hullFlAlign) {
938 if (newtype < hullAlign) {
940 setType(hullEqnArray);
942 } else if (newtype == hullGather || newtype == hullMultline) {
945 } else if (newtype == hullXXAlignAt) {
946 for (row_type row = 0; row < nrows(); ++row)
947 numbered(row, false);
954 else if (type_ == hullXXAlignAt) {
955 for (row_type row = 0; row < nrows(); ++row)
956 numbered(row, false);
957 if (newtype < hullAlign) {
959 setType(hullEqnArray);
961 } else if (newtype == hullGather || newtype == hullMultline) {
969 else if (type_ == hullMultline || type_ == hullGather) {
970 if (newtype == hullGather || newtype == hullMultline)
972 else if (newtype == hullAlign || newtype == hullFlAlign ||
973 newtype == hullAlignAt || newtype == hullXAlignAt) {
976 } else if (newtype == hullXXAlignAt) {
978 for (row_type row = 0; row < nrows(); ++row)
979 numbered(row, false);
983 setType(hullEqnArray);
989 lyxerr << "mutation from '" << to_utf8(hullName(type_))
990 << "' to '" << to_utf8(hullName(newtype))
991 << "' not implemented" << endl;
996 docstring InsetMathHull::eolString(row_type row, bool emptyline, bool fragile) const
999 if (numberedType()) {
1000 if (label_[row] && !nonum_[row])
1001 res += "\\label{" + label_[row]->getParam("name") + '}';
1002 if (nonum_[row] && (type_ != hullMultline))
1003 res += "\\nonumber ";
1005 return res + InsetMathGrid::eolString(row, emptyline, fragile);
1009 void InsetMathHull::write(WriteStream & os) const
1012 InsetMathGrid::write(os);
1017 void InsetMathHull::normalize(NormalStream & os) const
1019 os << "[formula " << hullName(type_) << ' ';
1020 InsetMathGrid::normalize(os);
1025 void InsetMathHull::mathmlize(MathStream & os) const
1027 InsetMathGrid::mathmlize(os);
1031 void InsetMathHull::infoize(odocstream & os) const
1033 os << "Type: " << hullName(type_);
1037 void InsetMathHull::check() const
1039 LASSERT(nonum_.size() == nrows(), /**/);
1040 LASSERT(label_.size() == nrows(), /**/);
1044 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1048 idocstringstream iss(func.argument());
1049 iss >> dlang >> extra;
1051 extra = from_ascii("noextra");
1052 string const lang = to_ascii(dlang);
1054 // FIXME: temporarily disabled
1055 //if (cur.selection()) {
1058 // lyxerr << "use selection: " << ar << endl;
1059 // insert(pipeThroughExtern(lang, extra, ar));
1064 eq.push_back(MathAtom(new InsetMathChar('=')));
1066 // go to first item in line
1067 cur.idx() -= cur.idx() % ncols();
1070 if (getType() == hullSimple) {
1071 size_type pos = cur.cell().find_last(eq);
1073 if (cur.inMathed() && cur.selection()) {
1074 asArray(grabAndEraseSelection(cur), ar);
1075 } else if (pos == cur.cell().size()) {
1077 lyxerr << "use whole cell: " << ar << endl;
1079 ar = MathData(cur.cell().begin() + pos + 1, cur.cell().end());
1080 lyxerr << "use partial cell form pos: " << pos << endl;
1082 cur.cell().append(eq);
1083 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1084 cur.pos() = cur.lastpos();
1088 if (getType() == hullEquation) {
1089 lyxerr << "use equation inset" << endl;
1090 mutate(hullEqnArray);
1091 MathData & ar = cur.cell();
1092 lyxerr << "use cell: " << ar << endl;
1096 cur.cell() = pipeThroughExtern(lang, extra, ar);
1097 // move to end of line
1098 cur.pos() = cur.lastpos();
1103 lyxerr << "use eqnarray" << endl;
1104 cur.idx() += 2 - cur.idx() % ncols();
1106 MathData ar = cur.cell();
1107 lyxerr << "use cell: " << ar << endl;
1108 // FIXME: temporarily disabled
1114 cur.cell() = pipeThroughExtern(lang, extra, ar);
1115 cur.pos() = cur.lastpos();
1120 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1122 //lyxerr << "action: " << cmd.action << endl;
1123 switch (cmd.action) {
1125 case LFUN_FINISHED_BACKWARD:
1126 case LFUN_FINISHED_FORWARD:
1127 case LFUN_FINISHED_RIGHT:
1128 case LFUN_FINISHED_LEFT:
1129 //lyxerr << "action: " << cmd.action << endl;
1130 InsetMathGrid::doDispatch(cur, cmd);
1134 case LFUN_BREAK_PARAGRAPH:
1135 // just swallow this
1138 case LFUN_NEWLINE_INSERT:
1139 // some magic for the common case
1140 if (type_ == hullSimple || type_ == hullEquation) {
1141 cur.recordUndoInset();
1143 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1144 mutate(align ? hullAlign : hullEqnArray);
1145 cur.idx() = nrows() * ncols() - 1;
1146 cur.pos() = cur.lastpos();
1148 InsetMathGrid::doDispatch(cur, cmd);
1151 case LFUN_MATH_NUMBER_TOGGLE: {
1152 //lyxerr << "toggling all numbers" << endl;
1153 cur.recordUndoInset();
1154 bool old = numberedType();
1155 if (type_ == hullMultline)
1156 numbered(nrows() - 1, !old);
1158 for (row_type row = 0; row < nrows(); ++row)
1159 numbered(row, !old);
1161 cur.message(old ? _("No number") : _("Number"));
1165 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1166 cur.recordUndoInset();
1167 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1168 bool old = numbered(r);
1169 cur.message(old ? _("No number") : _("Number"));
1174 case LFUN_LABEL_INSERT: {
1175 cur.recordUndoInset();
1176 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1177 docstring old_label = label(r);
1178 docstring const default_label = from_ascii(
1179 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1180 if (old_label.empty())
1181 old_label = default_label;
1183 InsetCommandParams p(LABEL_CODE);
1184 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1185 string const data = InsetCommand::params2string("label", p);
1187 if (cmd.argument().empty())
1188 cur.bv().showDialog("label", data);
1190 FuncRequest fr(LFUN_INSET_INSERT, data);
1196 case LFUN_WORD_DELETE_FORWARD:
1197 case LFUN_CHAR_DELETE_FORWARD:
1198 if (col(cur.idx()) + 1 == ncols()
1199 && cur.pos() == cur.lastpos()) {
1200 if (!label(row(cur.idx())).empty()) {
1201 cur.recordUndoInset();
1202 label(row(cur.idx()), docstring());
1203 } else if (numbered(row(cur.idx()))) {
1204 cur.recordUndoInset();
1205 numbered(row(cur.idx()), false);
1207 InsetMathGrid::doDispatch(cur, cmd);
1211 InsetMathGrid::doDispatch(cur, cmd);
1216 case LFUN_INSET_INSERT: {
1217 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1218 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1219 string const name = cmd.getArg(0);
1220 if (name == "label") {
1221 InsetCommandParams p(LABEL_CODE);
1222 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1223 docstring str = p["name"];
1224 cur.recordUndoInset();
1225 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1229 docstring old = label(r);
1232 // The label will take care of the reference update.
1236 // Newly created inset so initialize it.
1237 label_[r]->initView();
1242 InsetMathGrid::doDispatch(cur, cmd);
1246 case LFUN_MATH_EXTERN:
1247 cur.recordUndoInset();
1251 case LFUN_MATH_MUTATE: {
1252 cur.recordUndoInset();
1253 row_type row = cur.row();
1254 col_type col = cur.col();
1255 mutate(hullType(cmd.argument()));
1256 cur.idx() = row * ncols() + col;
1257 if (cur.idx() > cur.lastidx()) {
1258 cur.idx() = cur.lastidx();
1259 cur.pos() = cur.lastpos();
1261 if (cur.pos() > cur.lastpos())
1262 cur.pos() = cur.lastpos();
1264 // FIXME: find some more clever handling of the selection,
1265 // i.e. preserve it.
1266 cur.clearSelection();
1267 //cur.dispatched(FINISHED);
1271 case LFUN_MATH_DISPLAY: {
1272 cur.recordUndoInset();
1273 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1275 cur.pos() = cur.lastpos();
1276 //cur.dispatched(FINISHED);
1281 InsetMathGrid::doDispatch(cur, cmd);
1287 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1288 FuncStatus & status) const
1290 switch (cmd.action) {
1291 case LFUN_FINISHED_BACKWARD:
1292 case LFUN_FINISHED_FORWARD:
1293 case LFUN_FINISHED_RIGHT:
1294 case LFUN_FINISHED_LEFT:
1297 case LFUN_NEWLINE_INSERT:
1298 case LFUN_MATH_EXTERN:
1299 case LFUN_MATH_MUTATE:
1300 case LFUN_MATH_DISPLAY:
1302 status.setEnabled(true);
1304 case LFUN_MATH_NUMBER_TOGGLE:
1305 // FIXME: what is the right test, this or the one of
1307 status.setEnabled(display());
1308 status.setOnOff(numberedType());
1310 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1311 // FIXME: what is the right test, this or the one of
1313 bool const enable = (type_ == hullMultline) ?
1314 (nrows() - 1 == cur.row()) : display();
1315 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1316 status.setEnabled(enable);
1317 status.setOnOff(numbered(r));
1320 case LFUN_LABEL_INSERT:
1321 status.setEnabled(type_ != hullSimple);
1323 case LFUN_INSET_INSERT:
1324 if (cmd.getArg(0) == "label") {
1325 status.setEnabled(type_ != hullSimple);
1328 return InsetMathGrid::getStatus(cur, cmd, status);
1329 case LFUN_TABULAR_FEATURE: {
1330 istringstream is(to_utf8(cmd.argument()));
1334 && (s == "append-row"
1335 || s == "delete-row"
1336 || s == "copy-row")) {
1337 status.message(bformat(
1338 from_utf8(N_("Can't change number of rows in '%1$s'")),
1340 status.setEnabled(false);
1344 && (s == "append-column"
1345 || s == "delete-column"
1346 || s == "copy-column")) {
1347 status.message(bformat(
1348 from_utf8(N_("Can't change number of columns in '%1$s'")),
1350 status.setEnabled(false);
1353 if ((type_ == hullSimple
1354 || type_ == hullEquation
1355 || type_ == hullNone) &&
1356 (s == "add-hline-above" || s == "add-hline-below")) {
1357 status.message(bformat(
1358 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1360 status.setEnabled(false);
1363 if (s == "add-vline-left" || s == "add-vline-right") {
1364 status.message(bformat(
1365 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1367 status.setEnabled(false);
1370 if (s == "valign-top" || s == "valign-middle"
1371 || s == "valign-bottom" || s == "align-left"
1372 || s == "align-center" || s == "align-right") {
1373 status.setEnabled(false);
1376 return InsetMathGrid::getStatus(cur, cmd, status);
1379 return InsetMathGrid::getStatus(cur, cmd, status);
1382 // This cannot really happen, but inserted to shut-up gcc
1383 return InsetMathGrid::getStatus(cur, cmd, status);
1387 /////////////////////////////////////////////////////////////////////
1391 // simply scrap this function if you want
1392 void InsetMathHull::mutateToText()
1395 // translate to latex
1397 latex(os, false, false);
1398 string str = os.str();
1401 Text * lt = view_->cursor().innerText();
1402 string::const_iterator cit = str.begin();
1403 string::const_iterator end = str.end();
1404 for (; cit != end; ++cit)
1405 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1408 //dispatch(LFUN_ESCAPE);
1413 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1414 docstring const & font)
1416 // this whole function is a hack and won't work for incremental font
1419 if (cur.inset().asInsetMath()->name() == font)
1420 cur.handleFont(to_utf8(font));
1422 cur.handleNest(createInsetMath(font));
1428 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1433 font.fromString(to_utf8(arg), b);
1434 if (font.fontInfo().color() != Color_inherit) {
1435 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
1436 cur.handleNest(at, 0);
1441 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1444 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1445 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1446 enter_front ? idxFirst(cur) : idxLast(cur);
1447 // The inset formula dimension is not necessarily the same as the
1448 // one of the instant preview image, so we have to indicate to the
1449 // BufferView that a metrics update is needed.
1450 cur.updateFlags(Update::Force);
1454 docstring InsetMathHull::editMessage() const
1456 return _("Math editor mode");
1460 void InsetMathHull::revealCodes(Cursor & cur) const
1462 if (!cur.inMathed())
1464 odocstringstream os;
1466 cur.message(os.str());
1468 // write something to the minibuffer
1469 // translate to latex
1473 string str = os.str();
1475 string::size_type pos = 0;
1477 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1480 else if (*it == '\0') {
1482 pos = it - str.begin();
1488 res = res.substr(pos - 30);
1489 if (res.size() > 60)
1490 res = res.substr(0, 60);
1496 InsetCode InsetMathHull::lyxCode() const
1502 /////////////////////////////////////////////////////////////////////
1506 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1509 // FIXME: completely broken
1510 static InsetMathHull * lastformula = 0;
1511 static CursorBase current = DocIterator(ibegin(nucleus()));
1513 static string laststr;
1515 if (lastformula != this || laststr != str) {
1516 //lyxerr << "reset lastformula to " << this << endl;
1519 current = ibegin(nucleus());
1521 mathed_parse_cell(ar, str);
1525 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1527 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1528 CursorSlice & top = it.back();
1529 MathData const & a = top.asInsetMath()->cell(top.idx_);
1530 if (a.matchpart(ar, top.pos_)) {
1531 bv->cursor().setSelection(it, ar.size());
1533 top.pos_ += ar.size();
1539 //lyxerr << "not found!" << endl;
1546 void InsetMathHull::write(ostream & os) const
1548 odocstringstream oss;
1549 WriteStream wi(oss, false, false, false);
1552 os << to_utf8(oss.str());
1556 void InsetMathHull::read(Lexer & lex)
1559 mathed_parse_normal(at, lex);
1560 operator=(*at->asHullInset());
1564 int InsetMathHull::plaintext(odocstream & os, OutputParams const & runparams) const
1566 if (0 && display()) {
1570 TextPainter tpain(dim.width(), dim.height());
1571 drawT(tpain, 0, dim.ascent());
1573 // reset metrics cache to "real" values
1575 return tpain.textheight();
1577 odocstringstream oss;
1578 WriteStream wi(oss, false, true, false, runparams.encoding);
1581 docstring const str = oss.str();
1588 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1593 if (getType() == hullSimple)
1594 name = from_ascii("inlineequation");
1596 name = from_ascii("informalequation");
1598 docstring bname = name;
1599 if (!label(0).empty())
1600 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1602 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1604 odocstringstream ls;
1605 if (runparams.flavor == OutputParams::XML) {
1606 ms << MTag("alt role='tex' ");
1607 // Workaround for db2latex: db2latex always includes equations with
1608 // \ensuremath{} or \begin{display}\end{display}
1609 // so we strip LyX' math environment
1610 WriteStream wi(ls, false, false, false, runparams.encoding);
1611 InsetMathGrid::write(wi);
1612 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1617 InsetMathGrid::mathmlize(ms);
1620 ms << MTag("alt role='tex'");
1621 res = latex(ls, runparams);
1622 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1626 ms << from_ascii("<graphic fileref=\"eqn/");
1627 if (!label(0).empty())
1628 ms << sgml::cleanID(buffer(), runparams, label(0));
1630 ms << sgml::uniqueID(from_ascii("anon"));
1632 if (runparams.flavor == OutputParams::XML)
1633 ms << from_ascii("\"/>");
1635 ms << from_ascii("\">");
1637 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1639 return ms.line() + res;
1643 void InsetMathHull::textString(odocstream & os) const
1645 plaintext(os, OutputParams(0));
1649 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1651 return from_ascii("context-math");