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)
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);
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 & insetPos,
461 graphics::PreviewLoader & /*ploader*/) const
463 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
464 reloadPreview(insetPos);
469 void InsetMathHull::reloadPreview(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;
488 docstring const snippet = macro_preamble.str() + latexString(*this);
489 LYXERR(Debug::MACROS, "Preview snippet: " << snippet);
490 preview_->addPreview(snippet, *buffer);
491 preview_->startLoading(*buffer);
494 bool InsetMathHull::notifyCursorLeaves(Cursor const & old, Cursor & cur)
496 if (RenderPreview::status() == LyXRC::PREVIEW_ON) {
498 cur.updateFlags(Update::Force);
504 docstring InsetMathHull::label(row_type row) const
506 LASSERT(row < nrows(), /**/);
507 if (InsetLabel * il = label_[row])
508 return il->screenLabel();
513 void InsetMathHull::label(row_type row, docstring const & label)
515 //lyxerr << "setting label '" << label << "' for row " << row << endl;
519 label_[row] = dummy_pointer;
520 // We need an update of the Buffer reference cache.
521 // This is achieved by updateLabels().
523 buffer().updateLabels();
526 label_[row]->updateCommand(label);
528 label_[row]->setParam("name", label);
532 InsetCommandParams p(LABEL_CODE);
534 label_[row] = new InsetLabel(buffer_, p);
536 label_[row]->setBuffer(buffer());
540 void InsetMathHull::numbered(row_type row, bool num)
543 if (nonum_[row] && label_[row]) {
547 // The buffer is set at the end of readInset.
548 // When parsing the inset, buffer_ is 0.
551 // We need an update of the Buffer reference cache.
552 // This is achieved by updateLabels().
553 buffer().updateLabels();
558 bool InsetMathHull::numbered(row_type row) const
564 bool InsetMathHull::ams() const
566 return type_ == hullAlign
567 || type_ == hullFlAlign
568 || type_ == hullMultline
569 || type_ == hullGather
570 || type_ == hullAlignAt
571 || type_ == hullXAlignAt
572 || type_ == hullXXAlignAt;
576 Inset::DisplayType InsetMathHull::display() const
578 if (type_ == hullSimple || type_ == hullNone || type_ == hullRegexp)
583 bool InsetMathHull::numberedType() const
585 if (type_ == hullNone)
587 if (type_ == hullSimple)
589 if (type_ == hullXXAlignAt)
591 if (type_ == hullRegexp)
593 for (row_type row = 0; row < nrows(); ++row)
600 void InsetMathHull::validate(LaTeXFeatures & features) const
603 features.require("amsmath");
605 // Validation is necessary only if not using AMS math.
606 // To be safe, we will always run mathedvalidate.
607 //if (features.amsstyle)
610 //features.binom = true;
612 InsetMathGrid::validate(features);
616 void InsetMathHull::header_write(WriteStream & os) const
618 bool n = numberedType();
632 os << "\\begin{equation" << star(n) << "}\n";
642 os << "\\begin{" << hullName(type_) << star(n) << "}\n";
647 os << "\\begin{" << hullName(type_) << star(n) << '}'
648 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
652 os << "\\begin{" << hullName(type_) << '}'
653 << '{' << static_cast<unsigned int>((ncols() + 1)/2) << "}\n";
661 os << "\\begin{unknown" << star(n) << '}';
667 void InsetMathHull::footer_write(WriteStream & os) const
669 bool n = numberedType();
682 os << "\\end{equation" << star(n) << "}\n";
694 os << "\\end{" << hullName(type_) << star(n) << "}\n";
698 os << "\\end{" << hullName(type_) << "}\n";
706 os << "\\end{unknown" << star(n) << '}';
712 bool InsetMathHull::rowChangeOK() const
715 type_ == hullEqnArray || type_ == hullAlign ||
716 type_ == hullFlAlign || type_ == hullAlignAt ||
717 type_ == hullXAlignAt || type_ == hullXXAlignAt ||
718 type_ == hullGather || type_ == hullMultline;
722 bool InsetMathHull::colChangeOK() const
725 type_ == hullAlign || type_ == hullFlAlign ||type_ == hullAlignAt ||
726 type_ == hullXAlignAt || type_ == hullXXAlignAt;
730 void InsetMathHull::addRow(row_type row)
735 bool numbered = numberedType();
737 if (type_ == hullMultline) {
738 if (row + 1 == nrows()) {
745 nonum_.insert(nonum_.begin() + row + 1, !numbered);
746 label_.insert(label_.begin() + row + 1, dummy_pointer);
749 InsetMathGrid::addRow(row);
753 void InsetMathHull::swapRow(row_type row)
757 if (row + 1 == nrows())
759 // gcc implements the standard std::vector<bool> which is *not* a container:
760 // http://www.gotw.ca/publications/N1185.pdf
761 // As a results, it doesn't like this:
762 // swap(nonum_[row], nonum_[row + 1]);
763 // so we do it manually:
764 bool const b = nonum_[row];
765 nonum_[row] = nonum_[row + 1];
767 swap(label_[row], label_[row + 1]);
768 InsetMathGrid::swapRow(row);
772 void InsetMathHull::delRow(row_type row)
774 if (nrows() <= 1 || !rowChangeOK())
776 if (row + 1 == nrows() && type_ == hullMultline) {
777 bool const b = nonum_[row - 1];
778 nonum_[row - 1] = nonum_[row];
780 swap(label_[row - 1], label_[row]);
781 InsetMathGrid::delRow(row);
784 InsetMathGrid::delRow(row);
785 // The last dummy row has no number info nor a label.
786 // Test nrows() + 1 because we have already erased the row.
787 if (row == nrows() + 1)
789 nonum_.erase(nonum_.begin() + row);
791 label_.erase(label_.begin() + row);
795 void InsetMathHull::addCol(col_type col)
799 InsetMathGrid::addCol(col);
803 void InsetMathHull::delCol(col_type col)
805 if (ncols() <= 1 || !colChangeOK())
807 InsetMathGrid::delCol(col);
811 docstring InsetMathHull::nicelabel(row_type row) const
816 return from_ascii("(#)");
817 return '(' + label_[row]->screenLabel() + from_ascii(", #)");
821 void InsetMathHull::glueall()
824 for (idx_type i = 0; i < nargs(); ++i)
826 *this = InsetMathHull(buffer_, hullSimple);
832 void InsetMathHull::splitTo2Cols()
834 LASSERT(ncols() == 1, /**/);
835 InsetMathGrid::addCol(1);
836 for (row_type row = 0; row < nrows(); ++row) {
837 idx_type const i = 2 * row;
838 pos_type pos = firstRelOp(cell(i));
839 cell(i + 1) = MathData(buffer_, cell(i).begin() + pos, cell(i).end());
840 cell(i).erase(pos, cell(i).size());
845 void InsetMathHull::splitTo3Cols()
847 LASSERT(ncols() < 3, /**/);
850 InsetMathGrid::addCol(2);
851 for (row_type row = 0; row < nrows(); ++row) {
852 idx_type const i = 3 * row + 1;
853 if (cell(i).size()) {
854 cell(i + 1) = MathData(buffer_, cell(i).begin() + 1, cell(i).end());
855 cell(i).erase(1, cell(i).size());
861 void InsetMathHull::changeCols(col_type cols)
865 else if (ncols() < cols) {
871 while (ncols() < cols)
872 InsetMathGrid::addCol(ncols());
878 for (row_type row = 0; row < nrows(); ++row) {
879 idx_type const i = row * ncols();
880 for (col_type col = cols; col < ncols(); ++col) {
881 cell(i + cols - 1).append(cell(i + col));
885 while (ncols() > cols) {
886 InsetMathGrid::delCol(ncols() - 1);
891 HullType InsetMathHull::getType() const
897 void InsetMathHull::setType(HullType type)
904 void InsetMathHull::mutate(HullType newtype)
906 //lyxerr << "mutating from '" << type_ << "' to '" << newtype << "'" << endl;
908 // we try to move along the chain
909 // none <-> simple <-> equation <-> eqnarray -> *align* -> multline, gather -+
911 // +-------------------------------------+
912 // we use eqnarray as intermediate type for mutations that are not
913 // directly supported because it handles labels and numbering for
916 if (newtype == type_) {
920 else if (newtype < hullNone) {
925 else if (type_ == hullNone) {
931 else if (type_ == hullSimple) {
932 if (newtype == hullNone) {
936 setType(hullEquation);
942 else if (type_ == hullEquation) {
943 if (newtype < type_) {
947 } else if (newtype == hullEqnArray) {
948 // split it "nicely" on the first relop
950 setType(hullEqnArray);
951 } else if (newtype == hullMultline || newtype == hullGather) {
961 else if (type_ == hullEqnArray) {
962 if (newtype < type_) {
963 // set correct (no)numbering
965 for (row_type row = 0; row < nrows(); ++row) {
972 // set first non-empty label
973 for (row_type row = 0; row < nrows(); ++row) {
975 label_[0] = label_[row];
982 } else { // align & Co.
989 else if (type_ == hullAlign || type_ == hullAlignAt ||
990 type_ == hullXAlignAt || type_ == hullFlAlign) {
991 if (newtype < hullAlign) {
993 setType(hullEqnArray);
995 } else if (newtype == hullGather || newtype == hullMultline) {
998 } else if (newtype == hullXXAlignAt) {
999 for (row_type row = 0; row < nrows(); ++row)
1000 numbered(row, false);
1007 else if (type_ == hullXXAlignAt) {
1008 for (row_type row = 0; row < nrows(); ++row)
1009 numbered(row, false);
1010 if (newtype < hullAlign) {
1012 setType(hullEqnArray);
1014 } else if (newtype == hullGather || newtype == hullMultline) {
1022 else if (type_ == hullMultline || type_ == hullGather) {
1023 if (newtype == hullGather || newtype == hullMultline)
1025 else if (newtype == hullAlign || newtype == hullFlAlign ||
1026 newtype == hullAlignAt || newtype == hullXAlignAt) {
1029 } else if (newtype == hullXXAlignAt) {
1031 for (row_type row = 0; row < nrows(); ++row)
1032 numbered(row, false);
1036 setType(hullEqnArray);
1042 lyxerr << "mutation from '" << to_utf8(hullName(type_))
1043 << "' to '" << to_utf8(hullName(newtype))
1044 << "' not implemented" << endl;
1049 docstring InsetMathHull::eolString(row_type row, bool fragile) const
1052 if (numberedType()) {
1053 if (label_[row] && !nonum_[row])
1054 res += "\\label{" + label_[row]->getParam("name") + '}';
1055 if (nonum_[row] && (type_ != hullMultline))
1056 res += "\\nonumber ";
1058 return res + InsetMathGrid::eolString(row, fragile);
1062 void InsetMathHull::write(WriteStream & os) const
1064 ModeSpecifier specifier(os, MATH_MODE);
1066 InsetMathGrid::write(os);
1071 void InsetMathHull::normalize(NormalStream & os) const
1073 os << "[formula " << hullName(type_) << ' ';
1074 InsetMathGrid::normalize(os);
1079 void InsetMathHull::mathmlize(MathStream & os) const
1081 InsetMathGrid::mathmlize(os);
1085 void InsetMathHull::infoize(odocstream & os) const
1087 os << "Type: " << hullName(type_);
1091 void InsetMathHull::check() const
1093 LASSERT(nonum_.size() == nrows(), /**/);
1094 LASSERT(label_.size() == nrows(), /**/);
1098 void InsetMathHull::doExtern(Cursor & cur, FuncRequest & func)
1102 idocstringstream iss(func.argument());
1103 iss >> dlang >> extra;
1105 extra = from_ascii("noextra");
1106 string const lang = to_ascii(dlang);
1108 // FIXME: temporarily disabled
1109 //if (cur.selection()) {
1112 // lyxerr << "use selection: " << ar << endl;
1113 // insert(pipeThroughExtern(lang, extra, ar));
1118 eq.push_back(MathAtom(new InsetMathChar('=')));
1120 // go to first item in line
1121 cur.idx() -= cur.idx() % ncols();
1124 if (getType() == hullSimple) {
1125 size_type pos = cur.cell().find_last(eq);
1127 if (cur.inMathed() && cur.selection()) {
1128 asArray(grabAndEraseSelection(cur), ar);
1129 } else if (pos == cur.cell().size()) {
1131 lyxerr << "use whole cell: " << ar << endl;
1133 ar = MathData(buffer_, cur.cell().begin() + pos + 1, cur.cell().end());
1134 lyxerr << "use partial cell form pos: " << pos << endl;
1136 cur.cell().append(eq);
1137 cur.cell().append(pipeThroughExtern(lang, extra, ar));
1138 cur.pos() = cur.lastpos();
1142 if (getType() == hullEquation) {
1143 lyxerr << "use equation inset" << endl;
1144 mutate(hullEqnArray);
1145 MathData & ar = cur.cell();
1146 lyxerr << "use cell: " << ar << endl;
1150 cur.cell() = pipeThroughExtern(lang, extra, ar);
1151 // move to end of line
1152 cur.pos() = cur.lastpos();
1157 lyxerr << "use eqnarray" << endl;
1158 cur.idx() += 2 - cur.idx() % ncols();
1160 MathData ar = cur.cell();
1161 lyxerr << "use cell: " << ar << endl;
1162 // FIXME: temporarily disabled
1168 cur.cell() = pipeThroughExtern(lang, extra, ar);
1169 cur.pos() = cur.lastpos();
1174 void InsetMathHull::doDispatch(Cursor & cur, FuncRequest & cmd)
1176 //lyxerr << "action: " << cmd.action << endl;
1177 switch (cmd.action) {
1179 case LFUN_FINISHED_BACKWARD:
1180 case LFUN_FINISHED_FORWARD:
1181 case LFUN_FINISHED_RIGHT:
1182 case LFUN_FINISHED_LEFT:
1183 //lyxerr << "action: " << cmd.action << endl;
1184 InsetMathGrid::doDispatch(cur, cmd);
1188 case LFUN_BREAK_PARAGRAPH:
1189 // just swallow this
1192 case LFUN_NEWLINE_INSERT:
1193 // some magic for the common case
1194 if (type_ == hullSimple || type_ == hullEquation) {
1195 cur.recordUndoInset();
1197 cur.bv().buffer().params().use_amsmath == BufferParams::package_on;
1198 mutate(align ? hullAlign : hullEqnArray);
1199 cur.idx() = nrows() * ncols() - 1;
1200 cur.pos() = cur.lastpos();
1202 InsetMathGrid::doDispatch(cur, cmd);
1205 case LFUN_MATH_NUMBER_TOGGLE: {
1206 //lyxerr << "toggling all numbers" << endl;
1207 cur.recordUndoInset();
1208 bool old = numberedType();
1209 if (type_ == hullMultline)
1210 numbered(nrows() - 1, !old);
1212 for (row_type row = 0; row < nrows(); ++row)
1213 numbered(row, !old);
1215 cur.message(old ? _("No number") : _("Number"));
1219 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1220 cur.recordUndoInset();
1221 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1222 bool old = numbered(r);
1223 cur.message(old ? _("No number") : _("Number"));
1228 case LFUN_LABEL_INSERT: {
1229 cur.recordUndoInset();
1230 row_type r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1231 docstring old_label = label(r);
1232 docstring const default_label = from_ascii(
1233 (lyxrc.label_init_length >= 0) ? "eq:" : "");
1234 if (old_label.empty())
1235 old_label = default_label;
1237 InsetCommandParams p(LABEL_CODE);
1238 p["name"] = cmd.argument().empty() ? old_label : cmd.argument();
1239 string const data = InsetCommand::params2string("label", p);
1241 if (cmd.argument().empty())
1242 cur.bv().showDialog("label", data);
1244 FuncRequest fr(LFUN_INSET_INSERT, data);
1250 case LFUN_LABEL_COPY_AS_REF: {
1252 if (cmd.argument().empty() && &cur.inset() == this)
1253 // if there is no argument and we're inside math, we retrieve
1254 // the row number from the cursor position.
1255 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1257 // if there is an argument, find the corresponding label, else
1258 // check whether there is at least one label.
1259 for (row = 0; row != nrows(); ++row)
1260 if (!nonum_[row] && label_[row]
1261 && (cmd.argument().empty() || label(row) == cmd.argument()))
1268 InsetCommandParams p(REF_CODE, "ref");
1269 p["reference"] = label(row);
1270 cap::clearSelection();
1271 cap::copyInset(cur, new InsetRef(buffer_, p), label(row));
1275 case LFUN_WORD_DELETE_FORWARD:
1276 case LFUN_CHAR_DELETE_FORWARD:
1277 if (col(cur.idx()) + 1 == ncols()
1278 && cur.pos() == cur.lastpos()
1279 && !cur.selection()) {
1280 if (!label(row(cur.idx())).empty()) {
1281 cur.recordUndoInset();
1282 label(row(cur.idx()), docstring());
1283 } else if (numbered(row(cur.idx()))) {
1284 cur.recordUndoInset();
1285 numbered(row(cur.idx()), false);
1287 InsetMathGrid::doDispatch(cur, cmd);
1291 InsetMathGrid::doDispatch(cur, cmd);
1296 case LFUN_INSET_INSERT: {
1297 //lyxerr << "arg: " << to_utf8(cmd.argument()) << endl;
1298 // FIXME: this should be cleaned up to use InsetLabel methods directly.
1299 string const name = cmd.getArg(0);
1300 if (name == "label") {
1301 InsetCommandParams p(LABEL_CODE);
1302 InsetCommand::string2params(name, to_utf8(cmd.argument()), p);
1303 docstring str = p["name"];
1304 cur.recordUndoInset();
1305 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1309 docstring old = label(r);
1312 // The label will take care of the reference update.
1316 // Newly created inset so initialize it.
1317 label_[r]->initView();
1322 InsetMathGrid::doDispatch(cur, cmd);
1326 case LFUN_MATH_EXTERN:
1327 cur.recordUndoInset();
1331 case LFUN_MATH_MUTATE: {
1332 cur.recordUndoInset();
1333 row_type row = cur.row();
1334 col_type col = cur.col();
1335 mutate(hullType(cmd.argument()));
1336 cur.idx() = row * ncols() + col;
1337 if (cur.idx() > cur.lastidx()) {
1338 cur.idx() = cur.lastidx();
1339 cur.pos() = cur.lastpos();
1341 if (cur.pos() > cur.lastpos())
1342 cur.pos() = cur.lastpos();
1344 // FIXME: find some more clever handling of the selection,
1345 // i.e. preserve it.
1346 cur.clearSelection();
1347 //cur.dispatched(FINISHED);
1351 case LFUN_MATH_DISPLAY: {
1352 cur.recordUndoInset();
1353 mutate(type_ == hullSimple ? hullEquation : hullSimple);
1355 cur.pos() = cur.lastpos();
1356 //cur.dispatched(FINISHED);
1361 InsetMathGrid::doDispatch(cur, cmd);
1367 bool InsetMathHull::getStatus(Cursor & cur, FuncRequest const & cmd,
1368 FuncStatus & status) const
1370 switch (cmd.action) {
1371 case LFUN_FINISHED_BACKWARD:
1372 case LFUN_FINISHED_FORWARD:
1373 case LFUN_FINISHED_RIGHT:
1374 case LFUN_FINISHED_LEFT:
1377 case LFUN_NEWLINE_INSERT:
1378 case LFUN_MATH_EXTERN:
1379 case LFUN_MATH_DISPLAY:
1381 status.setEnabled(true);
1384 case LFUN_MATH_MUTATE: {
1385 HullType ht = hullType(cmd.argument());
1386 status.setOnOff(type_ == ht);
1387 status.setEnabled(true);
1391 case LFUN_MATH_NUMBER_TOGGLE:
1392 // FIXME: what is the right test, this or the one of
1394 status.setEnabled(display());
1395 status.setOnOff(numberedType());
1398 case LFUN_MATH_NUMBER_LINE_TOGGLE: {
1399 // FIXME: what is the right test, this or the one of
1401 bool const enable = (type_ == hullMultline)
1402 ? (nrows() - 1 == cur.row())
1403 : display() != Inline && nrows() > 1;
1404 row_type const r = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1405 status.setEnabled(enable);
1406 status.setOnOff(enable && numbered(r));
1410 case LFUN_LABEL_INSERT:
1411 status.setEnabled(type_ != hullSimple);
1414 case LFUN_LABEL_COPY_AS_REF: {
1415 bool enabled = false;
1417 if (cmd.argument().empty() && &cur.inset() == this) {
1418 // if there is no argument and we're inside math, we retrieve
1419 // the row number from the cursor position.
1420 row = (type_ == hullMultline) ? nrows() - 1 : cur.row();
1421 enabled = numberedType() && label_[row] && !nonum_[row];
1423 // if there is an argument, find the corresponding label, else
1424 // check whether there is at least one label.
1425 for (row_type row = 0; row != nrows(); ++row) {
1426 if (!nonum_[row] && label_[row] &&
1427 (cmd.argument().empty() || label(row) == cmd.argument())) {
1433 status.setEnabled(enabled);
1437 case LFUN_INSET_INSERT:
1438 if (cmd.getArg(0) == "label") {
1439 status.setEnabled(type_ != hullSimple);
1442 return InsetMathGrid::getStatus(cur, cmd, status);
1444 case LFUN_TABULAR_FEATURE: {
1445 istringstream is(to_utf8(cmd.argument()));
1449 && (s == "append-row"
1450 || s == "delete-row"
1451 || s == "copy-row")) {
1452 status.message(bformat(
1453 from_utf8(N_("Can't change number of rows in '%1$s'")),
1455 status.setEnabled(false);
1459 && (s == "append-column"
1460 || s == "delete-column"
1461 || s == "copy-column")) {
1462 status.message(bformat(
1463 from_utf8(N_("Can't change number of columns in '%1$s'")),
1465 status.setEnabled(false);
1468 if ((type_ == hullSimple
1469 || type_ == hullEquation
1470 || type_ == hullNone) &&
1471 (s == "add-hline-above" || s == "add-hline-below")) {
1472 status.message(bformat(
1473 from_utf8(N_("Can't add horizontal grid lines in '%1$s'")),
1475 status.setEnabled(false);
1478 if (s == "add-vline-left" || s == "add-vline-right") {
1479 status.message(bformat(
1480 from_utf8(N_("Can't add vertical grid lines in '%1$s'")),
1482 status.setEnabled(false);
1485 if (s == "valign-top" || s == "valign-middle"
1486 || s == "valign-bottom" || s == "align-left"
1487 || s == "align-center" || s == "align-right") {
1488 status.setEnabled(false);
1491 return InsetMathGrid::getStatus(cur, cmd, status);
1495 return InsetMathGrid::getStatus(cur, cmd, status);
1498 // This cannot really happen, but inserted to shut-up gcc
1499 return InsetMathGrid::getStatus(cur, cmd, status);
1503 /////////////////////////////////////////////////////////////////////
1507 // simply scrap this function if you want
1508 void InsetMathHull::mutateToText()
1511 // translate to latex
1513 latex(os, false, false);
1514 string str = os.str();
1517 Text * lt = view_->cursor().innerText();
1518 string::const_iterator cit = str.begin();
1519 string::const_iterator end = str.end();
1520 for (; cit != end; ++cit)
1521 view_->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
1524 //dispatch(LFUN_ESCAPE);
1529 void InsetMathHull::handleFont(Cursor & cur, docstring const & arg,
1530 docstring const & font)
1532 // this whole function is a hack and won't work for incremental font
1535 if (cur.inset().asInsetMath()->name() == font)
1536 cur.handleFont(to_utf8(font));
1538 cur.handleNest(createInsetMath(font, cur.buffer()));
1544 void InsetMathHull::handleFont2(Cursor & cur, docstring const & arg)
1549 font.fromString(to_utf8(arg), b);
1550 if (font.fontInfo().color() != Color_inherit) {
1551 MathAtom at = MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color()));
1552 cur.handleNest(at, 0);
1557 void InsetMathHull::edit(Cursor & cur, bool front, EntryDirection entry_from)
1560 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1561 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1562 enter_front ? idxFirst(cur) : idxLast(cur);
1563 // The inset formula dimension is not necessarily the same as the
1564 // one of the instant preview image, so we have to indicate to the
1565 // BufferView that a metrics update is needed.
1566 cur.updateFlags(Update::Force);
1570 void InsetMathHull::revealCodes(Cursor & cur) const
1572 if (!cur.inMathed())
1574 odocstringstream os;
1576 cur.message(os.str());
1578 // write something to the minibuffer
1579 // translate to latex
1583 string str = os.str();
1585 string::size_type pos = 0;
1587 for (string::iterator it = str.begin(); it != str.end(); ++it) {
1590 else if (*it == '\0') {
1592 pos = it - str.begin();
1598 res = res.substr(pos - 30);
1599 if (res.size() > 60)
1600 res = res.substr(0, 60);
1606 /////////////////////////////////////////////////////////////////////
1610 bool InsetMathHull::searchForward(BufferView * bv, string const & str,
1613 // FIXME: completely broken
1614 static InsetMathHull * lastformula = 0;
1615 static CursorBase current = DocIterator(ibegin(nucleus()));
1617 static string laststr;
1619 if (lastformula != this || laststr != str) {
1620 //lyxerr << "reset lastformula to " << this << endl;
1623 current = ibegin(nucleus());
1625 mathed_parse_cell(ar, str, Parse::NORMAL, &buffer());
1629 //lyxerr << "searching '" << str << "' in " << this << ar << endl;
1631 for (DocIterator it = current; it != iend(nucleus()); increment(it)) {
1632 CursorSlice & top = it.back();
1633 MathData const & a = top.asInsetMath()->cell(top.idx_);
1634 if (a.matchpart(ar, top.pos_)) {
1635 bv->cursor().setSelection(it, ar.size());
1637 top.pos_ += ar.size();
1643 //lyxerr << "not found!" << endl;
1650 void InsetMathHull::write(ostream & os) const
1652 odocstringstream oss;
1653 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1656 os << to_utf8(oss.str());
1660 void InsetMathHull::read(Lexer & lex)
1663 mathed_parse_normal(buffer_, at, lex, Parse::TRACKMACRO);
1664 operator=(*at->asHullInset());
1668 bool InsetMathHull::readQuiet(Lexer & lex)
1671 bool success = mathed_parse_normal(buffer_, at, lex, Parse::QUIET);
1673 operator=(*at->asHullInset());
1678 int InsetMathHull::plaintext(odocstream & os, OutputParams const &) const
1680 if (0 && display()) {
1684 TextPainter tpain(dim.width(), dim.height());
1685 drawT(tpain, 0, dim.ascent());
1687 // reset metrics cache to "real" values
1689 return tpain.textheight();
1691 odocstringstream oss;
1692 Encoding const * const enc = encodings.fromLyXName("utf8");
1693 WriteStream wi(oss, false, true, WriteStream::wsDefault, enc);
1695 if (type_ == hullRegexp)
1699 docstring const str = oss.str();
1706 int InsetMathHull::docbook(odocstream & os, OutputParams const & runparams) const
1711 if (getType() == hullSimple)
1712 name = from_ascii("inlineequation");
1714 name = from_ascii("informalequation");
1716 docstring bname = name;
1717 if (!label(0).empty())
1718 bname += " id='" + sgml::cleanID(buffer(), runparams, label(0)) + "'";
1720 ++ms.tab(); ms.cr(); ms.os() << '<' << bname << '>';
1722 odocstringstream ls;
1723 if (runparams.flavor == OutputParams::XML) {
1724 ms << MTag("alt role='tex' ");
1725 // Workaround for db2latex: db2latex always includes equations with
1726 // \ensuremath{} or \begin{display}\end{display}
1727 // so we strip LyX' math environment
1728 WriteStream wi(ls, false, false, WriteStream::wsDefault, runparams.encoding);
1729 InsetMathGrid::write(wi);
1730 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1735 InsetMathGrid::mathmlize(ms);
1738 ms << MTag("alt role='tex'");
1739 res = latex(ls, runparams);
1740 ms << from_utf8(subst(subst(to_utf8(ls.str()), "&", "&"), "<", "<"));
1744 ms << from_ascii("<graphic fileref=\"eqn/");
1745 if (!label(0).empty())
1746 ms << sgml::cleanID(buffer(), runparams, label(0));
1748 ms << sgml::uniqueID(from_ascii("anon"));
1750 if (runparams.flavor == OutputParams::XML)
1751 ms << from_ascii("\"/>");
1753 ms << from_ascii("\">");
1755 ms.cr(); --ms.tab(); ms.os() << "</" << name << '>';
1757 return ms.line() + res;
1761 docstring InsetMathHull::xhtml(odocstream & os, OutputParams const &) const
1763 if (getType() == hullSimple)
1764 os << "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1766 os << "<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">";
1768 InsetMathGrid::mathmlize(ms);
1774 void InsetMathHull::tocString(odocstream & os) const
1776 plaintext(os, OutputParams(0));
1780 docstring InsetMathHull::contextMenu(BufferView const &, int, int) const
1782 return from_ascii("context-math");