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 "InsetMathHull.h"
15 #include "InsetMathChar.h"
16 #include "InsetMathColor.h"
17 #include "MathExtern.h"
18 #include "MathFactory.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
31 #include "MacroTable.h"
33 #include "TextPainter.h"
34 #include "TocBackend.h"
36 #include "insets/InsetLabel.h"
37 #include "insets/InsetRef.h"
38 #include "insets/RenderPreview.h"
40 #include "graphics/PreviewImage.h"
42 #include "frontends/Painter.h"
44 #include "support/lassert.h"
45 #include "support/debug.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
52 using namespace lyx::support;
56 using cap::grabAndEraseSelection;
60 int getCols(HullType type)
77 // returns position of first relation operator in the array
78 // used for "intelligent splitting"
79 size_t firstRelOp(MathData const & ar)
81 for (MathData::const_iterator it = ar.begin(); it != ar.end(); ++it)
83 return it - ar.begin();
88 char const * star(bool numbered)
90 return numbered ? "" : "*";
94 } // end anon namespace
97 HullType hullType(docstring const & s)
99 if (s == "none") return hullNone;
100 if (s == "simple") return hullSimple;
101 if (s == "equation") return hullEquation;
102 if (s == "eqnarray") return hullEqnArray;
103 if (s == "align") return hullAlign;
104 if (s == "alignat") return hullAlignAt;
105 if (s == "xalignat") return hullXAlignAt;
106 if (s == "xxalignat") return hullXXAlignAt;
107 if (s == "multline") return hullMultline;
108 if (s == "gather") return hullGather;
109 if (s == "flalign") return hullFlAlign;
110 if (s == "regexp") return hullRegexp;
111 lyxerr << "unknown hull type '" << to_utf8(s) << "'" << endl;
116 docstring hullName(HullType type)
119 case hullNone: return from_ascii("none");
120 case hullSimple: return from_ascii("simple");
121 case hullEquation: return from_ascii("equation");
122 case hullEqnArray: return from_ascii("eqnarray");
123 case hullAlign: return from_ascii("align");
124 case hullAlignAt: return from_ascii("alignat");
125 case hullXAlignAt: return from_ascii("xalignat");
126 case hullXXAlignAt: return from_ascii("xxalignat");
127 case hullMultline: return from_ascii("multline");
128 case hullGather: return from_ascii("gather");
129 case hullFlAlign: return from_ascii("flalign");
130 case hullRegexp: return from_ascii("regexp");
132 lyxerr << "unknown hull type '" << type << "'" << endl;
133 return from_ascii("none");
137 static InsetLabel * dummy_pointer = 0;
139 InsetMathHull::InsetMathHull(Buffer * buf)
140 : InsetMathGrid(buf, 1, 1), type_(hullNone), nonum_(1, false),
141 label_(1, dummy_pointer), preview_(new RenderPreview(this))
143 //lyxerr << "sizeof InsetMath: " << sizeof(InsetMath) << endl;
144 //lyxerr << "sizeof MetricsInfo: " << sizeof(MetricsInfo) << endl;
145 //lyxerr << "sizeof InsetMathChar: " << sizeof(InsetMathChar) << endl;
146 //lyxerr << "sizeof FontInfo: " << sizeof(FontInfo) << endl;
153 InsetMathHull::InsetMathHull(Buffer * buf, HullType type)
154 : InsetMathGrid(buf, getCols(type), 1), type_(type), nonum_(1, false),
155 label_(1, dummy_pointer), preview_(new RenderPreview(this))
163 InsetMathHull::InsetMathHull(InsetMathHull const & other) : InsetMathGrid(other)
169 InsetMathHull::~InsetMathHull()
171 for (size_t i = 0; i < label_.size(); ++i)
176 Inset * InsetMathHull::clone() const
178 return new InsetMathHull(*this);
182 InsetMathHull & InsetMathHull::operator=(InsetMathHull const & other)
186 InsetMathGrid::operator=(other);
188 nonum_ = other.nonum_;
189 buffer_ = other.buffer_;
190 for (size_t i = 0; i < label_.size(); ++i)
192 label_ = other.label_;
193 for (size_t i = 0; i != label_.size(); ++i) {
195 label_[i] = new InsetLabel(*label_[i]);
197 preview_.reset(new RenderPreview(*other.preview_, this));
203 void InsetMathHull::setBuffer(Buffer & buffer)
205 InsetMathGrid::setBuffer(buffer);
207 for (size_t i = 0; i != label_.size(); ++i) {
209 label_[i]->setBuffer(buffer);
214 void InsetMathHull::updateLabels(ParIterator const & it, bool out)
217 //FIXME: buffer_ should be set at creation for this inset! Problem is
218 // This inset is created at too many places (see Parser::parse1() in
222 for (size_t i = 0; i != label_.size(); ++i) {
224 label_[i]->updateLabels(it, out);
229 void InsetMathHull::addToToc(DocIterator const & pit)
232 //FIXME: buffer_ should be set at creation for this inset! Problem is
233 // This inset is created at too many places (see Parser::parse1() in
238 Toc & toc = buffer().tocBackend().toc("equation");
240 for (row_type row = 0; row != nrows(); ++row) {
244 label_[row]->addToToc(pit);
245 toc.push_back(TocItem(pit, 0, nicelabel(row)));
250 Inset * InsetMathHull::editXY(Cursor & cur, int x, int y)
256 return InsetMathNest::editXY(cur, x, y);
260 InsetMath::mode_type InsetMathHull::currentMode() const
262 if (type_ == hullNone)
263 return UNDECIDED_MODE;
264 // definitely math mode ...
269 bool InsetMathHull::idxFirst(Cursor & cur) const
277 bool InsetMathHull::idxLast(Cursor & cur) const
279 cur.idx() = nargs() - 1;
280 cur.pos() = cur.lastpos();
285 char InsetMathHull::defaultColAlign(col_type col)
287 if (type_ == hullEqnArray)
289 if (type_ == hullGather)
291 if (type_ >= hullAlign)
292 return "rl"[col & 1];
297 int InsetMathHull::defaultColSpace(col_type col)
299 if (type_ == hullAlign || type_ == hullAlignAt)
301 if (type_ == hullXAlignAt)
302 return (col & 1) ? 20 : 0;
303 if (type_ == hullXXAlignAt || type_ == hullFlAlign)
304 return (col & 1) ? 40 : 0;
309 docstring InsetMathHull::standardFont() const
311 return from_ascii(type_ == hullNone ? "lyxnochange" : "mathnormal");
315 bool InsetMathHull::previewState(BufferView * bv) const
317 if (!editing(bv) && RenderPreview::status() == LyXRC::PREVIEW_ON) {
318 graphics::PreviewImage const * pimage =
319 preview_->getPreviewImage(bv->buffer());
320 return pimage && pimage->image();
326 void InsetMathHull::metrics(MetricsInfo & mi, Dimension & dim) const
328 if (previewState(mi.base.bv)) {
329 preview_->metrics(mi, dim);
330 // insert a one pixel gap in front of the formula
333 dim.des += displayMargin();
334 // Cache the inset dimension.
335 setDimCache(mi, dim);
339 FontSetChanger dummy1(mi.base, standardFont());
340 StyleChanger dummy2(mi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
342 // let the cells adjust themselves
343 InsetMathGrid::metrics(mi, dim);
346 dim.asc += displayMargin();
347 dim.des += displayMargin();
350 if (numberedType()) {
351 FontSetChanger dummy(mi.base, from_ascii("mathbf"));
353 for (row_type row = 0; row < nrows(); ++row)
354 l = max(l, mathed_string_width(mi.base.font, nicelabel(row)));
360 // make it at least as high as the current font
363 math_font_max_dim(mi.base.font, asc, des);
364 dim.asc = max(dim.asc, asc);
365 dim.des = max(dim.des, des);
366 // Cache the inset dimension.
367 // FIXME: This will overwrite InsetMathGrid dimension, is that OK?
368 setDimCache(mi, dim);
372 void InsetMathHull::drawBackground(PainterInfo & pi, int x, int y) const
374 Dimension const dim = dimension(*pi.base.bv);
375 pi.pain.fillRectangle(x + 1, y - dim.asc + 1, dim.wid - 2,
376 dim.asc + dim.des - 1, pi.backgroundColor(this));
380 void InsetMathHull::draw(PainterInfo & pi, int x, int y) const
382 use_preview_ = previewState(pi.base.bv);
385 // one pixel gap in front
386 preview_->draw(pi, x + 1, y);
387 setPosCache(pi, x, y);
391 FontSetChanger dummy1(pi.base, standardFont());
392 StyleChanger dummy2(pi.base, display() ? LM_ST_DISPLAY : LM_ST_TEXT);
393 InsetMathGrid::draw(pi, x + 1, y);
395 if (numberedType()) {
396 int const xx = x + colinfo_.back().offset_ + colinfo_.back().width_ + 20;
397 for (row_type row = 0; row < nrows(); ++row) {
398 int const yy = y + rowinfo_[row].offset_;
399 FontSetChanger dummy(pi.base, from_ascii("mathrm"));
400 docstring const nl = nicelabel(row);
404 setPosCache(pi, x, y);
408 void InsetMathHull::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
411 InsetMathGrid::metricsT(mi, dim);
414 WriteStream wi(os, false, true, WriteStream::wsDefault);
416 dim.wid = os.str().size();
423 void InsetMathHull::drawT(TextPainter & pain, int x, int y) const
426 InsetMathGrid::drawT(pain, x, y);
429 WriteStream wi(os, false, true, WriteStream::wsDefault);
431 pain.draw(x, y, os.str().c_str());
436 static docstring latexString(InsetMathHull const & inset)
439 // This has to be static, because a preview snippet or a math
440 // macro containing math in text mode (such as $\text{$\phi$}$ or
441 // \newcommand{\xxx}{\text{$\phi$}}) gets processed twice. The
442 // first time as a whole, and the second time only the inner math.
443 // In this last case inset.buffer() would be invalid.
444 static Encoding const * encoding = 0;
445 if (inset.isBufferValid())
446 encoding = &(inset.buffer().params().encoding());
447 WriteStream wi(ls, false, true, WriteStream::wsPreview, encoding);
453 void InsetMathHull::initUnicodeMath() const
455 // Trigger classification of the unicode symbols in this inset
456 docstring const dummy = latexString(*this);
460 void InsetMathHull::addPreview(DocIterator const & inset_pos,
461 graphics::PreviewLoader & /*ploader*/) const
463 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
464 preparePreview(inset_pos);
469 void InsetMathHull::preparePreview(DocIterator const & pos) const
471 Buffer const * buffer = pos.buffer();
473 // collect macros at this position
475 buffer->listMacroNames(macros);
476 MacroNameSet::iterator it = macros.begin();
477 MacroNameSet::iterator end = macros.end();
478 odocstringstream macro_preamble;
479 for (; it != end; ++it) {
480 MacroData const * data = buffer->getMacro(*it, pos, true);
482 data->write(macro_preamble, true);
483 macro_preamble << endl;
487 docstring const snippet = macro_preamble.str() + latexString(*this);
488 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
489 preview_->addPreview(snippet, *buffer);
493 void InsetMathHull::reloadPreview(DocIterator const & pos) const
496 preview_->startLoading(*pos.buffer());
500 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
502 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
504 cur.updateFlags(Update::Force);
510 docstring InsetMathHull::label(row_type row) const
512 LASSERT(row < nrows(), /**/);
513 if (InsetLabel * il = label_[row])
514 return il->screenLabel();
519 void InsetMathHull::label(row_type row, docstring const & label)
521 //lyxerr << "setting label '" << label << "' for row " << row << endl;
525 label_[row] = dummy_pointer;
526 // We need an update of the Buffer reference cache.
527 // This is achieved by updateLabels().
529 buffer().updateLabels();
532 label_[row]->updateCommand(label);
534 label_[row]->setParam("name", label);
538 InsetCommandParams p(LABEL_CODE);
540 label_[row] = new InsetLabel(buffer_, p);
542 label_[row]->setBuffer(buffer());
546 void InsetMathHull::numbered(row_type row, bool num)
549 if (nonum_[row] && label_[row]) {
553 // The buffer is set at the end of readInset.
554 // When parsing the inset, buffer_ is 0.
557 // We need an update of the Buffer reference cache.
558 // This is achieved by updateLabels().
559 buffer().updateLabels();
564 bool InsetMathHull::numbered(row_type row) const
570 bool InsetMathHull::ams() const
572 return type_ == hullAlign
573 || type_ == hullFlAlign
574 || type_ == hullMultline
575 || type_ == hullGather
576 || type_ == hullAlignAt
577 || type_ == hullXAlignAt
578 || type_ == hullXXAlignAt;
582 Inset::DisplayType InsetMathHull::display() const
584 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
589 bool InsetMathHull::numberedType() const
591 if (type_ == hullNone)
593 if (type_ == hullSimple)
595 if (type_ == hullXXAlignAt)
597 if (type_ == hullRegexp)
599 for (row_type row = 0; row < nrows(); ++row)
606 void InsetMathHull::validate(LaTeXFeatures & features) const
609 features.require("amsmath");
611 // Validation is necessary only if not using AMS math.
612 // To be safe, we will always run mathedvalidate.
613 //if (features.amsstyle)
616 //features.binom = true;
618 InsetMathGrid::validate(features);
622 void InsetMathHull::header_write(WriteStream & os) const
624 bool n = numberedType();
638 os << "\\begin{equation" << star(n) << "}\n";
648 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
653 os << "\\begin{" << hullName(type_) << star(n) << '}'
654 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
658 os << "\\begin{" << hullName(type_) << '}'
659 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
667 os << "\\begin{unknown" << star(n) << '}';
673 void InsetMathHull::footer_write(WriteStream & os) const
675 bool n = numberedType();
688 os << "\\end{equation" << star(n) << "}\n";
700 os << "\\end{" << hullName(type_) << star(n) << "}\n";
704 os << "\\end{" << hullName(type_) << "}\n";
712 os << "\\end{unknown" << star(n) << '}';
718 bool InsetMathHull::rowChangeOK() const
721 type_ == hullEqnArray || type_ == hullAlign ||
722 type_ == hullFlAlign || type_ == hullAlignAt ||
723 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
724 type_ == hullGather || type_ == hullMultline;
728 bool InsetMathHull::colChangeOK() const
731 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
732 type_ == hullXAlignAt || type_ == hullXXAlignAt;
736 void InsetMathHull::addRow(row_type row)
741 bool numbered = numberedType();
743 if (type_ == hullMultline) {
744 if (row + 1 == nrows()) {
751 nonum_.insert(nonum_.begin() + row + 1, !numbered);
752 label_.insert(label_.begin() + row + 1, dummy_pointer);
755 InsetMathGrid::addRow(row);
759 void InsetMathHull::swapRow(row_type row)
763 if (row + 1 == nrows())
765 // gcc implements the standard std::vector<bool> which is *not* a container:
766 // http://www.gotw.ca/publications/N1185.pdf
767 // As a results, it doesn't like this:
768 // swap(nonum_[row], nonum_[row + 1]);
769 // so we do it manually:
770 bool const b = nonum_[row];
771 nonum_[row] = nonum_[row + 1];
773 swap(label_[row], label_[row + 1]);
774 InsetMathGrid::swapRow(row);
778 void InsetMathHull::delRow(row_type row)
780 if (nrows() <= 1 || !rowChangeOK())
782 if (row + 1 == nrows() && type_ == hullMultline) {
783 bool const b = nonum_[row - 1];
784 nonum_[row - 1] = nonum_[row];
786 swap(label_[row - 1], label_[row]);
787 InsetMathGrid::delRow(row);
790 InsetMathGrid::delRow(row);
791 // The last dummy row has no number info nor a label.
792 // Test nrows() + 1 because we have already erased the row.
793 if (row == nrows() + 1)
795 nonum_.erase(nonum_.begin() + row);
797 label_.erase(label_.begin() + row);
801 void InsetMathHull::addCol(col_type col)
805 InsetMathGrid::addCol(col);
809 void InsetMathHull::delCol(col_type col)
811 if (ncols() <= 1 || !colChangeOK())
813 InsetMathGrid::delCol(col);
817 docstring InsetMathHull::nicelabel(row_type row) const
822 return from_ascii("(#)");
823 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
827 void InsetMathHull::glueall()
830 for (idx_type i = 0; i < nargs(); ++i)
832 *this = InsetMathHull(buffer_, hullSimple);
838 void InsetMathHull::splitTo2Cols()
840 LASSERT(ncols() == 1, /**/);
841 InsetMathGrid::addCol(1);
842 for (row_type row = 0; row < nrows(); ++row) {
843 idx_type const i = 2 * row;
844 pos_type pos = firstRelOp(cell(i));
845 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
846 cell(i).erase(pos, cell(i).size());
851 void InsetMathHull::splitTo3Cols()
853 LASSERT(ncols() < 3, /**/);
856 InsetMathGrid::addCol(2);
857 for (row_type row = 0; row < nrows(); ++row) {
858 idx_type const i = 3 * row + 1;
859 if (cell(i).size()) {
860 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
861 cell(i).erase(1, cell(i).size());
867 void InsetMathHull::changeCols(col_type cols)
871 else if (ncols() < cols) {
877 while (ncols() < cols)
878 InsetMathGrid::addCol(ncols());
884 for (row_type row = 0; row < nrows(); ++row) {
885 idx_type const i = row * ncols();
886 for (col_type col = cols; col < ncols(); ++col) {
887 cell(i + cols - 1).append(cell(i + col));
891 while (ncols() > cols) {
892 InsetMathGrid::delCol(ncols() - 1);
897 HullType InsetMathHull::getType() const
903 void InsetMathHull::setType(HullType type)
910 void InsetMathHull::mutate(HullType newtype)
912 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
914 // we try to move along the chain
915 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
917 // +-------------------------------------+
918 // we use eqnarray as intermediate type for mutations that are not
919 // directly supported because it handles labels and numbering for
922 if (newtype == type_) {
926 else if (newtype < hullNone) {
931 else if (type_ == hullNone) {
937 else if (type_ == hullSimple) {
938 if (newtype == hullNone) {
942 setType(hullEquation);
948 else if (type_ == hullEquation) {
949 if (newtype < type_) {
953 } else if (newtype == hullEqnArray) {
954 // split it "nicely" on the first relop
956 setType(hullEqnArray);
957 } else if (newtype == hullMultline || newtype == hullGather) {
967 else if (type_ == hullEqnArray) {
968 if (newtype < type_) {
969 // set correct (no)numbering
971 for (row_type row = 0; row < nrows(); ++row) {
978 // set first non-empty label
979 for (row_type row = 0; row < nrows(); ++row) {
981 label_[0] = label_[row];
988 } else { // align & Co.
995 else if (type_ == hullAlign || type_ == hullAlignAt ||
996 type_ == hullXAlignAt || type_ == hullFlAlign) {
997 if (newtype < hullAlign) {
999 setType(hullEqnArray);
1001 } else if (newtype == hullGather || newtype == hullMultline) {
1004 } else if (newtype == hullXXAlignAt) {
1005 for (row_type row = 0; row < nrows(); ++row)
1006 numbered(row, false);
1013 else if (type_ == hullXXAlignAt) {
1014 for (row_type row = 0; row < nrows(); ++row)
1015 numbered(row, false);
1016 if (newtype < hullAlign) {
1018 setType(hullEqnArray);
1020 } else if (newtype == hullGather || newtype == hullMultline) {
1028 else if (type_ == hullMultline || type_ == hullGather) {
1029 if (newtype == hullGather || newtype == hullMultline)
1031 else if (newtype == hullAlign || newtype == hullFlAlign ||
1032 newtype == hullAlignAt || newtype == hullXAlignAt) {
1035 } else if (newtype == hullXXAlignAt) {
1037 for (row_type row = 0; row < nrows(); ++row)
1038 numbered(row, false);
1042 setType(hullEqnArray);
1048 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1049 << "' to '" << to_utf8(hullName(newtype))
1050 << "' not implemented" << endl;
1055 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1058 if (numberedType()) {
1059 if (label_[row] && !nonum_[row])
1060 res += "\\label{" + label_[row]->getParam("name") + '}';
1061 if (nonum_[row] && (type_ != hullMultline))
1062 res += "\\nonumber ";
1064 return res + InsetMathGrid::eolString(row, fragile);
1068 void InsetMathHull::write(WriteStream & os) const
1070 ModeSpecifier specifier(os, MATH_MODE);
1072 InsetMathGrid::write(os);
1077 void InsetMathHull::normalize(NormalStream & os) const
1079 os << "[formula " << hullName(type_) << ' ';
1080 InsetMathGrid::normalize(os);
1085 void InsetMathHull::mathmlize(MathStream & os) const
1087 InsetMathGrid::mathmlize(os);
1091 void InsetMathHull::infoize(odocstream & os) const
1093 os << "Type: " << hullName(type_);
1097 void InsetMathHull::check() const
1099 LASSERT(nonum_.size() == nrows(), /**/);
1100 LASSERT(label_.size() == nrows(), /**/);
1104 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1108 idocstringstream iss(func.argument());
1109 iss >> dlang >> extra;
1111 extra = from_ascii("noextra");
1112 string const lang = to_ascii(dlang);
1114 // FIXME: temporarily disabled
1115 //if (cur.selection()) {
1118 // lyxerr << "use selection: " << ar << endl;
1119 // insert(pipeThroughExtern(lang, extra, ar));
1124 eq.push_back(MathAtom(new InsetMathChar('=')));
1126 // go to first item in line
1127 cur.idx() -= cur.idx() % ncols();
1130 if (getType() == hullSimple) {
1131 size_type pos = cur.cell().find_last(eq);
1133 if (cur.inMathed() && cur.selection()) {
1134 asArray(grabAndEraseSelection(cur), ar);
1135 } else if (pos == cur.cell().size()) {
1137 lyxerr << "use whole cell: " << ar << endl;
1139 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1140 lyxerr << "use partial cell form pos: " << pos << endl;
1142 cur.cell().append(eq);
1143 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1144 cur.pos() = cur.lastpos();
1148 if (getType() == hullEquation) {
1149 lyxerr << "use equation inset" << endl;
1150 mutate(hullEqnArray);
1151 MathData & ar = cur.cell();
1152 lyxerr << "use cell: " << ar << endl;
1156 cur.cell() = pipeThroughExtern(lang, extra, ar);
1157 // move to end of line
1158 cur.pos() = cur.lastpos();
1163 lyxerr << "use eqnarray" << endl;
1164 cur.idx() += 2 - cur.idx() % ncols();
1166 MathData ar = cur.cell();
1167 lyxerr << "use cell: " << ar << endl;
1168 // FIXME: temporarily disabled
1174 cur.cell() = pipeThroughExtern(lang, extra, ar);
1175 cur.pos() = cur.lastpos();
1180 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1182 //lyxerr << "action: " << cmd.action << endl;
1183 switch (cmd.action) {
1185 case LFUN_FINISHED_BACKWARD:
1186 case LFUN_FINISHED_FORWARD:
1187 case LFUN_FINISHED_RIGHT:
1188 case LFUN_FINISHED_LEFT:
1189 //lyxerr << "action: " << cmd.action << endl;
1190 InsetMathGrid::doDispatch(cur, cmd);
1194 case LFUN_BREAK_PARAGRAPH:
1195 // just swallow this
1198 case LFUN_NEWLINE_INSERT:
1199 // some magic for the common case
1200 if (type_ == hullSimple || type_ == hullEquation) {
1201 cur.recordUndoInset();
1203 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1204 mutate(align ? hullAlign : hullEqnArray);
1205 cur.idx() = nrows() * ncols() - 1;
1206 cur.pos() = cur.lastpos();
1208 InsetMathGrid::doDispatch(cur, cmd);
1211 case LFUN_MATH_NUMBER_TOGGLE: {
1212 //lyxerr << "toggling all numbers" << endl;
1213 cur.recordUndoInset();
1214 bool old = numberedType();
1215 if (type_ == hullMultline)
1216 numbered(nrows() - 1, !old);
1218 for (row_type row = 0; row < nrows(); ++row)
1219 numbered(row, !old);
1221 cur.message(old ? _("No number") : _("Number"));
1225 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1226 cur.recordUndoInset();
1227 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1228 bool old = numbered(r);
1229 cur.message(old ? _("No number") : _("Number"));
1234 case LFUN_LABEL_INSERT: {
1235 cur.recordUndoInset();
1236 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1237 docstring old_label = label(r);
1238 docstring const default_label = from_ascii(
1239 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1240 if (old_label.empty())
1241 old_label = default_label;
1243 InsetCommandParams p(LABEL_CODE);
1244 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1245 string const data = InsetCommand::params2string("label", p);
1247 if (cmd.argument().empty())
1248 cur.bv().showDialog("label", data);
1250 FuncRequest fr(LFUN_INSET_INSERT, data);
1256 case LFUN_LABEL_COPY_AS_REF: {
1258 if (cmd.argument().empty() && &cur.inset() == this)
1259 // if there is no argument and we're inside math, we retrieve
1260 // the row number from the cursor position.
1261 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1263 // if there is an argument, find the corresponding label, else
1264 // check whether there is at least one label.
1265 for (row = 0; row != nrows(); ++row)
1266 if (!nonum_[row] && label_[row]
1267 && (cmd.argument().empty() || label(row) == cmd.argument()))
1274 InsetCommandParams p(REF_CODE, "ref");
1275 p["reference"] = label(row);
1276 cap::clearSelection();
1277 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1281 case LFUN_WORD_DELETE_FORWARD:
1282 case LFUN_CHAR_DELETE_FORWARD:
1283 if (col(cur.idx()) + 1 == ncols()
1284 && cur.pos() == cur.lastpos()
1285 && !cur.selection()) {
1286 if (!label(row(cur.idx())).empty()) {
1287 cur.recordUndoInset();
1288 label(row(cur.idx()), docstring());
1289 } else if (numbered(row(cur.idx()))) {
1290 cur.recordUndoInset();
1291 numbered(row(cur.idx()), false);
1293 InsetMathGrid::doDispatch(cur, cmd);
1297 InsetMathGrid::doDispatch(cur, cmd);
1302 case LFUN_INSET_INSERT: {
1303 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1304 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1305 string const name = cmd.getArg(0);
1306 if (name == "label") {
1307 InsetCommandParams p(LABEL_CODE);
1308 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1309 docstring str = p["name"];
1310 cur.recordUndoInset();
1311 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1315 docstring old = label(r);
1318 // The label will take care of the reference update.
1322 // Newly created inset so initialize it.
1323 label_[r]->initView();
1328 InsetMathGrid::doDispatch(cur, cmd);
1332 case LFUN_MATH_EXTERN:
1333 cur.recordUndoInset();
1337 case LFUN_MATH_MUTATE: {
1338 cur.recordUndoInset();
1339 row_type row = cur.row();
1340 col_type col = cur.col();
1341 mutate(hullType(cmd.argument()));
1342 cur.idx() = row * ncols() + col;
1343 if (cur.idx() > cur.lastidx()) {
1344 cur.idx() = cur.lastidx();
1345 cur.pos() = cur.lastpos();
1347 if (cur.pos() > cur.lastpos())
1348 cur.pos() = cur.lastpos();
1350 // FIXME: find some more clever handling of the selection,
1351 // i.e. preserve it.
1352 cur.clearSelection();
1353 //cur.dispatched(FINISHED);
1357 case LFUN_MATH_DISPLAY: {
1358 cur.recordUndoInset();
1359 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1361 cur.pos() = cur.lastpos();
1362 //cur.dispatched(FINISHED);
1367 InsetMathGrid::doDispatch(cur, cmd);
1373 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1374 FuncStatus & status) const
1376 switch (cmd.action) {
1377 case LFUN_FINISHED_BACKWARD:
1378 case LFUN_FINISHED_FORWARD:
1379 case LFUN_FINISHED_RIGHT:
1380 case LFUN_FINISHED_LEFT:
1383 case LFUN_NEWLINE_INSERT:
1384 case LFUN_MATH_EXTERN:
1385 case LFUN_MATH_DISPLAY:
1387 status.setEnabled(true);
1390 case LFUN_MATH_MUTATE: {
1391 HullType ht = hullType(cmd.argument());
1392 status.setOnOff(type_ == ht);
1393 status.setEnabled(true);
1397 case LFUN_MATH_NUMBER_TOGGLE:
1398 // FIXME: what is the right test, this or the one of
1400 status.setEnabled(display());
1401 status.setOnOff(numberedType());
1404 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1405 // FIXME: what is the right test, this or the one of
1407 bool const enable = (type_ == hullMultline)
1408 ? (nrows() - 1 == cur.row())
1409 : display() != Inline && nrows() > 1;
1410 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1411 status.setEnabled(enable);
1412 status.setOnOff(enable && numbered(r));
1416 case LFUN_LABEL_INSERT:
1417 status.setEnabled(type_ != hullSimple);
1420 case LFUN_LABEL_COPY_AS_REF: {
1421 bool enabled = false;
1423 if (cmd.argument().empty() && &cur.inset() == this) {
1424 // if there is no argument and we're inside math, we retrieve
1425 // the row number from the cursor position.
1426 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1427 enabled = numberedType() && label_[row] && !nonum_[row];
1429 // if there is an argument, find the corresponding label, else
1430 // check whether there is at least one label.
1431 for (row_type row = 0; row != nrows(); ++row) {
1432 if (!nonum_[row] && label_[row] &&
1433 (cmd.argument().empty() || label(row) == cmd.argument())) {
1439 status.setEnabled(enabled);
1443 case LFUN_INSET_INSERT:
1444 if (cmd.getArg(0) == "label") {
1445 status.setEnabled(type_ != hullSimple);
1448 return InsetMathGrid::getStatus(cur, cmd, status);
1450 case LFUN_TABULAR_FEATURE: {
1451 istringstream is(to_utf8(cmd.argument()));
1455 && (s == "append-row"
1456 || s == "delete-row"
1457 || s == "copy-row")) {
1458 status.message(bformat(
1459 from_utf8(N_("Can't change number of rows in '%1$s'")),
1461 status.setEnabled(false);
1465 && (s == "append-column"
1466 || s == "delete-column"
1467 || s == "copy-column")) {
1468 status.message(bformat(
1469 from_utf8(N_("Can't change number of columns in '%1$s'")),
1471 status.setEnabled(false);
1474 if ((type_ == hullSimple
1475 || type_ == hullEquation
1476 || type_ == hullNone) &&
1477 (s == "add-hline-above" || s == "add-hline-below")) {
1478 status.message(bformat(
1479 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1481 status.setEnabled(false);
1484 if (s == "add-vline-left" || s == "add-vline-right") {
1485 status.message(bformat(
1486 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1488 status.setEnabled(false);
1491 if (s == "valign-top" || s == "valign-middle"
1492 || s == "valign-bottom" || s == "align-left"
1493 || s == "align-center" || s == "align-right") {
1494 status.setEnabled(false);
1497 return InsetMathGrid::getStatus(cur, cmd, status);
1501 return InsetMathGrid::getStatus(cur, cmd, status);
1504 // This cannot really happen, but inserted to shut-up gcc
1505 return InsetMathGrid::getStatus(cur, cmd, status);
1509 /////////////////////////////////////////////////////////////////////
1513 // simply scrap this function if you want
1514 void InsetMathHull::mutateToText()
1517 // translate to latex
1519 latex(os, false, false);
1520 string str = os.str();
1523 Text * lt = view_->cursor().innerText();
1524 string::const_iterator cit = str.begin();
1525 string::const_iterator end = str.end();
1526 for (; cit != end; ++cit)
1527 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1530 //dispatch(LFUN_ESCAPE);
1535 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1536 docstring const & font)
1538 // this whole function is a hack and won't work for incremental font
1541 if (cur.inset().asInsetMath()->name() == font)
1542 cur.handleFont(to_utf8(font));
1544 cur.handleNest(createInsetMath(font, cur.buffer()));
1550 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1555 font.fromString(to_utf8(arg), b);
1556 if (font.fontInfo().color() != Color_inherit) {
1557 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1558 cur.handleNest(at, 0);
1563 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1566 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1567 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1568 enter_front ? idxFirst(cur) : idxLast(cur);
1569 // The inset formula dimension is not necessarily the same as the
1570 // one of the instant preview image, so we have to indicate to the
1571 // BufferView that a metrics update is needed.
1572 cur.updateFlags(Update::Force);
1576 void InsetMathHull::revealCodes(Cursor & cur) const
1578 if (!cur.inMathed())
1580 odocstringstream os;
1582 cur.message(os.str());
1584 // write something to the minibuffer
1585 // translate to latex
1589 string str = os.str();
1591 string::size_type pos = 0;
1593 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1596 else if (*it == '\0') {
1598 pos = it - str.begin();
1604 res = res.substr(pos - 30);
1605 if (res.size() > 60)
1606 res = res.substr(0, 60);
1612 /////////////////////////////////////////////////////////////////////
1616 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1619 // FIXME: completely broken
1620 static InsetMathHull * lastformula = 0;
1621 static CursorBase current = DocIterator(ibegin(nucleus()));
1623 static string laststr;
1625 if (lastformula != this || laststr != str) {
1626 //lyxerr << "reset lastformula to " << this << endl;
1629 current = ibegin(nucleus());
1631 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1635 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1637 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1638 CursorSlice & top = it.back();
1639 MathData const & a = top.asInsetMath()->cell(top.idx_);
1640 if (a.matchpart(ar, top.pos_)) {
1641 bv->cursor().setSelection(it, ar.size());
1643 top.pos_ += ar.size();
1649 //lyxerr << "not found!" << endl;
1656 void InsetMathHull::write(ostream & os) const
1658 odocstringstream oss;
1659 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1662 os << to_utf8(oss.str());
1666 void InsetMathHull::read(Lexer & lex)
1669 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1670 operator=(*at->asHullInset());
1674 bool InsetMathHull::readQuiet(Lexer & lex)
1677 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1679 operator=(*at->asHullInset());
1684 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1686 if (0 && display()) {
1690 TextPainter tpain(dim.width(), dim.height());
1691 drawT(tpain, 0, dim.ascent());
1693 // reset metrics cache to "real" values
1695 return tpain.textheight();
1697 odocstringstream oss;
1698 Encoding const * const enc = encodings.fromLyXName("utf8");
1699 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1701 if (type_ == hullRegexp)
1705 docstring const str = oss.str();
1712 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1717 if (getType() == hullSimple)
1718 name = from_ascii("inlineequation");
1720 name = from_ascii("informalequation");
1722 docstring bname = name;
1723 if (!label(0).empty())
1724 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1726 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1728 odocstringstream ls;
1729 if (runparams.flavor == OutputParams::XML) {
1730 ms << MTag("alt role='tex' ");
1731 // Workaround for db2latex: db2latex always includes equations with
1732 // \ensuremath{} or \begin{display}\end{display}
1733 // so we strip LyX' math environment
1734 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1735 InsetMathGrid::write(wi);
1736 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1741 InsetMathGrid::mathmlize(ms);
1744 ms << MTag("alt role='tex'");
1745 res = latex(ls, runparams);
1746 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1750 ms << from_ascii("<graphic fileref=\"eqn/");
1751 if (!label(0).empty())
1752 ms << sgml::cleanID(buffer(), runparams, label(0));
1754 ms << sgml::uniqueID(from_ascii("anon"));
1756 if (runparams.flavor == OutputParams::XML)
1757 ms << from_ascii("\"/>");
1759 ms << from_ascii("\">");
1761 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1763 return ms.line() + res;
1767 docstring InsetMathHull::xhtml(odocstream & os, OutputParams const &) const
1769 if (getType() == hullSimple)
1770 os << "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1772 os << "<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1774 InsetMathGrid::mathmlize(ms);
1780 void InsetMathHull::tocString(odocstream & os) const
1782 plaintext(os, OutputParams(0));
1786 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1788 return from_ascii("context-math");