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);
492 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
494 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
496 preview_->startLoading(buffer());
497 cur.updateFlags(Update::Force);
503 docstring InsetMathHull::label(row_type row) const
505 LASSERT(row < nrows(), /**/);
506 if (InsetLabel * il = label_[row])
507 return il->screenLabel();
512 void InsetMathHull::label(row_type row, docstring const & label)
514 //lyxerr << "setting label '" << label << "' for row " << row << endl;
518 label_[row] = dummy_pointer;
519 // We need an update of the Buffer reference cache.
520 // This is achieved by updateLabels().
522 buffer().updateLabels();
525 label_[row]->updateCommand(label);
527 label_[row]->setParam("name", label);
531 InsetCommandParams p(LABEL_CODE);
533 label_[row] = new InsetLabel(buffer_, p);
535 label_[row]->setBuffer(buffer());
539 void InsetMathHull::numbered(row_type row, bool num)
542 if (nonum_[row] && label_[row]) {
546 // The buffer is set at the end of readInset.
547 // When parsing the inset, buffer_ is 0.
550 // We need an update of the Buffer reference cache.
551 // This is achieved by updateLabels().
552 buffer().updateLabels();
557 bool InsetMathHull::numbered(row_type row) const
563 bool InsetMathHull::ams() const
565 return type_ == hullAlign
566 || type_ == hullFlAlign
567 || type_ == hullMultline
568 || type_ == hullGather
569 || type_ == hullAlignAt
570 || type_ == hullXAlignAt
571 || type_ == hullXXAlignAt;
575 Inset::DisplayType InsetMathHull::display() const
577 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
582 bool InsetMathHull::numberedType() const
584 if (type_ == hullNone)
586 if (type_ == hullSimple)
588 if (type_ == hullXXAlignAt)
590 if (type_ == hullRegexp)
592 for (row_type row = 0; row < nrows(); ++row)
599 void InsetMathHull::validate(LaTeXFeatures & features) const
602 features.require("amsmath");
604 // Validation is necessary only if not using AMS math.
605 // To be safe, we will always run mathedvalidate.
606 //if (features.amsstyle)
609 //features.binom = true;
611 InsetMathGrid::validate(features);
615 void InsetMathHull::header_write(WriteStream & os) const
617 bool n = numberedType();
631 os << "\\begin{equation" << star(n) << "}\n";
641 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
646 os << "\\begin{" << hullName(type_) << star(n) << '}'
647 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
651 os << "\\begin{" << hullName(type_) << '}'
652 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
660 os << "\\begin{unknown" << star(n) << '}';
666 void InsetMathHull::footer_write(WriteStream & os) const
668 bool n = numberedType();
681 os << "\\end{equation" << star(n) << "}\n";
693 os << "\\end{" << hullName(type_) << star(n) << "}\n";
697 os << "\\end{" << hullName(type_) << "}\n";
705 os << "\\end{unknown" << star(n) << '}';
711 bool InsetMathHull::rowChangeOK() const
714 type_ == hullEqnArray || type_ == hullAlign ||
715 type_ == hullFlAlign || type_ == hullAlignAt ||
716 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
717 type_ == hullGather || type_ == hullMultline;
721 bool InsetMathHull::colChangeOK() const
724 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
725 type_ == hullXAlignAt || type_ == hullXXAlignAt;
729 void InsetMathHull::addRow(row_type row)
734 bool numbered = numberedType();
736 if (type_ == hullMultline) {
737 if (row + 1 == nrows()) {
744 nonum_.insert(nonum_.begin() + row + 1, !numbered);
745 label_.insert(label_.begin() + row + 1, dummy_pointer);
748 InsetMathGrid::addRow(row);
752 void InsetMathHull::swapRow(row_type row)
756 if (row + 1 == nrows())
758 // gcc implements the standard std::vector<bool> which is *not* a container:
759 // http://www.gotw.ca/publications/N1185.pdf
760 // As a results, it doesn't like this:
761 // swap(nonum_[row], nonum_[row + 1]);
762 // so we do it manually:
763 bool const b = nonum_[row];
764 nonum_[row] = nonum_[row + 1];
766 swap(label_[row], label_[row + 1]);
767 InsetMathGrid::swapRow(row);
771 void InsetMathHull::delRow(row_type row)
773 if (nrows() <= 1 || !rowChangeOK())
775 if (row + 1 == nrows() && type_ == hullMultline) {
776 bool const b = nonum_[row - 1];
777 nonum_[row - 1] = nonum_[row];
779 swap(label_[row - 1], label_[row]);
780 InsetMathGrid::delRow(row);
783 InsetMathGrid::delRow(row);
784 // The last dummy row has no number info nor a label.
785 // Test nrows() + 1 because we have already erased the row.
786 if (row == nrows() + 1)
788 nonum_.erase(nonum_.begin() + row);
790 label_.erase(label_.begin() + row);
794 void InsetMathHull::addCol(col_type col)
798 InsetMathGrid::addCol(col);
802 void InsetMathHull::delCol(col_type col)
804 if (ncols() <= 1 || !colChangeOK())
806 InsetMathGrid::delCol(col);
810 docstring InsetMathHull::nicelabel(row_type row) const
815 return from_ascii("(#)");
816 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
820 void InsetMathHull::glueall()
823 for (idx_type i = 0; i < nargs(); ++i)
825 *this = InsetMathHull(buffer_, hullSimple);
831 void InsetMathHull::splitTo2Cols()
833 LASSERT(ncols() == 1, /**/);
834 InsetMathGrid::addCol(1);
835 for (row_type row = 0; row < nrows(); ++row) {
836 idx_type const i = 2 * row;
837 pos_type pos = firstRelOp(cell(i));
838 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
839 cell(i).erase(pos, cell(i).size());
844 void InsetMathHull::splitTo3Cols()
846 LASSERT(ncols() < 3, /**/);
849 InsetMathGrid::addCol(2);
850 for (row_type row = 0; row < nrows(); ++row) {
851 idx_type const i = 3 * row + 1;
852 if (cell(i).size()) {
853 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
854 cell(i).erase(1, cell(i).size());
860 void InsetMathHull::changeCols(col_type cols)
864 else if (ncols() < cols) {
870 while (ncols() < cols)
871 InsetMathGrid::addCol(ncols());
877 for (row_type row = 0; row < nrows(); ++row) {
878 idx_type const i = row * ncols();
879 for (col_type col = cols; col < ncols(); ++col) {
880 cell(i + cols - 1).append(cell(i + col));
884 while (ncols() > cols) {
885 InsetMathGrid::delCol(ncols() - 1);
890 HullType InsetMathHull::getType() const
896 void InsetMathHull::setType(HullType type)
903 void InsetMathHull::mutate(HullType newtype)
905 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
907 // we try to move along the chain
908 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
910 // +-------------------------------------+
911 // we use eqnarray as intermediate type for mutations that are not
912 // directly supported because it handles labels and numbering for
915 if (newtype == type_) {
919 else if (newtype < hullNone) {
924 else if (type_ == hullNone) {
930 else if (type_ == hullSimple) {
931 if (newtype == hullNone) {
935 setType(hullEquation);
941 else if (type_ == hullEquation) {
942 if (newtype < type_) {
946 } else if (newtype == hullEqnArray) {
947 // split it "nicely" on the first relop
949 setType(hullEqnArray);
950 } else if (newtype == hullMultline || newtype == hullGather) {
960 else if (type_ == hullEqnArray) {
961 if (newtype < type_) {
962 // set correct (no)numbering
964 for (row_type row = 0; row < nrows(); ++row) {
971 // set first non-empty label
972 for (row_type row = 0; row < nrows(); ++row) {
974 label_[0] = label_[row];
981 } else { // align & Co.
988 else if (type_ == hullAlign || type_ == hullAlignAt ||
989 type_ == hullXAlignAt || type_ == hullFlAlign) {
990 if (newtype < hullAlign) {
992 setType(hullEqnArray);
994 } else if (newtype == hullGather || newtype == hullMultline) {
997 } else if (newtype == hullXXAlignAt) {
998 for (row_type row = 0; row < nrows(); ++row)
999 numbered(row, false);
1006 else if (type_ == hullXXAlignAt) {
1007 for (row_type row = 0; row < nrows(); ++row)
1008 numbered(row, false);
1009 if (newtype < hullAlign) {
1011 setType(hullEqnArray);
1013 } else if (newtype == hullGather || newtype == hullMultline) {
1021 else if (type_ == hullMultline || type_ == hullGather) {
1022 if (newtype == hullGather || newtype == hullMultline)
1024 else if (newtype == hullAlign || newtype == hullFlAlign ||
1025 newtype == hullAlignAt || newtype == hullXAlignAt) {
1028 } else if (newtype == hullXXAlignAt) {
1030 for (row_type row = 0; row < nrows(); ++row)
1031 numbered(row, false);
1035 setType(hullEqnArray);
1041 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1042 << "' to '" << to_utf8(hullName(newtype))
1043 << "' not implemented" << endl;
1048 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1051 if (numberedType()) {
1052 if (label_[row] && !nonum_[row])
1053 res += "\\label{" + label_[row]->getParam("name") + '}';
1054 if (nonum_[row] && (type_ != hullMultline))
1055 res += "\\nonumber ";
1057 return res + InsetMathGrid::eolString(row, fragile);
1061 void InsetMathHull::write(WriteStream & os) const
1063 ModeSpecifier specifier(os, MATH_MODE);
1065 InsetMathGrid::write(os);
1070 void InsetMathHull::normalize(NormalStream & os) const
1072 os << "[formula " << hullName(type_) << ' ';
1073 InsetMathGrid::normalize(os);
1078 void InsetMathHull::mathmlize(MathStream & os) const
1080 InsetMathGrid::mathmlize(os);
1084 void InsetMathHull::infoize(odocstream & os) const
1086 os << "Type: " << hullName(type_);
1090 void InsetMathHull::check() const
1092 LASSERT(nonum_.size() == nrows(), /**/);
1093 LASSERT(label_.size() == nrows(), /**/);
1097 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1101 idocstringstream iss(func.argument());
1102 iss >> dlang >> extra;
1104 extra = from_ascii("noextra");
1105 string const lang = to_ascii(dlang);
1107 // FIXME: temporarily disabled
1108 //if (cur.selection()) {
1111 // lyxerr << "use selection: " << ar << endl;
1112 // insert(pipeThroughExtern(lang, extra, ar));
1117 eq.push_back(MathAtom(new InsetMathChar('=')));
1119 // go to first item in line
1120 cur.idx() -= cur.idx() % ncols();
1123 if (getType() == hullSimple) {
1124 size_type pos = cur.cell().find_last(eq);
1126 if (cur.inMathed() && cur.selection()) {
1127 asArray(grabAndEraseSelection(cur), ar);
1128 } else if (pos == cur.cell().size()) {
1130 lyxerr << "use whole cell: " << ar << endl;
1132 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1133 lyxerr << "use partial cell form pos: " << pos << endl;
1135 cur.cell().append(eq);
1136 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1137 cur.pos() = cur.lastpos();
1141 if (getType() == hullEquation) {
1142 lyxerr << "use equation inset" << endl;
1143 mutate(hullEqnArray);
1144 MathData & ar = cur.cell();
1145 lyxerr << "use cell: " << ar << endl;
1149 cur.cell() = pipeThroughExtern(lang, extra, ar);
1150 // move to end of line
1151 cur.pos() = cur.lastpos();
1156 lyxerr << "use eqnarray" << endl;
1157 cur.idx() += 2 - cur.idx() % ncols();
1159 MathData ar = cur.cell();
1160 lyxerr << "use cell: " << ar << endl;
1161 // FIXME: temporarily disabled
1167 cur.cell() = pipeThroughExtern(lang, extra, ar);
1168 cur.pos() = cur.lastpos();
1173 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1175 //lyxerr << "action: " << cmd.action << endl;
1176 switch (cmd.action) {
1178 case LFUN_FINISHED_BACKWARD:
1179 case LFUN_FINISHED_FORWARD:
1180 case LFUN_FINISHED_RIGHT:
1181 case LFUN_FINISHED_LEFT:
1182 //lyxerr << "action: " << cmd.action << endl;
1183 InsetMathGrid::doDispatch(cur, cmd);
1187 case LFUN_BREAK_PARAGRAPH:
1188 // just swallow this
1191 case LFUN_NEWLINE_INSERT:
1192 // some magic for the common case
1193 if (type_ == hullSimple || type_ == hullEquation) {
1194 cur.recordUndoInset();
1196 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1197 mutate(align ? hullAlign : hullEqnArray);
1198 cur.idx() = nrows() * ncols() - 1;
1199 cur.pos() = cur.lastpos();
1201 InsetMathGrid::doDispatch(cur, cmd);
1204 case LFUN_MATH_NUMBER_TOGGLE: {
1205 //lyxerr << "toggling all numbers" << endl;
1206 cur.recordUndoInset();
1207 bool old = numberedType();
1208 if (type_ == hullMultline)
1209 numbered(nrows() - 1, !old);
1211 for (row_type row = 0; row < nrows(); ++row)
1212 numbered(row, !old);
1214 cur.message(old ? _("No number") : _("Number"));
1218 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1219 cur.recordUndoInset();
1220 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1221 bool old = numbered(r);
1222 cur.message(old ? _("No number") : _("Number"));
1227 case LFUN_LABEL_INSERT: {
1228 cur.recordUndoInset();
1229 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1230 docstring old_label = label(r);
1231 docstring const default_label = from_ascii(
1232 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1233 if (old_label.empty())
1234 old_label = default_label;
1236 InsetCommandParams p(LABEL_CODE);
1237 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1238 string const data = InsetCommand::params2string("label", p);
1240 if (cmd.argument().empty())
1241 cur.bv().showDialog("label", data);
1243 FuncRequest fr(LFUN_INSET_INSERT, data);
1249 case LFUN_LABEL_COPY_AS_REF: {
1251 if (cmd.argument().empty() && &cur.inset() == this)
1252 // if there is no argument and we're inside math, we retrieve
1253 // the row number from the cursor position.
1254 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1256 // if there is an argument, find the corresponding label, else
1257 // check whether there is at least one label.
1258 for (row = 0; row != nrows(); ++row)
1259 if (!nonum_[row] && label_[row]
1260 && (cmd.argument().empty() || label(row) == cmd.argument()))
1267 InsetCommandParams p(REF_CODE, "ref");
1268 p["reference"] = label(row);
1269 cap::clearSelection();
1270 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1274 case LFUN_WORD_DELETE_FORWARD:
1275 case LFUN_CHAR_DELETE_FORWARD:
1276 if (col(cur.idx()) + 1 == ncols()
1277 && cur.pos() == cur.lastpos()
1278 && !cur.selection()) {
1279 if (!label(row(cur.idx())).empty()) {
1280 cur.recordUndoInset();
1281 label(row(cur.idx()), docstring());
1282 } else if (numbered(row(cur.idx()))) {
1283 cur.recordUndoInset();
1284 numbered(row(cur.idx()), false);
1286 InsetMathGrid::doDispatch(cur, cmd);
1290 InsetMathGrid::doDispatch(cur, cmd);
1295 case LFUN_INSET_INSERT: {
1296 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1297 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1298 string const name = cmd.getArg(0);
1299 if (name == "label") {
1300 InsetCommandParams p(LABEL_CODE);
1301 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1302 docstring str = p["name"];
1303 cur.recordUndoInset();
1304 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1308 docstring old = label(r);
1311 // The label will take care of the reference update.
1315 // Newly created inset so initialize it.
1316 label_[r]->initView();
1321 InsetMathGrid::doDispatch(cur, cmd);
1325 case LFUN_MATH_EXTERN:
1326 cur.recordUndoInset();
1330 case LFUN_MATH_MUTATE: {
1331 cur.recordUndoInset();
1332 row_type row = cur.row();
1333 col_type col = cur.col();
1334 mutate(hullType(cmd.argument()));
1335 cur.idx() = row * ncols() + col;
1336 if (cur.idx() > cur.lastidx()) {
1337 cur.idx() = cur.lastidx();
1338 cur.pos() = cur.lastpos();
1340 if (cur.pos() > cur.lastpos())
1341 cur.pos() = cur.lastpos();
1343 // FIXME: find some more clever handling of the selection,
1344 // i.e. preserve it.
1345 cur.clearSelection();
1346 //cur.dispatched(FINISHED);
1350 case LFUN_MATH_DISPLAY: {
1351 cur.recordUndoInset();
1352 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1354 cur.pos() = cur.lastpos();
1355 //cur.dispatched(FINISHED);
1360 InsetMathGrid::doDispatch(cur, cmd);
1366 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1367 FuncStatus & status) const
1369 switch (cmd.action) {
1370 case LFUN_FINISHED_BACKWARD:
1371 case LFUN_FINISHED_FORWARD:
1372 case LFUN_FINISHED_RIGHT:
1373 case LFUN_FINISHED_LEFT:
1376 case LFUN_NEWLINE_INSERT:
1377 case LFUN_MATH_EXTERN:
1378 case LFUN_MATH_DISPLAY:
1380 status.setEnabled(true);
1383 case LFUN_MATH_MUTATE: {
1384 HullType ht = hullType(cmd.argument());
1385 status.setOnOff(type_ == ht);
1386 status.setEnabled(true);
1390 case LFUN_MATH_NUMBER_TOGGLE:
1391 // FIXME: what is the right test, this or the one of
1393 status.setEnabled(display());
1394 status.setOnOff(numberedType());
1397 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1398 // FIXME: what is the right test, this or the one of
1400 bool const enable = (type_ == hullMultline)
1401 ? (nrows() - 1 == cur.row())
1402 : display() != Inline && nrows() > 1;
1403 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1404 status.setEnabled(enable);
1405 status.setOnOff(enable && numbered(r));
1409 case LFUN_LABEL_INSERT:
1410 status.setEnabled(type_ != hullSimple);
1413 case LFUN_LABEL_COPY_AS_REF: {
1414 bool enabled = false;
1416 if (cmd.argument().empty() && &cur.inset() == this) {
1417 // if there is no argument and we're inside math, we retrieve
1418 // the row number from the cursor position.
1419 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1420 enabled = numberedType() && label_[row] && !nonum_[row];
1422 // if there is an argument, find the corresponding label, else
1423 // check whether there is at least one label.
1424 for (row_type row = 0; row != nrows(); ++row) {
1425 if (!nonum_[row] && label_[row] &&
1426 (cmd.argument().empty() || label(row) == cmd.argument())) {
1432 status.setEnabled(enabled);
1436 case LFUN_INSET_INSERT:
1437 if (cmd.getArg(0) == "label") {
1438 status.setEnabled(type_ != hullSimple);
1441 return InsetMathGrid::getStatus(cur, cmd, status);
1443 case LFUN_TABULAR_FEATURE: {
1444 istringstream is(to_utf8(cmd.argument()));
1448 && (s == "append-row"
1449 || s == "delete-row"
1450 || s == "copy-row")) {
1451 status.message(bformat(
1452 from_utf8(N_("Can't change number of rows in '%1$s'")),
1454 status.setEnabled(false);
1458 && (s == "append-column"
1459 || s == "delete-column"
1460 || s == "copy-column")) {
1461 status.message(bformat(
1462 from_utf8(N_("Can't change number of columns in '%1$s'")),
1464 status.setEnabled(false);
1467 if ((type_ == hullSimple
1468 || type_ == hullEquation
1469 || type_ == hullNone) &&
1470 (s == "add-hline-above" || s == "add-hline-below")) {
1471 status.message(bformat(
1472 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1474 status.setEnabled(false);
1477 if (s == "add-vline-left" || s == "add-vline-right") {
1478 status.message(bformat(
1479 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1481 status.setEnabled(false);
1484 if (s == "valign-top" || s == "valign-middle"
1485 || s == "valign-bottom" || s == "align-left"
1486 || s == "align-center" || s == "align-right") {
1487 status.setEnabled(false);
1490 return InsetMathGrid::getStatus(cur, cmd, status);
1494 return InsetMathGrid::getStatus(cur, cmd, status);
1497 // This cannot really happen, but inserted to shut-up gcc
1498 return InsetMathGrid::getStatus(cur, cmd, status);
1502 /////////////////////////////////////////////////////////////////////
1506 // simply scrap this function if you want
1507 void InsetMathHull::mutateToText()
1510 // translate to latex
1512 latex(os, false, false);
1513 string str = os.str();
1516 Text * lt = view_->cursor().innerText();
1517 string::const_iterator cit = str.begin();
1518 string::const_iterator end = str.end();
1519 for (; cit != end; ++cit)
1520 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1523 //dispatch(LFUN_ESCAPE);
1528 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1529 docstring const & font)
1531 // this whole function is a hack and won't work for incremental font
1534 if (cur.inset().asInsetMath()->name() == font)
1535 cur.handleFont(to_utf8(font));
1537 cur.handleNest(createInsetMath(font, cur.buffer()));
1543 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1548 font.fromString(to_utf8(arg), b);
1549 if (font.fontInfo().color() != Color_inherit) {
1550 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1551 cur.handleNest(at, 0);
1556 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1559 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1560 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1561 enter_front ? idxFirst(cur) : idxLast(cur);
1562 // The inset formula dimension is not necessarily the same as the
1563 // one of the instant preview image, so we have to indicate to the
1564 // BufferView that a metrics update is needed.
1565 cur.updateFlags(Update::Force);
1569 void InsetMathHull::revealCodes(Cursor & cur) const
1571 if (!cur.inMathed())
1573 odocstringstream os;
1575 cur.message(os.str());
1577 // write something to the minibuffer
1578 // translate to latex
1582 string str = os.str();
1584 string::size_type pos = 0;
1586 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1589 else if (*it == '\0') {
1591 pos = it - str.begin();
1597 res = res.substr(pos - 30);
1598 if (res.size() > 60)
1599 res = res.substr(0, 60);
1605 /////////////////////////////////////////////////////////////////////
1609 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1612 // FIXME: completely broken
1613 static InsetMathHull * lastformula = 0;
1614 static CursorBase current = DocIterator(ibegin(nucleus()));
1616 static string laststr;
1618 if (lastformula != this || laststr != str) {
1619 //lyxerr << "reset lastformula to " << this << endl;
1622 current = ibegin(nucleus());
1624 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1628 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1630 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1631 CursorSlice & top = it.back();
1632 MathData const & a = top.asInsetMath()->cell(top.idx_);
1633 if (a.matchpart(ar, top.pos_)) {
1634 bv->cursor().setSelection(it, ar.size());
1636 top.pos_ += ar.size();
1642 //lyxerr << "not found!" << endl;
1649 void InsetMathHull::write(ostream & os) const
1651 odocstringstream oss;
1652 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1655 os << to_utf8(oss.str());
1659 void InsetMathHull::read(Lexer & lex)
1662 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1663 operator=(*at->asHullInset());
1667 bool InsetMathHull::readQuiet(Lexer & lex)
1670 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1672 operator=(*at->asHullInset());
1677 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1679 if (0 && display()) {
1683 TextPainter tpain(dim.width(), dim.height());
1684 drawT(tpain, 0, dim.ascent());
1686 // reset metrics cache to "real" values
1688 return tpain.textheight();
1690 odocstringstream oss;
1691 Encoding const * const enc = encodings.fromLyXName("utf8");
1692 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1694 if (type_ == hullRegexp)
1698 docstring const str = oss.str();
1705 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1710 if (getType() == hullSimple)
1711 name = from_ascii("inlineequation");
1713 name = from_ascii("informalequation");
1715 docstring bname = name;
1716 if (!label(0).empty())
1717 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1719 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1721 odocstringstream ls;
1722 if (runparams.flavor == OutputParams::XML) {
1723 ms << MTag("alt role='tex' ");
1724 // Workaround for db2latex: db2latex always includes equations with
1725 // \ensuremath{} or \begin{display}\end{display}
1726 // so we strip LyX' math environment
1727 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1728 InsetMathGrid::write(wi);
1729 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1734 InsetMathGrid::mathmlize(ms);
1737 ms << MTag("alt role='tex'");
1738 res = latex(ls, runparams);
1739 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1743 ms << from_ascii("<graphic fileref=\"eqn/");
1744 if (!label(0).empty())
1745 ms << sgml::cleanID(buffer(), runparams, label(0));
1747 ms << sgml::uniqueID(from_ascii("anon"));
1749 if (runparams.flavor == OutputParams::XML)
1750 ms << from_ascii("\"/>");
1752 ms << from_ascii("\">");
1754 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1756 return ms.line() + res;
1760 docstring InsetMathHull::xhtml(odocstream & os, OutputParams const &) const
1762 if (getType() == hullSimple)
1763 os << "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1765 os << "<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1767 InsetMathGrid::mathmlize(ms);
1773 void InsetMathHull::tocString(odocstream & os) const
1775 plaintext(os, OutputParams(0));
1779 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1781 return from_ascii("context-math");